store

package
v0.0.0-...-b6c9e3d Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: AGPL-3.0 Imports: 69 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NotificationEventIssue       = "issue"
	NotificationEventPullRequest = "pull_request"
	NotificationEventRelease     = "release"
	NotificationEventDiscussion  = "discussion"
	NotificationEventCommit      = "commit"
	NotificationEventActions     = "actions"
	NotificationEventDependabot  = "dependabot"
)

Notification event types. Only issue and pull_request raise threads today; the rest are stored so the settings page round-trips.

View Source
const (
	ActionsArtifactsBucket = "actions_artifacts"
	ActionsCachesBucket    = "actions_caches"
)
View Source
const (
	// Type discriminators GitHub puts at the head of a git object's global id.
	GitCommitNodeIDPrefix = "C"
	GitBlobNodeIDPrefix   = "B"
	GitTreeNodeIDPrefix   = "T"
	GitTagNodeIDPrefix    = "TA"
	GitRefNodeIDPrefix    = "REF"
)
View Source
const (
	// #nosec G101 -- public token type prefix, not a credential.
	TokenPrefixInstallation = "ghs_"
	TokenPrefixOAuthUser    = "gho_" // classic OAuth-App user token
	TokenPrefixAppUser      = "ghu_" // GitHub-App user-to-server token
	TokenPrefixRefresh      = "ghr_" // refresh token (never valid as auth)
)

GitHub token prefixes. Each selects a different lookup table and auth shape in authenticateRequest.

View Source
const (
	PersistenceEncryptionKeyEnvironment = "BLEEPHUB_PERSISTENCE_ENCRYPTION_KEY"
	SealedPersistenceValuePrefix        = "bleephub:sealed:v1:"
	OpaquePersistenceKeyPrefix          = "hmac:v1:"
)
View Source
const (
	EcosystemNPM      = "npm"
	EcosystemPip      = "pip"
	EcosystemMaven    = "maven"
	EcosystemNuGet    = "nuget"
	EcosystemRubyGems = "rubygems"
	EcosystemGo       = "go"
	EcosystemComposer = "composer"
	EcosystemRust     = "rust"
	EcosystemActions  = "actions"
	EcosystemPub      = "pub"
	EcosystemErlang   = "erlang"
	EcosystemSwift    = "swift"
)

Canonical ecosystem keys: the REST spelling the store records on an alert. GraphQL's SecurityAdvisoryEcosystem enum is the uppercased form.

View Source
const (
	CopilotPlanBusiness   = "business"
	CopilotPlanEnterprise = "enterprise"
	CopilotPlanIndividual = "individual"
	CopilotPlanUnknown    = "unknown"
)

Copilot plan types, matching the copilot-organization-details schema.

View Source
const (
	CopilotSeatsAssignAll      = "assign_all"
	CopilotSeatsAssignSelected = "assign_selected"
	CopilotSeatsDisabled       = "disabled"
	CopilotSeatsUnconfigured   = "unconfigured"
)

Copilot seat-management settings.

View Source
const (
	CopilotFeatureEnabled      = "enabled"
	CopilotFeatureDisabled     = "disabled"
	CopilotFeatureUnconfigured = "unconfigured"
	CopilotSuggestionsAllow    = "allow"
	CopilotSuggestionsBlock    = "block"
)

Copilot feature policy values.

View Source
const (
	EnterpriseAdminInvitationNodeIDPrefix  = "EAI_kgDO"
	EnterpriseMemberInvitationNodeIDPrefix = "EMI_kgDO"
	IPAllowListEntryNodeIDPrefix           = "IPALE_kgDO"
)

EnterpriseAdminInvitationNodeIDPrefix and EnterpriseMemberInvitationNodeIDPrefix are the global-id prefixes for the two enterprise invitation kinds.

View Source
const (
	IPAllowListOwnerEnterprise   = "Enterprise"
	IPAllowListOwnerOrganization = "Organization"
	IPAllowListOwnerUser         = "User"
)

IP allow list owner types. The user-scoped list has no GraphQL owner and is reachable only from the account's own /ui-data surface.

View Source
const (
	EnterprisePolicyEnabled  = "ENABLED"
	EnterprisePolicyDisabled = "DISABLED"
	EnterprisePolicyNoPolicy = "NO_POLICY"
	// EnterprisePolicyDisallowInsecure bans the second-factor methods classed
	// insecure.
	EnterprisePolicyDisallowInsecure = "INSECURE"
	// The two proof-of-presence requirements beside NO_POLICY: a fresh MFA
	// challenge, or a full re-authentication against the identity provider.
	EnterpriseProofOfPresenceMFA    = "MFA"
	EnterpriseProofOfPresenceReauth = "REAUTH"
)

Policy-setting values, spelled with GitHub's enum values. A policy field's zero value is never served: the enterprise is created with GitHub's defaults, so a non-null GraphQL field always has a value.

View Source
const (
	DefaultEnterpriseBandwidthQuotaGB = 100.0
	DefaultEnterpriseStorageQuotaGB   = 50.0
	DefaultEnterpriseTotalLicenses    = 50
)

Provisioned billing entitlements a new enterprise starts with.

View Source
const (
	LoginSessionsBucket = "login_sessions"

	// LoginSessionsByUserBucket is a durable secondary index, one row per session
	// keyed by `<userID>:<sessionStorageKey>`, so a user's sessions are fetched by
	// a bounded prefix scan (STORE-025) rather than scanning the whole bucket.
	// PutLoginSession writes the index row in the session's batch, so it is a
	// superset of live sessions and revocation never misses one; stale rows are
	// reclaimed on the next per-user purge.
	LoginSessionsByUserBucket = "login_sessions_by_user"
)
View Source
const (
	MarketplaceCategoryNodeIDPrefix = "MC_kgDO"
	MarketplaceListingNodeIDPrefix  = "ML_kgDO"
)

Global-id prefixes for the two Marketplace node types.

View Source
const (
	MarketplaceListingDraft                             = "draft"
	MarketplaceListingUnverified                        = "unverified"
	MarketplaceListingUnverifiedPending                 = "unverified_pending"
	MarketplaceListingVerificationPendingFromDraft      = "verification_pending_from_draft"
	MarketplaceListingVerificationPendingFromUnverified = "verification_pending_from_unverified"
	MarketplaceListingVerified                          = "verified"
	MarketplaceListingRejected                          = "rejected"
	MarketplaceListingArchived                          = "archived"
)

Marketplace listing verification states, matching the is* flags on GitHub's MarketplaceListing type. Exactly one holds at a time.

View Source
const (
	MigrationStatePending   = "pending"
	MigrationStateExporting = "exporting"
	MigrationStateExported  = "exported"
	MigrationStateFailed    = "failed"
)

The states a GitHub export migration moves through: created pending, claimed into exporting, ending in exactly one of exported or failed.

View Source
const (
	MigrationSourceNodeIDPrefix     = "MS_kgDO"
	RepositoryMigrationNodeIDPrefix = "RM_kgDO"
	OrgMigrationNodeIDPrefix        = "OM_kgDO"
)

Global-id prefixes for the GEI entities.

View Source
const (
	MigrationSourceTypeAzureDevOps     = "AZURE_DEVOPS"
	MigrationSourceTypeBitbucketServer = "BITBUCKET_SERVER"
	MigrationSourceTypeGitHubArchive   = "GITHUB_ARCHIVE"
	MigrationSourceTypeGitLab          = "GITLAB"
)

MigrationSourceType values — GitHub's MigrationSourceType enum.

View Source
const (
	GEIMigrationStateNotStarted        = "NOT_STARTED"
	GEIMigrationStateQueued            = "QUEUED"
	GEIMigrationStatePendingValidation = "PENDING_VALIDATION"
	GEIMigrationStateFailedValidation  = "FAILED_VALIDATION"
	GEIMigrationStateInProgress        = "IN_PROGRESS"
	GEIMigrationStateSucceeded         = "SUCCEEDED"
	GEIMigrationStateFailed            = "FAILED"
)

GEIMigrationState values — GitHub's MigrationState enum. A repository migration goes QUEUED → IN_PROGRESS → SUCCEEDED/FAILED/FAILED_VALIDATION.

View Source
const (
	OrgMigrationStatePreRepoMigration  = "PRE_REPO_MIGRATION"
	OrgMigrationStateRepoMigration     = "REPO_MIGRATION"
	OrgMigrationStatePostRepoMigration = "POST_REPO_MIGRATION"
)

Extra states for an organization migration: OrganizationMigrationState is MigrationState plus these three phases.

View Source
const (
	MaxReadThreadIDs     = 50000
	PruneReadThreadSlack = 5000
)

MaxReadThreadIDs bounds the per-user read-marker set; PruneReadThreadSlack is the slack past the cap before a prune, amortising the O(n log n) prune to O(log n) per mark. Without the bound the map — re-serialised in full on every mark — grows unbounded (STORE-023).

View Source
const (
	NotificationViewSaved = "saved"
	NotificationViewDone  = "done"
)

Web-only inbox views (/ui-data); the empty view is the normal inbox.

View Source
const (
	ProjectV2EventProject      = "projects_v2"
	ProjectV2EventItem         = "projects_v2_item"
	ProjectV2EventStatusUpdate = "projects_v2_status_update"
)
View Source
const (
	SponsorsListingNodeIDPrefix             = "SL_kgDO"
	SponsorsTierNodeIDPrefix                = "ST_kgDO"
	SponsorshipNodeIDPrefix                 = "SP_kgDO"
	SponsorsActivityNodeIDPrefix            = "SA_kgDO"
	SponsorshipNewsletterNodeIDPrefix       = "SN_kgDO"
	SponsorsListingFeaturedItemNodeIDPrefix = "SLFI_kgDO"
)

Node-id prefixes for the Sponsors object graph ("<PREFIX>_kgDO%08d").

View Source
const (
	SponsorshipPrivacyPublic  = "PUBLIC"
	SponsorshipPrivacyPrivate = "PRIVATE"
)

Sponsorship privacy levels, matching GraphQL's SponsorshipPrivacy.

View Source
const (
	SponsorshipPaymentSourceGitHub  = "GITHUB"
	SponsorshipPaymentSourcePatreon = "PATREON"
)

Sponsorship payment sources, matching GraphQL's SponsorshipPaymentSource.

View Source
const (
	SponsorsActivityNewSponsorship       = "NEW_SPONSORSHIP"
	SponsorsActivityCancelledSponsorship = "CANCELLED_SPONSORSHIP"
	SponsorsActivityTierChange           = "TIER_CHANGE"
	SponsorsActivityPendingChange        = "PENDING_CHANGE"
	SponsorsActivityRefund               = "REFUND"
	SponsorsActivitySponsorMatchDisabled = "SPONSOR_MATCH_DISABLED"
)

SponsorsActivity actions, matching GraphQL's SponsorsActivityAction.

View Source
const (
	SponsorsGoalMonthlyAmount = "MONTHLY_SPONSORSHIP_AMOUNT"
	SponsorsGoalTotalSponsors = "TOTAL_SPONSORS_COUNT"
)

SponsorsGoal kinds, matching GraphQL's SponsorsGoalKind.

View Source
const (
	SponsorsFeatureableRepository = "REPOSITORY"
	SponsorsFeatureableUser       = "USER"
)

Featureable kinds, matching GraphQL's SponsorsListingFeaturedItemFeatureableType.

View Source
const (
	// TOTPDigits is the code length (RFC 6238 §5.3).
	TOTPDigits = 6
	// TOTPPeriod is the time step.
	TOTPPeriod = 30 * time.Second
	// TOTPDriftSteps accepts codes this many steps either side of now, absorbing
	// clock skew (RFC 6238 §5.2). One step bounds validity to 90s.
	TOTPDriftSteps = 1
)

RFC 6238 TOTP with the defaults every mainstream authenticator app assumes: HMAC-SHA1, 6 digits, 30-second step. Stated explicitly in the otpauth:// URI so a scanner never has to guess.

View Source
const (
	SetPrimaryEmailOK setPrimaryEmailResult = iota

	SetPrimaryEmailUnknown
	SetPrimaryEmailUnverified
)
View Source
const (
	DeleteEmailsOK deleteEmailsResult = iota

	DeleteEmailsPrimary
)
View Source
const (
	VerifiableDomainOwnerEnterprise   = "Enterprise"
	VerifiableDomainOwnerOrganization = "Organization"
)

GitHub's VerifiableDomainOwner union admits an enterprise or an organization.

View Source
const CodespaceDockerLifecycleTimeout = 2 * time.Minute

CodespaceDockerLifecycleTimeout bounds user-visible start, stop and remove operations without mistaking a loaded Docker daemon for a failed runtime.

View Source
const CodespaceGiB = int64(1) << 30
View Source
const CurrentSchemaVersion = 3

CurrentSchemaVersion is the schema this build writes and reads. Startup refuses a database stamped with a higher version.

View Source
const EnterpriseNodeIDPrefix = "E_kgDO"

EnterpriseNodeIDPrefix is the global-id prefix for Enterprise nodes.

View Source
const EnterpriseUserAccountNodeIDPrefix = "EUA_kgDO"

EnterpriseUserAccountNodeIDPrefix is the global-id prefix for the EnterpriseUserAccount projection of a user's membership; the suffix is the membership's database id.

View Source
const GithubActionsAppID = 15368

GithubActionsAppID is the app id GitHub attributes Actions check suites/runs to.

View Source
const LinkedBranchNodeIDPrefix = "LB"

LinkedBranchNodeIDPrefix is the type prefix of a linked branch's global id.

View Source
const MaxAuditLogEntries = 5000

MaxAuditLogEntries bounds the in-memory audit log; an uncapped prepend-only slice would grow without limit and make each write O(n).

View Source
const MaxHookDeliveries = 500

MaxHookDeliveries caps retained per-hook delivery history, mirroring GitHub's ≈30-day window and bounding unbounded growth.

View Source
const MaxJSONSafeInteger = uint64(1<<53 - 1)
View Source
const MaxPinnedDiscussions = 4

MaxPinnedDiscussions is github.com's per-repository pinned-discussion limit.

View Source
const MaxPinnedIssuesPerRepo = 3

MaxPinnedIssuesPerRepo mirrors GitHub's cap on pinned issues per repository.

View Source
const MaxPinnedRepos = 6

MaxPinnedRepos matches github.com's limit of six pinned items on a profile.

View Source
const MaxWikiPageRevisions = 100

MaxWikiPageRevisions bounds a page's projected history to the newest snapshots; their IDs still count from the page's first revision.

View Source
const ObjectChecksumMetadataKey = "bleephub-sha256"
View Source
const PendingDeletionsBucket = "pending_deletions"

PendingDeletionsBucket records that a cascading delete has started. The intent commits before any bytes are destroyed and clears with the last metadata row, so a delete interrupted between is finished on the next start.

View Source
const PendingRenamesBucket = "pending_renames"

PendingRenamesBucket records a repository rename whose slow object-store prefix copy runs outside the store lock (STORE-013). On crash recovery: if metadata moved to `To`, purge the leftover `From`; if not, purge the partial `To` copy.

View Source
const SchemaMetaDDL = `CREATE TABLE IF NOT EXISTS schema_meta (
	key   TEXT NOT NULL PRIMARY KEY,
	value TEXT NOT NULL
);`

SchemaMetaDDL bootstraps the schema-version table. It predates versioning, so it is created unconditionally on every open.

View Source
const VerifiableDomainNodeIDPrefix = "VD_kgDN"

VerifiableDomainNodeIDPrefix is the node-id prefix for VerifiableDomain rows.

View Source
const VerifiableDomainTokenTTL = 7 * 24 * time.Hour

VerifiableDomainTokenTTL matches GitHub's seven-day DNS TXT token expiry.

View Source
const WikiPageExtension = ".md"

WikiPageExtension is the extension a page created through the UI is written with (markdown, as github's editor writes).

View Source
const WikiStorageSuffix = ".wiki.git"

WikiStorageSuffix keys a wiki's git storage: `admin/docs` stores its wiki under `admin/docs.wiki.git`. The `.git` is deliberate — repository names ending in `.git` are refused at creation, so no repository can collide with this key, and the wiki gets the same pluggable storer as any repository.

View Source
const WikiURLSuffix = ".wiki"

WikiURLSuffix is the repository-name suffix a git client addresses a wiki with, after the transport trims the trailing `.git`.

Variables

View Source
var (
	ErrGitTreeishNotFound = errors.New("git treeish not found")
	// ErrGitTreeishInvalidObject: a revision resolved to an object that cannot
	// answer the request (a blob where a tree is required).
	ErrGitTreeishInvalidObject = errors.New("git treeish must identify a commit or tree")
)
View Source
var (
	ErrCodespaceNoRepository = fmt.Errorf("codespace has no repository")
	ErrCodespacePublished    = fmt.Errorf("codespace already has a repository")
	ErrRepoNameTaken         = fmt.Errorf("repository name already exists")
)

Codespace export / publish failure modes surfaced to handlers.

View Source
var (
	ErrTeamNotFound     = errors.New("team not found")
	ErrTeamSlugConflict = errors.New("team slug already exists")
)
View Source
var ArtifactDigestPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)
View Source
var CodesOfConductCatalog = []CodeOfConduct{
	{Key: "citizen_code_of_conduct", Name: "Citizen Code of Conduct", Body: cocCitizenCodeOfConductBody},
	{Key: "contributor_covenant", Name: "Contributor Covenant", Body: cocContributorCovenantBody},
}

CodesOfConductCatalog is ordered alphabetically by key, as GitHub lists it.

View Source
var CodespaceMachines = []CodespaceMachine{
	{Name: "basicLinux32", DisplayName: "2 cores, 4 GB RAM, 32 GB storage", Type: "standard", CPUs: 2, MemoryBytes: 4 * CodespaceGiB, StorageBytes: 32 * CodespaceGiB},
	{Name: "standardLinux32", DisplayName: "4 cores, 8 GB RAM, 32 GB storage", Type: "standard", CPUs: 4, MemoryBytes: 8 * CodespaceGiB, StorageBytes: 32 * CodespaceGiB},
	{Name: "premiumLinux64", DisplayName: "8 cores, 16 GB RAM, 64 GB storage", Type: "premium", CPUs: 8, MemoryBytes: 16 * CodespaceGiB, StorageBytes: 64 * CodespaceGiB},
	{Name: "largeLinux64", DisplayName: "16 cores, 32 GB RAM, 64 GB storage", Type: "premium", CPUs: 16, MemoryBytes: 32 * CodespaceGiB, StorageBytes: 64 * CodespaceGiB},
}
View Source
var ErrOpenPullRequestExists = errors.New("an open pull request already exists for the head and base")
View Source
var ErrReleaseAssetNameExists = errors.New("release asset name already exists")

ErrReleaseAssetNameExists reports a duplicate asset name; GitHub 422s it.

View Source
var LicenseMetadata = map[string]LicenseMeta{
	"mit": {
		Description:    "A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.",
		Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "private-use"},
		Conditions:     []string{"include-copyright"},
		Limitations:    []string{"liability", "warranty"},
		Featured:       true,
	},
	"apache-2.0": {
		Description:    "A permissive license whose main conditions require preservation of copyright and license notices. Contributors provide an express grant of patent rights. Licensed works, modifications, and larger works may be distributed under different terms and without source code.",
		Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Change the copyright notice at the bottom of the text to include your details.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "patent-use", "private-use"},
		Conditions:     []string{"include-copyright", "document-changes"},
		Limitations:    []string{"trademark-use", "liability", "warranty"},
		Featured:       true,
	},
	"gpl-3.0": {
		Description:    "Permissions of this strong copyleft license are conditioned on making available complete source code of licensed works and modifications, which include larger works using a licensed work, under the same license. Copyright and license notices must be preserved. Contributors provide an express grant of patent rights.",
		Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "patent-use", "private-use"},
		Conditions:     []string{"include-copyright", "document-changes", "disclose-source", "same-license"},
		Limitations:    []string{"liability", "warranty"},
		Featured:       true,
	},
	"bsd-2-clause": {
		Description:    "A permissive license that comes in two variants, the BSD 2-Clause and BSD 3-Clause. Both have very minute differences to the MIT license.",
		Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "private-use"},
		Conditions:     []string{"include-copyright"},
		Limitations:    []string{"liability", "warranty"},
		Featured:       false,
	},
	"bsd-3-clause": {
		Description:    "A permissive license similar to the BSD 2-Clause License, but with a 3rd clause that prohibits others from using the name of the copyright holder or its contributors to promote derived products without written consent.",
		Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "private-use"},
		Conditions:     []string{"include-copyright"},
		Limitations:    []string{"liability", "warranty"},
		Featured:       false,
	},
	"mpl-2.0": {
		Description:    "Permissions of this weak copyleft license are conditioned on making available source code of licensed files and modifications of those files under the same license (or in certain cases, one of the GNU licenses). Copyright and license notices must be preserved. Contributors provide an express grant of patent rights.",
		Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "patent-use", "private-use"},
		Conditions:     []string{"disclose-source", "include-copyright", "same-license--file"},
		Limitations:    []string{"liability", "trademark-use", "warranty"},
		Featured:       false,
	},
	"unlicense": {
		Description:    "A license with no conditions whatsoever which dedicates works to the public domain. Unlicensed works, modifications, and larger works may be distributed under different terms and without source code.",
		Implementation: "Create a text file (typically named UNLICENSE or LICENSE) in the root of your source code and copy the text of the license into the file.",
		Permissions:    []string{"commercial-use", "modifications", "distribution", "private-use"},
		Conditions:     []string{},
		Limitations:    []string{"liability", "warranty"},
		Featured:       false,
	},
}

LicenseMetadata maps each LicenseTemplates key to its metadata.

View Source
var LicenseTemplates = map[string]struct {
	Name   string `json:"-"`
	SpdxID string `json:"-"`
	NodeID string `json:"-"`
	Body   string `json:"-"`
}{
	"mit": {
		Name:   "MIT License",
		SpdxID: "MIT",
		NodeID: "MDc6TGljZW5zZTEz",
		Body: `MIT License

Copyright (c) [year] [fullname]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`,
	},
	"apache-2.0": {
		Name:   "Apache License 2.0",
		SpdxID: "Apache-2.0",
		NodeID: "MDc6TGljZW5zZTE=",
		Body: `Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
`,
	},
	"gpl-3.0": {
		Name:   "GNU General Public License v3.0",
		SpdxID: "GPL-3.0",
		NodeID: "MDc6TGljZW5zZTE1",
		Body: `GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
`,
	},
	"bsd-2-clause": {
		Name:   "BSD 2-Clause \"Simplified\" License",
		SpdxID: "BSD-2-Clause",
		NodeID: "MDc6TGljZW5zZTQ=",
		Body: `BSD 2-Clause License

Copyright (c) [year], [fullname]
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
`,
	},
	"bsd-3-clause": {
		Name:   "BSD 3-Clause \"New\" or \"Revised\" License",
		SpdxID: "BSD-3-Clause",
		NodeID: "MDc6TGljZW5zZTU=",
		Body: `BSD 3-Clause License

Copyright (c) [year], [fullname]
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
`,
	},
	"mpl-2.0": {
		Name:   "Mozilla Public License 2.0",
		SpdxID: "MPL-2.0",
		NodeID: "MDc6TGljZW5zZTE2",
		Body: `Mozilla Public License Version 2.0
==================================

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
`,
	},
	"unlicense": {
		Name:   "The Unlicense",
		SpdxID: "Unlicense",
		NodeID: "MDc6TGljZW5zZTE4",
		Body: `This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
`,
	},
}

LicenseTemplates maps license keys to full texts. Keys match the SPDX identifiers GitHub accepts in the license_template field of repo creation.

MarkdownModeRenderer matches GitHub's `markdown` mode: GFM extensions minus task lists and hard line breaks.

NotificationEventTypes is the ordered set of accepted event types; an unknown key in a payload is dropped.

View Source
var PredefinedOrgRoleBaseRoles = map[int]string{
	138: "read",
	139: "triage",
	140: "write",
	141: "maintain",
	142: "admin",
	143: "read",
}

PredefinedOrgRoleBaseRoles maps GitHub's predefined organization-role IDs to the repository base role each confers on every repository in the org. It mirrors the server's predefined-role catalog for the enforcement path in the store layer; TestPredefinedOrgRoleBaseRolesMatchCatalog guards against drift.

View Source
var ProjectV2DefaultStatusOptions = []*ProjectV2SingleSelectOption{
	{Name: "Todo", Color: "RED", Description: "This item hasn't been started"},
	{Name: "In Progress", Color: "YELLOW", Description: "This is actively being worked on"},
	{Name: "Done", Color: "GREEN", Description: "This has been completed"},
}

ProjectV2DefaultStatusOptions is the Status option set GitHub seeds.

View Source
var ProjectV2StatusUpdateStatuses = []string{"INACTIVE", "ON_TRACK", "AT_RISK", "OFF_TRACK", "COMPLETE"}

ProjectV2StatusUpdateStatuses is GitHub's ProjectV2StatusUpdateStatus enum.

View Source
var ReplicaInfrastructureStoreFields = map[string]struct{}{
	"ObjectByteStore": {},
	"PackageDataDir":  {},
}
View Source
var ReplicaLocalStoreFields = map[string]struct{}{
	"Agents":           {},
	"AuthCodes":        {},
	"DeviceCodes":      {},
	"Jobs":             {},
	"LogFiles":         {},
	"LogLines":         {},
	"LogMasks":         {},
	"ManifestCodes":    {},
	"NextAgent":        {},
	"NextLog":          {},
	"NextMsg":          {},
	"NextReqID":        {},
	"OIDCLogoutClaims": {},
	"PendingMessages":  {},
	"Sessions":         {},
}

ReplicaLocalStoreFields are the process-local parts of Store. Every other exported field is durable metadata, replaced from a fresh snapshot when a peer replica advances the revision.

View Source
var ReplicaServerAccessStoreFields = map[string]struct{}{
	"ActionsArtifacts":            {},
	"ApiRequestRecordCap":         {},
	"ClockMu":                     {},
	"ClockNow":                    {},
	"CodespaceRuntimeDelete":      {},
	"CodespaceWorkspacePrepare":   {},
	"JobsByPlanID":                {},
	"Logger":                      {},
	"Mu":                          {},
	"PendingRepoCreations":        {},
	"Persist":                     {},
	"PersistenceRecoveryRequired": {},
	"PlanIDByScope":               {},
	"PlanScopes":                  {},
	"RepoPrefixCopy":              {},
	"RepoPrefixDelete":            {},
	"RepoStorageOpen":             {},
	"WikiGitStorages":             {},
	"WikiMu":                      {},
	"WikiProjections":             {},
	"WorkflowsByRunID":            {},
}

ReplicaServerAccessStoreFields are exported (for the server package, per ARCH-001) but never copied from a snapshot: locks, clock overrides, injected callbacks, derived runtime indexes and process-local caches. Copying them would replace a locked mutex, drop a test clock, or import a peer's indexes.

View Source
var (
	SqliteDialect = dbDialect{
		Name:   "sqlite",
		PutSQL: `INSERT INTO kv (bucket, key, value) VALUES (?, ?, ?) ON CONFLICT(bucket, key) DO UPDATE SET value = excluded.value`,

		ListSQL: `SELECT key, value FROM kv WHERE bucket = ?`,

		ReadVersion:  `SELECT value FROM schema_meta WHERE key = 'version'`,
		WriteVersion: `INSERT INTO schema_meta (key, value) VALUES ('version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
		// contains filtered or unexported fields
	}
)
View Source
var ValidReactionContent = map[string]bool{
	"+1":       true,
	"-1":       true,
	"laugh":    true,
	"confused": true,
	"heart":    true,
	"hooray":   true,
	"rocket":   true,
	"eyes":     true,
}

ValidReactionContent is the set GitHub accepts.

Functions

func AbbreviatedGitOID

func AbbreviatedGitOID(oid string) string

AbbreviatedGitOID is the 7-character object-id prefix GitHub renders for abbreviatedOid and in archive directory names.

func AdminToken

func AdminToken() string

AdminToken returns the seeded admin token from BLEEPHUB_ADMIN_TOKEN. The token is a credential with no default: the sim fails loudly rather than seed a guessable value.

func AdvisoryCVSSScore

func AdvisoryCVSSScore(a *SecurityAdvisory) (float64, bool)

AdvisoryCVSSScore returns the author-supplied score if any, else the one the vector implies, reporting false when the advisory has neither.

func AdvisoryEcosystemFromGraphQL

func AdvisoryEcosystemFromGraphQL(enum string) string

AdvisoryEcosystemFromGraphQL turns a SecurityAdvisoryEcosystem enum value back into the canonical key.

func AdvisoryEcosystemGraphQL

func AdvisoryEcosystemGraphQL(ecosystem string) string

AdvisoryEcosystemGraphQL renders a canonical key as its SecurityAdvisoryEcosystem enum value, or "" for an ecosystem the enum does not name (the field is nullable so this reports honestly).

func AdvisoryWithdrawnAt

func AdvisoryWithdrawnAt(advisory *SecurityAdvisory) *time.Time

AdvisoryWithdrawnAt reports when an advisory was withdrawn, or nil when it stands. Withdrawal has no timestamp of its own, so UpdatedAt stands in.

func ArtifactDataKey

func ArtifactDataKey(id int64) string

func AttestationBundleDataKey

func AttestationBundleDataKey(id int) string

func AuditEntryVisibleInOrgLog

func AuditEntryVisibleInOrgLog(e *AuditEntry, org string) bool

AuditEntryVisibleInOrgLog reports whether an audit entry belongs in org's audit log. An org-scoped entry matches its org exactly. Repository events are recorded without an org field (org=""); such an entry is included only when the repository it names is owned by this org. Personal/user events (org="", no repo) never appear in an org log — including every org-less entry unconditionally leaked other tenants' private-repo names and user key/secret events across org boundaries.

func AuthorAssociation

func AuthorAssociation(st *Store, authorID int, repo *Repo) string

AuthorAssociation returns the author_association of authorID within repo. Must not be called with st.Mu held; it takes the read lock itself.

func AuthorAssociationLocked

func AuthorAssociationLocked(st *Store, authorID int, repo *Repo) string

AuthorAssociationLocked is AuthorAssociation for callers already holding st.Mu.

func AvatarURLFor

func AvatarURLFor(stored string, id int, baseURL string) string

AvatarURLFor resolves an account's `avatar_url`. An account with no stored avatar still must name one (the field is required, format: uri), defaulting to the instance-served <base>/avatars/u/{id}?v=4 as GitHub Enterprise does. An already-absolute stored value is preserved; a relative one joins the base.

func Base64urlDecode

func Base64urlDecode(s string) ([]byte, error)

Base64urlDecode handles JWT's unpadded base64url encoding.

func BoolPointer

func BoolPointer(v bool) *bool

func BpKey

func BpKey(repoID int, branch string) string

func BranchProtectionRuleNodeID

func BranchProtectionRuleNodeID(repoID int, pattern string) string

BranchProtectionRuleNodeID encodes the (repo, pattern) pair, since protection is keyed by that rather than by a row id.

func CVSSBaseScore

func CVSSBaseScore(vector string) (float64, bool)

CVSSBaseScore computes the base score of a v3.0/v3.1 vector, reporting false when the string is not a complete v3 base vector. All eight metrics must be present with legal values: CVSS defines no default for a missing metric.

func CWENodeID

func CWENodeID(cweID string) string

CWENodeID is the node id a CWE is addressed by.

func CacheDataKey

func CacheDataKey(id int64) string

func CacheLookupKey

func CacheLookupKey(repo, key, version string) string

func CacheParsedKey

func CacheParsedKey(k *UserKey) error

CacheParsedKey parses a user key's authorized-key text into k.parsed. An unparseable key stays registered (listed, deletable) but can never authenticate.

func CanAdminRepo

func CanAdminRepo(st *Store, user *User, repo *Repo) bool

func CanPushRepo

func CanPushRepo(st *Store, user *User, repo *Repo) bool

CanPushRepo reports whether user can push: ownership, sufficient org base permission, team push, or collaborator push/admin access.

func CanReadRepoAsUser

func CanReadRepoAsUser(st *Store, user *User, repo *Repo) bool

CanReadRepoAsUser reports read access: public repos are readable by all, private repos require ownership, org membership, team access, or collaborator pull access. Must not be called with st.Mu held; it takes the read lock.

func CloneCustomPropertyValue

func CloneCustomPropertyValue(value interface{}) interface{}

func ClonePointer

func ClonePointer[T any](p *T) *T

func CoalesceStr

func CoalesceStr(a, b string) string

func CodeQLDatabaseDataKeyHashed

func CodeQLDatabaseDataKeyHashed(id int, sha256Sum []byte) string

CodeQLDatabaseDataKeyHashed builds the key from an already-computed SHA-256, so a streamed upload never has to hold the whole database in memory to hash it.

func CodeQLVariantAnalysisQueryPackDataKey

func CodeQLVariantAnalysisQueryPackDataKey(id int) string

func CodespaceContainerName

func CodespaceContainerName(codespaceName string) string

func CodespaceMachineExists

func CodespaceMachineExists(name string) bool

CodespaceMachineExists reports whether name matches a catalog machine exactly; unlike CodespaceMachineByName it does not fall back, so create handlers can reject unknown names with 422.

func CodespaceSecretScopeKey

func CodespaceSecretScopeKey(scope, key string) string

func CommentCountKey

func CommentCountKey(parentType string, parentID int) string

CommentCountKey builds the CommentCounts index key for a comment parent.

func CommentToJSON

func CommentToJSON(c *Comment, st *Store, baseURL, repoFullName string, issueNumber int) map[string]interface{}

func CommitTouchesPath

func CommitTouchesPath(commit *object.Commit, requested string) (bool, error)

CommitTouchesPath reports whether a commit changed the file or directory at requested against its first parent (or, for a root commit, contains it).

func CommitsBetween

func CommitsBetween(stor gitStorage.Storer, base, head plumbing.Hash) ([]*object.Commit, error)

CommitsBetween returns the commits reachable from head but not base, newest first. If base is not an ancestor of head, the result is head's full history.

func CompareEcosystemVersions

func CompareEcosystemVersions(ecosystem, left, right string) (int, bool)

CompareEcosystemVersions orders two versions under the ecosystem's own rules. The bool is false when either string is unparseable; callers must not then treat the versions as ordered.

func CopilotNextCycleDate

func CopilotNextCycleDate(now time.Time) string

CopilotNextCycleDate returns the first day of the next calendar month, when a cancelled seat lapses (GitHub bills Copilot monthly).

func CopyGitObjects

func CopyGitObjects(src, dst gitStorage.Storer) error

func CustomImageMatchesTarget

func CustomImageMatchesTarget(image *HostedRunnerCustomImage, target RunnerScope) bool

func DecodeNodeDBID

func DecodeNodeDBID(nodeID, prefix string) (int, bool)

DecodeNodeDBID extracts the trailing database id from a node ID shaped "<prefix><digits>" (e.g. "R_kgDO00000123"). It returns false when the id lacks the prefix or doesn't end in digits, so a foreign-shaped id (e.g. "U_bleephub_<login>") falls through to a scan rather than mis-resolving.

func DependabotAlertEventPayload

func DependabotAlertEventPayload(alert *DependabotAlert, repository, sender, dismisser map[string]interface{}, action string) map[string]interface{}

DependabotAlertEventPayload renders a dependabot_alert webhook body. Shared by the REST routes and the GraphQL dismissal mutation so a subscriber can't tell which surface moved the alert. repository, sender and dismisser arrive already rendered (their hypermedia is the HTTP layer's); dismisser is nil for an alert that stands.

func DependabotAlertGraphQLState

func DependabotAlertGraphQLState(state DependabotAlertState) string

DependabotAlertGraphQLState renders an alert's state as the RepositoryVulnerabilityAlertState enum member GraphQL names.

func DependabotAlertManifestFilename

func DependabotAlertManifestFilename(manifestPath string) string

DependabotAlertManifestFilename is the manifest's base name.

func DependabotDismissReasonFromGraphQL

func DependabotDismissReasonFromGraphQL(reason string) (string, bool)

DependabotDismissReasonFromGraphQL translates a DismissReason enum member to its stored spelling, reporting false for a value outside the enum.

func DependabotDismissReasonText

func DependabotDismissReasonText(reason string) string

DependabotDismissReasonText renders a stored dismissal reason as prose, or "" when the alert was never dismissed.

func DependencyGraphManifestNodeID

func DependencyGraphManifestNodeID(repoID int, filename string) string

DependencyGraphManifestNodeID derives a manifest's node id from (repo, path). Manifests have no row of their own; they are a view over the latest submitted snapshots.

func DependencyPackageManager

func DependencyPackageManager(ecosystem string) string

DependencyPackageManager renders a canonical ecosystem key as GitHub's DependencyGraphDependency.packageManager name.

func DiscussionCategoryNodeID

func DiscussionCategoryNodeID(id int) string

func DockerRemoveContainer

func DockerRemoveContainer(ctx context.Context, id string) error

func DockerStartContainer

func DockerStartContainer(ctx context.Context, id string) error

func DockerStateToCodespaceState

func DockerStateToCodespaceState(containerID string) string

func DockerStopContainer

func DockerStopContainer(ctx context.Context, id string) error

func DqliteDialer

func DqliteDialer(addresses dqliteaddr.Map, secret string) client.DialFunc

DqliteDialer binds member address resolution and the cluster credential to the driver's transport.

func DqliteHTTPDial

func DqliteHTTPDial(ctx context.Context, address, secret string) (net.Conn, error)

DqliteHTTPDial opens the dqlite HTTP-upgrade transport at a private member address. The upgrade keeps the wire protocol private while letting ECS tasks keep stable advertised identities across replacement and scale-to-zero.

func EmailInVerifiedDomain

func EmailInVerifiedDomain(email string, domains []string) bool

EmailInVerifiedDomain reports whether an address's domain is one of the verified domains or a subdomain of one — an approved domain covers the hosts beneath it.

func EnterpriseMembershipKey

func EnterpriseMembershipKey(enterpriseID, userID int) string

EnterpriseMembershipKey is the map key for enterprise/user membership.

func EnvScopeKey

func EnvScopeKey(repoKey, envName string) string

EnvScopeKey packs (repoKey, envName) into one collision-free key for Store.EnvSecrets / Store.EnvVariables. The unit separator (not NUL: these are also persistence bucket keys and must stay text-safe) cannot appear in either half.

func ExprToString

func ExprToString(v interface{}) string

ExprToString renders a value as GitHub interpolates it into strings: null→"", bools→true/false, numbers in shortest form, arrays/objects as the literal words "Array"/"Object".

func ExternalIdentityKey

func ExternalIdentityKey(issuer, subject string) string

ExternalIdentityKey keys a federated identity by the stable (issuer, subject) pair, never the mutable username. An empty issuer or subject collapses to "" so the caller falls back to the username index rather than keying on half a pair.

func FindDiscussionPollOptionByNodeID

func FindDiscussionPollOptionByNodeID(st *Store, nodeID string) (*DiscussionPollOption, *DiscussionPoll)

FindDiscussionPollOptionByNodeID resolves an option's global id to the live option and its poll (Find* live-row convention).

func FindIssueByLinkedBranchNodeID

func FindIssueByLinkedBranchNodeID(st *Store, nodeID string) (*Issue, LinkedBranch, bool)

FindIssueByLinkedBranchNodeID resolves a linked branch's global id to the issue that carries it and the link itself, reporting false when no such link currently exists.

func FindMergeBase

func FindMergeBase(stor gitStorage.Storer, a, b plumbing.Hash) (plumbing.Hash, error)

FindMergeBase returns the nearest common ancestor of a and b, or ZeroHash if none exists. It walks a's ancestor set, then walks from b until it hits it.

func FindPackageVersionByNodeID

func FindPackageVersionByNodeID(st *Store, nodeID string) (*PackageVersion, *Package)

FindPackageVersionByNodeID resolves a package version's node id to its live row and owning package.

func FindTeamByNodeID

func FindTeamByNodeID(st *Store, nodeID string) (*Team, *Org)

FindTeamByNodeID resolves a team's node id to its live row and owning org.

func FoldName

func FoldName(s string) string

FoldName canonicalizes a name for case-insensitive comparison: NFKC normalization then lower-casing, the same folding AUTH-028 applies to logins.

func GEIMigrationTerminal

func GEIMigrationTerminal(state string) bool

GEIMigrationTerminal reports whether a migration state admits no further transitions.

func GenerateCodespaceName

func GenerateCodespaceName(repoKey string) (string, error)

func GenerateCodespaceNameWithReader

func GenerateCodespaceNameWithReader(repoKey string, random io.Reader) (string, error)

func GitBlobIsBinary

func GitBlobIsBinary(content []byte) bool

GitBlobIsBinary applies git's heuristic: a NUL byte in the leading bytes means binary, which GitHub reports as Blob.text null.

func GitCommitDiffStats

func GitCommitDiffStats(commit *object.Commit) (additions, deletions, changedFiles int, err error)

GitCommitDiffStats returns the additions, deletions and changed-file count a commit introduced against its first parent. A root commit is measured against the empty tree, matching `git show --stat`.

func GitObjectNodeID

func GitObjectNodeID(prefix string, repoID int, oid string) string

GitObjectNodeID renders a git object's global id.

func GitObjectNodeIDPrefixForType

func GitObjectNodeIDPrefixForType(objectType plumbing.ObjectType) string

GitObjectNodeIDPrefixForType maps a stored object type to its node id prefix.

func GitObjectTypeOf

func GitObjectTypeOf(stor gitStorage.Storer, hash plumbing.Hash) (plumbing.ObjectType, error)

func GitTreeEntryAtPath

func GitTreeEntryAtPath(tree *object.Tree, path string) (*object.TreeEntry, error)

GitTreeEntryAtPath resolves a slash-separated path within a tree. git rejects empty path components and trailing slashes, so this does too.

func GitTreeEntryType

func GitTreeEntryType(mode filemode.FileMode) string

GitTreeEntryType renders a tree entry's mode as the "blob"/"tree"/"commit" discriminator GitHub reports for TreeEntry.type and the git trees API.

func HostedRunnerMatchesTarget

func HostedRunnerMatchesTarget(runner *HostedRunner, target RunnerScope) bool

func InstallationOwnsRepo

func InstallationOwnsRepo(inst *Installation, repo *Repo) bool

InstallationOwnsRepo reports whether repo belongs to the installation's target.

func InteractionLimitExpiry

func InteractionLimitExpiry(expiry string, from time.Time) (time.Time, bool)

InteractionLimitExpiry translates GitHub's expiry vocabulary into the instant a limit set at from lapses. An empty expiry defaults to one day.

func IsInteractionGroup

func IsInteractionGroup(limit string) bool

IsInteractionGroup reports whether limit is a group GitHub accepts as an interaction limit. Shared by the REST routes and GraphQL set-limit mutations.

func IsPackageType

func IsPackageType(t string) bool

func IsPermanentPersistenceError

func IsPermanentPersistenceError(err error) bool

IsPermanentPersistenceError reports whether err (or anything it wraps) is a permanentPersistenceError.

func IsSecretScanningProviderPattern

func IsSecretScanningProviderPattern(tokenType string) bool

func IsSensitivePersistenceBucket

func IsSensitivePersistenceBucket(bucket string) bool

func IsWorkflowYAMLPath

func IsWorkflowYAMLPath(p string) bool

func IssueEventBase

func IssueEventBase(e *IssueEvent, st *Store, baseURL, repoFullName string) map[string]interface{}

IssueEventBase returns the fields common to every issue-event response.

func IssueEventForTimelineToJSON

func IssueEventForTimelineToJSON(e *IssueEvent, st *Store, baseURL, repoFullName string) map[string]interface{}

IssueEventForTimelineToJSON renders an IssueEvent to the timeline-event shape.

func IssueEventLabelToJSON

func IssueEventLabelToJSON(l *IssueLabel) map[string]interface{}

IssueEventLabelToJSON returns the slim label shape used inside issue events.

func IssueEventMilestoneToJSON

func IssueEventMilestoneToJSON(ms *Milestone) map[string]interface{}

IssueEventMilestoneToJSON returns the slim milestone shape used inside issue events.

func IssueHasAllLabels

func IssueHasAllLabels(st *Store, issue *Issue, labelNames []string, repoID int) bool

IssueHasAllLabels reports whether an issue carries every named label.

func JobMessageScopeAndRepo

func JobMessageScopeAndRepo(message string) (scopeID, repo string)

JobMessageScopeAndRepo reads a dispatched job message's plan scopeIdentifier and repository. An operator-submitted job carries no repo and yields "".

func JsonSafePositiveID

func JsonSafePositiveID(hash uint64) int64

func LFSObjectDataKey

func LFSObjectDataKey(oid string) string

LFSObjectDataKey names the bytes of one Git LFS object. The key is content-addressed on the oid (a bare SHA-256), so repositories sharing an object share one stored copy. The two-level fan-out mirrors git-lfs's on-disk layout and keeps any listing prefix small.

func LFSStagingKey

func LFSStagingKey(uploadID string) string

LFSStagingKey names the temporary bytes of an in-progress LFS upload, keyed by a unique per-upload id (NOT the oid). An upload streams here first and is promoted to the content-addressed LFSObjectDataKey only after its SHA-256 is verified, so a concurrent mismatched upload of the same oid can never overwrite or delete a good object's committed bytes.

func LabelIDsCoverNames

func LabelIDsCoverNames(st *Store, labelIDs []int, labelNames []string) bool

LabelIDsCoverNames asks about label ids rather than issues, so pull requests can be filtered by the same predicate.

func LanguageForFilename

func LanguageForFilename(name string) (string, bool)

LanguageForFilename maps a file name to its Linguist-style language. The small approximate mapping suffices since the API returns byte totals only.

func LicenseJSON

func LicenseJSON(repo *Repo) interface{}

func LinkedBranchNodeID

func LinkedBranchNodeID(issueID int, ref string) string

LinkedBranchNodeID renders a linked branch's global id from its (issue, ref) pair, of which there is at most one — so the id needs no counter and is stable across restarts.

func ListGitReferences

func ListGitReferences(stor gitStorage.Storer, prefix string) ([]*plumbing.Reference, error)

ListGitReferences returns references under prefix, sorted by full name. Symrefs (HEAD) are excluded, matching Repository.refs(refPrefix:).

func LoadJSON

func LoadJSON(raw []byte, v interface{}) error

func LogDataKey

func LogDataKey(id int) string

func LoginSessionMapKey

func LoginSessionMapKey(persist *Persistence, id string) string

func LoginSessionUserIndexPrefix

func LoginSessionUserIndexPrefix(userID int) string

func MarketplaceListingNodeID

func MarketplaceListingNodeID(slug string) string

MarketplaceListingNodeID derives a listing's global id from its slug, so the id is stable without a counter and a profile-less listing still has one.

func MarketplacePurchaseKey

func MarketplacePurchaseKey(listingSlug, accountType string, accountID int) string

func MatchBranchPattern

func MatchBranchPattern(pattern, branch string) bool

MatchBranchPattern reports whether a branch matches an fnmatch pattern with GitHub's branch-protection semantics: `*` spans one path segment (not `/`), `**` spans segments, `?` matches one non-`/` char, everything else literal.

func MembershipKey

func MembershipKey(orgLogin string, userID int) string

MembershipKey returns the map key for org/user membership lookups.

func MigrationArchiveObjectKey

func MigrationArchiveObjectKey(scope MigrationScope, id int, guid string) string

MigrationArchiveObjectKey locates an export migration's bytes. The guid is in the key so a reissued id can never address a deleted migration's archive.

func NewFineGrainedPATTokenFromReader

func NewFineGrainedPATTokenFromReader(random io.Reader) (string, error)

func NewHostedComputeIDFromReader

func NewHostedComputeIDFromReader(random io.Reader) (string, error)

func NewTOTPSecret

func NewTOTPSecret() (string, error)

NewTOTPSecret draws a fresh shared secret as unpadded base32. It is the only value that leaves the store in the clear, and only once, at enrolment.

func NilOrString

func NilOrString(s string) interface{}

func NormalizeAdvisoryEcosystem

func NormalizeAdvisoryEcosystem(ecosystem string) string

NormalizeAdvisoryEcosystem folds the several spellings of one ecosystem (purl "pypi"/"cargo", REST "pip"/"rust", GraphQL "PIP") onto the canonical key, so matching compares folded forms rather than three names that never meet.

func NormalizeAppPermissions

func NormalizeAppPermissions(perms map[string]string) map[string]string

NormalizeAppPermissions adds the mandatory Metadata:read grant GitHub gives every installation. Returns a copy so App/Installation/InstallationToken never share a permissions map.

func NormalizeCWEID

func NormalizeCWEID(cweID string) string

NormalizeCWEID renders a CWE identifier in canonical "CWE-79" form, accepting a bare number.

func NormalizeVerifiedDomain

func NormalizeVerifiedDomain(domain string) string

NormalizeVerifiedDomain reduces a domain to the stored form: lower case, no surrounding space, no leading "@", no trailing dot. A non-domain reduces to "".

func NormalizeYAMLValue

func NormalizeYAMLValue(v interface{}) interface{}

NormalizeYAMLValue coerces YAML-decoded integers to float64 to match every other expression number.

func NotificationEventTypeForThread

func NotificationEventTypeForThread(subjectType string) string

NotificationEventTypeForThread maps a thread subject type to its preference key.

func NotificationThreadID

func NotificationThreadID(sourceType string, sourceID int) string

func NullableTimestamp

func NullableTimestamp(t time.Time) interface{}

func OTPAuthURI

func OTPAuthURI(issuer, account, secret string) string

OTPAuthURI renders the provisioning URI an authenticator reads from a QR code, stating every parameter explicitly:

otpauth://totp/Issuer:account?secret=…&issuer=Issuer&algorithm=SHA1&digits=6&period=30

func OidcLogoutReplayKey

func OidcLogoutReplayKey(provider, issuer, clientID, jti string) string

func OpenDqlite

func OpenDqlite(addresses string) (*sql.DB, error)

OpenDqlite connects to the dqlite quorum from a seed set of private addresses; the driver discovers the leader and refreshes membership from the quorum.

func OpenGitBlob

func OpenGitBlob(stor gitStorage.Storer, hash plumbing.Hash) (io.ReadCloser, int64, error)

OpenGitBlob streams a blob's contents and reports its size, for raw file serving where a blob may exceed the per-request memory ReadGitBlob would use. The caller closes the reader.

func OpenSQLite

func OpenSQLite(dataDir string) (*sql.DB, error)

func OrgAsSimpleUserJSON

func OrgAsSimpleUserJSON(org *Org, baseURL string) map[string]interface{}

OrgAsSimpleUserJSON renders an Org in the simple-user shape GitHub uses as the owner field of org-owned repositories. Fields match UserToJSON; only the type differs. Hypermedia is absolute, as the simple-user schema requires.

func OrgLoginForIssueTypeRepo

func OrgLoginForIssueTypeRepo(repo *Repo) string

func OrgMigratorRoleKey

func OrgMigratorRoleKey(orgID int, actorType, actor string) string

OrgMigratorRoleKey is the map and persistence key for one grant.

func PRReviewThreadNodeID

func PRReviewThreadNodeID(threadID int) string

PRReviewThreadNodeID renders the GraphQL node id of a PR review thread. Node-ID codecs live in store so both API surfaces share one format (ARCH-003).

func PackageFileDataKey

func PackageFileDataKey(fileID int) string

func PackageKey

func PackageKey(pkgType, name string) string

PackageKey is the lookup key for a package within an owner scope.

func PackageRegistryBlobDataKey

func PackageRegistryBlobDataKey(digest string) string

func ParseActionRef

func ParseActionRef(uses string) (nameWithOwner, path, ref string, isLocal bool)

ParseActionRef splits a "uses" reference like "actions/checkout@v4" into owner/repo, path (if any), and ref. Supported formats:

  • "owner/repo@ref"
  • "owner/repo/path@ref"
  • "./local/path" (returns empty owner/repo, path only)

func ParseBranchProtectionRuleNodeID

func ParseBranchProtectionRuleNodeID(nodeID string) (repoID int, pattern string, ok bool)

ParseBranchProtectionRuleNodeID inverts BranchProtectionRuleNodeID.

func ParseDependencyGraphManifestNodeID

func ParseDependencyGraphManifestNodeID(nodeID string) (repoID int, filename string, ok bool)

ParseDependencyGraphManifestNodeID reverses DependencyGraphManifestNodeID.

func ParseGitObjectNodeID

func ParseGitObjectNodeID(nodeID string) (prefix string, repoID int, value string, ok bool)

ParseGitObjectNodeID decodes a git object global id into its type prefix, repository and object id (or, for a Ref, its qualified name).

func ParseLinkedBranchNodeID

func ParseLinkedBranchNodeID(nodeID string) (issueID int, ref string, ok bool)

ParseLinkedBranchNodeID decodes a linked branch's global id.

func ParseMarketplaceListingNodeID

func ParseMarketplaceListingNodeID(nodeID string) (string, bool)

ParseMarketplaceListingNodeID recovers the slug a listing global id names.

func ParsePRReviewThreadNodeID

func ParsePRReviewThreadNodeID(nodeID string) (int, bool)

ParsePRReviewThreadNodeID decodes a PR review thread node id.

func ParsePackageURL

func ParsePackageURL(purl string) (ecosystem, name, version string)

ParsePackageURL splits a package-url into ecosystem type, name and version. The name keeps its namespace ("@babel/core"), the coordinate advisories are written against.

func ParseProjectV2Date

func ParseProjectV2Date(value string) (string, error)

ParseProjectV2Date validates a YYYY-MM-DD date, returning it unchanged.

func ParseSigstoreBundleSubjects

func ParseSigstoreBundleSubjects(bundle json.RawMessage) (subjects []string, predicateType string, err error)

ParseSigstoreBundleSubjects decodes a Sigstore bundle's DSSE envelope payload and returns the in-toto statement's subject digests ("algorithm:hex") and predicate type.

func PeelGitTagObjects

func PeelGitTagObjects(stor gitStorage.Storer, hash plumbing.Hash) (plumbing.Hash, error)

PeelGitTagObjects follows annotated tag objects to the first non-tag object.

func PendingOrgDeletionKey

func PendingOrgDeletionKey(login string) string

func PendingRepoDeletionKey

func PendingRepoDeletionKey(fullName string) string

func PendingRepoRenameKey

func PendingRepoRenameKey(to string) string

func PendingUserDeletionKey

func PendingUserDeletionKey(login string) string

func PermanentErrf

func PermanentErrf(format string, args ...any) error

PermanentErrf builds a permanent persistence error.

func PermissionAtLeast

func PermissionAtLeast(perm, minPerm TeamPermission) bool

PermissionAtLeast reports whether perm ranks at least minPerm (pull < push < admin).

func PullRequestCommitObjectsFromStorage

func PullRequestCommitObjectsFromStorage(stor gitStorage.Storer, pr *PullRequest) ([]*object.Commit, error)

PullRequestCommitObjectsFromStorage lists the PR's commits (oldest first): those reachable from head but not from the merge base with the base branch.

func PullRequestGitStorage

func PullRequestGitStorage(st *Store, repo *Repo, pr *PullRequest) (gitStorage.Storer, string)

PullRequestGitStorage returns the git storage holding the PR's head branch plus that repository's full name.

func PullRequestHeadRepoID

func PullRequestHeadRepoID(pr *PullRequest) int

PullRequestHeadRepoID is the repository the PR's head branch lives in — the fork for cross-repository PRs, the base repository otherwise.

func PullRequestHeadSHALocked

func PullRequestHeadSHALocked(pr *PullRequest, st *Store) string

PullRequestHeadSHALocked resolves the PR head branch's current commit SHA; the caller holds st.Mu.

func RandomBytes

func RandomBytes(n int) ([]byte, error)

func RandomHex

func RandomHex(n int) (string, error)

func ReadGitBlob

func ReadGitBlob(stor gitStorage.Storer, hash plumbing.Hash) ([]byte, error)

func RefHash

func RefHash(r *plumbing.Reference, stor gitStorage.Storer) (plumbing.Hash, error)

func ReleaseAssetDataKey

func ReleaseAssetDataKey(id int) string

func RepoCollaboratorPermissionAtLeastLocked

func RepoCollaboratorPermissionAtLeastLocked(st *Store, repoFullName, login, minPerm string) bool

RepoCollaboratorPermissionAtLeastLocked checks direct collaboration while the caller holds st.Mu.

func RepoHasDiscussions

func RepoHasDiscussions(repo *Repo) bool

func RepoSubscriptionKey

func RepoSubscriptionKey(userID, repoID int) string

func RepoToJSON

func RepoToJSON(repo *Repo, st *Store, baseURL string) map[string]interface{}

RepoToJSON converts a Repo to the GitHub `repository` shape. watchers mirrors stargazers, as on real GitHub. Must not be called with st.Mu held: it derives open_issues_count from the store.

func RepoToJSONForViewer

func RepoToJSONForViewer(repo *Repo, st *Store, baseURL string, viewer *User) map[string]interface{}

func RepositoryMigrationLogObjectKey

func RepositoryMigrationLogObjectKey(id int) string

RepositoryMigrationLogObjectKey is where a repository migration's log lives in the object byte store.

func ResolveBranchSha

func ResolveBranchSha(stor gitStorage.Storer, branch string) string

ResolveBranchSha resolves a branch name to its commit sha, empty when unknown.

func ResolveGitObjectReference

func ResolveGitObjectReference(stor gitStorage.Storer, value string) (plumbing.Hash, bool, error)

ResolveGitObjectReference resolves a ref name to the hash it records without peeling annotated tags, trying `refs/...` verbatim, the HEAD symref, the `heads/`/`tags/` shorthands, then branch and tag short names. found is false when no reference carries the name (the caller may then read it as an object id).

func ResolveGitRef

func ResolveGitRef(stor gitStorage.Storer, ref string) (plumbing.Hash, error)

ResolveGitRef turns a ref name (branch, tag, full ref, or SHA) into a commit hash, returning an error describing the resolution failure.

func ResolveGitTreeish

func ResolveGitTreeish(stor gitStorage.Storer, value string) (plumbing.Hash, *object.Tree, error)

ResolveGitTreeish implements GitHub's broader tree_sha contract: a tree SHA, commit SHA, or branch/tag name. References are dereferenced (including annotated tags), while a raw tag-object SHA is rejected as on github.com.

func ResolvedReferenceHash

func ResolvedReferenceHash(stor gitStorage.Storer, ref *plumbing.Reference, seen map[plumbing.ReferenceName]bool) (plumbing.Hash, error)

ResolvedReferenceHash follows a symref chain to the hash at its end. seen breaks a cycle.

func RunDockerCLI

func RunDockerCLI(ctx context.Context, args ...string) ([]byte, error)

func SecretEqual

func SecretEqual(a, b string) bool

SecretEqual compares two credential strings in constant time. Use it for all secret material (client secrets, CSRF tokens, webhook signatures, download tokens): some comparisons are reachable unauthenticated and unthrottled, exactly the shape a byte-at-a-time timing oracle needs.

func SetGitHeadBranch

func SetGitHeadBranch(stor storer.ReferenceStorer, branch string) error

SetGitHeadBranch points a repository's git HEAD at refs/heads/<branch>. The sole writer of the HEAD symref: a clone reads it (symref=HEAD capability) to pick its checkout branch, so it must agree with the recorded default branch. The branch need not exist yet, matching `git init` writing HEAD before the first commit.

func Slugify

func Slugify(name string) string

Slugify converts a team name to a URL-safe slug.

func SortAdvisoriesByPublicationOrder

func SortAdvisoriesByPublicationOrder(advisories []*SecurityAdvisory, ascending bool)

SortAdvisoriesByPublicationOrder orders advisories by publication time in the requested direction, the PUBLISHED_AT field of SecurityAdvisoryOrder.

func SortAdvisoriesByUpdate

func SortAdvisoriesByUpdate(advisories []*SecurityAdvisory, ascending bool)

SortAdvisoriesByUpdate orders advisories by update time, the UPDATED_AT field of SecurityAdvisoryOrder.

func SortHistory

func SortHistory(history []*GistHistory)

func SplitRepoFullName

func SplitRepoFullName(fullName string) (owner, name string, ok bool)

func SponsorsNextPayoutDate

func SponsorsNextPayoutDate(now time.Time) string

SponsorsNextPayoutDate is the first day of the next calendar month.

func SshGitURL

func SshGitURL(fullName string) string

func SshSigningKeyEntryID

func SshSigningKeyEntryID(entry map[string]interface{}) int

SshSigningKeyEntryID extracts the numeric key ID from an SSH signing key entry. Fresh entries store an int; reloaded ones decode as float64, so handle both.

func StableWorkflowFileID

func StableWorkflowFileID(repoFullName, path string) int64

StableWorkflowFileID returns the GitHub-shape int64 ID for (repo, path): FNV-1a 64-bit, JSON-safe-integer masked.

func StageUpload

func StageUpload(r io.Reader) (f *os.File, size int64, sum []byte, err error)

StageUpload spools everything read from r to a temp file while computing its size and SHA-256, then rewinds it. The caller owns the returned file and must Close and os.Remove it; uploading it via ActionsByteStore.PutStreamHashed keeps the whole object off the heap and avoids a second hash pass. This is how a handler turns a (size-capped) request body into a digest + size for metadata without buffering the object in memory.

func TeamSlugKey

func TeamSlugKey(orgLogin, slug string) string

TeamSlugKey returns the map key for org/team slug lookups.

func TimelineCommentToJSON

func TimelineCommentToJSON(c *Comment, st *Store, baseURL, repoFullName string, issueNumber int, repo *Repo) map[string]interface{}

TimelineCommentToJSON renders a comment in the issue-timeline shape.

func ToStringSlice

func ToStringSlice(value interface{}) []string

ToStringSlice coerces a stored multi-value ([]string in memory, []interface{} after a persistence reload) into []string.

func UserListSlug

func UserListSlug(name string) string

UserListSlug derives a list's slug: lower case, each run of non-alphanumerics collapsed to one hyphen.

func UserStatusNodeID

func UserStatusNodeID(userID int) string

UserStatusNodeID is the GraphQL node id of a user's status.

func UserToJSON

func UserToJSON(u *User, baseURL string) map[string]interface{}

UserToJSON renders a User as GitHub's `simple-user` shape (the user nested inside repos, issues, pulls, and so on); the fuller shape belongs only on GET /user and GET /users/{username}, see fullUserJSON. A nil user renders as the `ghost` account rather than JSON null.

Hypermedia members are absolute against baseURL: `simple-user` declares them format: uri, and clients build their next request by resolving an object's own `url`, so a relative value would double the /api/v3 prefix.

func ValidAdvisoryCreditType

func ValidAdvisoryCreditType(t string) bool

ValidAdvisoryCreditType reports whether t is a security-advisory-credit-types enum value.

func ValidAdvisorySeverity

func ValidAdvisorySeverity(s string) bool

func ValidAdvisoryState

func ValidAdvisoryState(s string) bool

func ValidEnterpriseAdministratorRole

func ValidEnterpriseAdministratorRole(role string) bool

ValidEnterpriseAdministratorRole reports whether role is one GitHub's EnterpriseAdministratorRole enum admits.

func ValidGitObjectID

func ValidGitObjectID(value string) bool

ValidGitObjectID reports whether value is a full-length hex object id.

func ValidMigrationSourceType

func ValidMigrationSourceType(value string) bool

ValidMigrationSourceType reports whether value is a member of GitHub's MigrationSourceType enum.

func ValidateClientCallbackURL

func ValidateClientCallbackURL(raw string) error

ValidateClientCallbackURL is the shared registration rule for an OAuth client's callback. An empty callback is legal (records no destination); a non-empty one must be an absolute http/https URL with a host.

func ValidateCustomPropertyValue

func ValidateCustomPropertyValue(def *CustomProperty, value interface{}) error

ValidateCustomPropertyValue checks a non-null value against the property's value type (and allowed values for the select types). Shared by the REST values routes and the GraphQL setRepositoryCustomPropertyValues mutation.

func VerifyObjectChecksum

func VerifyObjectChecksum(metadata map[string]string, data []byte) error

func VersionInVulnerableRange

func VersionInVulnerableRange(ecosystem, version, rangeExpr string) bool

VersionInVulnerableRange reports whether version falls inside an advisory's vulnerableVersionRange. The grammar is GitHub's: comma-separated constraints, all of which must hold (e.g. ">= 4.3.0, < 4.3.5").

func WikiPageFileName

func WikiPageFileName(title string) string

WikiPageFileName maps a page title to its file name the way github does: spaces and path separators become hyphens and the extension is appended, so "Getting Started" is `Getting-Started.md`. Folding separators keeps a title from escaping into a subdirectory, where it would no longer round-trip.

func WikiPageName

func WikiPageName(title string) string

WikiPageName is WikiPageFileName without the extension: the hyphenated name github addresses a page by.

func WikiSlug

func WikiSlug(title string) string

WikiSlug normalizes a page title into its URL-safe key, mirroring GitHub wikis (spaces become hyphens).

func WikiStorageName

func WikiStorageName(repoKey string) string

WikiStorageName maps a repository's full name to its wiki's storage key.

func WikiTitleFromPath

func WikiTitleFromPath(filePath string) (string, bool)

WikiTitleFromPath is the inverse mapping, with hyphens read back as spaces. Only a markup file at the repository root is a page (the mapping is a bijection there); anything else reports false.

func WriteGHValidationError

func WriteGHValidationError(w http.ResponseWriter, resource, field, code string)

WriteGHValidationError writes a GitHub 422 validation error with detailed errors array.

Types

type APIInsightsActorType

type APIInsightsActorType string

APIInsightsActorType is the credential taxonomy of a request's actor; APIInsightsSubjectType is the account it ran on behalf of.

type APIInsightsSubjectType

type APIInsightsSubjectType string

type APIRequestRecord

type APIRequestRecord struct {
	ID          int64                  `json:"id"`
	Timestamp   time.Time              `json:"timestamp"`
	Method      string                 `json:"method"`
	Route       string                 `json:"route"` // route template relative to /api/v3, e.g. "/repos/{owner}/{repo}"
	StatusCode  int                    `json:"status_code"`
	RateLimited bool                   `json:"rate_limited"`
	ActorType   APIInsightsActorType   `json:"actor_type"` // installation | classic_pat | fine_grained_pat | oauth_app | github_app_user_to_server
	ActorID     int64                  `json:"actor_id"`
	ActorName   string                 `json:"actor_name"`
	SubjectType APIInsightsSubjectType `json:"subject_type"` // "user" | "installation"
	SubjectID   int64                  `json:"subject_id"`
	SubjectName string                 `json:"subject_name"`
	UserID      int                    `json:"user_id,omitempty"` // 0 for installation tokens
	// GitHub App / OAuth app identity behind an app-derived actor.
	IntegrationID *int64 `json:"integration_id,omitempty"`
	OAuthAppID    *int64 `json:"oauth_application_id,omitempty"`
	// Orgs attributed at request time: the actor's active memberships, or the
	// installation's target org.
	OrgLogins []string `json:"org_logins,omitempty"`
}

APIRequestRecord is one observed, attributed /api/v3 request.

type AccountAuthKind

type AccountAuthKind string

AccountAuthKind names where an account's credentials live.

const (
	AccountAuthLocal AccountAuthKind = "local"
	// AccountAuthExternal is bound to a federated identity; its password and
	// second factor belong to the identity provider.
	AccountAuthExternal AccountAuthKind = "external"
)

type AccountAuthentication

type AccountAuthentication struct {
	Kind AccountAuthKind `json:"kind"`
	// Providers lists the issuers bound to the account (external accounts only).
	Providers   []string `json:"providers,omitempty"`
	PasswordSet bool     `json:"password_set"`
}

AccountAuthentication describes the credential source of one account.

type AccountKind

type AccountKind int

AccountKind distinguishes the two account namespaces an entitlement can target. Users and organizations share one login space, so authorization checks must not match on login alone. AnyAccount covers resources that hang off either kind, such as a ProjectV2.

const (
	AnyAccount AccountKind = iota
	OrganizationAccount
)

type AccountSecurityResult

type AccountSecurityResult int

AccountSecurityResult is the outcome of an enrolment or verification attempt; callers map it to a status code.

const (
	SecurityOK AccountSecurityResult = iota
	SecurityUnknownUser
	SecurityInvalidCode
	SecurityTwoFactorNotEnabled
	SecurityTwoFactorAlreadyEnabled
	// SecurityNoPendingEnrollment: no live provisioned secret to confirm (never
	// started, or the enrolment window elapsed).
	SecurityNoPendingEnrollment
	// SecurityExternalAccount: credentials are governed by an external identity
	// provider, so there is no second factor to enrol here.
	SecurityExternalAccount
	// SecurityInternalError: the entropy source failed.
	SecurityInternalError
	// SecurityMethodDisallowed: a genuine code arrived through a method an
	// enterprise policy bans; distinct from SecurityInvalidCode because the
	// remedy is to use the other factor.
	SecurityMethodDisallowed
)

type ActionsAllowed

type ActionsAllowed struct {
	GithubOwnedAllowed bool     `json:"github_owned_allowed"`
	VerifiedAllowed    bool     `json:"verified_allowed"`
	PatternsAllowed    []string `json:"patterns_allowed"`
}

type ActionsByteStore

type ActionsByteStore interface {
	Put(ctx context.Context, key string, data []byte) error
	Get(ctx context.Context, key string) ([]byte, error)
	// PutStream stores everything read from r; implementations must not buffer
	// the entire stream in memory.
	PutStream(ctx context.Context, key string, r io.Reader) error
	// PutStreamHashed stores exactly size bytes read from r whose SHA-256 is
	// sha256Sum, uploading directly without a re-spool or re-hash. Callers that
	// have already staged the object to a temp file (to compute its size + digest
	// for metadata) use this to avoid holding the whole object on the heap.
	PutStreamHashed(ctx context.Context, key string, r io.Reader, size int64, sha256Sum []byte) error
	// GetStream returns the object as a stream the caller must Close. The stored
	// SHA-256 cannot be checked before the first byte reaches the client, but the
	// stream recomputes it and fails the final Read (a non-EOF error) on mismatch,
	// so corruption surfaces as a truncated/failed response rather than silently
	// served bad bytes. Objects predating checksummed writes stream unverified.
	GetStream(ctx context.Context, key string) (io.ReadCloser, error)
	Delete(ctx context.Context, key string) error
}

ActionsByteStore stores opaque object bytes. The streaming forms move large objects without the whole value ever residing in the process heap (STORE-019).

func NewActionsByteStoreFromEnv

func NewActionsByteStoreFromEnv(ctx context.Context) (ActionsByteStore, error)

func NewLocalByteStore

func NewLocalByteStore(dataDir string) ActionsByteStore

NewLocalByteStore returns the fallback byte store: filesystem-backed beneath dataDir when one is configured, process-memory-backed when it is not.

type ActionsUsageLine

type ActionsUsageLine struct {
	Date     string `json:"-"`
	OrgName  string `json:"-"`
	RepoName string `json:"-"`
	Minutes  int    `json:"-"`
}

ActionsUsageLine is minutes consumed by one repository's jobs on one date.

type ActionsVariable

type ActionsVariable struct {
	Name            string    `json:"name"`
	Value           string    `json:"value"`
	Visibility      string    `json:"visibility,omitempty"`
	SelectedRepoIDs []int     `json:"selected_repository_ids,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

ActionsVariable is an Actions configuration variable. Visibility and SelectedRepoIDs are populated only at the organization level.

func (*ActionsVariable) ItemVisibility

func (v *ActionsVariable) ItemVisibility() string

func (*ActionsVariable) SelectedIDs

func (v *ActionsVariable) SelectedIDs() []int

func (*ActionsVariable) SetSelectedIDs

func (v *ActionsVariable) SetSelectedIDs(ids []int)

func (*ActionsVariable) TouchUpdated

func (v *ActionsVariable) TouchUpdated(now time.Time)

type Agent

type Agent struct {
	ID             int                 `json:"id"`
	Name           string              `json:"name"`
	Version        string              `json:"version"`
	Enabled        bool                `json:"enabled"`
	Status         string              `json:"status"`
	OSDescription  string              `json:"osDescription"`
	Labels         []Label             `json:"labels"`
	Authorization  *AgentAuthorization `json:"authorization,omitempty"`
	Ephemeral      bool                `json:"ephemeral,omitempty"`
	RunnerGroupID  int                 `json:"runnerGroupId,omitempty"`
	MaxParallelism int                 `json:"maxParallelism,omitempty"`
	ProvisionState string              `json:"provisioningState,omitempty"`
	CreatedOn      time.Time           `json:"createdOn"`
	// Scope is the repository or organization the agent registered against. It
	// is recorded here rather than encoded into the clientId because the runner
	// deserializes that field as a GUID and rejects anything else.
	Scope RunnerScope `json:"scope"`

	// AssignedJobID is the broker's process-local busy bookkeeping: the job
	// this agent currently holds (set when a job message is delivered, cleared
	// when a non-ephemeral agent's job completes or the lease is reclaimed).
	// EverAssigned records that the agent has held a job at least once; for an
	// EPHEMERAL agent that alone disqualifies it from another job — the flag
	// MUST survive the GC of the completed job's stub, or a used ephemeral
	// runner could be handed a second job (see agentTakesAJobLocked). Neither
	// field is serialized: the runner's TaskAgent contract has no such fields.
	AssignedJobID string `json:"-"`
	EverAssigned  bool   `json:"-"`
}

Agent represents a registered runner agent.

func (*Agent) AddLabels

func (a *Agent) AddLabels(names []string)

AddLabels appends custom labels, deduplicating by name.

func (*Agent) ClearLabels

func (a *Agent) ClearLabels()

ClearLabels removes every custom label, leaving system labels in place.

func (*Agent) RemoveLabels

func (a *Agent) RemoveLabels(names []string)

RemoveLabels removes custom labels by name; system labels are never removed.

func (*Agent) SetLabels

func (a *Agent) SetLabels(names []string)

SetLabels replaces custom labels, preserving system (read-only) labels.

type AgentAuthorization

type AgentAuthorization struct {
	AuthorizationURL string          `json:"authorizationUrl,omitempty"`
	ClientID         string          `json:"clientId,omitempty"`
	PublicKey        *AgentPublicKey `json:"publicKey,omitempty"`
}

AgentAuthorization holds the agent's RSA public key and auth URL.

type AgentPublicKey

type AgentPublicKey struct {
	Exponent string `json:"exponent"`
	Modulus  string `json:"modulus"`
}

AgentPublicKey is the RSA public key components.

type AgentTask

type AgentTask struct {
	ID          string             `json:"id"`
	RepoID      int                `json:"repo_id"`
	OwnerID     int                `json:"owner_id"`
	CreatorID   int                `json:"creator_id"`
	CreatorType string             `json:"creator_type"` // user | organization
	Name        string             `json:"name"`
	Prompt      string             `json:"prompt"`
	Model       string             `json:"model"`
	CreatePR    bool               `json:"create_pull_request"`
	BaseRef     string             `json:"base_ref"`
	HeadRef     string             `json:"head_ref"`
	State       string             `json:"state"`
	Sessions    []AgentTaskSession `json:"sessions"`
	ArchivedAt  *time.Time         `json:"archived_at"`
	CreatedAt   time.Time          `json:"created_at"`
	UpdatedAt   time.Time          `json:"updated_at"`
}

AgentTask is a Copilot coding agent task.

type AgentTaskFilter

type AgentTaskFilter struct {
	RepoID     int        `json:"-"` // 0 = any repository
	CreatorID  int        `json:"-"` // 0 = any creator
	CreatorIDs []int      `json:"-"` // non-empty = restrict to these creators
	States     []string   `json:"-"`
	IsArchived bool       `json:"-"`
	Since      *time.Time `json:"-"`
	SortField  string     // "updated_at" (default) | "created_at"
	Direction  string     // "desc" (default) | "asc"
}

AgentTaskFilter carries the documented list-tasks query filters.

type AgentTaskSession

type AgentTaskSession struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	State     string    `json:"state"`
	Prompt    string    `json:"prompt"`
	HeadRef   string    `json:"head_ref"`
	BaseRef   string    `json:"base_ref"`
	Model     string    `json:"model"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

AgentTaskSession is one Copilot coding agent session within a task.

type App

type App struct {
	ID                 int               `json:"id"`
	NodeID             string            `json:"node_id"`
	Slug               string            `json:"slug"`
	Name               string            `json:"name"`
	ClientID           string            `json:"client_id"`
	ClientSecret       string            `json:"client_secret"`
	Description        string            `json:"description"`
	ExternalURL        string            `json:"external_url"`
	WebhookURL         string            `json:"webhook_url"`
	WebhookSecret      string            `json:"webhook_secret"`
	WebhookActive      bool              `json:"webhook_active"`
	WebhookEvents      []string          `json:"webhook_events"`
	WebhookContentType string            `json:"webhook_content_type"` // "json" | "form" (default "form")
	WebhookInsecureSSL string            `json:"webhook_insecure_ssl"` // "0" | "1" (default "0")
	CallbackURL        string            `json:"callback_url"`         // OAuth web-flow destination; empty means none
	PEMPrivateKey      string            `json:"pem_private_key"`
	Permissions        map[string]string `json:"permissions"`
	Events             []string          `json:"events"`
	OwnerID            int               `json:"owner_id"`
	CreatedAt          time.Time         `json:"created_at"`
	UpdatedAt          time.Time         `json:"updated_at"`
}

App is a registered GitHub App. The credential/webhook-config json names are the persisted form; client responses go through appToJSON / appHookConfigJSON.

type AppSeedSpec

type AppSeedSpec struct {
	ID             int                    `json:"id"`                   // required
	Slug           string                 `json:"slug"`                 // defaults to Slugify(name)
	Name           string                 `json:"name"`                 // required
	ClientID       string                 `json:"client_id"`            // defaults to Iv1.<id>
	PrivateKeyPEM  string                 `json:"private_key_pem"`      // RSA key (PKCS1 or PKCS8)
	PrivateKeyFile string                 `json:"private_key_pem_file"` // alternative to inline PEM
	Owner          string                 `json:"owner"`                // required
	Permissions    map[string]string      `json:"permissions"`
	Events         []string               `json:"events"`
	WebhookURL     string                 `json:"webhook_url"`
	WebhookSecret  string                 `json:"webhook_secret"`
	Installations  []InstallationSeedSpec `json:"installations"`
}

AppSeedSpec describes one GitHub App to pre-register at startup, so a coordinate-only consumer holds the same (app id + private key + org) coordinates against bleephub as against real GitHub. Supplied via BLEEPHUB_SEED_APPS (inline JSON) or BLEEPHUB_SEED_APPS_FILE (path).

type Artifact

type Artifact struct {
	ID                   int64     `json:"id"`
	Name                 string    `json:"name"`
	Size                 int64     `json:"size"`
	Data                 []byte    `json:"-"`
	Finalized            bool      `json:"finalized"`
	RunID                string    `json:"runId"`
	GitHubRunID          int       `json:"githubRunId"`
	RepoFullName         string    `json:"repoFullName"`
	WorkflowRunBackendID string    `json:"workflowRunBackendId"`
	CreatedAt            time.Time `json:"createdAt"`
	Digest               string    `json:"digest,omitempty"`
}

type ArtifactDeploymentJob

type ArtifactDeploymentJob struct {
	ID         int       `json:"job_id"`
	OrgID      int       `json:"org_id"`
	Cluster    string    `json:"cluster"`
	Status     string    `json:"status"`
	StartedAt  time.Time `json:"started_at"`
	TotalCount int       `json:"total_count"`
	Errors     []any     `json:"errors"`
}

ArtifactDeploymentJob records one bulk cluster update. The batch is applied before the 202, so a new job is already completed; it persists to preserve GitHub's polling contract.

type ArtifactDeploymentRecord

type ArtifactDeploymentRecord struct {
	ID                  int               `json:"id"`
	OrgID               int               `json:"org_id"`
	Name                string            `json:"name"`
	Digest              string            `json:"digest"`
	Version             string            `json:"version"`
	Status              string            `json:"status"` // deployed, decommissioned
	LogicalEnvironment  string            `json:"logical_environment"`
	PhysicalEnvironment string            `json:"physical_environment"`
	Cluster             string            `json:"cluster"`
	DeploymentName      string            `json:"deployment_name"`
	Tags                map[string]string `json:"tags"`
	RuntimeRisks        []string          `json:"runtime_risks"`
	GitHubRepository    string            `json:"github_repository"`
	CreatedAt           time.Time         `json:"created_at"`
	UpdatedAt           time.Time         `json:"updated_at"`
}

ArtifactDeploymentRecord records one deployment, identified by (logical env, physical env, cluster, deployment name); repeated posts update it in place.

type ArtifactStorageRecord

type ArtifactStorageRecord struct {
	ID               int       `json:"id"`
	OrgID            int       `json:"org_id"`
	Name             string    `json:"name"`
	Digest           string    `json:"digest"`
	Version          string    `json:"version"`
	ArtifactURL      string    `json:"artifact_url"`
	Path             string    `json:"path"`
	RegistryURL      string    `json:"registry_url"`
	Repository       string    `json:"repository"`
	Status           string    `json:"status"` // active, eol, deleted
	GitHubRepository string    `json:"github_repository"`
	CreatedAt        time.Time `json:"created_at"`
	UpdatedAt        time.Time `json:"updated_at"`
}

ArtifactStorageRecord records where a digest-identified artifact is stored.

type ArtifactStore

type ArtifactStore struct {
	Mu          sync.RWMutex          `json:"-"`
	Artifacts   map[int64]*Artifact   `json:"-"`
	NextID      int64                 `json:"-"`
	Caches      map[int64]*CacheEntry `json:"-"`
	CacheIndex  map[string]int64      `json:"-"`
	NextCacheID int64                 `json:"-"`

	DataDir string `json:"-"` // empty = in-memory mode

	ByteStore ActionsByteStore `json:"-"`
	Persist   *Persistence     `json:"-"`

	// MaxRepoCacheBytes is the per-repo cache budget; finalizing over it evicts
	// LRU finalized entries. A field so tests can drive eviction with small caches.
	MaxRepoCacheBytes int64 `json:"-"`
	// contains filtered or unexported fields
}

ArtifactStore holds artifact/cache metadata for @actions/artifact v4 and the byte backend for artifact/cache/log content. Persisted startup requires byteStore so durable bytes reach object storage, not local disk.

func NewArtifactStoreWithByteStore

func NewArtifactStoreWithByteStore(dataDir string, byteStore ActionsByteStore) *ArtifactStore

func (*ArtifactStore) AppendArtifactChunk

func (as *ArtifactStore) AppendArtifactChunk(id int64, chunk []byte) error

AppendArtifactChunk appends one upload chunk to the artifact's staging file (O(chunk), not O(total)). Callers serialize on ArtifactStore.Mu.

func (*ArtifactStore) ArtifactByID

func (as *ArtifactStore) ArtifactByID(id int64) (*Artifact, bool)

func (*ArtifactStore) ClaimLog

func (as *ArtifactStore) ClaimLog(logID int, planID string)

func (*ArtifactStore) DeleteArtifact

func (as *ArtifactStore) DeleteArtifact(ctx context.Context, id int64) (bool, error)

func (*ArtifactStore) DeleteLogData

func (as *ArtifactStore) DeleteLogData(ctx context.Context, logID int) error

func (*ArtifactStore) DiscardArtifactStaging

func (as *ArtifactStore) DiscardArtifactStaging(id int64)

DiscardArtifactStaging removes a staging file for an upload that never finalized. Best-effort.

func (*ArtifactStore) FinalizeArtifactUpload

func (as *ArtifactStore) FinalizeArtifactUpload(ctx context.Context, art *Artifact) error

FinalizeArtifactUpload moves the staged bytes to the artifact's durable home (object store, else the data dir, else memory) exactly once, computing the SHA-256 digest, and removes the staging file. It sets art.Size, art.Digest, and — for object-backed stores — leaves art.Data nil so the finalized artifact does not pin its payload in RAM. Callers hold ArtifactStore.Mu.

func (*ArtifactStore) FinalizedArtifacts

func (as *ArtifactStore) FinalizedArtifacts() []*Artifact

func (*ArtifactStore) FinalizedRepoCaches

func (as *ArtifactStore) FinalizedRepoCaches(repo string) []*CacheEntry

FinalizedRepoCaches returns every finalized cache for repo, ordered by id.

func (*ArtifactStore) FindArtifactByNameLocked

func (as *ArtifactStore) FindArtifactByNameLocked(name, workflowRunBackendID string, finalized bool) *Artifact

func (*ArtifactStore) LogBelongsToPlan

func (as *ArtifactStore) LogBelongsToPlan(logID int, planID string) bool

LogBelongsToPlan reports whether planID reserved logID. An unreserved log id belongs to nobody, so uploads to it are refused.

func (*ArtifactStore) PersistCacheMeta

func (as *ArtifactStore) PersistCacheMeta(entry *CacheEntry) error

func (*ArtifactStore) PersistMeta

func (as *ArtifactStore) PersistMeta(art *Artifact) error

PersistMeta writes finalized artifact metadata to durable persistence, and to the local disk copy when configured.

func (*ArtifactStore) PopulateArtifactDigest

func (as *ArtifactStore) PopulateArtifactDigest(art *Artifact)

func (*ArtifactStore) RefreshFromPersistenceIfStale

func (as *ArtifactStore) RefreshFromPersistenceIfStale() error

RefreshFromPersistenceIfStale pulls Actions metadata written by another dqlite replica into this process. In-flight local uploads are preserved; only finalized rows are durable and replaceable.

func (*ArtifactStore) ReleaseLogClaimsForPlans

func (as *ArtifactStore) ReleaseLogClaimsForPlans(planIDs []string) []int

ReleaseLogClaimsForPlans drops the log-container claims held by the given plans and reports the released log ids. Only the in-memory claim registry is touched; durable byte-store log objects are untouched.

func (*ArtifactStore) RenameRepository

func (as *ArtifactStore) RenameRepository(oldFullName, newFullName string) error

func (*ArtifactStore) ReserveID

func (as *ArtifactStore) ReserveID(bucket string, local *int64) (int64, error)

func (*ArtifactStore) SetPersistence

func (as *ArtifactStore) SetPersistence(p *Persistence) error

SetPersistence moves Actions artifact/cache metadata onto the durable SQLite/dqlite store. Local metadata migrates only when the durable buckets are empty; once durable metadata exists it is authoritative, so a stale replica cannot overwrite newer shared records.

func (*ArtifactStore) WriteArtifactData

func (as *ArtifactStore) WriteArtifactData(ctx context.Context, art *Artifact) error

func (*ArtifactStore) WriteCacheChunkToDisk

func (as *ArtifactStore) WriteCacheChunkToDisk(entry *CacheEntry, chunk []byte, offset int64) error

WriteCacheChunkToDisk lands one ranged chunk at its Content-Range offset in the cache's local data file. No-op in in-memory mode.

func (*ArtifactStore) WriteCacheDataAt

func (as *ArtifactStore) WriteCacheDataAt(entry *CacheEntry, chunk []byte, offset int64) error

WriteCacheDataAt writes a ranged chunk to the cache's on-disk data file at its Content-Range offset, for restart recovery (entry.Data is authoritative in-process).

func (*ArtifactStore) WriteLogData

func (as *ArtifactStore) WriteLogData(ctx context.Context, logID int, data []byte) error

type Attestation

type Attestation struct {
	ID             int             `json:"id"`
	RepoID         int             `json:"repo_id"`
	Bundle         json.RawMessage `json:"-"`
	StoragePath    string          `json:"storage_path,omitempty"`
	SubjectDigests []string        `json:"subject_digests"` // "algorithm:hex", lowercased
	PredicateType  string          `json:"predicate_type"`
	Initiator      string          `json:"initiator"` // login of the uploading user
	CreatedAt      time.Time       `json:"created_at"`
}

Attestation is one uploaded artifact attestation.

func (*Attestation) HasSubjectDigest

func (a *Attestation) HasSubjectDigest(digest string) bool

HasSubjectDigest reports whether the attestation covers the digest.

type AttributionInvitation

type AttributionInvitation struct {
	ID           int       `json:"id"`
	OrgID        int       `json:"org_id"`
	SourceNodeID string    `json:"source_node_id"`
	TargetNodeID string    `json:"target_node_id"`
	CreatedAt    time.Time `json:"created_at"`
}

type AuditEntry

type AuditEntry struct {
	ID        int64                  `json:"_document_id"`
	Timestamp string                 `json:"@timestamp"`
	Action    string                 `json:"action"`
	Actor     string                 `json:"actor"`
	Org       string                 `json:"org,omitempty"`
	Data      map[string]interface{} `json:"data,omitempty"`
	Version   string                 `json:"version"`
}

type AuditLogEvent

type AuditLogEvent struct {
	ID         int64                  `json:"id"`
	Timestamp  string                 `json:"timestamp"`
	Actor      string                 `json:"actor"`
	Action     string                 `json:"action"`
	TargetType string                 `json:"target_type"`
	TargetID   string                 `json:"target_id"`
	Org        string                 `json:"org,omitempty"`
	Details    map[string]interface{} `json:"details,omitempty"`
	CreatedAt  time.Time              `json:"-"`
}

type AuthCode

type AuthCode struct {
	Code        string
	ClientID    string
	RedirectURI string
	Scopes      string
	State       string
	UserID      int
	CreatedAt   time.Time
	ExpiresAt   time.Time
}

AuthCode is a one-time-use OAuth authorization code keyed off a client_id + state pair.

type BPActor

type BPActor struct {
	Login string `json:"login"`
	ID    int    `json:"id"`
	Type  string `json:"type"`
}

type BPBypassAllowances

type BPBypassAllowances struct {
	Users []BPActor `json:"users,omitempty"`
	Teams []BPActor `json:"teams,omitempty"`
	Apps  []BPActor `json:"apps,omitempty"`
}

type BPCheck

type BPCheck struct {
	Context string `json:"context"`
	AppID   *int64 `json:"app_id"`
}

BPCheck is an entry in required_status_checks.checks. app_id is a required, nullable member — null when no app is pinned.

type BPEnabled

type BPEnabled struct {
	Enabled bool `json:"enabled"`
}

type BPEnabledURL

type BPEnabledURL struct {
	URL     string `json:"url,omitempty"`
	Enabled bool   `json:"enabled"`
}

BPEnabledURL is required_signatures, which also carries a URL.

type BPEnforceAdmins

type BPEnforceAdmins struct {
	URL     string `json:"url,omitempty"`
	Enabled bool   `json:"enabled"`
}

type BPPullRequestReviews

type BPPullRequestReviews struct {
	URL                          string              `json:"url,omitempty"`
	DismissStaleReviews          bool                `json:"dismiss_stale_reviews"`
	RequireCodeOwnerReviews      bool                `json:"require_code_owner_reviews"`
	RequireLastPushApproval      bool                `json:"require_last_push_approval"`
	RequiredApprovingReviewCount int                 `json:"required_approving_review_count"`
	DismissalRestrictions        *BPRestrictions     `json:"dismissal_restrictions,omitempty"`
	BypassPullRequestAllowances  *BPBypassAllowances `json:"bypass_pull_request_allowances,omitempty"`
}

type BPRestrictions

type BPRestrictions struct {
	Users    []BPActor `json:"users"`
	Teams    []BPActor `json:"teams"`
	Apps     []BPActor `json:"apps"`
	URL      string    `json:"url,omitempty"`
	UsersURL string    `json:"users_url,omitempty"`
	TeamsURL string    `json:"teams_url,omitempty"`
	AppsURL  string    `json:"apps_url,omitempty"`
}

BPRestrictions is the restrictions object. users/teams/apps are required members of the published schema, so they serialize even when empty.

type BPStatusChecks

type BPStatusChecks struct {
	URL              string    `json:"url,omitempty"`
	EnforcementLevel string    `json:"enforcement_level,omitempty"`
	Contexts         []string  `json:"contexts"`
	Checks           []BPCheck `json:"checks"`
	Strict           bool      `json:"strict"`
	ContextsURL      string    `json:"contexts_url,omitempty"`
}

BPStatusChecks is the required_status_checks object. contexts and checks are required members of the published schema, so they serialize even when empty (hydrateBranchProtectionURLs normalizes nil slices before responses).

func (*BPStatusChecks) SetChecks

func (sc *BPStatusChecks) SetChecks(checks []BPCheck)

SetChecks replaces the check set from the richer view, deriving contexts.

func (*BPStatusChecks) SetContexts

func (sc *BPStatusChecks) SetContexts(contexts []string)

SetContexts replaces the check set from the names view, deriving checks. A context that already named an app keeps it: the legacy view must not widen which app may report a check.

type BillingUsageItem

type BillingUsageItem struct {
	Date         time.Time
	Product      string
	SKU          string
	RepoFullName string
	Quantity     int
	UnitType     string
	PricePerUnit float64
}

type BranchProtection

type BranchProtection struct {
	RequiredStatusChecks           *BPStatusChecks       `json:"required_status_checks,omitempty"`
	RequiredPullRequestReviews     *BPPullRequestReviews `json:"required_pull_request_reviews,omitempty"`
	EnforceAdmins                  *BPEnforceAdmins      `json:"enforce_admins,omitempty"`
	Restrictions                   *BPRestrictions       `json:"restrictions,omitempty"`
	RequiredLinearHistory          *BPEnabled            `json:"required_linear_history,omitempty"`
	AllowForcePushes               *BPEnabled            `json:"allow_force_pushes,omitempty"`
	AllowDeletions                 *BPEnabled            `json:"allow_deletions,omitempty"`
	BlockCreations                 *BPEnabled            `json:"block_creations,omitempty"`
	RequiredConversationResolution *BPEnabled            `json:"required_conversation_resolution,omitempty"`
	RequiredSignatures             *BPEnabledURL         `json:"required_signatures,omitempty"`
	LockBranch                     *BPEnabled            `json:"lock_branch,omitempty"`
	AllowForkSyncing               *BPEnabled            `json:"allow_fork_syncing,omitempty"`
	URL                            string                `json:"url,omitempty"`
	// Enabled records that the branch is protected at all: set only by
	// PUT .../protection, cleared only by DELETE — never by turning one rule
	// off. Without it, disabling the last rule silently dropped protection.
	Enabled bool `json:"enabled,omitempty"`
}

BranchProtection is the REST shape for GET /repos/{owner}/{repo}/branches/{branch}/protection. Pointer sub-fields are omitempty so an unset rule doesn't appear.

func (*BranchProtection) IsProtected

func (bp *BranchProtection) IsProtected() bool

IsProtected reports whether the branch has any protection rule enabled.

type BranchProtectionPatternRule

type BranchProtectionPatternRule struct {
	Pattern    string            `json:"pattern"`
	Protection *BranchProtection `json:"protection"`
}

BranchProtectionPatternRule is a web-only branch protection rule addressed by an fnmatch pattern. GitHub's REST API forbids wildcards, so these live under /ui-data, and the enforcement chokepoint consults them only when no exact-name rule matches the branch.

type BranchProtectionRuleExtras

type BranchProtectionRuleExtras struct {
	CreatorLogin                   string    `json:"creator_login,omitempty"`
	RequiresDeployments            bool      `json:"requires_deployments,omitempty"`
	RequiredDeploymentEnvironments []string  `json:"required_deployment_environments,omitempty"`
	BypassForcePushActors          []BPActor `json:"bypass_force_push_actors,omitempty"`
}

BranchProtectionRuleExtras carries members GitHub's GraphQL surface declares but its REST protection shape does not. Stored separately so REST responses, which serialize BranchProtection directly, never grow non-schema keys.

type CacheChunk

type CacheChunk struct {
	Start int64  `json:"-"`
	Data  []byte `json:"-"`
}

CacheChunk is one ranged upload body and its start offset.

type CacheEntry

type CacheEntry struct {
	ID             int64     `json:"id"`
	Repo           string    `json:"repo"`
	Key            string    `json:"key"`
	Version        string    `json:"version"`
	Size           int64     `json:"size"`
	Data           []byte    `json:"-"`
	Finalized      bool      `json:"finalized"`
	DownloadToken  string    `json:"downloadToken"`
	CreatedAt      time.Time `json:"createdAt"`
	LastAccessedAt time.Time `json:"lastAccessedAt"`

	// Chunks holds the ranged bodies received for an unfinalized reservation;
	// finalize tiles them into Data. Buffering only what arrived bounds the memory
	// a client can make this server allocate by the bytes it uploaded, not the
	// Content-Range it declared.
	Chunks   []CacheChunk `json:"-"`
	Received int64        `json:"-"`
}

CacheEntry is one immutable Actions dependency cache archive, scoped to the repo whose run created it. DownloadToken stands in for GitHub's pre-signed archive URL: the toolkit fetches it unauthenticated, so it must be unguessable.

type Campaign

type Campaign struct {
	Number             int           `json:"number"`
	OrgLogin           string        `json:"org_login"`
	Name               string        `json:"name"`
	Description        string        `json:"description"`
	ManagerLogins      []string      `json:"manager_logins"`
	TeamManagerSlugs   []string      `json:"team_manager_slugs"`
	EndsAt             time.Time     `json:"ends_at"`
	ContactLink        *string       `json:"contact_link"`
	State              string        `json:"state"`
	PublishedAt        time.Time     `json:"published_at"`
	ClosedAt           *time.Time    `json:"closed_at"`
	CreatedAt          time.Time     `json:"created_at"`
	UpdatedAt          time.Time     `json:"updated_at"`
	CodeScanningAlerts map[int][]int `json:"code_scanning_alerts"` // repo ID → alert numbers
}

Campaign is an organization security campaign.

type CheckAnnotation

type CheckAnnotation struct {
	Path            string `json:"path"`
	StartLine       int    `json:"start_line"`
	EndLine         int    `json:"end_line"`
	StartColumn     *int   `json:"start_column,omitempty"`
	EndColumn       *int   `json:"end_column,omitempty"`
	AnnotationLevel string `json:"annotation_level"` // notice, warning, failure
	Message         string `json:"message"`
	Title           string `json:"title,omitempty"`
	RawDetails      string `json:"raw_details,omitempty"`
}

CheckAnnotation is a per-line annotation on a CheckRun's output.

type CheckImage

type CheckImage struct {
	Alt      string `json:"alt"`
	ImageURL string `json:"image_url"`
	Caption  string `json:"caption,omitempty"`
}

CheckImage attaches an image to a CheckRun.

type CheckRun

type CheckRun struct {
	ID          int64           `json:"id"`
	NodeID      string          `json:"node_id"`
	HeadSHA     string          `json:"head_sha"`
	ExternalID  string          `json:"external_id"`
	Name        string          `json:"name"`
	Status      string          `json:"status"`     // queued, in_progress, completed
	Conclusion  string          `json:"conclusion"` // success, failure, neutral, cancelled, skipped, timed_out, action_required, stale, startup_failure
	StartedAt   time.Time       `json:"started_at"`
	CompletedAt *time.Time      `json:"completed_at,omitempty"`
	Output      *CheckRunOutput `json:"output,omitempty"`
	DetailsURL  string          `json:"details_url"`
	// Actions are the integrator-defined requested-action buttons. GitHub's REST
	// responses do not render them (they surface only as requested_action webhook
	// triggers), so checkRunToJSON emits no member for them.
	Actions []*CheckRunAction `json:"actions,omitempty"`
	AppID   int               `json:"app_id"`
	SuiteID int64             `json:"check_suite_id"`
	// RepoKey carries a real json name so persistence round-trips it (post-reload
	// commit lookups match on it). Client responses go through checkRunToJSON.
	RepoKey string `json:"repo_key"`
}

CheckRun is a single check execution attached to a commit SHA, mirroring GitHub's Checks API shape.

type CheckRunAction

type CheckRunAction struct {
	Label       string `json:"label"`
	Description string `json:"description"`
	Identifier  string `json:"identifier"`
}

CheckRunAction is one requested-action button (the `actions` member of the create/update requests).

type CheckRunOutput

type CheckRunOutput struct {
	Title            string             `json:"title,omitempty"`
	Summary          string             `json:"summary,omitempty"`
	Text             string             `json:"text,omitempty"`
	AnnotationsCount int                `json:"annotations_count"`
	Annotations      []*CheckAnnotation `json:"annotations"` // rendered only via the annotations list endpoint
	Images           []*CheckImage      `json:"images,omitempty"`
}

CheckRunOutput is the title/summary/text/annotations bundle on a CheckRun.

type CheckSuite

type CheckSuite struct {
	ID                   int64  `json:"id"`
	NodeID               string `json:"node_id"`
	HeadBranch           string `json:"head_branch"`
	HeadSHA              string `json:"head_sha"`
	Status               string `json:"status"`
	Conclusion           string `json:"conclusion"`
	AppID                int    `json:"app_id"`
	WorkflowRunID        int    `json:"workflow_run_id,omitempty"`
	WorkflowRunBackendID string `json:"workflow_run_backend_id,omitempty"`
	WorkflowName         string `json:"workflow_name,omitempty"`
	WorkflowFileID       int64  `json:"workflow_file_id,omitempty"`
	WorkflowFilePath     string `json:"workflow_file_path,omitempty"`
	// RepoKey carries a real json name so persistence round-trips it; client
	// responses go through checkSuiteToJSON.
	RepoKey   string    `json:"repo_key"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

CheckSuite groups CheckRuns by (repo, head_sha, app).

type CheckSuitePref

type CheckSuitePref struct {
	AppID   int  `json:"app_id"`
	Setting bool `json:"setting"`
}

CheckSuitePref controls auto-trigger of CheckSuites for a (repo, app) pair.

type Classroom

type Classroom struct {
	ID       int                `json:"id"`
	Name     string             `json:"name"`
	Archived bool               `json:"archived"`
	OrgID    int                `json:"org_id"`
	Roster   []ClassroomStudent `json:"roster,omitempty"`
}

Classroom is a GitHub Classroom classroom owned by an organization.

type ClassroomAcceptedAssignment

type ClassroomAcceptedAssignment struct {
	ID           int                `json:"id"`
	AssignmentID int                `json:"assignment_id"`
	Students     []ClassroomStudent `json:"students"`
	RepoID       int                `json:"repo_id"`
	GroupName    string             `json:"group_name"`
	AcceptedAt   time.Time          `json:"accepted_at"`
	BaselineSHA  string             `json:"baseline_sha"`
	SubmittedAt  time.Time          `json:"submitted_at,omitempty"` // reloads pre-transition Classroom records
}

ClassroomAcceptedAssignment records a student's or team's acceptance of an assignment, backed by the repository the acceptance created.

type ClassroomAssignment

type ClassroomAssignment struct {
	ID                          int                        `json:"id"`
	ClassroomID                 int                        `json:"classroom_id"`
	Title                       string                     `json:"title"`
	Type                        string                     `json:"type"` // "individual" or "group"
	Slug                        string                     `json:"slug"`
	InviteCode                  string                     `json:"invite_code"`
	InvitationsEnabled          bool                       `json:"invitations_enabled"`
	PublicRepo                  bool                       `json:"public_repo"`
	StudentsAreRepoAdmins       bool                       `json:"students_are_repo_admins"`
	FeedbackPullRequestsEnabled bool                       `json:"feedback_pull_requests_enabled"`
	MaxTeams                    *int                       `json:"max_teams"`
	MaxMembers                  *int                       `json:"max_members"`
	Editor                      string                     `json:"editor"`
	Language                    string                     `json:"language"`
	Deadline                    *time.Time                 `json:"deadline"`
	StarterCodeRepoID           int                        `json:"starter_code_repo_id"`
	AutogradingTests            []ClassroomAutogradingTest `json:"autograding_tests,omitempty"`
}

ClassroomAssignment is an assignment within a classroom.

type ClassroomAutogradingTest

type ClassroomAutogradingTest struct {
	Name    string `json:"name"`
	Command string `json:"command"`
	Points  int    `json:"points"`
}

type ClassroomStudent

type ClassroomStudent struct {
	UserID           int    `json:"user_id"`
	RosterIdentifier string `json:"roster_identifier"`
}

type CodeOfConduct

type CodeOfConduct struct {
	Key  string
	Name string
	Body string
}

CodeOfConduct is one entry of the codes-of-conduct catalog.

type CodeQLDatabase

type CodeQLDatabase struct {
	ID          int       `json:"id"`
	RepoKey     string    `json:"repo_key"`
	Name        string    `json:"name"`
	Language    string    `json:"language"`
	UploaderID  int       `json:"uploader_id"`
	ContentType string    `json:"content_type"`
	Size        int64     `json:"size"`
	StoragePath string    `json:"storage_path,omitempty"`
	Content     []byte    `json:"-"`
	CommitOID   string    `json:"commit_oid"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

CodeQLDatabase is a CodeQL database for one repo + language pair. StoragePath points at the durable archive bytes; Content is used only by non-persistent in-memory stores.

type CodeQLVariantAnalysis

type CodeQLVariantAnalysis struct {
	ID                  int                             `json:"id"`
	ControllerRepoKey   string                          `json:"controller_repo_key"`
	ActorID             int                             `json:"actor_id"`
	QueryLanguage       string                          `json:"query_language"`
	QueryPack           string                          `json:"-"`
	QueryPackSize       int64                           `json:"query_pack_size"`
	StoragePath         string                          `json:"storage_path,omitempty"`
	Status              string                          `json:"status"` // in_progress | succeeded | failed | cancelled
	FailureReason       string                          `json:"failure_reason"`
	ScannedRepositories []CodeQLVariantAnalysisRepoTask `json:"scanned_repositories"`
	NotFoundRepos       []string                        `json:"not_found_repos"`    // full names
	NoCodeQLDBRepos     []int                           `json:"no_codeql_db_repos"` // repo IDs
	CreatedAt           time.Time                       `json:"created_at"`
	UpdatedAt           time.Time                       `json:"updated_at"`
	CompletedAt         *time.Time                      `json:"completed_at"`
}

CodeQLVariantAnalysis is a multi-repository variant analysis for a CodeQL query pack. StoragePath points at the durable query-pack tarball; QueryPack is used only by non-persistent in-memory stores. GitHub runs the query via an Actions workflow; bleephub resolves targets synchronously (a repo is queryable only with a CodeQL database for the language) and completes immediately.

type CodeQLVariantAnalysisRepoTask

type CodeQLVariantAnalysisRepoTask struct {
	RepoID            int                        `json:"repo_id"`
	FullName          string                     `json:"full_name"`
	AnalysisStatus    CodeScanningAnalysisStatus `json:"analysis_status"`
	ResultCount       int                        `json:"result_count"`
	DatabaseCommitSHA string                     `json:"database_commit_sha"`
}

CodeQLVariantAnalysisRepoTask is the per-repository result row of a variant analysis.

type CodeQualityFinding

type CodeQualityFinding struct {
	Number    int                        `json:"number"`
	RepoKey   string                     `json:"repo_key"`
	State     string                     `json:"state"`
	Rule      CodeQualityFindingRule     `json:"rule"`
	Location  CodeQualityFindingLocation `json:"location"`
	Message   CodeQualityFindingMessage  `json:"message"`
	CreatedAt time.Time                  `json:"created_at"`
}

type CodeQualityFindingLocation

type CodeQualityFindingLocation struct {
	Path        string `json:"path"`
	StartLine   int    `json:"start_line,omitempty"`
	StartColumn int    `json:"start_column,omitempty"`
	EndLine     int    `json:"end_line,omitempty"`
	EndColumn   int    `json:"end_column,omitempty"`
}

type CodeQualityFindingMessage

type CodeQualityFindingMessage struct {
	Text     string `json:"text"`
	Markdown string `json:"markdown"`
}

type CodeQualityFindingRule

type CodeQualityFindingRule struct {
	ID          string `json:"id"`
	Title       string `json:"title"`
	Description string `json:"description"`
	Help        string `json:"help,omitempty"`
	Severity    string `json:"severity"`
	Category    string `json:"category"`
}

type CodeQualitySetup

type CodeQualitySetup struct {
	RepoFullName string     `json:"repo_full_name"`
	State        string     `json:"state"`
	Languages    []string   `json:"languages"`
	RunnerType   string     `json:"runner_type"`
	RunnerLabel  string     `json:"runner_label"`
	Schedule     string     `json:"schedule"`
	UpdatedAt    *time.Time `json:"updated_at"`
}

CodeQualitySetup is a repository's code quality configuration. Empty strings model the null runner_type / runner_label / schedule members.

type CodeScanningAlert

type CodeScanningAlert struct {
	ID           int    `json:"id"`
	NodeID       string `json:"node_id"`
	Number       int    `json:"number"`
	RepoKey      string `json:"repo_key"`
	RuleID       string `json:"rule_id"`
	RuleSeverity string `json:"rule_severity"`
	// SecuritySeverityLevel is the low/medium/high/critical bucket derived from a
	// rule's numeric SARIF security-severity score; empty (null) for a quality rule.
	SecuritySeverityLevel string                      `json:"security_severity_level"`
	RuleDescription       string                      `json:"rule_description"`
	ToolName              string                      `json:"tool_name"`
	ToolGUID              string                      `json:"tool_guid"`
	State                 CodeScanningState           `json:"state"`
	DismissedReason       CodeScanningDismissedReason `json:"dismissed_reason"`
	DismissedComment      string                      `json:"dismissed_comment"`
	DismissedAt           *time.Time                  `json:"dismissed_at"`
	FixedAt               *time.Time                  `json:"fixed_at"`
	HTMLURL               string                      `json:"html_url"`
	URL                   string                      `json:"url"`
	InstancesURL          string                      `json:"instances_url"`
	// Fingerprint is the internal dedup key (tool + rule + primary-location
	// fingerprint) that correlates a result across SARIF uploads. Persisted but
	// not part of the GitHub API shape (codeScanningAlertToJSON omits it).
	Fingerprint string                      `json:"fingerprint,omitempty"`
	Instances   []CodeScanningAlertInstance `json:"instances"`
	CreatedAt   time.Time                   `json:"created_at"`
	UpdatedAt   time.Time                   `json:"updated_at"`
}

CodeScanningAlert is a repo-scoped alert from a SARIF upload or the operator seeding endpoint.

type CodeScanningAlertInstance

type CodeScanningAlertInstance struct {
	Ref         string            `json:"ref"`
	AnalysisKey string            `json:"analysis_key"`
	Category    string            `json:"category"`
	State       CodeScanningState `json:"state"`
	CommitSHA   string            `json:"commit_sha"`
	Path        string            `json:"path"`
	StartLine   int               `json:"start_line"`
	EndLine     int               `json:"end_line"`
	StartColumn int               `json:"start_column"`
	EndColumn   int               `json:"end_column"`
	Message     string            `json:"message"`
}

CodeScanningAlertInstance is one occurrence of a code-scanning alert.

type CodeScanningAnalysis

type CodeScanningAnalysis struct {
	ID            int       `json:"id"`
	NodeID        string    `json:"node_id"`
	RepoKey       string    `json:"repo_key"`
	Ref           string    `json:"ref"`
	CommitSHA     string    `json:"commit_sha"`
	AnalysisKey   string    `json:"analysis_key"`
	Category      string    `json:"category"`
	ToolName      string    `json:"tool_name"`
	ToolGUID      string    `json:"tool_guid"`
	ResultsCount  int       `json:"results_count"`
	RulesCount    int       `json:"rules_count"`
	SARIFUploadID string    `json:"sarif_upload_id,omitempty"`
	CreatedAt     time.Time `json:"created_at"`
	HTMLURL       string    `json:"html_url"`
	URL           string    `json:"url"`
}

CodeScanningAnalysis is a single code-scanning analysis run for a repo.

type CodeScanningAnalysisStatus

type CodeScanningAnalysisStatus string

CodeScanningAnalysisStatus is a CodeQL variant-analysis repo task's status; GitHub emits only these six values.

const (
	CSAnalysisPending    CodeScanningAnalysisStatus = "pending"
	CSAnalysisInProgress CodeScanningAnalysisStatus = "in_progress"
	CSAnalysisSucceeded  CodeScanningAnalysisStatus = "succeeded"
	CSAnalysisFailed     CodeScanningAnalysisStatus = "failed"
	CSAnalysisCanceled   CodeScanningAnalysisStatus = "canceled"
	CSAnalysisTimedOut   CodeScanningAnalysisStatus = "timed_out"
)

type CodeScanningAutofix

type CodeScanningAutofix struct {
	RepoKey     string    `json:"repo_key"`
	AlertNumber int       `json:"alert_number"`
	Status      string    `json:"status"` // pending | error | success | outdated
	Description string    `json:"description"`
	StartedAt   time.Time `json:"started_at"`
}

CodeScanningAutofix is a Copilot Autofix suggestion for one alert. GitHub generates it asynchronously; bleephub does so synchronously, so a created autofix is immediately in "success" status.

type CodeScanningDefaultSetup

type CodeScanningDefaultSetup struct {
	RepoKey     string    `json:"repo_key"`
	State       string    `json:"state"` // "configured" or "not-configured"
	QuerySuite  string    `json:"query_suite"`
	Languages   []string  `json:"languages"`
	RunnerType  string    `json:"runner_type,omitempty"`
	RunnerLabel string    `json:"runner_label,omitempty"`
	ThreatModel string    `json:"threat_model,omitempty"`
	UpdatedAt   time.Time `json:"updated_at"`
}

CodeScanningDefaultSetup is one repository's default-setup configuration. A repo without a row reports "not-configured".

type CodeScanningDismissedReason

type CodeScanningDismissedReason string

CodeScanningDismissedReason is the reason recorded when an alert is dismissed; only these four values are accepted.

const (
	// GitHub's code-scanning dismissed_reason enum uses spaces, not underscores
	// (unlike the secret-scanning resolution enum), and has no "ignored" value
	// (PAR-010).
	CodeScanningDismissedFalsePositive CodeScanningDismissedReason = "false positive"
	CodeScanningDismissedWontFix       CodeScanningDismissedReason = "won't fix"
	CodeScanningDismissedUsedInTests   CodeScanningDismissedReason = "used in tests"
	CodeScanningDismissedMitigated     CodeScanningDismissedReason = "mitigated"
)

type CodeScanningState

type CodeScanningState string

CodeScanningState is a code-scanning alert's lifecycle state; the three constants are the only values GitHub emits.

const (
	CodeScanningStateOpen      CodeScanningState = "open"
	CodeScanningStateDismissed CodeScanningState = "dismissed"
	CodeScanningStateFixed     CodeScanningState = "fixed"
)

type CodeSecurityConfiguration

type CodeSecurityConfiguration struct {
	ID                                  int       `json:"id"`
	OrgLogin                            string    `json:"org_login"`
	Name                                string    `json:"name"`
	Description                         string    `json:"description"`
	TargetType                          string    `json:"target_type"`
	AdvancedSecurity                    string    `json:"advanced_security"`
	DependencyGraph                     string    `json:"dependency_graph"`
	DependencyGraphAutosubmitAction     string    `json:"dependency_graph_autosubmit_action"`
	DependencyGraphAutosubmitLabeled    *bool     `json:"dependency_graph_autosubmit_labeled"`
	DependabotAlerts                    string    `json:"dependabot_alerts"`
	DependabotSecurityUpdates           string    `json:"dependabot_security_updates"`
	DependabotDelegatedAlertDismissal   string    `json:"dependabot_delegated_alert_dismissal"`
	CodeScanningDefaultSetup            string    `json:"code_scanning_default_setup"`
	CodeScanningRunnerType              *string   `json:"code_scanning_runner_type"`
	CodeScanningRunnerLabel             *string   `json:"code_scanning_runner_label"`
	CodeScanningDelegatedAlertDismissal string    `json:"code_scanning_delegated_alert_dismissal"`
	SecretScanning                      string    `json:"secret_scanning"`
	SecretScanningPushProtection        string    `json:"secret_scanning_push_protection"`
	SecretScanningDelegatedBypass       string    `json:"secret_scanning_delegated_bypass"`
	SecretScanningValidityChecks        string    `json:"secret_scanning_validity_checks"`
	SecretScanningNonProviderPatterns   string    `json:"secret_scanning_non_provider_patterns"`
	SecretScanningGenericSecrets        string    `json:"secret_scanning_generic_secrets"`
	SecretScanningDelegatedDismissal    string    `json:"secret_scanning_delegated_alert_dismissal"`
	SecretScanningExtendedMetadata      string    `json:"secret_scanning_extended_metadata"`
	CodeScanningAllowAdvanced           *bool     `json:"code_scanning_allow_advanced"`
	PrivateVulnerabilityReporting       string    `json:"private_vulnerability_reporting"`
	Enforcement                         string    `json:"enforcement"`
	DefaultForNewRepos                  string    `json:"default_for_new_repos"`
	CreatedAt                           time.Time `json:"created_at"`
	UpdatedAt                           time.Time `json:"updated_at"`
}

CodeSecurityConfiguration is an organization code security configuration.

type CodeSecurityConfigurationRequest

type CodeSecurityConfigurationRequest struct {
	Name                             *string `json:"name"`
	Description                      *string `json:"description"`
	AdvancedSecurity                 *string `json:"advanced_security"`
	CodeSecurity                     *string `json:"code_security"`
	SecretProtection                 *string `json:"secret_protection"`
	DependencyGraph                  *string `json:"dependency_graph"`
	DependencyGraphAutosubmitAction  *string `json:"dependency_graph_autosubmit_action"`
	DependencyGraphAutosubmitOptions *struct {
		LabeledRunners *bool `json:"labeled_runners"`
	} `json:"dependency_graph_autosubmit_action_options"`
	DependabotAlerts                  *string `json:"dependabot_alerts"`
	DependabotSecurityUpdates         *string `json:"dependabot_security_updates"`
	DependabotDelegatedAlertDismissal *string `json:"dependabot_delegated_alert_dismissal"`
	CodeScanningDefaultSetup          *string `json:"code_scanning_default_setup"`
	CodeScanningDefaultSetupOptions   *struct {
		RunnerType  *string `json:"runner_type"`
		RunnerLabel *string `json:"runner_label"`
	} `json:"code_scanning_default_setup_options"`
	CodeScanningDelegatedAlertDismissal *string `json:"code_scanning_delegated_alert_dismissal"`
	SecretScanning                      *string `json:"secret_scanning"`
	SecretScanningPushProtection        *string `json:"secret_scanning_push_protection"`
	SecretScanningDelegatedBypass       *string `json:"secret_scanning_delegated_bypass"`
	SecretScanningValidityChecks        *string `json:"secret_scanning_validity_checks"`
	SecretScanningNonProviderPatterns   *string `json:"secret_scanning_non_provider_patterns"`
	SecretScanningGenericSecrets        *string `json:"secret_scanning_generic_secrets"`
	SecretScanningDelegatedDismissal    *string `json:"secret_scanning_delegated_alert_dismissal"`
	SecretScanningExtendedMetadata      *string `json:"secret_scanning_extended_metadata"`
	CodeScanningOptions                 *struct {
		AllowAdvanced *bool `json:"allow_advanced"`
	} `json:"code_scanning_options"`
	PrivateVulnerabilityReporting *string `json:"private_vulnerability_reporting"`
	Enforcement                   *string `json:"enforcement"`
}

CodeSecurityConfigurationRequest is the create/update wire shape. The code_security / secret_protection members are write-only toggles GitHub folds into advanced_security.

func (*CodeSecurityConfigurationRequest) ValidateEnums

ValidateEnums checks every provided enum member, writing a validation error and returning false on the first invalid one.

type Codespace

type Codespace struct {
	ID                     int              `json:"id"`
	Name                   string           `json:"name"`
	OwnerLogin             string           `json:"owner_login"`
	RepoKey                string           `json:"repo_key,omitempty"`
	GitRef                 string           `json:"git_ref"`
	MachineName            string           `json:"machine_name"`
	MachineDisplayName     string           `json:"machine_display_name"`
	MachineType            string           `json:"machine_type"`
	DisplayName            string           `json:"display_name"`
	Location               string           `json:"location,omitempty"`
	WorkingDirectory       string           `json:"working_directory,omitempty"`
	Geolocation            string           `json:"geolocation,omitempty"`
	IdleTimeoutMinutes     int              `json:"idle_timeout_minutes"`
	CreatedAt              time.Time        `json:"created_at"`
	UpdatedAt              time.Time        `json:"updated_at"`
	LastUsedAt             time.Time        `json:"last_used_at"`
	State                  string           `json:"state"`
	ContainerID            string           `json:"container_id"`
	ContainerName          string           `json:"container_name"`
	DevcontainerPath       string           `json:"devcontainer_path"`
	ImageName              string           `json:"image_name"`
	RetentionPeriodMinutes int              `json:"retention_period_minutes"`
	WorkspaceMount         string           `json:"workspace_mount,omitempty"`
	Runtime                string           `json:"runtime,omitempty"`
	LatestExport           *CodespaceExport `json:"latest_export,omitempty"`
}

Codespace represents a GitHub Codespace. Docker-backed instances use a container; without a Docker CLI they fall back to the built-in workspace runtime with the same lifecycle.

func CloneCodespace

func CloneCodespace(cs *Codespace) *Codespace

type CodespaceCreateOptions

type CodespaceCreateOptions struct {
	MachineName            string
	DisplayName            string
	WorkingDirectory       string
	DevcontainerPath       string
	Geolocation            string
	IdleTimeoutMinutes     int
	RetentionPeriodMinutes int
}

CodespaceCreateOptions carries the create fields beyond identity/ref.

type CodespaceExport

type CodespaceExport struct {
	ID          string    `json:"id"`
	State       string    `json:"state"`
	Branch      string    `json:"branch"`
	SHA         string    `json:"sha"`
	CompletedAt time.Time `json:"completed_at"`
}

CodespaceExport captures one export of a codespace to a repository branch. GitHub addresses export details with the id "latest".

type CodespaceMachine

type CodespaceMachine struct {
	Name         string
	DisplayName  string
	Type         string // "standard" or "premium"
	CPUs         int
	MemoryBytes  int64
	StorageBytes int64
}

CodespaceMachine describes a machine type offered for Codespaces.

func CodespaceDefaultMachine

func CodespaceDefaultMachine() CodespaceMachine

func CodespaceMachineByName

func CodespaceMachineByName(name string) CodespaceMachine

CodespaceMachineByName resolves a catalog machine by name; unknown names fall back to the default machine.

type CodespaceSecret

type CodespaceSecret struct {
	Name            string    `json:"name"`
	Key             string    `json:"key"`
	Value           string    `json:"value"` // decrypted plaintext; never returned by an API response, persisted only in the encrypted bucket
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
	SelectedRepoIDs []int     `json:"selected_repository_ids,omitempty"`
	Visibility      string    `json:"visibility,omitempty"`
}

CodespaceSecret is a user/repo/org-level Codespaces secret.

func (*CodespaceSecret) ItemVisibility

func (sec *CodespaceSecret) ItemVisibility() string

func (*CodespaceSecret) SelectedIDs

func (sec *CodespaceSecret) SelectedIDs() []int

func (*CodespaceSecret) SetSelectedIDs

func (sec *CodespaceSecret) SetSelectedIDs(ids []int)

func (*CodespaceSecret) TouchUpdated

func (sec *CodespaceSecret) TouchUpdated(now time.Time)

type Comment

type Comment struct {
	ID              int
	NodeID          string
	ParentType      string // "issue" or "pull_request"
	IssueID         int    // issue or PR database ID per ParentType
	AuthorID        int
	Body            string
	CreatedAt       time.Time
	UpdatedAt       time.Time
	LastEditedAt    *time.Time // nil when never edited after creation
	EditorID        int        // user who performed the last edit; 0 when never edited
	MinimizedReason string     // "" when not minimized; otherwise OFF_TOPIC / OUTDATED / RESOLVED / DUPLICATE / SPAM / ABUSE
	MinimizedByID   int        // user who minimized; 0 when not minimized
	Pinned          bool       // pinned comments appear first in some GitHub UIs
}

Comment is a conversation comment on an issue or PR. GitHub stores both in one table (PRs are issues internally); ParentType discriminates and IssueID holds the issue or PR database ID accordingly.

func FindIssueCommentByNodeID

func FindIssueCommentByNodeID(st *Store, nodeID string) *Comment

FindIssueCommentByNodeID resolves an issue/PR conversation comment (IC_kgDO…).

type CommitComment

type CommitComment struct {
	ID        int       `json:"id"`
	NodeID    string    `json:"node_id"`
	RepoID    int       `json:"repo_id"`
	CommitID  string    `json:"commit_id"`
	AuthorID  int       `json:"author_id"`
	Body      string    `json:"body"`
	Path      string    `json:"path,omitempty"`
	Position  *int      `json:"position,omitempty"`
	Line      *int      `json:"line,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func FindCommitCommentByNodeID

func FindCommitCommentByNodeID(st *Store, nodeID string) *CommitComment

FindCommitCommentByNodeID resolves a commit comment (CC_kgDO…).

type CommitCommentStore

type CommitCommentStore struct {
	Mu     sync.RWMutex             `json:"-"`
	ByID   map[int]*CommitComment   `json:"-"`
	ByRepo map[int][]*CommitComment `json:"-"`

	NextID  int          `json:"-"`
	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

CommitCommentStore holds commit comments keyed by id, repo, and commit.

func (*CommitCommentStore) Create

func (s *CommitCommentStore) Create(repoID int, commitID string, authorID int, body, path string, position, line *int) *CommitComment

func (*CommitCommentStore) Delete

func (s *CommitCommentStore) Delete(id int, reactions *ReactionStore) bool

Delete removes a commit comment. The comment row and its reactions delete in one transaction (STORE-001/002).

func (*CommitCommentStore) Get

func (s *CommitCommentStore) Get(id int) *CommitComment

func (*CommitCommentStore) IDsForRepo

func (s *CommitCommentStore) IDsForRepo(repoID int) map[int]bool

func (*CommitCommentStore) ListForCommit

func (s *CommitCommentStore) ListForCommit(repoID int, commitID string) []*CommitComment

ListForCommit returns one commit's comments, newest first.

func (*CommitCommentStore) ListForRepo

func (s *CommitCommentStore) ListForRepo(repoID int) []*CommitComment

ListForRepo returns a repo's commit comments, newest first.

func (*CommitCommentStore) Update

func (s *CommitCommentStore) Update(id int, body string) bool

type CommitContributionDay

type CommitContributionDay struct {
	RepoID     int
	Date       time.Time // midnight UTC of the day
	Count      int
	OccurredAt time.Time // latest commit time on that day
}

CommitContributionDay is one repository's commits by the user on one UTC day.

type CommitStatus

type CommitStatus struct {
	ID          int               `json:"id"`
	NodeID      string            `json:"node_id"`
	State       CommitStatusState `json:"state"`
	TargetURL   string            `json:"target_url"`
	Description string            `json:"description"`
	Context     string            `json:"context"`
	CreatorID   int               `json:"creator_id"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
}

type CommitStatusState

type CommitStatusState string

CommitStatusState is a commit status's state; normalizeStatusState collapses any client input to one of the four values.

const (
	CommitStatusSuccess CommitStatusState = "success"
	CommitStatusFailure CommitStatusState = "failure"
	CommitStatusPending CommitStatusState = "pending"
	CommitStatusError   CommitStatusState = "error"
)

type CommitStatusStore

type CommitStatusStore struct {
	Mu sync.RWMutex `json:"-"`

	NextID  int          `json:"-"`
	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

CommitStatusStore holds commit statuses keyed by repo+ref.

func (*CommitStatusStore) Combined

func (s *CommitStatusStore) Combined(repoKey, ref string) (state string, total int, statuses []*CommitStatus)

Combined returns the combined state plus the latest status per context.

func (*CommitStatusStore) Create

func (s *CommitStatusStore) Create(repoKey, sha string, creatorID int, state, targetURL, description, context string) *CommitStatus

func (*CommitStatusStore) List

func (s *CommitStatusStore) List(repoKey, ref string) []*CommitStatus

List returns statuses for a repo+ref newest-first.

type ConcurrencyDef

type ConcurrencyDef struct {
	Group            string `yaml:"group" json:"group"`
	CancelInProgress bool   `yaml:"cancel-in-progress" json:"cancel_in_progress"`
}

ConcurrencyDef represents workflow-level concurrency control.

type ContainerDef

type ContainerDef struct {
	Image   string            `yaml:"image"`
	Env     map[string]string `yaml:"env"`
	Ports   []interface{}     `yaml:"ports"`
	Volumes []string          `yaml:"volumes"`
	Options string            `yaml:"options"`
}

ContainerDef represents a container configuration when specified as an object.

type ContributionData

type ContributionData struct {
	UserID   int
	User     *User
	From, To time.Time
	Now      time.Time
	OrgID    int

	// Window-scoped contributions, sorted ascending by creation/submission.
	Issues       []*Issue
	PullRequests []*PullRequest
	Reviews      []*PullRequestReview
	ReviewRepoID map[int]int // review.ID -> repository ID
	Repos        []*Repo     // repositories the user created in the window

	CommitDays   []CommitContributionDay
	TotalCommits int

	// Distinct repositories the user contributed to in the window, per kind.
	ReposWithCommits map[int]bool
	ReposWithIssues  map[int]bool
	ReposWithPRs     map[int]bool
	ReposWithReviews map[int]bool

	// Comment counts for the window's issues/PRs, keyed by record ID; drive the
	// popular* selection and the excludePopular argument.
	IssueComments map[int]int
	PRComments    map[int]int

	// The user's all-time first issue/PR/repository. GraphQL's first*Contribution
	// surfaces these only when they fall inside the window.
	FirstIssue *Issue
	FirstPR    *PullRequest
	FirstRepo  *Repo

	// The window's most-commented issue and pull request.
	PopularIssue *Issue
	PopularPR    *PullRequest

	// Per-day contribution counts (commits + issues/PRs opened + reviews
	// submitted), keyed by "2006-01-02" (UTC).
	DayCounts map[ContributionDayKey]int

	// Distinct years with any all-time contribution, most recent first.
	ContributionYears []int

	HasActivityInThePast bool
}

ContributionData is everything GraphQL's ContributionsCollection needs for one user over one window. Record slices are detached snapshots.

type ContributionDayKey

type ContributionDayKey = string

ContributionDayKey is a calendar day rendered as "2006-01-02" (UTC).

func ContributionDate

func ContributionDate(t time.Time) ContributionDayKey

ContributionDate renders a time as its calendar day key.

type CopilotChatMetrics

type CopilotChatMetrics struct {
	EngagedUsers int
	Chats        int
	Insertions   int
}

type CopilotCodingAgentPermissions

type CopilotCodingAgentPermissions struct {
	OrgLogin              string `json:"org_login"`
	EnabledRepositories   string `json:"enabled_repositories"` // all | selected | none
	SelectedRepositoryIDs []int  `json:"selected_repository_ids"`
}

CopilotCodingAgentPermissions is the org policy for which repositories may use Copilot cloud agent.

type CopilotContentExclusion

type CopilotContentExclusion struct {
	OrgLogin string                   `json:"org_login"`
	Rules    map[string][]interface{} `json:"rules"`
}

CopilotContentExclusion holds an org's content exclusion rules: scope (repository "owner/name" or "*") → rules, each a path string or an ifAnyMatch/ifNoneMatch object, stored as configured.

type CopilotDailyMetrics

type CopilotDailyMetrics struct {
	Date              string
	TotalActiveUsers  int
	TotalEngagedUsers int

	CompletionsEngagedUsers int
	ChatEngagedUsers        int

	Editors   []CopilotEditorMetrics
	ChatTotal CopilotChatMetrics
}

CopilotDailyMetrics is one day of aggregated usage, shaped as the metrics endpoints report it.

func AggregateCopilotMetrics

func AggregateCopilotMetrics(records []*CopilotUsageRecord) []CopilotDailyMetrics

AggregateCopilotMetrics rolls usage rows into the daily metrics shape. Pure function of the ledger: no rows yields no days (the "no activity" response).

type CopilotEditorMetrics

type CopilotEditorMetrics struct {
	Name         string
	EngagedUsers int
	Models       []CopilotModelMetrics
}

CopilotEditorMetrics is one editor's slice of a day, broken down by model and language.

type CopilotLanguageMetrics

type CopilotLanguageMetrics struct {
	Name            string
	EngagedUsers    int
	SuggestionCount int
	AcceptanceCount int
	LinesSuggested  int
	LinesAccepted   int
}

CopilotLanguageMetrics is the leaf of the completions breakdown.

type CopilotModelMetrics

type CopilotModelMetrics struct {
	Name         string
	EngagedUsers int
	Languages    []CopilotLanguageMetrics
}

type CopilotOrgPolicy

type CopilotOrgPolicy struct {
	OrgLogin              string    `json:"org_login"`
	PlanType              string    `json:"plan_type"`
	SeatManagementSetting string    `json:"seat_management_setting"`
	PublicCodeSuggestions string    `json:"public_code_suggestions"`
	IDEChat               string    `json:"ide_chat"`
	PlatformChat          string    `json:"platform_chat"`
	CLI                   string    `json:"cli"`
	UpdatedAt             time.Time `json:"updated_at"`
}

CopilotOrgPolicy is an organization's Copilot subscription: plan, seat handout, and which features members may use.

func DefaultCopilotOrgPolicy

func DefaultCopilotOrgPolicy(orgLogin string) *CopilotOrgPolicy

DefaultCopilotOrgPolicy is the provisioning posture: Business, seats assigned individually, every feature on.

type CopilotOrgPolicyUpdate

type CopilotOrgPolicyUpdate struct {
	PlanType              *string
	SeatManagementSetting *string
	PublicCodeSuggestions *string
	IDEChat               *string
	PlatformChat          *string
	CLI                   *string
}

CopilotOrgPolicyUpdate is a sparse patch; nil fields are left unchanged.

type CopilotPolicyStore

type CopilotPolicyStore struct {
	Mu      sync.RWMutex `json:"-"`
	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

func NewCopilotPolicyStore

func NewCopilotPolicyStore() *CopilotPolicyStore

func (*CopilotPolicyStore) GetCopilotOrgPolicy

func (cs *CopilotPolicyStore) GetCopilotOrgPolicy(orgLogin string) *CopilotOrgPolicy

GetCopilotOrgPolicy returns the org's Copilot policy; an unconfigured org reads as the default posture and nothing is materialized.

func (*CopilotPolicyStore) GetCopilotSeatActivity

func (cs *CopilotPolicyStore) GetCopilotSeatActivity(orgLogin string, userID int) *CopilotSeatActivity

GetCopilotSeatActivity returns when the member last used Copilot, or nil.

func (*CopilotPolicyStore) ListCopilotUsage

func (cs *CopilotPolicyStore) ListCopilotUsage(orgLogin, teamSlug, since, until string) []*CopilotUsageRecord

ListCopilotUsage returns usage rows in the inclusive day window [since, until] (either bound may be empty), optionally narrowed to one team.

func (*CopilotPolicyStore) RecordCopilotUsage

func (cs *CopilotPolicyStore) RecordCopilotUsage(record *CopilotUsageRecord, at time.Time) (*CopilotUsageRecord, error)

RecordCopilotUsage files one day's usage and advances the seat's last-activity marker. Both commit together, so metrics and seat details can never disagree about whether a member has used Copilot.

func (*CopilotPolicyStore) SetCopilotOrgPolicy

func (cs *CopilotPolicyStore) SetCopilotOrgPolicy(orgLogin string, patch CopilotOrgPolicyUpdate, now time.Time) (*CopilotOrgPolicy, error)

SetCopilotOrgPolicy applies a sparse patch, rejecting any value GitHub does not define for the field.

type CopilotSeat

type CopilotSeat struct {
	OrgLogin                string    `json:"org_login"`
	UserID                  int       `json:"user_id"`
	AssigningTeamSlug       string    `json:"assigning_team_slug"`
	PendingCancellationDate string    `json:"pending_cancellation_date"`
	CreatedAt               time.Time `json:"created_at"`
	UpdatedAt               time.Time `json:"updated_at"`
}

CopilotSeat is one Copilot Business seat, assigned directly (AssigningTeamSlug empty) or through a team. Cancellation defers to the end of the billing cycle: PendingCancellationDate is the YYYY-MM-DD expiry, and expired seats are dropped lazily on access.

type CopilotSeatActivity

type CopilotSeatActivity struct {
	OrgLogin       string    `json:"org_login"`
	UserID         int       `json:"user_id"`
	LastActivityAt time.Time `json:"last_activity_at"`
	LastEditor     string    `json:"last_activity_editor"`
}

CopilotSeatActivity is when a seat was last used, and from where. Separate from the seat because usage writes it, not seat administration.

type CopilotSpace

type CopilotSpace struct {
	ID                  int64                       `json:"id"`
	Number              int                         `json:"number"`
	OwnerType           string                      `json:"owner_type"` // "User" | "Organization"
	OwnerLogin          string                      `json:"owner_login"`
	Name                string                      `json:"name"`
	Description         string                      `json:"description"`
	GeneralInstructions string                      `json:"general_instructions"`
	BaseRole            string                      `json:"base_role"`
	CreatorID           int                         `json:"creator_id"`
	Collaborators       []*CopilotSpaceCollaborator `json:"collaborators"`
	Resources           []*CopilotSpaceResource     `json:"resources"`
	NextResourceID      int                         `json:"next_resource_id"`
	CreatedAt           time.Time                   `json:"created_at"`
	UpdatedAt           time.Time                   `json:"updated_at"`
}

CopilotSpace is one space. Number identifies it within its owner; ID is global.

type CopilotSpaceCollaborator

type CopilotSpaceCollaborator struct {
	ActorType string `json:"actor_type"` // "User" | "Team"
	UserID    int    `json:"user_id"`    // set when ActorType == "User"
	TeamID    int    `json:"team_id"`    // set when ActorType == "Team"
	Role      string `json:"role"`       // reader | writer | admin
}

CopilotSpaceCollaborator grants a user or a team a role on a space.

type CopilotSpaceResource

type CopilotSpaceResource struct {
	ID           int                    `json:"id"`
	ResourceType string                 `json:"resource_type"`
	Metadata     map[string]interface{} `json:"metadata"`
	CreatedAt    time.Time              `json:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at"`
}

type CopilotUsageRecord

type CopilotUsageRecord struct {
	ID              int    `json:"id"`
	OrgLogin        string `json:"org_login"`
	TeamSlug        string `json:"team_slug,omitempty"`
	UserID          int    `json:"user_id"`
	UserLogin       string `json:"user_login"`
	Day             string `json:"day"` // YYYY-MM-DD
	Editor          string `json:"editor"`
	Model           string `json:"model,omitempty"`
	Language        string `json:"language,omitempty"`
	RepoFullName    string `json:"repo_full_name,omitempty"`
	Suggestions     int    `json:"suggestions"`
	Acceptances     int    `json:"acceptances"`
	LinesSuggested  int    `json:"lines_suggested"`
	LinesAccepted   int    `json:"lines_accepted"`
	ChatTurns       int    `json:"chat_turns"`
	ChatAcceptances int    `json:"chat_acceptances"`
}

CopilotUsageRecord is one member's Copilot usage for one day/editor/language. The metrics endpoints are pure aggregations of these rows.

type CreateAdvisoryReq

type CreateAdvisoryReq struct {
	Summary     string `json:"summary"`
	Description string `json:"description"`
	Severity    string `json:"severity"`
	// CVEID lets a reporter who already holds a CVE name it at creation.
	CVEID     string  `json:"cve_id"`
	CVSSScore float64 `json:"cvss_score"`
	// CVSSVector must be spelt cvss_vector_string (the member
	// repository-advisory-create/-update use); cvss_vector silently discarded
	// every SDK's vector.
	CVSSVector string   `json:"cvss_vector_string"`
	CWEs       []string `json:"cwe_ids"`
	State      string   `json:"state"`
	// StartPrivateFork requests the temporary private fork for fixing.
	StartPrivateFork       bool   `json:"start_private_fork"`
	VulnerableVersionRange string `json:"vulnerable_version_range"`
	Vulnerabilities        []struct {
		Package struct {
			Ecosystem string `json:"ecosystem"`
			Name      string `json:"name"`
		} `json:"package"`
		VulnerableVersionRange string   `json:"vulnerable_version_range"`
		FirstPatchedVersion    string   `json:"first_patched_version"`
		PatchedVersions        string   `json:"patched_versions"`
		VulnerableFunctions    []string `json:"vulnerable_functions"`
	} `json:"vulnerabilities"`
	Credits            []SecurityAdvisoryCredit `json:"credits"`
	CollaboratingUsers []string                 `json:"collaborating_users"`
	CollaboratingTeams []string                 `json:"collaborating_teams"`
}

CreateAdvisoryReq is the request body for creating a security advisory.

type CreatePersonalAccessTokenWebRequest

type CreatePersonalAccessTokenWebRequest struct {
	Name                string            `json:"name"`
	ResourceOwner       string            `json:"resource_owner"`
	RepositorySelection string            `json:"repository_selection"`
	RepositoryIDs       []int             `json:"repository_ids"`
	Permissions         OrgPATPermissions `json:"permissions"`
	ExpiresAt           *time.Time        `json:"expires_at"`
	Reason              *string           `json:"reason"`
}

type CustomProperty

type CustomProperty struct {
	PropertyName          string      `json:"property_name"`
	ValueType             string      `json:"value_type"`
	Required              bool        `json:"required"`
	DefaultValue          interface{} `json:"default_value"`
	Description           *string     `json:"description"`
	AllowedValues         []string    `json:"allowed_values"`
	ValuesEditableBy      string      `json:"values_editable_by"`
	RequireExplicitValues bool        `json:"require_explicit_values"`
	// Regex is a GraphQL-only member (createRepositoryCustomProperty); GitHub's
	// REST schema omits it, so the REST renderers leave it out.
	Regex *string `json:"regex,omitempty"`
}

CustomProperty is an organization custom property definition.

type CustomPropertyValuePayload

type CustomPropertyValuePayload struct {
	PropertyName string      `json:"property_name"`
	Value        interface{} `json:"value"`
}

type DeliveryRequest

type DeliveryRequest struct {
	Headers map[string]string `json:"headers"`
	Payload interface{}       `json:"payload"`
}

DeliveryRequest holds the request details of a webhook delivery.

type DeliveryResponse

type DeliveryResponse struct {
	StatusCode int               `json:"status_code"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
}

DeliveryResponse holds the response details of a webhook delivery.

type DependabotAlert

type DependabotAlert struct {
	ID                     int                  `json:"id"`
	NodeID                 string               `json:"node_id"`
	Number                 int                  `json:"number"`
	RepoKey                string               `json:"repo_key"`
	PackageName            string               `json:"package_name"`
	PackageEcosystem       string               `json:"package_ecosystem"`
	ManifestPath           string               `json:"manifest_path"`
	VulnerabilityID        string               `json:"vulnerability_id"` // GHSA id
	CVEID                  string               `json:"cve_id"`
	Severity               string               `json:"severity"`
	State                  DependabotAlertState `json:"state"`
	DismissedReason        string               `json:"dismissed_reason"`
	DismissedComment       string               `json:"dismissed_comment"`
	DismissedByLogin       string               `json:"dismissed_by_login"`
	DismissedAt            *time.Time           `json:"dismissed_at"`
	FixedAt                *time.Time           `json:"fixed_at"`
	AutoDismissedAt        *time.Time           `json:"auto_dismissed_at"`
	Summary                string               `json:"summary"`
	Description            string               `json:"description"`
	VulnerableVersionRange string               `json:"vulnerable_version_range"`
	FirstPatchedVersion    string               `json:"first_patched_version"`
	CreatedAt              time.Time            `json:"created_at"`
	UpdatedAt              time.Time            `json:"updated_at"`
}

type DependabotAlertState

type DependabotAlertState string

DependabotAlertState is a Dependabot alert's lifecycle state. Only open ⇄ dismissed transitions are user-driven; fixed and auto_dismissed are platform-produced.

const (
	DependabotStateOpen          DependabotAlertState = "open"
	DependabotStateDismissed     DependabotAlertState = "dismissed"
	DependabotStateFixed         DependabotAlertState = "fixed"
	DependabotStateAutoDismissed DependabotAlertState = "auto_dismissed"
)

type DependabotDefaultLevel

type DependabotDefaultLevel string

DependabotDefaultLevel is an enterprise's Dependabot default repository access level. Empty means "never set" (serialized as null).

const (
	DependabotDefaultLevelPublic   DependabotDefaultLevel = "public"
	DependabotDefaultLevelInternal DependabotDefaultLevel = "internal"
)

type DependabotOrgSecret

type DependabotOrgSecret struct {
	DependabotSecret
	Visibility      string `json:"visibility"`
	SelectedRepoIDs []int  `json:"selected_repository_ids,omitempty"`
}

DependabotOrgSecret is an org-level Dependabot secret with visibility scoping.

func (*DependabotOrgSecret) ItemVisibility

func (sec *DependabotOrgSecret) ItemVisibility() string

func (*DependabotOrgSecret) SelectedIDs

func (sec *DependabotOrgSecret) SelectedIDs() []int

func (*DependabotOrgSecret) SetSelectedIDs

func (sec *DependabotOrgSecret) SetSelectedIDs(ids []int)

func (*DependabotOrgSecret) TouchUpdated

func (sec *DependabotOrgSecret) TouchUpdated(now time.Time)

type DependabotSecret

type DependabotSecret struct {
	Name      string    `json:"name"`
	Value     string    `json:"value"` // encrypted (base64 sealed box)
	KeyID     string    `json:"key_id"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

DependabotSecret is a repository-level Dependabot secret. Value is the client's libsodium sealed-box ciphertext, never decrypted here.

type DependabotUserSecret

type DependabotUserSecret struct {
	DependabotSecret
}

type DependencySnapshot

type DependencySnapshot struct {
	ID        int                          `json:"id"`
	RepoID    int                          `json:"repo_id"`
	Version   int                          `json:"version"`
	Ref       string                       `json:"ref"`
	Sha       string                       `json:"sha"`
	Job       SnapshotJob                  `json:"job"`
	Detector  SnapshotDetector             `json:"detector"`
	Scanned   string                       `json:"scanned"`
	Manifests map[string]*SnapshotManifest `json:"manifests,omitempty"`
	// Result is SUCCESS, ACCEPTED, or INVALID. An INVALID snapshot is stored
	// but never contributes to the repository's dependency set.
	Result    string    `json:"result"`
	CreatedAt time.Time `json:"created_at"`
}

DependencySnapshot is a submitted dependency snapshot, mirroring the dependency submission API's snapshot object.

type Deployment

type Deployment struct {
	ID            int                    `json:"id"`
	NodeID        string                 `json:"node_id"`
	URL           string                 `json:"url"`
	Sha           string                 `json:"sha"`
	Ref           string                 `json:"ref"`
	Task          string                 `json:"task"`
	Payload       map[string]interface{} `json:"payload"`
	OriginalEnv   string                 `json:"original_environment"`
	Environment   string                 `json:"environment"`
	Description   string                 `json:"description"`
	CreatorID     int                    `json:"creator_id"`
	RepoID        int                    `json:"repo_id"`
	AutoMerge     bool                   `json:"auto_merge"`
	ProductionEnv bool                   `json:"production_environment"`
	TransientEnv  bool                   `json:"transient_environment"`
	CreatedAt     time.Time              `json:"created_at"`
	UpdatedAt     time.Time              `json:"updated_at"`
	Statuses      []*DeploymentStatus    `json:"-"`
}

Deployment json tags shape the persisted row, not client responses (those go through deploymentToJSON). Statuses stays json:"-": statuses persist in their own bucket and the loader relinks them via DeploymentID.

type DeploymentBranchPolicy

type DeploymentBranchPolicy struct {
	ProtectedBranches    bool `json:"protected_branches"`
	CustomBranchPolicies bool `json:"custom_branch_policies"`
}

type DeploymentBranchPolicyRule

type DeploymentBranchPolicyRule struct {
	ID     int                        `json:"id"`
	NodeID string                     `json:"node_id"`
	Name   string                     `json:"name"`
	Type   DeploymentBranchPolicyType `json:"type"`
}

DeploymentBranchPolicyRule is one branch/tag pattern allowed to deploy to an environment.

type DeploymentBranchPolicyType

type DeploymentBranchPolicyType string

DeploymentBranchPolicyType is the kind of a deployment branch/tag policy rule.

type DeploymentStatus

type DeploymentStatus struct {
	ID             int                   `json:"id"`
	NodeID         string                `json:"node_id"`
	State          DeploymentStatusState `json:"state"`
	CreatorID      int                   `json:"creator_id"`
	DeploymentID   int                   `json:"deployment_id"`
	Description    string                `json:"description"`
	Environment    string                `json:"environment"`
	TargetURL      string                `json:"target_url"`
	LogURL         string                `json:"log_url"`
	EnvironmentURL string                `json:"environment_url"`
	AutoInactive   bool                  `json:"auto_inactive"`
	CreatedAt      time.Time             `json:"created_at"`
	UpdatedAt      time.Time             `json:"updated_at"`
}

type DeploymentStatusState

type DeploymentStatusState string

DeploymentStatusState is one of the seven states GitHub emits.

const (
	DeploymentStateError      DeploymentStatusState = "error"
	DeploymentStateFailure    DeploymentStatusState = "failure"
	DeploymentStateInactive   DeploymentStatusState = "inactive"
	DeploymentStateInProgress DeploymentStatusState = "in_progress"
	DeploymentStateQueued     DeploymentStatusState = "queued"
	DeploymentStatePending    DeploymentStatusState = "pending"
	DeploymentStateSuccess    DeploymentStatusState = "success"
)

type DeploymentStore

type DeploymentStore struct {
	Mu sync.RWMutex `json:"-"`

	ByRepo   map[int][]*Deployment     `json:"-"`
	Statuses map[int]*DeploymentStatus `json:"-"`

	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

func (*DeploymentStore) AddStatus

func (ds *DeploymentStore) AddStatus(deploymentID, creatorID int, state, description, targetURL, logURL, envURL, env string, autoInactive bool) (*DeploymentStatus, []autoInactiveDeployment)

func (*DeploymentStore) CreateDeployment

func (ds *DeploymentStore) CreateDeployment(repoID, creatorID int, ref, sha, task, env, description string, payload map[string]interface{}, productionEnv, transientEnv bool) *Deployment

func (*DeploymentStore) DeleteDeployment

func (ds *DeploymentStore) DeleteDeployment(id int) bool

func (*DeploymentStore) DeleteEnvironment

func (ds *DeploymentStore) DeleteEnvironment(repoID int, name string) bool

func (*DeploymentStore) DeleteRepo

func (ds *DeploymentStore) DeleteRepo(repoID int) []int

func (*DeploymentStore) DeleteRepoBatch

func (ds *DeploymentStore) DeleteRepoBatch(repoID int, batch *PersistBatch) []int

func (*DeploymentStore) GetDeployment

func (ds *DeploymentStore) GetDeployment(id int) *Deployment

func (*DeploymentStore) GetDeploymentByNodeID

func (ds *DeploymentStore) GetDeploymentByNodeID(nodeID string) *Deployment

GetDeploymentByNodeID returns a detached snapshot (STORE-021), or nil.

func (*DeploymentStore) GetEnvironment

func (ds *DeploymentStore) GetEnvironment(repoID int, name string) *Environment

func (*DeploymentStore) GetEnvironmentByID

func (ds *DeploymentStore) GetEnvironmentByID(id int) *Environment

func (*DeploymentStore) GetEnvironmentByNodeID

func (ds *DeploymentStore) GetEnvironmentByNodeID(nodeID string) *Environment

GetEnvironmentByNodeID returns a detached snapshot (STORE-021), or nil.

func (*DeploymentStore) GetPinnedEnvironment

func (ds *DeploymentStore) GetPinnedEnvironment(repoID, envID int) *PinnedEnvironment

GetPinnedEnvironment returns a detached snapshot (STORE-021) of the pin, or nil when the environment is not pinned.

func (*DeploymentStore) GetStatus

func (ds *DeploymentStore) GetStatus(id int) *DeploymentStatus

func (*DeploymentStore) ListDeployments

func (ds *DeploymentStore) ListDeployments(repoID int) []*Deployment

func (*DeploymentStore) ListEnvironments

func (ds *DeploymentStore) ListEnvironments(repoID int) []*Environment

func (*DeploymentStore) ListPinnedEnvironments

func (ds *DeploymentStore) ListPinnedEnvironments(repoID int) []*PinnedEnvironment

ListPinnedEnvironments returns the repository's pins as detached snapshots (STORE-021) in position order.

func (*DeploymentStore) ListStatuses

func (ds *DeploymentStore) ListStatuses(deploymentID int) []*DeploymentStatus

func (*DeploymentStore) PinEnvironment

func (ds *DeploymentStore) PinEnvironment(repoID, envID int, now time.Time) *PinnedEnvironment

PinEnvironment pins an environment at the end of its repository's pinned list and returns a detached snapshot (STORE-021). Idempotent: an already-pinned environment returns its existing pin unchanged.

func (*DeploymentStore) ReorderPinnedEnvironment

func (ds *DeploymentStore) ReorderPinnedEnvironment(repoID, envID, position int, now time.Time) bool

ReorderPinnedEnvironment moves a pinned environment to the 1-based position, shifting neighbours; out-of-range positions clamp. Reports whether the environment was pinned.

func (*DeploymentStore) SetEnvironmentBranchPolicyConfig

func (ds *DeploymentStore) SetEnvironmentBranchPolicyConfig(repoID int, name string, policy *DeploymentBranchPolicy)

SetEnvironmentBranchPolicyConfig sets an environment's deployment branch policy. nil clears it (all branches may deploy), matching GitHub's full-replace.

func (*DeploymentStore) SetEnvironmentPreventSelfReview

func (ds *DeploymentStore) SetEnvironmentPreventSelfReview(repoID int, name string, prevent bool)

SetEnvironmentPreventSelfReview flips the environment's self-review refusal.

func (*DeploymentStore) SetEnvironmentProtection

func (ds *DeploymentStore) SetEnvironmentProtection(repoID int, name string, waitTimer *int, reviewers []map[string]interface{})

SetEnvironmentProtection updates an environment's reviewer and wait-timer config.

func (*DeploymentStore) UnpinEnvironment

func (ds *DeploymentStore) UnpinEnvironment(repoID, envID int, now time.Time) bool

UnpinEnvironment removes an environment's pin and closes the position gap. Reports whether a pin existed.

func (*DeploymentStore) UpsertEnvironment

func (ds *DeploymentStore) UpsertEnvironment(repoID int, name string) *Environment

type DeviceCode

type DeviceCode struct {
	Code          string
	UserCode      string
	ClientID      string
	Scopes        string
	Token         string
	UserID        int
	AppID         int
	OAuthClientID string
	ApprovedAt    time.Time
	ExpiresAt     time.Time
}

DeviceCode represents a pending device authorization flow.

type Discussion

type Discussion struct {
	ID           int        `json:"id"`
	NodeID       string     `json:"node_id"`
	RepoID       int        `json:"repo_id"`
	CategoryID   int        `json:"category_id"`
	Number       int        `json:"number"`
	Title        string     `json:"title"`
	Body         string     `json:"body"`
	AuthorID     int        `json:"author_id"`
	Locked       bool       `json:"locked"`
	LockedReason string     `json:"locked_reason"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	LastEditedAt *time.Time `json:"last_edited_at"`
	PublishedAt  *time.Time `json:"published_at"`
	Deleted      bool       `json:"deleted"`
	UpvoterIDs   []int      `json:"upvoter_ids"`
	// StateReason is github's close reason: RESOLVED, OUTDATED, DUPLICATE, REOPENED.
	Closed      bool       `json:"closed"`
	ClosedAt    *time.Time `json:"closed_at"`
	StateReason string     `json:"state_reason"`
}

Discussion is a repository discussion.

func FindDiscussionByNodeID

func FindDiscussionByNodeID(st *Store, nodeID string) *Discussion

type DiscussionCategory

type DiscussionCategory struct {
	ID           int       `json:"id"`
	NodeID       string    `json:"node_id"`
	RepoID       int       `json:"repo_id"`
	Name         string    `json:"name"`
	Emoji        string    `json:"emoji"`
	Description  string    `json:"description"`
	IsAnswerable bool      `json:"is_answerable"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

DiscussionCategory is a repository discussion category.

func FindDiscussionCategoryByNodeID

func FindDiscussionCategoryByNodeID(st *Store, nodeID string) *DiscussionCategory

type DiscussionComment

type DiscussionComment struct {
	ID           int        `json:"id"`
	NodeID       string     `json:"node_id"`
	DiscussionID int        `json:"discussion_id"`
	AuthorID     int        `json:"author_id"`
	Body         string     `json:"body"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	LastEditedAt *time.Time `json:"last_edited_at"`
	IsAnswer     bool       `json:"is_answer"`
	ParentID     int        `json:"parent_id"`
	Deleted      bool       `json:"deleted"`
	UpvoterIDs   []int      `json:"upvoter_ids"`
}

DiscussionComment is a comment on a discussion (top-level or reply).

func FindDiscussionCommentByNodeID

func FindDiscussionCommentByNodeID(st *Store, nodeID string) *DiscussionComment

type DiscussionPoll

type DiscussionPoll struct {
	ID           int    `json:"id"`
	NodeID       string `json:"node_id"`
	DiscussionID int    `json:"discussion_id"`
	Question     string `json:"question"`
	// Options in authored order; vote-count order is derived at read time.
	Options     []*DiscussionPollOption `json:"options"`
	VotesByUser map[int]int             `json:"votes_by_user"`
}

DiscussionPoll is a discussion's optional poll. VotesByUser keys on user id, making github's one-vote-per-poll rule structural.

type DiscussionPollOption

type DiscussionPollOption struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`
	PollID int    `json:"poll_id"`
	Option string `json:"option"`
}

DiscussionPollOption is one answer in a discussion poll.

type Enterprise

type Enterprise struct {
	ID                   int              `json:"id"`
	NodeID               string           `json:"node_id"`
	Slug                 string           `json:"slug"`
	Name                 string           `json:"name"`
	Description          string           `json:"description"`
	Location             string           `json:"location"`
	WebsiteURL           string           `json:"website_url"`
	AvatarURL            string           `json:"avatar_url"`
	BillingEmail         string           `json:"billing_email"`
	SecurityContactEmail string           `json:"security_contact_email"`
	Readme               string           `json:"readme"`
	Policy               EnterprisePolicy `json:"policy"`
	// IdentityProvider is nil until setEnterpriseIdentityProvider binds one.
	IdentityProvider *EnterpriseSAMLIdentityProvider `json:"identity_provider,omitempty"`
	// MigratorLogins is the set of user logins granted the migrator role on
	// every organization in the enterprise.
	MigratorLogins []string `json:"migrator_logins,omitempty"`
	// VerifiedDomains are the enterprise's verified domains, stored lower-cased
	// and without a leading "@". The notification-delivery restriction is
	// expressed against them.
	VerifiedDomains []string `json:"verified_domains,omitempty"`
	// Provisioned billing entitlements; usage is measured from actual
	// repositories and packages rather than stored.
	BillingBandwidthQuotaGB float64   `json:"billing_bandwidth_quota_gb"`
	BillingStorageQuotaGB   float64   `json:"billing_storage_quota_gb"`
	BillingTotalLicenses    int       `json:"billing_total_licenses"`
	CreatedAt               time.Time `json:"created_at"`
	UpdatedAt               time.Time `json:"updated_at"`
}

Enterprise is an enterprise account.

func FindEnterpriseByNodeID

func FindEnterpriseByNodeID(st *Store, nodeID string) *Enterprise

FindEnterpriseByNodeID resolves an enterprise global id to the LIVE row — the write path's lookup.

type EnterpriseAnnouncement

type EnterpriseAnnouncement struct {
	Announcement    string  `json:"announcement"`
	ExpiresAt       *string `json:"expires_at"`
	UserDismissible bool    `json:"user_dismissible"`
}

EnterpriseAnnouncement is the enterprise-wide banner. ExpiresAt stays a string (GitHub returns ISO-8601, and null has distinct semantics).

type EnterpriseAuditLogStream

type EnterpriseAuditLogStream struct {
	ID             int                    `json:"id"`
	StreamType     string                 `json:"stream_type"`
	StreamDetails  string                 `json:"stream_details"`
	Enabled        bool                   `json:"enabled"`
	VendorSpecific map[string]interface{} `json:"vendor_specific,omitempty"`
	CreatedAt      time.Time              `json:"created_at"`
	UpdatedAt      time.Time              `json:"updated_at"`
	PausedAt       *time.Time             `json:"paused_at"`
}

EnterpriseAuditLogStream is a durable audit-log delivery configuration. VendorSpecific holds opaque connection settings, never rendered to clients.

type EnterpriseBillingReport

type EnterpriseBillingReport struct {
	ID           string    `json:"id"`
	ReportType   string    `json:"report_type"`
	StartDate    string    `json:"start_date"`
	EndDate      string    `json:"end_date"`
	Status       string    `json:"status"`
	DownloadURLs []string  `json:"download_urls,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
	Actor        string    `json:"actor"`
}

EnterpriseBillingReport records one asynchronous usage export request. Pending reports complete when read, giving a deterministic lifecycle without a background task.

type EnterpriseCodeSecurity

type EnterpriseCodeSecurity struct {
	AdvancedSecurityEnabledForNewRepositories                  bool    `json:"advanced_security_enabled_for_new_repositories"`
	AdvancedSecurityEnabledNewUserNamespaceRepos               bool    `json:"advanced_security_enabled_new_user_namespace_repos"`
	DependabotAlertsEnabledForNewRepositories                  bool    `json:"dependabot_alerts_enabled_for_new_repositories"`
	SecretScanningEnabledForNewRepositories                    bool    `json:"secret_scanning_enabled_for_new_repositories"`
	SecretScanningPushProtectionEnabledForNewRepositories      bool    `json:"secret_scanning_push_protection_enabled_for_new_repositories"`
	SecretScanningPushProtectionCustomLink                     *string `json:"secret_scanning_push_protection_custom_link"`
	SecretScanningNonProviderPatternsEnabledForNewRepositories bool    `json:"secret_scanning_non_provider_patterns_enabled_for_new_repositories"`
}

EnterpriseCodeSecurity is the legacy enterprise security policy GitHub keeps alongside code-security configurations.

type EnterpriseCodeSecurityAttachment

type EnterpriseCodeSecurityAttachment struct {
	RepoID   int `json:"repo_id"`
	ConfigID int `json:"config_id"`
}

EnterpriseCodeSecurityAttachment persists one repo's config attachment. A repository has at most one attached configuration.

type EnterpriseCodeSecurityConfiguration

type EnterpriseCodeSecurityConfiguration struct {
	ID                                    int       `json:"id"`
	Name                                  string    `json:"name"`
	Description                           string    `json:"description"`
	AdvancedSecurity                      string    `json:"advanced_security"`
	DependencyGraph                       string    `json:"dependency_graph"`
	DependencyGraphAutosubmitAction       string    `json:"dependency_graph_autosubmit_action"`
	DependencyGraphAutosubmitLabeled      bool      `json:"dependency_graph_autosubmit_labeled_runners"`
	DependabotAlerts                      string    `json:"dependabot_alerts"`
	DependabotSecurityUpdates             string    `json:"dependabot_security_updates"`
	CodeScanningAllowAdvanced             *bool     `json:"code_scanning_allow_advanced"`
	CodeScanningDefaultSetup              string    `json:"code_scanning_default_setup"`
	CodeScanningRunnerType                *string   `json:"code_scanning_runner_type"`
	CodeScanningRunnerLabel               *string   `json:"code_scanning_runner_label"`
	CodeScanningDelegatedAlertDismissal   string    `json:"code_scanning_delegated_alert_dismissal"`
	SecretScanning                        string    `json:"secret_scanning"`
	SecretScanningPushProtection          string    `json:"secret_scanning_push_protection"`
	SecretScanningValidityChecks          string    `json:"secret_scanning_validity_checks"`
	SecretScanningNonProviderPatterns     string    `json:"secret_scanning_non_provider_patterns"`
	SecretScanningGenericSecrets          string    `json:"secret_scanning_generic_secrets"`
	SecretScanningDelegatedAlertDismissal string    `json:"secret_scanning_delegated_alert_dismissal"`
	SecretScanningExtendedMetadata        string    `json:"secret_scanning_extended_metadata"`
	PrivateVulnerabilityReporting         string    `json:"private_vulnerability_reporting"`
	Enforcement                           string    `json:"enforcement"`
	DefaultForNewRepos                    string    `json:"default_for_new_repos"` // "none" unless set via the defaults endpoint
	CreatedAt                             time.Time `json:"created_at"`
	UpdatedAt                             time.Time `json:"updated_at"`
}

EnterpriseCodeSecurityConfiguration mirrors GitHub's code-security-configuration schema with target_type "enterprise". Feature fields hold enabled/disabled/not_set enum values.

type EnterpriseCostCenter

type EnterpriseCostCenter struct {
	ID                  string                         `json:"id"`
	Name                string                         `json:"name"`
	State               string                         `json:"state"`
	Resources           []EnterpriseCostCenterResource `json:"resources"`
	AICreditPoolEnabled bool                           `json:"ai_credit_pool_enabled"`
	CreatedAt           time.Time                      `json:"created_at"`
	UpdatedAt           time.Time                      `json:"updated_at"`
}

EnterpriseCostCenter is a durable enhanced-billing cost allocation. A resource belongs to at most one active cost center; adding it elsewhere reassigns it.

type EnterpriseCostCenterResource

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

type EnterpriseInnerSourceSyncJob

type EnterpriseInnerSourceSyncJob struct {
	ID        string                            `json:"id"`
	Status    string                            `json:"status"`
	Processed int                               `json:"processed"`
	Created   int                               `json:"created"`
	Updated   int                               `json:"updated"`
	Withdrawn int                               `json:"withdrawn"`
	Errors    int                               `json:"errors"`
	Results   []EnterpriseInnerSourceSyncResult `json:"results"`
	CreatedAt time.Time                         `json:"created_at"`
	UpdatedAt time.Time                         `json:"updated_at"`
}

type EnterpriseInnerSourceSyncResult

type EnterpriseInnerSourceSyncResult struct {
	ExternalID string `json:"external_id"`
	Status     string `json:"status"`
	GHSAID     string `json:"ghsa_id,omitempty"`
}

type EnterpriseInvitation

type EnterpriseInvitation struct {
	ID           int    `json:"id"`
	NodeID       string `json:"node_id"`
	EnterpriseID int    `json:"enterprise_id"`
	// Kind is "admin" or "member".
	Kind string `json:"kind"`
	// InviterID is the enterprise owner who issued the invitation.
	InviterID int `json:"inviter_id"`
	// InviteeID is 0 when the invitation was addressed to an email address
	// that belongs to no account on this instance.
	InviteeID int    `json:"invitee_id"`
	Email     string `json:"email"`
	// Role is meaningful for Kind "admin" only.
	Role      EnterpriseRole `json:"role"`
	CreatedAt time.Time      `json:"created_at"`
}

EnterpriseInvitation is an outstanding invitation to an enterprise. Kind distinguishes the admin invitation (carries a role) from the member one (does not); one record type keeps their lifecycles aligned.

func FindEnterpriseInvitationByNodeID

func FindEnterpriseInvitationByNodeID(st *Store, nodeID string) *EnterpriseInvitation

FindEnterpriseInvitationByNodeID resolves an invitation global id to the LIVE row.

type EnterpriseMembership

type EnterpriseMembership struct {
	ID           int            `json:"id"`
	EnterpriseID int            `json:"enterprise_id"`
	UserID       int            `json:"user_id"`
	Role         EnterpriseRole `json:"role"`
	// SupportEntitlement is set by addEnterpriseSupportEntitlement.
	SupportEntitlement bool      `json:"support_entitlement"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
}

EnterpriseMembership binds a user to an enterprise with a role.

type EnterpriseOrganization

type EnterpriseOrganization struct {
	EnterpriseID int       `json:"enterprise_id"`
	OrgID        int       `json:"org_id"`
	CreatedAt    time.Time `json:"created_at"`
}

EnterpriseOrganization binds an organization to the enterprise that owns it. An organization belongs to at most one enterprise.

type EnterprisePolicy

type EnterprisePolicy struct {
	// AllowPrivateRepositoryForking governs whether private/internal repos may be
	// forked at all; PolicyValue narrows where a permitted fork may land.
	AllowPrivateRepositoryForking            string `json:"allow_private_repository_forking"`
	AllowPrivateRepositoryForkingPolicyValue string `json:"allow_private_repository_forking_policy_value"`
	// DefaultRepositoryPermission is the ceiling on the base permission an
	// organization may grant its members.
	DefaultRepositoryPermission          string `json:"default_repository_permission"`
	MembersCanChangeRepositoryVisibility string `json:"members_can_change_repository_visibility"`
	// Per-visibility refinement GitHub applies when MembersCanCreateRepositories
	// is neither DISABLED nor NO_POLICY.
	MembersCanCreateRepositories         string `json:"members_can_create_repositories"`
	MembersCanCreatePublicRepositories   *bool  `json:"members_can_create_public_repositories"`
	MembersCanCreatePrivateRepositories  *bool  `json:"members_can_create_private_repositories"`
	MembersCanCreateInternalRepositories *bool  `json:"members_can_create_internal_repositories"`
	MembersCanDeleteIssues               string `json:"members_can_delete_issues"`
	MembersCanDeleteRepositories         string `json:"members_can_delete_repositories"`
	MembersCanInviteCollaborators        string `json:"members_can_invite_collaborators"`
	MembersCanMakePurchases              string `json:"members_can_make_purchases"`
	MembersCanUpdateProtectedBranches    string `json:"members_can_update_protected_branches"`
	MembersCanViewDependencyInsights     string `json:"members_can_view_dependency_insights"`
	OrganizationProjects                 string `json:"organization_projects"`
	RepositoryProjects                   string `json:"repository_projects"`
	RepositoryDeployKey                  string `json:"repository_deploy_key"`
	TeamDiscussions                      string `json:"team_discussions"`
	TwoFactorRequired                    string `json:"two_factor_required"`
	// TwoFactorDisallowedMethods bans insecure second factors (SMS).
	TwoFactorDisallowedMethods string `json:"two_factor_disallowed_methods"`
	// ProofOfPresenceRequired demands a fresh proof of presence before a
	// sensitive action.
	ProofOfPresenceRequired string `json:"proof_of_presence_required"`
	// NotificationDeliveryRestrictionEnabled restricts notification delivery to
	// the enterprise's verified domains.
	NotificationDeliveryRestrictionEnabled string `json:"notification_delivery_restriction_enabled"`
	IPAllowListEnabled                     string `json:"ip_allow_list_enabled"`
	IPAllowListForInstalledAppsEnabled     string `json:"ip_allow_list_for_installed_apps_enabled"`
	IPAllowListUserLevelEnforcementEnabled string `json:"ip_allow_list_user_level_enforcement_enabled"`
	// Report an unfinished enterprise-wide roll-out. bleephub applies a policy to
	// every org in one batch write, so both are false outside a mid-apply window.
	IsUpdatingDefaultRepositoryPermission bool `json:"is_updating_default_repository_permission"`
	IsUpdatingTwoFactorRequirement        bool `json:"is_updating_two_factor_requirement"`
}

EnterprisePolicy is the enterprise-wide policy set. Each field is stored with GitHub's enum spelling and read by every consumer — REST handlers, GraphQL resolvers and the server-package enforcement predicates.

type EnterpriseRole

type EnterpriseRole string

EnterpriseRole is a principal's standing in an enterprise account, spelled with GitHub's enum values so the stored value is what GraphQL serves.

const (
	// EnterpriseRoleOwner has full administrative authority over the enterprise.
	EnterpriseRoleOwner EnterpriseRole = "OWNER"
	// EnterpriseRoleBillingManager may read and change billing only.
	EnterpriseRoleBillingManager EnterpriseRole = "BILLING_MANAGER"
	// EnterpriseRoleMember belongs to at least one of the enterprise's
	// organizations, or was added directly.
	EnterpriseRoleMember EnterpriseRole = "MEMBER"
	// EnterpriseRoleUnaffiliated is an invited principal belonging to none of
	// the enterprise's organizations.
	EnterpriseRoleUnaffiliated EnterpriseRole = "UNAFFILIATED"
)

type EnterpriseSAMLIdentityProvider

type EnterpriseSAMLIdentityProvider struct {
	EnterpriseID    int       `json:"enterprise_id"`
	NodeID          string    `json:"node_id"`
	SSOURL          string    `json:"sso_url"`
	Issuer          string    `json:"issuer"`
	IDPCertificate  string    `json:"idp_certificate"`
	SignatureMethod string    `json:"signature_method"`
	DigestMethod    string    `json:"digest_method"`
	RecoveryCodes   []string  `json:"recovery_codes"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

EnterpriseSAMLIdentityProvider is an enterprise's SAML binding plus its one-time recovery codes. It describes the delegation to the external OIDC provider bleephub already authenticates against; it is not a second authentication mechanism.

type EnterpriseSCIMEmail

type EnterpriseSCIMEmail struct {
	Value   string `json:"value"`
	Type    string `json:"type,omitempty"`
	Primary bool   `json:"primary,omitempty"`
}

type EnterpriseSCIMGroup

type EnterpriseSCIMGroup struct {
	Schemas     []string               `json:"schemas"`
	ID          string                 `json:"id"`
	ExternalID  string                 `json:"externalId,omitempty"`
	DisplayName string                 `json:"displayName"`
	Members     []EnterpriseSCIMMember `json:"members"`
	TeamID      int                    `json:"team_id"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
}

type EnterpriseSCIMMember

type EnterpriseSCIMMember struct {
	Value   string `json:"value"`
	Display string `json:"display,omitempty"`
}

type EnterpriseSCIMName

type EnterpriseSCIMName struct {
	GivenName  string `json:"givenName,omitempty"`
	FamilyName string `json:"familyName,omitempty"`
	Formatted  string `json:"formatted,omitempty"`
}

type EnterpriseSCIMUser

type EnterpriseSCIMUser struct {
	Schemas     []string              `json:"schemas"`
	ID          string                `json:"id"`
	ExternalID  string                `json:"externalId,omitempty"`
	UserName    string                `json:"userName"`
	Name        EnterpriseSCIMName    `json:"name,omitempty"`
	DisplayName string                `json:"displayName,omitempty"`
	Active      bool                  `json:"active"`
	Emails      []EnterpriseSCIMEmail `json:"emails,omitempty"`
	UserID      int                   `json:"user_id"`
	CreatedAt   time.Time             `json:"created_at"`
	UpdatedAt   time.Time             `json:"updated_at"`
}

type EnterpriseSettings

type EnterpriseSettings struct {
	// Enterprise administration settings.
	Announcement                    *EnterpriseAnnouncement                    `json:"announcement,omitempty"`
	AccessRestrictionsEnabled       bool                                       `json:"access_restrictions_enabled"`
	CodeSecurityAndAnalysis         EnterpriseCodeSecurity                     `json:"code_security_and_analysis"`
	AuditLogStreams                 []*EnterpriseAuditLogStream                `json:"audit_log_streams,omitempty"`
	NextAuditLogStreamID            int                                        `json:"next_audit_log_stream_id"`
	RepositoryCustomProperties      map[string]*CustomProperty                 `json:"repository_custom_properties,omitempty"`
	OrganizationCustomProperties    map[string]*CustomProperty                 `json:"organization_custom_properties,omitempty"`
	OrganizationPropertyValues      map[string]map[string]interface{}          `json:"organization_property_values,omitempty"`
	SCIMUsers                       map[string]*EnterpriseSCIMUser             `json:"scim_users,omitempty"`
	SCIMGroups                      map[string]*EnterpriseSCIMGroup            `json:"scim_groups,omitempty"`
	EnterpriseRoleTeamAssignments   map[int][]int                              `json:"enterprise_role_team_assignments,omitempty"`
	EnterpriseRoleUserAssignments   map[int][]int                              `json:"enterprise_role_user_assignments,omitempty"`
	VisualStudioSubscriptions       map[string]*VisualStudioSubscription       `json:"visual_studio_subscriptions,omitempty"`
	InnerSourceSyncJobs             map[string]*EnterpriseInnerSourceSyncJob   `json:"innersource_sync_jobs,omitempty"`
	EnterpriseCopilotSeats          map[string]*CopilotSeat                    `json:"enterprise_copilot_seats,omitempty"`
	CopilotCustomAgentsSourceOrgID  int                                        `json:"copilot_custom_agents_source_org_id,omitempty"`
	CopilotCustomAgentsRulesetID    int                                        `json:"copilot_custom_agents_ruleset_id,omitempty"`
	EnterpriseBudgets               map[string]*OrgBudget                      `json:"enterprise_budgets,omitempty"`
	EnterpriseCostCenters           map[string]*EnterpriseCostCenter           `json:"enterprise_cost_centers,omitempty"`
	EnterpriseBillingReports        map[string]*EnterpriseBillingReport        `json:"enterprise_billing_reports,omitempty"`
	GHESManagement                  *GHESManagementState                       `json:"ghes_management,omitempty"`
	GHESGlobalHooks                 []*Webhook                                 `json:"ghes_global_hooks,omitempty"`
	GHESPreReceiveEnvironments      map[int]*GHESPreReceiveEnvironment         `json:"ghes_pre_receive_environments,omitempty"`
	GHESPreReceiveHooks             map[int]*GHESPreReceiveHook                `json:"ghes_pre_receive_hooks,omitempty"`
	GHESOrgPreReceiveOverrides      map[string]map[int]*GHESPreReceiveOverride `json:"ghes_org_pre_receive_overrides,omitempty"`
	GHESRepoPreReceiveOverrides     map[string]map[int]*GHESPreReceiveOverride `json:"ghes_repo_pre_receive_overrides,omitempty"`
	NextGHESPreReceiveEnvironmentID int                                        `json:"next_ghes_pre_receive_environment_id"`
	NextGHESPreReceiveHookID        int                                        `json:"next_ghes_pre_receive_hook_id"`
	GHESLDAPUserMappings            map[string]string                          `json:"ghes_ldap_user_mappings,omitempty"`
	GHESLDAPTeamMappings            map[int]string                             `json:"ghes_ldap_team_mappings,omitempty"`

	// Dependabot repository access across organizations.
	DependabotAccessibleRepoIDs []int                  `json:"dependabot_accessible_repo_ids"`
	DependabotDefaultLevel      DependabotDefaultLevel `json:"dependabot_default_level"` // "" = never set (null); else public|internal

	// GitHub Actions cache policy. GHES defaults: 14-day retention, 10 GB
	// per-repository storage.
	ActionsCacheRetentionDays int `json:"actions_cache_retention_days"`
	ActionsCacheSizeGB        int `json:"actions_cache_size_gb"`
	ActionsDefaultCacheSizeGB int `json:"actions_default_cache_size_gb"`

	// Repository custom properties included in OIDC token claims, in insertion
	// order.
	OIDCCustomProperties      []string `json:"oidc_custom_properties"`
	OIDCIncludeEnterpriseSlug bool     `json:"oidc_include_enterprise_slug"`

	// Enterprise-wide Actions policy, stored independently of org policy: org
	// settings may narrow it but cannot replace this source of truth.
	ActionsEnabledOrganizations     string                       `json:"actions_enabled_organizations"`
	ActionsAllowedActions           string                       `json:"actions_allowed_actions"`
	ActionsSHAPinningRequired       bool                         `json:"actions_sha_pinning_required"`
	ActionsSelectedOrganizationIDs  []int                        `json:"actions_selected_organization_ids"`
	ActionsAllowed                  *ActionsAllowed              `json:"actions_allowed,omitempty"`
	ActionsWorkflowPermissions      *WorkflowPermissions         `json:"actions_workflow_permissions,omitempty"`
	ActionsArtifactRetentionDays    int                          `json:"actions_artifact_retention_days"`
	ActionsForkPRApprovalPolicy     string                       `json:"actions_fork_pr_approval_policy"`
	ActionsForkPRWorkflowsPrivate   *ForkPRWorkflowsPrivateRepos `json:"actions_fork_pr_workflows_private,omitempty"`
	ActionsDisableSelfHostedRunners bool                         `json:"actions_disable_self_hosted_runners"`

	// Copilot coding agent policy. "" = never set.
	CopilotCodingAgentPolicy string   `json:"copilot_coding_agent_policy"`
	CopilotCodingAgentOrgs   []string `json:"copilot_coding_agent_orgs"`
}

EnterpriseSettings holds the singleton enterprise-level settings, persisted as one row under the "enterprise_settings" bucket. normalizeEnterpriseSettings seeds zero-value fields with defaults.

type EnterpriseTeam

type EnterpriseTeam struct {
	ID                        int       `json:"id"`
	Name                      string    `json:"name"`
	Description               string    `json:"description"`
	Slug                      string    `json:"slug"`
	OrganizationSelectionType string    `json:"organization_selection_type"`
	GroupID                   *string   `json:"group_id"`
	NotificationSetting       string    `json:"notification_setting"`
	MemberIDs                 []int     `json:"member_ids"`
	SelectedOrgLogins         []string  `json:"selected_org_logins"`
	CreatedAt                 time.Time `json:"created_at"`
	UpdatedAt                 time.Time `json:"updated_at"`
}

EnterpriseTeam is a team scoped to the enterprise, not one org. OrganizationSelectionType governs org assignments: "disabled" none, "all" every org on the instance, "selected" exactly SelectedOrgLogins.

type EnvApproval

type EnvApproval struct {
	State     string    `json:"state"` // approved | rejected
	Comment   string    `json:"comment"`
	UserID    int       `json:"userId"`
	EnvIDs    []int     `json:"envIds"`
	EnvNames  []string  `json:"envNames"`
	CreatedAt time.Time `json:"createdAt"`
}

EnvApproval is one submitted deployment review (approve or reject).

type EnvCustomProtectionRule

type EnvCustomProtectionRule struct {
	ID      int    `json:"id"`
	NodeID  string `json:"node_id"`
	Enabled bool   `json:"enabled"`
	AppID   int    `json:"app_id"`
}

EnvCustomProtectionRule is a custom deployment protection rule backed by a GitHub App.

type Environment

type Environment struct {
	ID        int                      `json:"id"`
	NodeID    string                   `json:"node_id"`
	Name      string                   `json:"name"`
	URL       string                   `json:"url"`
	HTMLURL   string                   `json:"html_url"`
	RepoID    int                      `json:"repo_id"`
	WaitTimer int                      `json:"wait_timer"`
	Reviewers []map[string]interface{} `json:"reviewers"`
	// PreventSelfReview refuses a review from the user who triggered the run.
	PreventSelfReview      bool                     `json:"prevent_self_review"`
	DeploymentBranchPolicy *DeploymentBranchPolicy  `json:"deployment_branch_policy"`
	CreatedAt              time.Time                `json:"created_at"`
	UpdatedAt              time.Time                `json:"updated_at"`
	ProtectionRules        []map[string]interface{} `json:"protection_rules"`
}

type ErrIssueSuggestionTarget

type ErrIssueSuggestionTarget struct {
	Field  string
	Reason string
}

ErrIssueSuggestionTarget reports a suggestion whose target no longer resolves.

func (*ErrIssueSuggestionTarget) Error

func (e *ErrIssueSuggestionTarget) Error() string

type ExternalIdentity

type ExternalIdentity struct {
	Issuer  string `json:"issuer"`
	Subject string `json:"subject"`
}

ExternalIdentity is one federated provider's stable (issuer, subject) handle on an account, unlike the mutable username it also presents.

type FilesystemByteStore

type FilesystemByteStore struct {
	Root string `json:"-"`
}

FilesystemByteStore keeps object bytes in a directory tree, one file per key. It streams uploads through a temp file renamed into place and hands back the open file on download, so an oversized object never lands on the heap (STORE-019).

func (*FilesystemByteStore) Delete

func (s *FilesystemByteStore) Delete(_ context.Context, key string) error

func (*FilesystemByteStore) Get

func (s *FilesystemByteStore) Get(_ context.Context, key string) ([]byte, error)

func (*FilesystemByteStore) GetStream

func (s *FilesystemByteStore) GetStream(_ context.Context, key string) (io.ReadCloser, error)

func (*FilesystemByteStore) Put

func (s *FilesystemByteStore) Put(ctx context.Context, key string, data []byte) error

func (*FilesystemByteStore) PutStream

func (s *FilesystemByteStore) PutStream(_ context.Context, key string, r io.Reader) error

func (*FilesystemByteStore) PutStreamHashed

func (s *FilesystemByteStore) PutStreamHashed(ctx context.Context, key string, r io.Reader, _ int64, _ []byte) error

PutStreamHashed streams r to disk like PutStream; the filesystem store keeps no per-object checksum (Get does not verify), so size and sha256Sum are unused.

type ForkPRWorkflowsPrivateRepos

type ForkPRWorkflowsPrivateRepos struct {
	RunWorkflowsFromForkPullRequests  bool `json:"run_workflows_from_fork_pull_requests"`
	SendWriteTokensToWorkflows        bool `json:"send_write_tokens_to_workflows"`
	SendSecretsAndVariables           bool `json:"send_secrets_and_variables"`
	RequireApprovalForForkPRWorkflows bool `json:"require_approval_for_fork_pr_workflows"`
}

type GHESMaintenanceState

type GHESMaintenanceState struct {
	Enabled                bool     `json:"enabled"`
	ScheduledTime          string   `json:"scheduled_time,omitempty"`
	IPExceptionList        []string `json:"ip_exception_list"`
	MaintenanceModeMessage string   `json:"maintenance_mode_message"`
}

type GHESManagementState

type GHESManagementState struct {
	SSHKeys      []string                 `json:"ssh_keys"`
	Settings     map[string]interface{}   `json:"settings"`
	License      map[string]interface{}   `json:"license,omitempty"`
	Maintenance  GHESMaintenanceState     `json:"maintenance"`
	ConfigStatus string                   `json:"config_status"`
	ConfigRunID  string                   `json:"config_run_id,omitempty"`
	ConfigEvents []map[string]interface{} `json:"config_events,omitempty"`
	Initialized  bool                     `json:"initialized"`
}

type GHESPreReceiveDownload

type GHESPreReceiveDownload struct {
	State        string     `json:"state"`
	DownloadedAt *time.Time `json:"downloaded_at,omitempty"`
	Message      *string    `json:"message,omitempty"`
}

type GHESPreReceiveEnvironment

type GHESPreReceiveEnvironment struct {
	ID                 int                     `json:"id"`
	Name               string                  `json:"name"`
	ImageURL           string                  `json:"image_url"`
	DefaultEnvironment bool                    `json:"default_environment"`
	CreatedAt          time.Time               `json:"created_at"`
	Download           *GHESPreReceiveDownload `json:"download,omitempty"`
}

type GHESPreReceiveHook

type GHESPreReceiveHook struct {
	ID                           int    `json:"id"`
	Name                         string `json:"name"`
	Script                       string `json:"script"`
	ScriptRepositoryID           int    `json:"script_repository_id"`
	EnvironmentID                int    `json:"environment_id"`
	Enforcement                  string `json:"enforcement"`
	AllowDownstreamConfiguration bool   `json:"allow_downstream_configuration"`
}

type GHESPreReceiveOverride

type GHESPreReceiveOverride struct {
	Enforcement                  string `json:"enforcement"`
	AllowDownstreamConfiguration bool   `json:"allow_downstream_configuration"`
}

type GPGKey

type GPGKey struct {
	ID                int           `json:"id"`
	PrimaryKeyID      int           `json:"primary_key_id"`
	KeyID             string        `json:"key_id"`
	RawKey            string        `json:"raw_key"`
	PublicKey         string        `json:"public_key"`
	Name              string        `json:"name,omitempty"`
	Emails            []GPGKeyEmail `json:"emails"`
	CanSign           bool          `json:"can_sign"`
	CanEncryptComms   bool          `json:"can_encrypt_comms"`
	CanEncryptStorage bool          `json:"can_encrypt_storage"`
	CanCertify        bool          `json:"can_certify"`
	Revoked           bool          `json:"revoked"`
	CreatedAt         time.Time     `json:"created_at"`
	ExpiresAt         *time.Time    `json:"expires_at,omitempty"`
	UserID            int           `json:"-"`
}

type GPGKeyEmail

type GPGKeyEmail struct {
	Email    string `json:"email"`
	Verified bool   `json:"verified"`
	Primary  bool   `json:"primary"`
}

type Gist

type Gist struct {
	ID          string               `json:"id"`
	NodeID      string               `json:"node_id"`
	Description string               `json:"description"`
	Public      bool                 `json:"public"`
	OwnerID     int                  `json:"owner_id"`
	Files       map[string]*GistFile `json:"files"`
	CreatedAt   time.Time            `json:"created_at"`
	UpdatedAt   time.Time            `json:"updated_at"`
	Comments    int                  `json:"comments"`
	CommentsURL string               `json:"comments_url"`
	HTMLURL     string               `json:"html_url"`
	URL         string               `json:"url"`
	ForksURL    string               `json:"forks_url"`
	CommitsURL  string               `json:"commits_url"`
	GitPullURL  string               `json:"git_pull_url"`
	GitPushURL  string               `json:"git_push_url"`
	History     []*GistHistory       `json:"history"`
	ForkOfID    string               `json:"fork_of_id,omitempty"`
	ForkIDs     []string             `json:"fork_ids,omitempty"`
}

Gist is a GitHub gist.

type GistComment

type GistComment struct {
	ID                int       `json:"id"`
	NodeID            string    `json:"node_id"`
	GistID            string    `json:"gist_id"`
	UserID            int       `json:"user_id"`
	Body              string    `json:"body"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
	AuthorAssociation string    `json:"author_association"`
	URL               string    `json:"url"`
}

GistComment is a comment on a gist.

type GistFile

type GistFile struct {
	Filename string `json:"filename"`
	Type     string `json:"type"`
	Language string `json:"language"`
	RawURL   string `json:"raw_url"`
	Size     int    `json:"size"`
	Content  string `json:"content,omitempty"`
}

GistFile is a single file inside a gist.

type GistHistory

type GistHistory struct {
	Version      string         `json:"version"`
	CommittedAt  time.Time      `json:"committed_at"`
	ChangeStatus map[string]int `json:"change_status"`
	URL          string         `json:"url"`
	// Files is the snapshot at this revision, reconstructing the gist at a given
	// sha (GET /gists/{id}/{sha}); internal state, not part of the wire shape.
	Files map[string]*GistFile `json:"files,omitempty"`
}

GistHistory captures one revision of a gist.

type GitRevision

type GitRevision struct {
	Hash plumbing.Hash
	Type plumbing.ObjectType
}

GitRevision is a resolved rev-parse result: the named object and its stored type.

func ResolveGitRevision

func ResolveGitRevision(stor gitStorage.Storer, expression string) (GitRevision, error)

ResolveGitRevision resolves the `git rev-parse` grammar GitHub's Repository.object(expression:) accepts:

HEAD, @                     the repository's checked-out branch
main, v1.0                  a branch or tag short name
refs/heads/main             a fully qualified reference
heads/main, tags/v1.0       the reference shorthands
3f2a1b9…                    a full object id
3f2a1b                      an unambiguous abbreviated object id
<rev>~, <rev>~3             first-parent ancestry
<rev>^, <rev>^2, <rev>^0    the nth parent (^0 peels to the commit)
<rev>^{}, <rev>^{commit}    peel an annotated tag; ^{tree}, ^{blob}, ^{tag}
<rev>:<path>                the tree entry at path within <rev>'s tree
<rev>:                      <rev>'s root tree

A ref resolves without peeling, so an annotated tag's name resolves to the tag object, as on github.com.

type GlobalAdvisoryFilter

type GlobalAdvisoryFilter struct {
	GHSAID string
	CVEID  string
	// Ecosystem and Package narrow to advisories with a matching vulnerability.
	Ecosystem string
	Package   string
	// Severities, when non-empty, keeps only advisories at one of them.
	Severities     []string
	PublishedSince *time.Time
	UpdatedSince   *time.Time
	// IncludeWithdrawn keeps withdrawn advisories in the browse listing. They
	// stay addressable by GHSA ID regardless.
	IncludeWithdrawn bool
}

GlobalAdvisoryFilter narrows a global-advisory listing. A zero filter matches every published advisory.

type GlobalSecurityVulnerability

type GlobalSecurityVulnerability struct {
	Advisory      *SecurityAdvisory
	Vulnerability SecurityAdvisoryVulnerability
}

GlobalSecurityVulnerability pairs one vulnerability with its advisory. Query.securityVulnerabilities enumerates pairs, not advisories, so a client filtering by package gets the matching entry rather than the whole advisory.

type HookLastResponse

type HookLastResponse struct {
	Code    int    `json:"code"`
	Status  string `json:"status"`
	Message string `json:"message"`
}

HookLastResponse is the outcome of a webhook's most recent delivery.

type HostedRunner

type HostedRunner struct {
	ID               int        `json:"id"`
	Org              string     `json:"org"`
	Enterprise       string     `json:"enterprise,omitempty"`
	Name             string     `json:"name"`
	RunnerGroupID    int        `json:"runner_group_id"`
	ImageID          string     `json:"image_id"`
	ImageSource      string     `json:"image_source"` // github | partner | custom
	ImageVersion     string     `json:"image_version,omitempty"`
	ImageSizeGB      int        `json:"image_size_gb"`
	ImageDisplayName string     `json:"image_display_name"`
	Platform         string     `json:"platform"`
	MachineSizeID    string     `json:"machine_size_id"`
	MaximumRunners   int        `json:"maximum_runners"`
	PublicIPEnabled  bool       `json:"public_ip_enabled"`
	ImageGen         bool       `json:"image_gen"`
	LastActiveOn     *time.Time `json:"last_active_on,omitempty"`
	CreatedAt        time.Time  `json:"created_at"`
}

HostedRunner is one GitHub-hosted runner (the actions-hosted-runner resource) configured in an org or enterprise.

type HostedRunnerCustomImage

type HostedRunnerCustomImage struct {
	ID         int                               `json:"id"`
	Org        string                            `json:"org"`
	Enterprise string                            `json:"enterprise,omitempty"`
	Name       string                            `json:"name"`
	Platform   string                            `json:"platform"`
	State      string                            `json:"state"`
	Versions   []*HostedRunnerCustomImageVersion `json:"versions"`
}

HostedRunnerCustomImage is one custom runner image definition (the actions-hosted-runner-custom-image resource) with its versions.

type HostedRunnerCustomImageVersion

type HostedRunnerCustomImageVersion struct {
	Version      string    `json:"version"`
	State        string    `json:"state"`
	SizeGB       int       `json:"size_gb"`
	CreatedOn    time.Time `json:"created_on"`
	StateDetails string    `json:"state_details"`
}

type IPAllowListEntry

type IPAllowListEntry struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`
	// OwnerType is "Enterprise" or "Organization".
	OwnerType      string    `json:"owner_type"`
	OwnerID        int       `json:"owner_id"`
	AllowListValue string    `json:"allow_list_value"`
	Name           string    `json:"name"`
	IsActive       bool      `json:"is_active"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

IPAllowListEntry is one CIDR on an IP allow list. OwnerType distinguishes enterprise from organization owners, whose ids come from different sequences.

func FindIPAllowListEntryByNodeID

func FindIPAllowListEntryByNodeID(st *Store, nodeID string) *IPAllowListEntry

FindIPAllowListEntryByNodeID resolves an allow-list entry global id to the LIVE row.

type Installation

type Installation struct {
	ID                  int               `json:"id"`
	AppID               int               `json:"app_id"`
	AppSlug             string            `json:"app_slug"`
	TargetType          string            `json:"target_type"`
	TargetID            int               `json:"target_id"`
	TargetLogin         string            `json:"target_login"`
	TargetNodeID        string            `json:"target_node_id"`    // snapshotted at install time
	TargetAvatarURL     string            `json:"target_avatar_url"` // snapshotted at install time
	Permissions         map[string]string `json:"permissions"`
	Events              []string          `json:"events"`
	RepositorySelection string            `json:"repository_selection"`
	SelectedRepoIDs     []int             `json:"selected_repo_ids"` // rendered only via installation emitters
	SuspendedAt         *time.Time        `json:"suspended_at"`
	SuspendedBy         *User             `json:"suspended_by"`
	SingleFileName      string            `json:"single_file_name"`
	CreatedAt           time.Time         `json:"created_at"`
	UpdatedAt           time.Time         `json:"updated_at"`
}

Installation represents an app installation on a user or org.

func CloneInstallation

func CloneInstallation(installation *Installation) *Installation

type InstallationSeedSpec

type InstallationSeedSpec struct {
	ID          int               `json:"id"`          // optional
	Account     string            `json:"account"`     // required
	TargetType  string            `json:"target_type"` // "Organization" | "User"; default Organization
	Permissions map[string]string `json:"permissions"`
	Events      []string          `json:"events"`
}

InstallationSeedSpec pre-installs the seeded App on an account so the consumer can mint an installation token by coordinates alone.

type InstallationToken

type InstallationToken struct {
	Token          string            `json:"token"`
	ExpiresAt      time.Time         `json:"expires_at"`
	Permissions    map[string]string `json:"permissions"`
	RepositoryIDs  []int             `json:"repository_ids"` // rendered only via installationTokenToJSON
	InstallationID int               `json:"installation_id"`
	AppID          int               `json:"app_id"`
}

InstallationToken is a short-lived token scoped to an installation.

type Issue

type Issue struct {
	ID               int
	NodeID           string
	Number           int // per-repo sequential
	RepoID           int
	Title            string
	Body             string
	State            string // "OPEN", "CLOSED"
	StateReason      string // "", "COMPLETED", "NOT_PLANNED"
	AuthorID         int
	AssigneeIDs      []int
	LabelIDs         []int
	MilestoneID      int // 0 = none
	IssueTypeID      int // 0 = none; organization issue type ID
	Locked           bool
	ActiveLockReason LockReason // empty = locked without a stated reason
	CreatedAt        time.Time
	UpdatedAt        time.Time
	ClosedAt         *time.Time
	PinnedAt         *time.Time // non-nil while pinned to the repo issues list; doubles as the pin order
	PinnedByID       int        // user who pinned the issue; 0 when not pinned
	// LinkedBranches are the branches recorded as work on this issue; see linked_branches.go.
	LinkedBranches []LinkedBranch
	// DuplicateOfID is the issue this one was closed as a duplicate of (0 = none).
	DuplicateOfID int
}

func FindIssueByNodeID

func FindIssueByNodeID(st *Store, nodeID string) *Issue

type IssueEvent

type IssueEvent struct {
	ID                  int
	NodeID              string
	RepoID              int
	ParentType          string
	IssueID             int
	ActorID             int
	Event               string
	CommitID            string
	CommitURL           string
	CreatedAt           time.Time
	LabelID             int
	AssigneeID          int
	AssignerID          int
	MilestoneID         int
	CommentID           int
	RequestedReviewerID int
	LockReason          string
	RenameFrom          string
	RenameTo            string
}

IssueEvent is an event in an issue's or PR's timeline. Event matches GitHub's REST issue-event type names ("opened", "closed", "labeled", ...). ParentType selects IssueID's ID space — "issue" (st.Issues) or "pull_request" (st.PullRequests); the two share a per-repo number sequence but independent global IDs.

type IssueField

type IssueField struct {
	ID          int                 `json:"id"`
	NodeID      string              `json:"node_id"`
	OrgLogin    string              `json:"org_login"`
	Name        string              `json:"name"`
	Description *string             `json:"description"`
	DataType    string              `json:"data_type"`
	Visibility  string              `json:"visibility"`
	Options     []*IssueFieldOption `json:"options,omitempty"`
	CreatedAt   time.Time           `json:"created_at"`
	UpdatedAt   time.Time           `json:"updated_at"`
}

IssueField is an organization-level issue field definition.

type IssueFieldOption

type IssueFieldOption struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Description *string   `json:"description"`
	Color       string    `json:"color"`
	Priority    int       `json:"priority"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

IssueFieldOption is one option of a single/multi select field.

type IssueFieldOptionRequest

type IssueFieldOptionRequest struct {
	ID          *int    `json:"id"`
	Name        *string `json:"name"`
	Description *string `json:"description"`
	Color       *string `json:"color"`
	Priority    *int    `json:"priority"`
}

type IssueLabel

type IssueLabel struct {
	ID          int
	NodeID      string
	RepoID      int
	Name        string
	Description string
	Color       string // hex without #, e.g. "d73a4a"
	Default     bool
	Archived    bool
	CreatedAt   time.Time
}

IssueLabel is named to avoid collision with the agent Label type in store.go.

func FindLabelByNodeID

func FindLabelByNodeID(st *Store, nodeID string) *IssueLabel

type IssueSuggestion

type IssueSuggestion struct {
	ID           int         `json:"id"`
	IssueID      int         `json:"issue_id"`
	Action       string      `json:"action"`
	State        string      `json:"state"`
	TargetID     *int        `json:"target_id"`
	TargetValue  interface{} `json:"target_value"`
	Rationale    *string     `json:"rationale"`
	Confidence   *string     `json:"confidence"`
	ActorID      *int        `json:"actor_id"`
	IssueEventID *int        `json:"issue_event_id"`
	ResolvedBy   *int        `json:"resolved_by"`
	CreatedAt    time.Time   `json:"created_at"`
	UpdatedAt    time.Time   `json:"updated_at"`
}

type IssueType

type IssueType struct {
	ID          int       `json:"id"`
	NodeID      string    `json:"node_id"`
	OrgLogin    string    `json:"org_login"`
	Name        string    `json:"name"`
	Description *string   `json:"description"`
	Color       *string   `json:"color"`
	IsEnabled   bool      `json:"is_enabled"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

IssueType is an organization-level issue type definition.

func FindIssueTypeByNodeID

func FindIssueTypeByNodeID(st *Store, nodeID string) *IssueType

FindIssueTypeByNodeID resolves an issue-type node id.

type IssueWithRepo

type IssueWithRepo struct {
	Issue *Issue `json:"-"`
	Repo  *Repo  `json:"-"`
}

type Job

type Job struct {
	ID          string    `json:"id"`
	RequestID   int64     `json:"requestId"`
	PlanID      string    `json:"planId"`
	TimelineID  string    `json:"timelineId"`
	Status      string    `json:"status"` // queued, running, completed
	Result      string    `json:"result"` // Succeeded, Failed, Cancelled
	Message     string    `json:"-"`      // JSON-encoded job request message (secret-bearing; cleared at run finalization)
	LockedUntil time.Time `json:"lockedUntil"`
	AgentID     int       `json:"agentId"`
	// CompletedAt is the janitor's retirement stamp: set when the runner reports
	// completion or the run finalizes, whichever first. runnerTokenTTL later, no
	// credential can address the job and its replica-local state is swept.
	CompletedAt time.Time `json:"-"`
}

Job represents a queued/running/completed job.

type JobDef

type JobDef struct {
	Name              string                 `yaml:"name"`
	RunsOn            interface{}            `yaml:"runs-on"`
	Container         interface{}            `yaml:"container"` // string or object
	Services          map[string]*ServiceDef // parsed from string or ServiceDef object
	Needs             []string               // parsed from string or list
	Env               map[string]string      `yaml:"env"`
	Outputs           map[string]string      `yaml:"outputs"`
	Strategy          *StrategyDef           `yaml:"strategy"`
	Steps             []StepDef              `yaml:"steps"`
	If                string                 `yaml:"if"`
	ContinueOnError   bool                   `yaml:"continue-on-error"`
	TimeoutMinutes    int                    `yaml:"timeout-minutes"`
	Environment       interface{}            `yaml:"environment"` // string or {name, url}
	Permissions       PermissionDef          `yaml:"permissions"`
	Defaults          RunDefaults            `yaml:"defaults"`
	Concurrency       *ConcurrencyDef        `yaml:"concurrency"`
	MatrixValues      map[string]interface{} `yaml:"-"`
	MatrixGroup       string                 `yaml:"-"`
	MatrixMaxParallel int                    `yaml:"-"`

	// Uses marks the job as a reusable-workflow call; With carries its inputs
	// (raw template strings) and SecretsInherit/SecretsMap its `secrets:`.
	Uses           string
	With           map[string]string
	SecretsInherit bool
	SecretsMap     map[string]string

	// Call links expanded reusable-workflow jobs to their call binding;
	// ServerCompleted marks synthetic gate/collector nodes the engine completes
	// itself rather than dispatching to a runner.
	Call            *WorkflowCallBinding
	ServerCompleted bool
	// CallRole distinguishes the synthetic nodes: "gate" (resolves inputs once
	// dependencies finish) or "collector" (maps called-workflow outputs onto
	// the caller job key).
	CallRole string
}

JobDef represents a single job definition within a workflow.

func (*JobDef) ContainerImage

func (jd *JobDef) ContainerImage() string

ContainerImage returns the container image string from a JobDef.Container, which may be a plain string or a ContainerDef object.

func (*JobDef) ContainerObject

func (jd *JobDef) ContainerObject() *ContainerDef

ContainerObject returns the parsed ContainerDef when `container:` was declared in object form, nil for the bare-string and absent forms.

func (*JobDef) EnvironmentName

func (jd *JobDef) EnvironmentName() string

EnvironmentName resolves the job's target environment name from the string or {name, url} object form; empty when none is declared.

func (*JobDef) FailFast

func (j *JobDef) FailFast() bool

FailFast returns the matrix strategy's fail-fast value, defaulting to true per the GitHub Actions spec when the strategy or field is absent.

func (*JobDef) RunsOnLabels

func (jd *JobDef) RunsOnLabels() []string

RunsOnLabels returns the job's runs-on labels (string or list form); nil when unset.

type JobStatus

type JobStatus string

JobStatus is the lifecycle state of a WorkflowJob.

const (
	JobStatusPending   JobStatus = "pending"
	JobStatusQueued    JobStatus = "queued"
	JobStatusRunning   JobStatus = "running"
	JobStatusCompleted JobStatus = "completed"
	JobStatusSkipped   JobStatus = "skipped"
	// JobStatusWaiting holds jobs targeting a reviewer-protected environment
	// until the run's pending deployment is approved.
	JobStatusWaiting JobStatus = "waiting"
)

type LFSLock

type LFSLock struct {
	ID        int       `json:"id"`
	RepoKey   string    `json:"repo_key"`
	Path      string    `json:"path"`
	Ref       string    `json:"ref,omitempty"`
	OwnerID   int       `json:"owner_id"`
	OwnerName string    `json:"owner_name"`
	LockedAt  time.Time `json:"locked_at"`
}

LFSLock is one Git LFS file lock: an advisory claim on a path, held until the owner or a forcing pusher releases it.

type Label

type Label struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	Type string `json:"type"`
}

Label is an agent label.

type LicenseMeta

type LicenseMeta struct {
	Description    string
	Implementation string
	Permissions    []string
	Conditions     []string
	Limitations    []string
	Featured       bool
}

LicenseMeta carries the choosealicense.com attributes GitHub returns beyond license text. Featured licenses appear in the default /licenses listing.

type LinkedBranch

type LinkedBranch struct {
	// RepoID holds the branch's repository, which GitHub allows to differ from
	// the issue's.
	RepoID int
	// Ref is the fully qualified reference, e.g. refs/heads/42-fix-the-thing.
	Ref string
}

LinkedBranch is one branch linked to an issue.

type LockReason

type LockReason string

LockReason is why a conversation is locked. GitHub accepts only these values (lowercase kebab-case in REST, uppercased in the GraphQL enum). Empty means locked without a stated reason.

const (
	LockReasonNone      LockReason = ""
	LockReasonOffTopic  LockReason = "off-topic"
	LockReasonTooHeated LockReason = "too heated"
	LockReasonResolved  LockReason = "resolved"
	LockReasonSpam      LockReason = "spam"
)

type LoginSession

type LoginSession struct {
	UserID       int
	CSRFToken    string
	ExpiresAt    time.Time
	OIDCProvider string
	OIDCIssuer   string
	OIDCSubject  string
	OIDCSID      string
	OIDCIDToken  string
	// Handle is a public, non-secret session name, so the "active sessions" list
	// can identify and revoke a session without exposing the cookie or its key.
	Handle string
	// CreatedAt, UserAgent and SignedInIP are what the sessions list shows.
	CreatedAt  time.Time
	UserAgent  string
	SignedInIP string
	// SudoAt is when this session last passed a proof-of-presence challenge
	// (sudo mode); per session, not per account. Zero means never elevated.
	SudoAt time.Time
	// SudoMFA records whether that proof carried a second factor, so a password
	// re-entry is not later mistaken for an MFA challenge.
	SudoMFA bool
}

LoginSession is a browser session created by POST /login, binding a session cookie to a user and carrying the OAuth-consent CSRF token.

type LoginSessionSummary

type LoginSessionSummary struct {
	Handle     string    `json:"handle"`
	CreatedAt  time.Time `json:"created_at,omitzero"`
	ExpiresAt  time.Time `json:"expires_at"`
	UserAgent  string    `json:"user_agent,omitempty"`
	SignedInIP string    `json:"signed_in_ip,omitempty"`
	// Provider names the establishing IdP, empty for a local sign-in.
	Provider string `json:"provider,omitempty"`
}

LoginSessionSummary is one row of the account's "active sessions" list, carrying no credential: the storage key, CSRF token and ID token stay in the store, and the UI revokes by Handle, drawn independently of the cookie.

type Mannequin

type Mannequin struct {
	ID         int       `json:"id"`
	NodeID     string    `json:"node_id"`
	OrgID      int       `json:"org_id"`
	Login      string    `json:"login"`
	Email      string    `json:"email"`
	ClaimantID int       `json:"claimant_id"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

func FindMannequinByNodeID

func FindMannequinByNodeID(st *Store, nodeID string) *Mannequin

FindMannequinByNodeID returns the live row (not a snapshot) for a node ID.

type MarketplaceBuyerAccount

type MarketplaceBuyerAccount struct {
	Id          int    `json:"-"`
	Login       string `json:"-"`
	AccountType string `json:"-"`
}

type MarketplaceCategory

type MarketplaceCategory struct {
	ID          int    `json:"id"`
	NodeID      string `json:"node_id"`
	Slug        string `json:"slug"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	HowItWorks  string `json:"how_it_works,omitempty"`
	// TopicAliases are the alternative slugs GitHub resolves by under
	// useTopicAliases.
	TopicAliases []string `json:"topic_aliases,omitempty"`
	// ParentSlug names a subcategory's parent; the taxonomy is one level deep.
	ParentSlug string `json:"parent_slug,omitempty"`
}

MarketplaceCategory is one entry in the Marketplace taxonomy.

type MarketplaceListing

type MarketplaceListing struct {
	Slug               string    `json:"slug"`
	Name               string    `json:"name"`
	Description        string    `json:"description"`
	FullDescription    string    `json:"full_description"`
	SetupURL           string    `json:"setup_url,omitempty"`
	InstallationURL    string    `json:"installation_url,omitempty"`
	GitHubAppID        int       `json:"github_app_id,omitempty"`
	OAuthAppClientID   string    `json:"oauth_app_client_id,omitempty"`
	WebhookURL         string    `json:"webhook_url,omitempty"`
	WebhookSecret      string    `json:"webhook_secret,omitempty"`
	WebhookContentType string    `json:"webhook_content_type,omitempty"`
	WebhookActive      bool      `json:"webhook_active"`
	WebhookID          int       `json:"webhook_id,omitempty"`
	Published          bool      `json:"published"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
}

type MarketplaceListingProfile

type MarketplaceListingProfile struct {
	Slug                  string    `json:"slug"`
	NodeID                string    `json:"node_id"`
	PrimaryCategorySlug   string    `json:"primary_category_slug"`
	SecondaryCategorySlug string    `json:"secondary_category_slug,omitempty"`
	ExtendedDescription   string    `json:"extended_description,omitempty"`
	HowItWorks            string    `json:"how_it_works,omitempty"`
	NormalizedShortDesc   string    `json:"normalized_short_description,omitempty"`
	LogoURL               string    `json:"logo_url,omitempty"`
	LogoBackgroundColor   string    `json:"logo_background_color,omitempty"`
	ScreenshotURLs        []string  `json:"screenshot_urls,omitempty"`
	CompanyURL            string    `json:"company_url,omitempty"`
	DocumentationURL      string    `json:"documentation_url,omitempty"`
	PricingURL            string    `json:"pricing_url,omitempty"`
	PrivacyPolicyURL      string    `json:"privacy_policy_url,omitempty"`
	StatusURL             string    `json:"status_url,omitempty"`
	SupportEmail          string    `json:"support_email,omitempty"`
	SupportURL            string    `json:"support_url,omitempty"`
	TermsOfServiceURL     string    `json:"terms_of_service_url,omitempty"`
	State                 string    `json:"state"`
	HasVerifiedOwner      bool      `json:"has_verified_owner"`
	CreatedAt             time.Time `json:"created_at"`
	UpdatedAt             time.Time `json:"updated_at"`
}

MarketplaceListingProfile is the publication half of a Marketplace listing, keyed by the listing slug the REST surface uses.

func DefaultMarketplaceListingProfile

func DefaultMarketplaceListingProfile(slug string) *MarketplaceListingProfile

DefaultMarketplaceListingProfile is the profile a listing has before its publisher fills one in: catch-all category, draft state, no marketing links. Synthesized, not written, so a GraphQL read does no durable write (STORE-034).

type MarketplacePendingChange

type MarketplacePendingChange struct {
	PlanID        int       `json:"plan_id,omitempty"`
	BillingCycle  string    `json:"billing_cycle,omitempty"`
	UnitCount     *int      `json:"unit_count,omitempty"`
	EffectiveDate time.Time `json:"effective_date"`
	Cancellation  bool      `json:"cancellation,omitempty"`
	ActorID       int       `json:"actor_id"`
}

type MarketplacePlan

type MarketplacePlan struct {
	ID                  int      `json:"id"`
	ListingSlug         string   `json:"listing_slug"`
	Number              int      `json:"number"`
	Name                string   `json:"name"`
	Description         string   `json:"description"`
	MonthlyPriceInCents int      `json:"monthly_price_in_cents"`
	YearlyPriceInCents  int      `json:"yearly_price_in_cents"`
	PriceModel          string   `json:"price_model"`
	HasFreeTrial        bool     `json:"has_free_trial"`
	UnitName            string   `json:"unit_name"`
	State               string   `json:"state"`
	Bullets             []string `json:"bullets"`
}

type MarketplaceProfileStore

type MarketplaceProfileStore struct {
	Mu      sync.RWMutex `json:"-"`
	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

MarketplaceProfileStore holds the taxonomy and the listing profiles.

func NewMarketplaceProfileStore

func NewMarketplaceProfileStore(now func() time.Time) *MarketplaceProfileStore

NewMarketplaceProfileStore builds an empty profile store.

func (*MarketplaceProfileStore) DeleteMarketplaceListingProfile

func (ms *MarketplaceProfileStore) DeleteMarketplaceListingProfile(slug string) bool

DeleteMarketplaceListingProfile drops a listing's profile.

func (*MarketplaceProfileStore) FindMarketplaceCategoryByNodeID

func (ms *MarketplaceProfileStore) FindMarketplaceCategoryByNodeID(nodeID string) *MarketplaceCategory

FindMarketplaceCategoryByNodeID returns the live category row.

func (*MarketplaceProfileStore) FindMarketplaceListingProfileByNodeID

func (ms *MarketplaceProfileStore) FindMarketplaceListingProfileByNodeID(nodeID string) *MarketplaceListingProfile

FindMarketplaceListingProfileByNodeID returns the live profile row.

func (*MarketplaceProfileStore) GetMarketplaceCategory

func (ms *MarketplaceProfileStore) GetMarketplaceCategory(slug string, useTopicAliases bool) *MarketplaceCategory

GetMarketplaceCategory resolves a category by slug, optionally through its topic aliases (useTopicAliases).

func (*MarketplaceProfileStore) GetMarketplaceListingProfile

func (ms *MarketplaceProfileStore) GetMarketplaceListingProfile(slug string) *MarketplaceListingProfile

GetMarketplaceListingProfile returns a listing's publication metadata.

func (*MarketplaceProfileStore) ListMarketplaceCategories

func (ms *MarketplaceProfileStore) ListMarketplaceCategories(includeCategories []string, excludeSubcategories, excludeEmpty bool, counts map[string]int) []*MarketplaceCategory

ListMarketplaceCategories returns the taxonomy ordered by name. Filters mirror Query.marketplaceCategories: includeCategories restricts to named slugs, excludeSubcategories drops anything with a parent, excludeEmpty drops categories no listing points at. The caller supplies per-slug counts, since listings live in the other store.

func (*MarketplaceProfileStore) ListMarketplaceListingProfiles

func (ms *MarketplaceProfileStore) ListMarketplaceListingProfiles() []*MarketplaceListingProfile

ListMarketplaceListingProfiles returns every profile, ordered by slug.

func (*MarketplaceProfileStore) SaveMarketplaceListingProfile

func (ms *MarketplaceProfileStore) SaveMarketplaceListingProfile(slug string, patch MarketplaceProfileUpdate) (*MarketplaceListingProfile, error)

SaveMarketplaceListingProfile creates or patches a listing's profile. A profile-less listing gets a draft one under the "utilities" catch-all so its primary category is never absent.

func (*MarketplaceProfileStore) SeedDefaultCategories

func (ms *MarketplaceProfileStore) SeedDefaultCategories() error

SeedDefaultCategories installs GitHub's taxonomy, leaving existing categories alone.

type MarketplaceProfileUpdate

type MarketplaceProfileUpdate struct {
	PrimaryCategorySlug   *string
	SecondaryCategorySlug *string
	ExtendedDescription   *string
	HowItWorks            *string
	NormalizedShortDesc   *string
	LogoURL               *string
	LogoBackgroundColor   *string
	ScreenshotURLs        []string
	CompanyURL            *string
	DocumentationURL      *string
	PricingURL            *string
	PrivacyPolicyURL      *string
	StatusURL             *string
	SupportEmail          *string
	SupportURL            *string
	TermsOfServiceURL     *string
	State                 *string
	HasVerifiedOwner      *bool
}

MarketplaceProfileUpdate is a sparse patch over a listing profile.

type MarketplacePurchase

type MarketplacePurchase struct {
	ListingSlug   string     `json:"listing_slug"`
	AccountID     int        `json:"account_id"`
	AccountType   string     `json:"account_type"`
	BillingCycle  string     `json:"billing_cycle"`
	PlanID        int        `json:"plan_id"`
	PlanName      string     `json:"plan_name"`
	OnFreeTrial   bool       `json:"on_free_trial"`
	FreeTrialEnds *time.Time `json:"free_trial_ends_on,omitempty"`
	// Members surfaced by GET /user/marketplace_purchases.
	UnitCount       *int                      `json:"unit_count,omitempty"`
	NextBillingDate *time.Time                `json:"next_billing_date,omitempty"`
	UpdatedAt       *time.Time                `json:"updated_at,omitempty"`
	InstallationID  *int                      `json:"installation_id,omitempty"`
	PendingChange   *MarketplacePendingChange `json:"pending_change,omitempty"`
}

func CloneMarketplacePurchase

func CloneMarketplacePurchase(purchase *MarketplacePurchase) *MarketplacePurchase

type MatrixDef

type MatrixDef struct {
	Values  map[string][]interface{} // non-reserved keys
	Order   []string                 // value keys in YAML declaration order
	Include []map[string]interface{} // include entries
	Exclude []map[string]interface{} // exclude entries
}

MatrixDef represents a matrix strategy configuration.

type Membership

type Membership struct {
	OrgID  int             `json:"org_id"`
	UserID int             `json:"user_id"`
	Role   OrgRole         `json:"role"`
	State  MembershipState `json:"state"`
	Public bool            `json:"public"` // publicized via PUT /orgs/{org}/public_members/{username}
}

Membership represents a user's membership in an organization.

type MembershipState

type MembershipState string

MembershipState is the lifecycle state of an org membership: "pending" while an invitation awaits acceptance, "active" once accepted.

const (
	MembershipStateActive  MembershipState = "active"
	MembershipStatePending MembershipState = "pending"
)

type MemoryByteStore

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

MemoryByteStore keeps object bytes in the process. It is the fallback for a server with no data directory, whose other state is already in memory and equally lost on restart.

func (*MemoryByteStore) Delete

func (s *MemoryByteStore) Delete(_ context.Context, key string) error

func (*MemoryByteStore) Get

func (s *MemoryByteStore) Get(_ context.Context, key string) ([]byte, error)

func (*MemoryByteStore) GetStream

func (s *MemoryByteStore) GetStream(ctx context.Context, key string) (io.ReadCloser, error)

func (*MemoryByteStore) Put

func (s *MemoryByteStore) Put(_ context.Context, key string, data []byte) error

func (*MemoryByteStore) PutStream

func (s *MemoryByteStore) PutStream(ctx context.Context, key string, r io.Reader) error

func (*MemoryByteStore) PutStreamHashed

func (s *MemoryByteStore) PutStreamHashed(ctx context.Context, key string, r io.Reader, _ int64, _ []byte) error

type MergeAsyncStatus

type MergeAsyncStatus string

MergeAsyncStatus is the terminal state of an async merge record.

type MigrationCommon

type MigrationCommon struct {
	ID                   int       `json:"id"`
	NodeID               string    `json:"node_id"`
	GUID                 string    `json:"guid"`
	State                string    `json:"state"`
	Repositories         []string  `json:"repositories"`
	LockRepositories     bool      `json:"lock_repositories"`
	ExcludeMetadata      bool      `json:"exclude_metadata"`
	ExcludeGitData       bool      `json:"exclude_git_data"`
	ExcludeAttachments   bool      `json:"exclude_attachments"`
	ExcludeReleases      bool      `json:"exclude_releases"`
	ExcludeOwnerProjects bool      `json:"exclude_owner_projects"`
	OrgMetadataOnly      bool      `json:"org_metadata_only"`
	URL                  string    `json:"url"`
	HTMLURL              string    `json:"html_url"`
	ArchiveURL           string    `json:"archive_url"`
	CreatedAt            time.Time `json:"created_at"`
	UpdatedAt            time.Time `json:"updated_at"`
	ExportedAt           time.Time `json:"exported_at"`

	// FailureReason records why an export failed. GitHub's payload has no field for it, so it is served through the UI and audit log, not the REST object.
	FailureReason string `json:"failure_reason,omitempty"`
	// ArchiveKey names the byte-store object holding the export's bytes, empty until success; ArchiveSize/ArchiveSHA256
	// answer a download's Content-Length and integrity header without reading the object back into memory.
	ArchiveKey    string `json:"archive_key,omitempty"`
	ArchiveSize   int64  `json:"archive_size,omitempty"`
	ArchiveSHA256 string `json:"archive_sha256,omitempty"`

	// Internal state omitted from API responses.
	LockedRepos    map[string]bool `json:"-"`
	ArchiveDeleted bool            `json:"-"`
}

MigrationCommon holds the fields shared by user and org migrations; it is the response payload for GitHub's Migration object.

type MigrationScope

type MigrationScope string

MigrationScope distinguishes the two migration families: separate id sequences, buckets and authorization rules, so every entry point takes the scope rather than guessing from the id.

const (
	UserMigrationScope MigrationScope = "user"
	OrgMigrationScope  MigrationScope = "orgs"
)

type MigrationSource

type MigrationSource struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`
	// OwnerOrgID is the org every read/write of this source is authorized
	// against.
	OwnerOrgID int    `json:"owner_org_id"`
	Name       string `json:"name"`
	Type       string `json:"type"`
	URL        string `json:"url"`
	// AccessToken authenticates against the source; GitHubPAT against the
	// target for signed archive URLs.
	AccessToken string    `json:"access_token,omitempty"`
	GitHubPAT   string    `json:"github_pat,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

MigrationSource is a place repositories are migrated from. Its stored credentials are never served — only the in-process migration worker reads them.

func FindMigrationSourceByNodeID

func FindMigrationSourceByNodeID(st *Store, nodeID string) *MigrationSource

FindMigrationSourceByNodeID resolves a source global id to the LIVE row.

type Milestone

type Milestone struct {
	ID          int
	NodeID      string
	RepoID      int
	Number      int // per-repo sequential
	Title       string
	Description string
	State       MilestoneState
	CreatorID   int // user who created the milestone
	DueOn       *time.Time
	ClosedAt    *time.Time // set when state transitions to "closed"
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

func FindMilestoneByNodeID

func FindMilestoneByNodeID(st *Store, nodeID string) *Milestone

type MilestoneState

type MilestoneState string

MilestoneState is a milestone's state; GitHub has only open and closed. (The "all" list filter is not a state and stays a plain string.)

const (
	MilestoneStateOpen   MilestoneState = "open"
	MilestoneStateClosed MilestoneState = "closed"
)

type MiscStore

type MiscStore struct {
	Mu               sync.RWMutex                 `json:"-"`
	UserKeys         map[int]*UserKey             `json:"-"`
	KeysByUser       map[int][]*UserKey           `json:"-"`
	GpgKeys          map[int]*GPGKey              `json:"-"`
	GpgKeysByUser    map[int][]*GPGKey            `json:"-"`
	Follows          map[string]map[string]bool   `json:"-"`
	PagesByRepo      map[int]*PagesSite           `json:"-"`
	PagesBuilds      map[string][]*PagesBuild     `json:"-"`
	BranchProtection map[string]*BranchProtection `json:"-"`
	// BranchProtectionPatterns holds web-only fnmatch pattern rules per repo ID,
	// consulted when no exact-name rule matches (served under /ui-data).
	BranchProtectionPatterns map[int][]*BranchProtectionPatternRule `json:"-"`
	// BranchProtectionExtras holds a rule's GraphQL-only members (deployment
	// requirements, force-push bypass actors, creator), keyed by BpKey. Kept
	// outside BranchProtection, whose JSON is GitHub's REST protection shape.
	BranchProtectionExtras map[string]*BranchProtectionRuleExtras `json:"-"`
	AuditLog               []*AuditEntry                          `json:"-"`
	AuditLogEvents         []*AuditLogEvent                       `json:"-"`

	MarketplacePurchases map[string]*MarketplacePurchase `json:"-"`

	// OidcClaimKeys maps an OIDC-subject-customization scope ("repo:owner/name"
	// or "org:login") to its include_claim_keys, per-scope to prevent cross-tenant
	// clobbering.
	OidcClaimKeys    map[string][]string `json:"-"`
	NextKeyID        int                 `json:"-"`
	NextGPGKeyID     int                 `json:"-"`
	NextPagesBuildID int64               `json:"-"`
	NextAuditID      int64               `json:"-"`
	NextAdminAuditID int64               `json:"-"`
	OidcKey          *rsa.PrivateKey     `json:"-"`
	Persist          *Persistence        `json:"-"`
	// contains filtered or unexported fields
}

type NetworkConfiguration

type NetworkConfiguration struct {
	ID                         string    `json:"id"`
	OrgLogin                   string    `json:"org_login"`
	Name                       string    `json:"name"`
	ComputeService             string    `json:"compute_service"`
	NetworkSettingsIDs         []string  `json:"network_settings_ids"`
	FailoverNetworkSettingsIDs []string  `json:"failover_network_settings_ids"`
	FailoverNetworkEnabled     bool      `json:"failover_network_enabled"`
	CreatedOn                  time.Time `json:"created_on"`
}

NetworkConfiguration is a hosted compute network configuration.

type NetworkConfigurationRequest

type NetworkConfigurationRequest struct {
	Name                       *string  `json:"name"`
	ComputeService             *string  `json:"compute_service"`
	NetworkSettingsIDs         []string `json:"network_settings_ids"`
	FailoverNetworkSettingsIDs []string `json:"failover_network_settings_ids"`
	FailoverNetworkEnabled     *bool    `json:"failover_network_enabled"`
}

type NetworkSettingsResource

type NetworkSettingsResource struct {
	ID                     string `json:"id"`
	OrgLogin               string `json:"org_login"`
	Name                   string `json:"name"`
	SubnetID               string `json:"subnet_id"`
	Region                 string `json:"region"`
	NetworkConfigurationID string `json:"network_configuration_id"`
}

NetworkSettingsResource is a hosted compute network settings resource.

type NewRepositoryMigration

type NewRepositoryMigration struct {
	OwnerOrgID           int
	SourceID             int
	RepositoryName       string
	SourceURL            string
	ContinueOnError      bool
	LockSource           bool
	SkipReleases         bool
	TargetRepoVisibility string
	GitArchiveURL        string
	MetadataArchiveURL   string
	OrgMigrationID       int
	StartedByUserID      int
}

NewRepositoryMigration is the create input for a repository migration.

type NotificationChannels

type NotificationChannels struct {
	Email bool `json:"email"`
	Web   bool `json:"web"`
}

NotificationChannels is the delivery selection: email, the web inbox, or both.

func DefaultNotificationChannels

func DefaultNotificationChannels() NotificationChannels

DefaultNotificationChannels is the delivery for an event type the user has no opinion about.

type NotificationListOptions

type NotificationListOptions struct {
	All           bool
	Participating bool
	Since         time.Time
	Before        time.Time
	RepoScope     string
	// View selects a web-only inbox view; REST listings always use "".
	View string
}

NotificationListOptions controls filtering of ListNotifications.

type NotificationPreferences

type NotificationPreferences struct {
	// Participating: threads the user authored, is assigned, review-requested, commented on, or @-mentioned in.
	Participating NotificationChannels `json:"participating"`
	// Watching: everything else from a watched repo or thread subscription.
	Watching                       NotificationChannels `json:"watching"`
	AutomaticallyWatchRepositories bool                 `json:"automatically_watch_repositories"`
	AutomaticallyWatchTeams        bool                 `json:"automatically_watch_teams"`
	// Events keys delivery by event type; a type absent from the map inherits DefaultNotificationChannels.
	Events                     map[string]NotificationChannels `json:"events"`
	IncludeOwnUpdates          bool                            `json:"include_own_updates"`
	ActionsFailedWorkflowsOnly bool                            `json:"actions_failed_workflows_only"`
	DependabotWeeklyDigest     bool                            `json:"dependabot_weekly_digest"`
	// EmailDeliveryRestricted is computed on every read (normalize clears it), never persisted: the enterprise policy bars this address, so every email channel above reads false.
	EmailDeliveryRestricted bool `json:"email_delivery_restricted,omitempty"`
}

NotificationPreferences is one account's full notification configuration.

func DefaultNotificationPreferences

func DefaultNotificationPreferences() NotificationPreferences

DefaultNotificationPreferences matches github.com's out-of-the-box defaults.

func (NotificationPreferences) NotificationDeliversWeb

func (p NotificationPreferences) NotificationDeliversWeb(subjectType, reason string) bool

NotificationDeliversWeb reports whether a thread of this subject type and reason reaches the web inbox. Both the subscription class and the event type must permit web delivery.

func (NotificationPreferences) SelectsEmailDelivery

func (p NotificationPreferences) SelectsEmailDelivery() bool

SelectsEmailDelivery reports whether the document requests email delivery anywhere. The write refuses it when the enterprise will not deliver to the address.

type NotificationThread

type NotificationThread struct {
	ID               string
	Repository       map[string]interface{}
	SubjectTitle     string
	SubjectURL       string
	SubjectType      string
	LatestCommentURL string
	HTMLURL          string
	Reason           string
	Unread           bool
	UpdatedAt        time.Time
	LastReadAt       *time.Time
	SubscriptionURL  string
	URL              string
}

NotificationThread is the wire-shape of a GitHub notification thread.

type NotificationThreadRow

type NotificationThreadRow struct {
	Repo *Repo `json:"-"`
	// contains filtered or unexported fields
}

NotificationThreadRow is one accepted thread source gathered under the read lock, carrying everything buildThread needs to render after the lock releases.

func (NotificationThreadRow) Saved

func (row NotificationThreadRow) Saved() bool

type OAuthApp

type OAuthApp struct {
	ClientID     string
	ClientSecret string
	Name         string
	Description  string
	URL          string
	CallbackURL  string
	OwnerID      int
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

OAuthApp is a classic OAuth app, distinct from a GitHub App (App above) though both support the OAuth web flow.

type ObjectListing

type ObjectListing struct {
	Key          string
	Size         int64
	LastModified time.Time
}

ObjectListing is one stored object, keyed relative to the store prefix.

type Org

type Org struct {
	ID                           int    `json:"id"`
	NodeID                       string `json:"node_id"`
	Login                        string `json:"login"`
	Name                         string `json:"name"`
	Description                  string `json:"description"`
	Email                        string `json:"email"`
	AvatarURL                    string `json:"avatar_url"`
	Type                         string `json:"type"`
	Company                      string `json:"company"`
	Blog                         string `json:"blog"`
	Location                     string `json:"location"`
	TwitterUsername              string `json:"twitter_username"`
	BillingEmail                 string `json:"billing_email"`
	DefaultRepositoryPermission  string `json:"default_repository_permission"` // "" = GitHub default "read"
	MembersCanCreateRepositories *bool  `json:"members_can_create_repositories"`
	// nil defaults: true for repos/pages/teams, false for forking private repos.
	MembersCanCreatePublicRepositories  *bool `json:"members_can_create_public_repositories"`
	MembersCanCreatePrivateRepositories *bool `json:"members_can_create_private_repositories"`
	MembersCanCreatePages               *bool `json:"members_can_create_pages"`
	MembersCanForkPrivateRepositories   *bool `json:"members_can_fork_private_repositories"`
	MembersCanCreateTeams               *bool `json:"members_can_create_teams"`
	WebCommitSignoffRequired            bool  `json:"web_commit_signoff_required"`
	// NotificationDeliveryRestrictionEnabled restricts the org's email
	// notifications to verified-domain addresses. It layers under the enterprise
	// policy of the same name: either being on restricts delivery.
	NotificationDeliveryRestrictionEnabled bool `json:"notification_delivery_restriction_enabled"`
	// PinnedRepos is the org profile's ordered pinned-repo full names; a web-only
	// feature served under /ui-data.
	PinnedRepos []string  `json:"pinned_repos,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

Org represents a GitHub organization account.

The *bool member-privilege fields are pointers because nil means "GitHub's default for that field", not false.

type OrgActionsPermissions

type OrgActionsPermissions struct {
	EnabledRepositories         string          `json:"enabled_repositories"`
	SelectedRepositoriesURL     string          `json:"selected_repositories_url,omitempty"`
	AllowedActions              string          `json:"allowed_actions"`
	SelectedActionsURL          string          `json:"selected_actions_url,omitempty"`
	SelectedRepositoryIDs       []int           `json:"selected_repository_ids,omitempty"`
	ActionsAllowed              *ActionsAllowed `json:"actions_allowed,omitempty"`
	WorkflowPermissions         *WorkflowPermissions
	CacheRetentionLimitDays     int
	CacheStorageLimitGB         int64
	ArtifactAndLogRetentionDays int
	// ForkPRApprovalPolicy names which fork-PR contributors approval is demanded
	// of; whether it is demanded at all is
	// ForkPRWorkflowsPrivateRepos.RequireApprovalForForkPRWorkflows.
	ForkPRApprovalPolicy                 string
	ForkPRWorkflowsPrivateRepos          *ForkPRWorkflowsPrivateRepos
	SelfHostedRunnersEnabledRepositories string
	SelfHostedRunnersSelectedRepoIDs     []int
	MaxCacheRetentionDays                int
	MaxCacheSizeGB                       int
}

OrgActionsPermissions models the organization-level Actions settings.

func DefaultOrgActionsPermissions

func DefaultOrgActionsPermissions() *OrgActionsPermissions

DefaultOrgActionsPermissions returns the GitHub-default org settings.

type OrgBudget

type OrgBudget struct {
	ID                  string            `json:"id"`
	BudgetScope         string            `json:"budget_scope"` // organization | repository | multi_user_customer | user
	BudgetEntityName    string            `json:"budget_entity_name"`
	BudgetAmount        int               `json:"budget_amount"`
	PreventFurtherUsage bool              `json:"prevent_further_usage"`
	BudgetProductSKU    string            `json:"budget_product_sku"`
	BudgetType          string            `json:"budget_type"` // ProductPricing | SkuPricing
	BudgetAlerting      OrgBudgetAlerting `json:"budget_alerting"`
	ExpiresAt           *time.Time        `json:"expires_at,omitempty"`
	CreatedAt           time.Time         `json:"created_at"`
}

OrgBudget is one organization spending budget.

func CloneBudget

func CloneBudget(b *OrgBudget) *OrgBudget

type OrgBudgetAlerting

type OrgBudgetAlerting struct {
	WillAlert       bool     `json:"will_alert"`
	AlertRecipients []string `json:"alert_recipients"`
}

OrgBudgetAlerting is the alert configuration on a budget.

type OrgCodespacesAccess

type OrgCodespacesAccess struct {
	Visibility        string   `json:"visibility"` // disabled | selected_members | all_members | all_members_and_outside_collaborators
	SelectedUsernames []string `json:"selected_usernames,omitempty"`
}

OrgCodespacesAccess records which org users can create org-billed codespaces.

type OrgCustomOrganizationRole

type OrgCustomOrganizationRole struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Description *string   `json:"description"`
	BaseRole    *string   `json:"base_role"`
	Permissions []string  `json:"permissions"`
	OrgLogin    string    `json:"-"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

OrgCustomOrganizationRole is an organization-defined organization role.

type OrgCustomRepositoryRole

type OrgCustomRepositoryRole struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Description *string   `json:"description"`
	BaseRole    string    `json:"base_role"`
	Permissions []string  `json:"permissions"`
	OrgLogin    string    `json:"-"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

OrgCustomRepositoryRole is an organization-defined repository role.

type OrgExternalIdentityGroup

type OrgExternalIdentityGroup struct {
	ID          string    `json:"group_id"`
	NumericID   int       `json:"numeric_id"`
	Name        string    `json:"group_name"`
	Description string    `json:"group_description"`
	MemberIDs   []int     `json:"member_ids"`
	UpdatedAt   time.Time `json:"updated_at"`
}

type OrgImmutableReleasesSettings

type OrgImmutableReleasesSettings struct {
	EnforcedRepositories  string `json:"enforced_repositories"`
	SelectedRepositoryIDs []int  `json:"selected_repository_ids"`
}

OrgImmutableReleasesSettings is the org enforcement policy.

type OrgInteractionLimit

type OrgInteractionLimit struct {
	Limit     string    `json:"limit"`
	ExpiresAt time.Time `json:"expires_at"`
}

OrgInteractionLimit is an org-wide interaction restriction that auto-expires at ExpiresAt.

type OrgInvitation

type OrgInvitation struct {
	ID           int        `json:"id"`
	NodeID       string     `json:"node_id"`
	OrgID        int        `json:"org_id"`
	UserID       int        `json:"user_id"` // resolved invitee; 0 when the email matches no account
	Login        string     `json:"login"`   // "" for email-only invitations
	Email        string     `json:"email"`
	Role         string     `json:"role"`
	InviterID    int        `json:"inviter_id"`
	TeamIDs      []int      `json:"team_ids"`
	Source       string     `json:"source"` // "member" for API-created invitations
	CreatedAt    time.Time  `json:"created_at"`
	FailedAt     *time.Time `json:"failed_at,omitempty"`
	FailedReason string     `json:"failed_reason,omitempty"`
}

OrgInvitation is a pending or failed invitation to join an org. Role holds the invitation-role wire value (direct_member | admin | billing_manager), distinct from the membership role enum.

type OrgMigration

type OrgMigration struct {
	MigrationCommon
	OrgLogin string `json:"-"`
}

OrgMigration is an organization-scoped GitHub migration export.

type OrgMigratorRole

type OrgMigratorRole struct {
	OrgID     int       `json:"org_id"`
	ActorType string    `json:"actor_type"`
	Actor     string    `json:"actor"`
	GrantedBy int       `json:"granted_by"`
	CreatedAt time.Time `json:"created_at"`
}

OrgMigratorRole is one grant of the org migrator role. Actor is a user login or team slug, per ActorType ("USER" | "TEAM").

type OrgPATGrant

type OrgPATGrant struct {
	ID                  int               `json:"id"`
	OrgLogin            string            `json:"org_login"`
	OwnerUserID         int               `json:"owner_user_id"`
	TokenID             int               `json:"token_id"`
	TokenName           string            `json:"token_name"`
	TokenValue          string            `json:"-"`
	RepositorySelection string            `json:"repository_selection"`
	RepositoryIDs       []int             `json:"repository_ids,omitempty"`
	Permissions         OrgPATPermissions `json:"permissions"`
	TokenExpiresAt      *time.Time        `json:"token_expires_at"`
	AccessGrantedAt     time.Time         `json:"access_granted_at"`
}

OrgPATGrant is an approved fine-grained PAT grant.

type OrgPATGrantRequest

type OrgPATGrantRequest struct {
	ID                  int               `json:"id"`
	OrgLogin            string            `json:"org_login"`
	OwnerUserID         int               `json:"owner_user_id"`
	TokenID             int               `json:"token_id"`
	TokenName           string            `json:"token_name"`
	TokenValue          string            `json:"-"`
	Reason              *string           `json:"reason"`
	RepositorySelection string            `json:"repository_selection"` // none | all | subset
	RepositoryIDs       []int             `json:"repository_ids,omitempty"`
	Permissions         OrgPATPermissions `json:"permissions"`
	TokenExpiresAt      *time.Time        `json:"token_expires_at"`
	CreatedAt           time.Time         `json:"created_at"`
}

OrgPATGrantRequest is a pending request for org access via a fine-grained PAT.

type OrgPATPermissions

type OrgPATPermissions struct {
	Organization map[string]string `json:"organization,omitempty"`
	Repository   map[string]string `json:"repository,omitempty"`
	Other        map[string]string `json:"other,omitempty"`
}

OrgPATPermissions mirrors the organization-programmatic-access-grant permissions shape.

type OrgRole

type OrgRole string

OrgRole is a user's role in an organization (GitHub's wire enum).

const (
	OrgRoleAdmin  OrgRole = "admin"
	OrgRoleMember OrgRole = "member"
)

type OrgScopedItem

type OrgScopedItem interface {
	ItemVisibility() string
	SelectedIDs() []int
	SetSelectedIDs([]int)
	TouchUpdated(time.Time)
}

OrgScopedItem is the selected-repositories surface shared by org secrets and variables, letting the per-repo add/remove endpoints run through one core.

type OrgSecret

type OrgSecret struct {
	Secret
	Visibility      string `json:"visibility"`
	SelectedRepoIDs []int  `json:"selected_repository_ids,omitempty"`
}

OrgSecret is an organization-level Actions secret plus its visibility scoping.

func (*OrgSecret) ItemVisibility

func (sec *OrgSecret) ItemVisibility() string

func (*OrgSecret) SelectedIDs

func (sec *OrgSecret) SelectedIDs() []int

func (*OrgSecret) SetSelectedIDs

func (sec *OrgSecret) SetSelectedIDs(ids []int)

func (*OrgSecret) TouchUpdated

func (sec *OrgSecret) TouchUpdated(now time.Time)

type OrgSecretScanningPatternConfig

type OrgSecretScanningPatternConfig struct {
	Version          string            `json:"version"`
	ProviderSettings map[string]string `json:"provider_settings"` // token_type → not-set | disabled | enabled
	CustomSettings   map[string]string `json:"custom_settings"`   // token_type → disabled | enabled
	UpdatedAt        time.Time         `json:"updated_at"`
}

OrgSecretScanningPatternConfig holds an org's push-protection pattern settings and the optimistic-concurrency version updates must present.

type OrganizationMigration

type OrganizationMigration struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`
	// EnterpriseID is the enterprise the target organization belongs to.
	EnterpriseID  int    `json:"enterprise_id"`
	SourceOrgURL  string `json:"source_org_url"`
	SourceOrgName string `json:"source_org_name"`
	TargetOrgName string `json:"target_org_name"`
	// TargetOrgID is 0 until the target organization has been created.
	TargetOrgID   int    `json:"target_org_id,omitempty"`
	State         string `json:"state"`
	FailureReason string `json:"failure_reason,omitempty"`
	// TotalRepositoriesCount is nil until the source has been enumerated.
	TotalRepositoriesCount     *int   `json:"total_repositories_count,omitempty"`
	RemainingRepositoriesCount *int   `json:"remaining_repositories_count,omitempty"`
	SourceAccessToken          string `json:"source_access_token,omitempty"`
	// StartedByUserID owns the target org and everything created under it.
	StartedByUserID int       `json:"started_by_user_id,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

OrganizationMigration is a whole organization coming across, fanning out into repository migrations.

func FindOrganizationMigrationByNodeID

func FindOrganizationMigrationByNodeID(st *Store, nodeID string) *OrganizationMigration

FindOrganizationMigrationByNodeID resolves an organization migration global id to the LIVE row.

type PRCreationCap

type PRCreationCap struct {
	Enabled             bool `json:"enabled"`
	MaxOpenPullRequests int  `json:"max_open_pull_requests"`
}

type PRReviewComment

type PRReviewComment struct {
	ID                int       `json:"id"`
	NodeID            string    `json:"node_id"`
	PullRequestID     int       `json:"-"`
	ReviewID          int       `json:"pull_request_review_id"`
	InReplyToID       int       `json:"in_reply_to_id,omitempty"`
	DiffHunk          string    `json:"diff_hunk"`
	Path              string    `json:"path"`
	Position          *int      `json:"position"`
	OriginalPosition  *int      `json:"original_position"`
	Line              *int      `json:"line"`
	OriginalLine      *int      `json:"original_line"`
	StartLine         *int      `json:"start_line"`
	OriginalStartLine *int      `json:"original_start_line"`
	Side              string    `json:"side"` // LEFT | RIGHT
	StartSide         string    `json:"start_side,omitempty"`
	CommitID          string    `json:"commit_id"`
	OriginalCommitID  string    `json:"original_commit_id"`
	Body              string    `json:"body"`
	AuthorID          int       `json:"-"`
	ThreadID          int       `json:"-"` // shared by thread root + replies
	Resolved          bool      `json:"-"` // thread-level flag, stored on the root
	ResolvedByID      int       `json:"-"` // 0 when unresolved
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
}

func FindPullRequestReviewCommentByNodeID

func FindPullRequestReviewCommentByNodeID(st *Store, nodeID string) *PRReviewComment

FindPullRequestReviewCommentByNodeID resolves a PR review comment (PRRC_kgDO…).

type PRReviewCommentStore

type PRReviewCommentStore struct {
	Mu   sync.RWMutex             `json:"-"`
	ByID map[int]*PRReviewComment `json:"-"`

	NextID  int          `json:"-"`
	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

func NewPRReviewCommentStore

func NewPRReviewCommentStore(p *Persistence) *PRReviewCommentStore

func (*PRReviewCommentStore) AttachToReview

func (s *PRReviewCommentStore) AttachToReview(commentID, reviewID int) bool

AttachToReview links a review comment to the review that created it.

func (*PRReviewCommentStore) CreateRootComment

func (s *PRReviewCommentStore) CreateRootComment(prID, authorID int, path, body, commitID, side string, line, startLine int) *PRReviewComment

CreateRootComment creates a top-level review comment.

func (*PRReviewCommentStore) Delete

func (s *PRReviewCommentStore) Delete(id int, reactions *ReactionStore) bool

Delete removes a review comment. The comment row and its reactions delete in one transaction (STORE-001/002).

func (*PRReviewCommentStore) DeleteForPR

func (s *PRReviewCommentStore) DeleteForPR(prID int)

func (*PRReviewCommentStore) DeleteForPRBatch

func (s *PRReviewCommentStore) DeleteForPRBatch(prID int, batch *PersistBatch)

func (*PRReviewCommentStore) Get

func (*PRReviewCommentStore) GetThread

func (s *PRReviewCommentStore) GetThread(threadID int) *ReviewThread

func (*PRReviewCommentStore) IDsForPR

func (s *PRReviewCommentStore) IDsForPR(prID int) map[int]bool

func (*PRReviewCommentStore) ListForPR

func (s *PRReviewCommentStore) ListForPR(prID int) []*PRReviewComment

func (*PRReviewCommentStore) ListThreads

func (s *PRReviewCommentStore) ListThreads(prID int) []*ReviewThread

func (*PRReviewCommentStore) Reply

func (s *PRReviewCommentStore) Reply(prID, rootID, authorID int, body string) *PRReviewComment

Reply appends a reply to a root comment.

func (*PRReviewCommentStore) ResolveThread

func (s *PRReviewCommentStore) ResolveThread(threadID int, resolved bool, resolverID int) bool

ResolveThread sets the thread root's Resolved flag and resolver. Unresolving clears the resolver.

func (*PRReviewCommentStore) Update

func (s *PRReviewCommentStore) Update(id int, body string) bool

type Package

type Package struct {
	ID           int        `json:"id"`
	NodeID       string     `json:"node_id"`
	Name         string     `json:"name"`
	PackageType  string     `json:"package_type"`
	OwnerType    string     `json:"owner_type"` // "User", "Organization", "Repository"
	OwnerKey     string     `json:"owner_key"`  // username, org login, or owner/repo
	Visibility   string     `json:"visibility"`
	URL          string     `json:"url"`
	HTMLURL      string     `json:"html_url"`
	VersionCount int        `json:"version_count"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	Deleted      bool       `json:"deleted,omitempty"`
	DeletedAt    *time.Time `json:"deleted_at,omitempty"`
}

Package is a GitHub software package. JSON tags define the persistence row shape; API responses are built by packageToJSON.

type PackageFile

type PackageFile struct {
	ID          int    `json:"id"`
	NodeID      string `json:"node_id"`
	VersionID   int    `json:"version_id"`
	Name        string `json:"name"`
	ContentType string `json:"content_type"`
	Size        int64  `json:"size"`
	URL         string `json:"url"`
	HTMLURL     string `json:"html_url"`
	DownloadURL string `json:"download_url"`
	StoragePath string `json:"storage_path,omitempty"`
	// UpdatedAt backs the required GraphQL PackageFile.updatedAt. A file is
	// immutable, so it equals the upload time.
	UpdatedAt time.Time `json:"updated_at"`
}

PackageFile is a single file attached to a package version. JSON tags define the persistence row shape.

type PackageFileInput

type PackageFileInput struct {
	Name          string `json:"name"`
	ContentType   string `json:"content_type"`
	ContentBase64 string `json:"content_base64"`
}

PackageFileInput is the wire payload for an uploaded package file.

type PackageVersion

type PackageVersion struct {
	ID          int                    `json:"id"`
	NodeID      string                 `json:"node_id"`
	PackageID   int                    `json:"package_id"`
	Version     string                 `json:"name"` // GitHub calls the version "name"
	Description string                 `json:"description"`
	Metadata    map[string]interface{} `json:"metadata"`
	// RegistryManifestDigest is internal registry lookup state; REST responses
	// expose container tags in metadata instead.
	RegistryManifestDigest string     `json:"registry_manifest_digest,omitempty"`
	URL                    string     `json:"url"`
	HTMLURL                string     `json:"html_url"`
	PackageURL             string     `json:"package_html_url"`
	CreatedAt              time.Time  `json:"created_at"`
	UpdatedAt              time.Time  `json:"updated_at"`
	Deleted                bool       `json:"deleted,omitempty"`
	DeletedAt              *time.Time `json:"deleted_at,omitempty"`
}

PackageVersion is a version of a package. JSON tags define the persistence row shape.

type PagesBuild

type PagesBuild struct {
	// ID routes GET .../pages/builds/{build_id}. Not serialized: GitHub's build
	// object has no top-level id, only the trailing segment of url.
	ID        int64          `json:"-"`
	URL       string         `json:"url"`
	Status    string         `json:"status"`
	Pusher    *PagesPusher   `json:"pusher"`
	Commit    string         `json:"commit"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	Duration  int            `json:"duration"`
	Error     *PagesBuildErr `json:"error"`
}

type PagesBuildErr

type PagesBuildErr struct {
	Message *string `json:"message"`
}

type PagesDeploymentRecord

type PagesDeploymentRecord struct {
	ID           int       `json:"id"`
	RepoID       int       `json:"repo_id"`
	Status       string    `json:"status"`
	Environment  string    `json:"environment"`
	BuildVersion string    `json:"pages_build_version"`
	ArtifactSize int64     `json:"artifact_size"`
	ArtifactSHA  string    `json:"artifact_sha256"`
	ArtifactKey  string    `json:"artifact_object_key"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

PagesDeploymentRecord is one Pages deployment. The publish is synchronous (no CDN tier), so a stored deployment is already terminal ("succeed") and cancellation, which needs a non-terminal deployment, is never observable.

type PagesHTTPSCertificate

type PagesHTTPSCertificate struct {
	State       string   `json:"state"`
	Description string   `json:"description"`
	Domains     []string `json:"domains"`
	ExpiresAt   *string  `json:"expires_at"`
}

type PagesPusher

type PagesPusher struct {
	Login string `json:"login"`
	ID    int    `json:"id"`
	Type  string `json:"type"`
}

type PagesSite

type PagesSite struct {
	CNAME                string                 `json:"cname"`
	URL                  string                 `json:"url"`
	HTMLURL              string                 `json:"html_url"`
	Status               string                 `json:"status"`
	Source               map[string]interface{} `json:"source"`
	Public               bool                   `json:"public"`
	Custom404            bool                   `json:"custom_404"`
	ProtectedDomainState *string                `json:"protected_domain_state"`
	BuildType            *string                `json:"build_type"`
	HTTPSCertificate     *PagesHTTPSCertificate `json:"https_certificate,omitempty"`
	HTTPSEnforced        bool                   `json:"https_enforced"`
}

type PendingDeletion

type PendingDeletion struct {
	Kind                string                    `json:"kind"`
	Name                string                    `json:"name"`
	StartedAt           time.Time                 `json:"started_at"`
	ObjectKeys          []string                  `json:"object_keys,omitempty"`
	LocalFiles          []string                  `json:"local_files,omitempty"`
	CodespaceRuntimes   []pendingCodespaceRuntime `json:"codespace_runtimes,omitempty"`
	ReleaseAssetObjects []string                  `json:"release_asset_objects,omitempty"`
	ReleaseAssetFiles   []string                  `json:"release_asset_files,omitempty"`
	ActionsObjectKeys   []string                  `json:"actions_object_keys,omitempty"`
	ActionsDirectories  []string                  `json:"actions_directories,omitempty"`
}

type PendingDeployment

type PendingDeployment struct {
	EnvID              int       `json:"envId"`
	EnvName            string    `json:"envName"`
	WaitTimerStartedAt time.Time `json:"waitTimerStartedAt"`
}

PendingDeployment is one reviewer-protected environment a run waits on.

type PendingRename

type PendingRename struct {
	From      string    `json:"from"`
	To        string    `json:"to"`
	StartedAt time.Time `json:"started_at"`
}

type PermLevel

type PermLevel int

PermLevel is the entitlement level a credential holds for a PermScope. Ordering: read < write < admin, each level implying the ones below it.

const (
	PermRead PermLevel = iota
	PermWrite
	PermAdmin
)

type PermScope

type PermScope string

PermScope is a GitHub fine-grained permission name. The values are the exact keys used in installation-token Permissions maps and the App API; they must not change.

const (
	ScopeMetadata          PermScope = "metadata"
	ScopeContents          PermScope = "contents"
	ScopeIssues            PermScope = "issues"
	ScopeDiscussions       PermScope = "discussions"
	ScopePullRequests      PermScope = "pull_requests"
	ScopeActions           PermScope = "actions"
	ScopeChecks            PermScope = "checks"
	ScopeSecrets           PermScope = "secrets"
	ScopeDeployments       PermScope = "deployments"
	ScopeAdministration    PermScope = "administration"
	ScopeMembers           PermScope = "members"
	ScopeOrgAdministration PermScope = "organization_administration"
	ScopeOrganizationHooks PermScope = "organization_hooks"
	ScopeSecurityEvents    PermScope = "security_events"
	ScopeDependabotSecrets PermScope = "dependabot_secrets" // #nosec G101 -- permission name, not a secret
	ScopeCodespaces        PermScope = "codespaces"
	ScopeReactions         PermScope = "reactions"
	ScopeProjects          PermScope = "projects"
	ScopePages             PermScope = "pages"
	ScopePATRequests       PermScope = "organization_personal_access_token_requests"
	ScopePATs              PermScope = "organization_personal_access_tokens"
	ScopeCopilotSpaces     PermScope = "copilot_spaces"
)

type PermissionDef

type PermissionDef map[string]string

PermissionDef is the normalized permissions block for the workflow's GITHUB_TOKEN. "*" represents the read-all/write-all scalar shorthand.

func (*PermissionDef) UnmarshalYAML

func (p *PermissionDef) UnmarshalYAML(node *yaml.Node) error

type PersistBatch

type PersistBatch struct {
	Err error `json:"-"`
	// contains filtered or unexported fields
}

PersistBatch accumulates one multi-step mutation's writes into a single transaction; a crash before Commit leaves the previous state intact.

func NewPersistBatch

func NewPersistBatch(p *Persistence) *PersistBatch

func (*PersistBatch) Commit

func (b *PersistBatch) Commit() error

func (*PersistBatch) Delete

func (b *PersistBatch) Delete(bucket, key string)

func (*PersistBatch) Put

func (b *PersistBatch) Put(bucket, key string, v interface{})

type Persistence

type Persistence struct {
	Db      *sql.DB    `json:"-"`
	Dialect dbDialect  `json:"-"`
	Mu      sync.Mutex `json:"-"`
	// contains filtered or unexported fields
}

func MustNewPersistence

func MustNewPersistence() *Persistence

func NewPersistence

func NewPersistence() (*Persistence, error)

func (*Persistence) AcquireLock

func (p *Persistence) AcquireLock(name, owner string, ttl time.Duration) (bool, error)

AcquireLock takes the named lock for owner until ttl elapses, returning false when another owner holds it. The expiry frees a lock stranded by a dead replica.

func (*Persistence) AllocateCounterValue

func (p *Persistence) AllocateCounterValue(name string, minimum int64) (int64, error)

AllocateCounterValue atomically reserves one value (>= minimum) from a durable sequence. The single upsert is safe under concurrent dqlite allocators, unlike a GetCounter/SetCounter pair.

func (*Persistence) ClaimOIDCLogoutAndDeleteSessions

func (p *Persistence) ClaimOIDCLogoutAndDeleteSessions(replayKey string, expiresAt, now time.Time, provider, issuer, sid, subject string) (bool, error)

ClaimOIDCLogoutAndDeleteSessions stores a replay marker and deletes the matching browser sessions in one transaction. The kv primary key makes the claim exclusive across processes and replicas.

func (*Persistence) ClaimScheduleFiring

func (p *Persistence) ClaimScheduleFiring(key string, minute time.Time, minInterval time.Duration) (bool, error)

ClaimScheduleFiring atomically selects one replica for a cron tuple/minute. Claims stay outside the metadata revision feed: they coordinate a Workflow row's creation but are not themselves API state. ClaimScheduleFiring claims a firing for a schedule at minute, honoring GitHub's per-schedule minimum interval: the claim succeeds only if the schedule has no prior firing or its last firing is at least minInterval old. One row per schedule holds the last firing time and is updated in place, so this doubles as the exact-minute dedup for ticker drift and catch-up replays.

func (*Persistence) Close

func (p *Persistence) Close() error

func (*Persistence) Delete

func (p *Persistence) Delete(bucket, key string) error

func (*Persistence) DeleteBatch

func (p *Persistence) DeleteBatch(entries ...PersistencePut) error

func (*Persistence) EnqueuedSeq

func (p *Persistence) EnqueuedSeq() int64

EnqueuedSeq is the highest group-commit sequence handed out; the HTTP durability barrier waits for it to become durable before flushing a response.

func (*Persistence) Get

func (p *Persistence) Get(bucket, key string) ([]byte, error)

func (*Persistence) GetCounter

func (p *Persistence) GetCounter(name string) (int64, error)

func (*Persistence) GroupCommitActive

func (p *Persistence) GroupCommitActive() bool

GroupCommitActive reports whether writes are batched off the caller's lock.

func (*Persistence) KeyHighWater

func (p *Persistence) KeyHighWater(bucket string) (int64, error)

KeyHighWater returns one past the highest identifier ever written to a bucket. Loaders max it with surviving rows so a deleted entity's id — also its object-store key for attestations, package files and artifacts — is never reused.

func (*Persistence) List

func (p *Persistence) List(bucket string) (map[string][]byte, error)

func (*Persistence) ListPrefix

func (p *Persistence) ListPrefix(bucket, prefix string) (map[string][]byte, error)

ListPrefix returns rows whose key begins with prefix via an indexed range scan `[prefix, prefixSuccessor)`, never a whole-bucket scan, for composite-key secondary indexes (e.g. login sessions keyed by user). The bucket must not be sensitive: a range scan cannot recover a per-row opaque storage key.

func (*Persistence) LocalRevision

func (p *Persistence) LocalRevision() int64

func (*Persistence) MustDelete

func (p *Persistence) MustDelete(bucket, key string)

func (*Persistence) MustPut

func (p *Persistence) MustPut(bucket, key string, v interface{})

MustPut writes a record or panics; the server's recovery middleware turns the panic into a 500 and the caller's deferred unlocks release the store lock.

func (*Persistence) OwnedExclusively

func (p *Persistence) OwnedExclusively() bool

OwnedExclusively reports whether this process is the only writer: true for a local SQLite file, false for a shared dqlite quorum this process must not rewrite at startup.

func (*Persistence) Put

func (p *Persistence) Put(bucket, key string, v interface{}) error

func (*Persistence) PutBatch

func (p *Persistence) PutBatch(entries ...PersistencePut) error

PutBatch commits related records in one transaction. Callers update their in-memory indexes only after it returns successfully.

func (*Persistence) Ready

func (p *Persistence) Ready(ctx context.Context) error

func (*Persistence) ReleaseLock

func (p *Persistence) ReleaseLock(name, owner string) error

ReleaseLock drops the named lock if owner still holds it.

func (*Persistence) ReleaseScheduleFiring

func (p *Persistence) ReleaseScheduleFiring(key string, minute time.Time) error

ReleaseScheduleFiring reverts a ClaimScheduleFiring whose firing failed transiently, so the occurrence can be retried. It removes the schedule's row only while this minute is still the one recorded (we are the latest claimant).

func (*Persistence) SetCounter

func (p *Persistence) SetCounter(name string, value int64) error

func (*Persistence) StateRevision

func (p *Persistence) StateRevision() (int64, error)

func (*Persistence) StorageKey

func (p *Persistence) StorageKey(bucket, key string) string

func (*Persistence) WaitDurable

func (p *Persistence) WaitDurable(ctx context.Context, seq int64) error

WaitDurable blocks until every write up to seq is durable, returning the commit error (or ctx error) if it cannot be.

type PersistenceFailure

type PersistenceFailure struct {
	Op     string `json:"-"`
	Bucket string `json:"-"`
	Key    string `json:"-"`
	Err    error  `json:"-"`
}

PersistenceFailure is raised by the Must* helpers to abort the mid-write request rather than the process.

func (*PersistenceFailure) Error

func (e *PersistenceFailure) Error() string

func (*PersistenceFailure) Unwrap

func (e *PersistenceFailure) Unwrap() error

type PersistencePut

type PersistencePut struct {
	Bucket string      `json:"-"`
	Key    string      `json:"-"`
	Value  interface{} `json:"-"`
}

type PinnedEnvironment

type PinnedEnvironment struct {
	ID        int       `json:"id"`
	NodeID    string    `json:"node_id"`
	RepoID    int       `json:"repo_id"`
	EnvID     int       `json:"env_id"`
	Position  int       `json:"position"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

PinnedEnvironment pins an environment at a 1-based position in its repository's pinned list.

type PorterAuthor

type PorterAuthor struct {
	ID         int    `json:"id"`
	RemoteID   string `json:"remote_id"`
	RemoteName string `json:"remote_name"`
	Email      string `json:"email"`
	Name       string `json:"name"`
}

PorterAuthor is one distinct commit author discovered by the import.

type PrivateRegistryConfiguration

type PrivateRegistryConfiguration struct {
	Name                     string    `json:"name"`
	RegistryType             string    `json:"registry_type"`
	AuthType                 string    `json:"auth_type"`
	URL                      string    `json:"url"`
	Username                 *string   `json:"username"`
	ReplacesBase             bool      `json:"replaces_base"`
	Visibility               string    `json:"visibility"`
	SelectedRepositoryIDs    []int     `json:"selected_repository_ids"`
	EncryptedValue           string    `json:"-"` // opaque sealed box; never emitted
	KeyID                    string    `json:"key_id"`
	TenantID                 string    `json:"tenant_id"`
	ClientID                 string    `json:"client_id"`
	AWSRegion                string    `json:"aws_region"`
	AccountID                string    `json:"account_id"`
	RoleName                 string    `json:"role_name"`
	Domain                   string    `json:"domain"`
	DomainOwner              string    `json:"domain_owner"`
	JfrogOIDCProviderName    string    `json:"jfrog_oidc_provider_name"`
	Audience                 string    `json:"audience"`
	IdentityMappingName      string    `json:"identity_mapping_name"`
	Namespace                string    `json:"namespace"`
	ServiceSlug              string    `json:"service_slug"`
	APIHost                  string    `json:"api_host"`
	WorkloadIdentityProvider string    `json:"workload_identity_provider"`
	ServiceAccount           string    `json:"service_account"`
	CreatedAt                time.Time `json:"created_at"`
	UpdatedAt                time.Time `json:"updated_at"`
}

PrivateRegistryConfiguration is an org private registry configuration.

type PrivateRegistryRequest

type PrivateRegistryRequest struct {
	RegistryType             *string `json:"registry_type"`
	URL                      *string `json:"url"`
	Username                 *string `json:"username"`
	ReplacesBase             *bool   `json:"replaces_base"`
	EncryptedValue           *string `json:"encrypted_value"`
	KeyID                    *string `json:"key_id"`
	Visibility               *string `json:"visibility"`
	SelectedRepositoryIDs    []int   `json:"selected_repository_ids"`
	AuthType                 *string `json:"auth_type"`
	TenantID                 *string `json:"tenant_id"`
	ClientID                 *string `json:"client_id"`
	AWSRegion                *string `json:"aws_region"`
	AccountID                *string `json:"account_id"`
	RoleName                 *string `json:"role_name"`
	Domain                   *string `json:"domain"`
	DomainOwner              *string `json:"domain_owner"`
	JfrogOIDCProviderName    *string `json:"jfrog_oidc_provider_name"`
	Audience                 *string `json:"audience"`
	IdentityMappingName      *string `json:"identity_mapping_name"`
	Namespace                *string `json:"namespace"`
	ServiceSlug              *string `json:"service_slug"`
	APIHost                  *string `json:"api_host"`
	WorkloadIdentityProvider *string `json:"workload_identity_provider"`
	ServiceAccount           *string `json:"service_account"`
}

type ProjectCard

type ProjectCard struct {
	ID            int       `json:"id"`
	NodeID        string    `json:"node_id"`
	ColumnID      int       `json:"column_id"`
	Note          string    `json:"note"`
	IssueID       int       `json:"issue_id"`
	PullRequestID int       `json:"pull_request_id,omitempty"`
	CreatorID     int       `json:"creator_id"`
	Archived      bool      `json:"archived,omitempty"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	Position      int64     `json:"position"` // ordering; persisted, not surfaced by the API mapper
}

ProjectCard is a card inside a ProjectColumn: either a note card (Note set) or a content card (exactly one of IssueID/PullRequestID set).

func FindProjectCardByNodeID

func FindProjectCardByNodeID(st *Store, nodeID string) *ProjectCard

FindProjectCardByNodeID returns the LIVE card row whose node id matches.

type ProjectClassic

type ProjectClassic struct {
	ID      int    `json:"id"`
	NodeID  string `json:"node_id"`
	RepoKey string `json:"repo_key"`
	// OwnerType is "User"/"Organization" for account-owned, empty for repo-scoped.
	OwnerType  string     `json:"owner_type,omitempty"`
	OwnerLogin string     `json:"owner_login,omitempty"`
	Name       string     `json:"name"`
	Body       string     `json:"body"`
	State      string     `json:"state"` // "open" or "closed"
	Number     int        `json:"number"`
	CreatorID  int        `json:"creator_id"`
	Public     bool       `json:"public,omitempty"`
	ClosedAt   *time.Time `json:"closed_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
	// LinkedRepoIDs are repositories linked to an account-owned project; a
	// repo-scoped project links nothing.
	LinkedRepoIDs []int `json:"linked_repo_ids,omitempty"`
}

ProjectClassic is a Projects classic (v1) project, owned by exactly one of a repository (RepoKey) or an account (OwnerType+OwnerLogin). It holds columns, which hold cards.

func FindProjectClassicByNodeID

func FindProjectClassicByNodeID(st *Store, nodeID string) *ProjectClassic

FindProjectClassicByNodeID returns the LIVE project row (Find* convention; callers must not mutate it — use the Get* snapshot for rendering).

type ProjectColumn

type ProjectColumn struct {
	ID        int       `json:"id"`
	NodeID    string    `json:"node_id"`
	ProjectID int       `json:"project_id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Position  int64     `json:"position"` // ordering; persisted, not surfaced by the API mapper
}

ProjectColumn is a column inside a ProjectClassic.

func FindProjectColumnByNodeID

func FindProjectColumnByNodeID(st *Store, nodeID string) *ProjectColumn

FindProjectColumnByNodeID returns the LIVE column row whose node id matches.

type ProjectV2

type ProjectV2 struct {
	ID        int
	NodeID    string
	Number    int    // per-owner sequential
	OwnerID   int    // user/org ID
	OwnerType string // "User" or "Organization"
	CreatorID int    // user who created the project
	Title     string
	Closed    bool
	ClosedAt  *time.Time
	Public    bool
	URL       string
	CreatedAt time.Time
	UpdatedAt time.Time

	// ShortDescription is the one-line blurb; Readme is the markdown body.
	ShortDescription string
	Readme           string
	// Template marks the project as one new projects may be copied from.
	Template bool
	// LinkedRepoIDs / LinkedTeamIDs are the linked repositories and teams.
	LinkedRepoIDs []int
	LinkedTeamIDs []int
	// Collaborators are per-account grants layered on the owner's access.
	Collaborators []*ProjectV2Collaborator
}

ProjectV2 is a Projects v2 project owned by a user or organization, with a stable per-owner Number and a globally unique NodeID.

type ProjectV2Change

type ProjectV2Change struct {
	From interface{}
	To   interface{}
}

type ProjectV2Collaborator

type ProjectV2Collaborator struct {
	UserID int
	TeamID int // set instead of UserID when the collaborator is a team
	Role   string
}

ProjectV2Collaborator is one account's explicit permission on a project. Role is GitHub's ProjectV2Roles enum: READER, WRITER, ADMIN or NONE.

type ProjectV2Event

type ProjectV2Event struct {
	Event   string
	Action  string
	Project *ProjectV2 // always set
	// Item and StatusUpdate are set for the events whose subject they are.
	Item         *ProjectV2Item
	StatusUpdate *ProjectV2StatusUpdate
	Sender       *User
	// Changes carries the before/after diff for `edited` actions, keyed by
	// field name; nil when the action has no diff.
	Changes map[string]ProjectV2Change
}

ProjectV2Event describes one delivery of the projects_v2 webhook family, built by both the GraphQL and REST write paths so the two surfaces agree. GitHub splits the family three ways, carrying a different object each:

projects_v2               the project itself
projects_v2_item          the item, plus the project it belongs to
projects_v2_status_update the status update, plus its project

None carry a repository, so delivery is to the owning account's hooks.

type ProjectV2Field

type ProjectV2Field struct {
	ID        int
	NodeID    string
	ProjectID int
	Name      string
	DataType  ProjectV2FieldDataType
	Options   []*ProjectV2SingleSelectOption
	Iteration *ProjectV2IterationConfiguration
	CreatedAt time.Time
	UpdatedAt time.Time
}

ProjectV2Field is a column on a project. SINGLE_SELECT carries per-option metadata in Options; ITERATION carries its schedule in Iteration.

type ProjectV2FieldDataType

type ProjectV2FieldDataType string

ProjectV2FieldDataType is the custom-field data type, spelled uppercase to match the GraphQL enum; REST handlers lowercase it on the wire.

const (
	ProjectV2FieldSingleSelect ProjectV2FieldDataType = "SINGLE_SELECT"
	ProjectV2FieldMultiSelect  ProjectV2FieldDataType = "MULTI_SELECT"
	ProjectV2FieldText         ProjectV2FieldDataType = "TEXT"
	ProjectV2FieldNumber       ProjectV2FieldDataType = "NUMBER"
	ProjectV2FieldDate         ProjectV2FieldDataType = "DATE"
	ProjectV2FieldIteration    ProjectV2FieldDataType = "ITERATION"
)

func (ProjectV2FieldDataType) SelectsOptions

func (t ProjectV2FieldDataType) SelectsOptions() bool

SelectsOptions reports whether the data type carries a list of selectable options, which SINGLE_SELECT and MULTI_SELECT both do.

type ProjectV2FieldUpdate

type ProjectV2FieldUpdate struct {
	Name    *string
	Options []*ProjectV2SingleSelectOption // replaces the option list wholesale when non-nil
	// Iteration replaces an ITERATION field's schedule wholesale when non-nil.
	Iteration *ProjectV2IterationConfiguration
}

ProjectV2FieldUpdate is the patch updateProjectV2Field applies.

type ProjectV2Item

type ProjectV2Item struct {
	ID          int
	NodeID      string
	ProjectID   int
	ContentType string
	ContentID   int // 0 for DraftIssue
	CreatorID   int
	DraftTitle  string
	DraftBody   string
	FieldValues map[int]*ProjectV2ItemFieldValue // fieldID → value
	CreatedAt   time.Time
	UpdatedAt   time.Time
	ArchivedAt  *time.Time
	// Position orders the item within its project. Items are handed out in
	// ascending Position, and updateProjectV2ItemPosition rewrites it.
	Position int
}

ProjectV2Item links an issue or PR (or a draft issue) to a project. ContentType is "Issue", "PullRequest", or "DraftIssue".

type ProjectV2ItemFieldUpdate

type ProjectV2ItemFieldUpdate struct {
	FieldID int
	Value   interface{}
}

ProjectV2FieldUpdate is one field write in a batch item update.

type ProjectV2ItemFieldValue

type ProjectV2ItemFieldValue struct {
	FieldID     int
	OptionID    string   // SINGLE_SELECT
	OptionName  string   // denormalised so reads don't chase the field
	TextValue   string   // TEXT
	NumberValue float64  // NUMBER
	DateValue   string   // DATE, YYYY-MM-DD
	IterationID string   // ITERATION
	OptionIDs   []string // MULTI_SELECT, ordered set
	OptionNames []string
}

ProjectV2ItemFieldValue is an item's value for one field; which member is set depends on the field's data type.

type ProjectV2Iteration

type ProjectV2Iteration struct {
	ID        string // same 8-char ID space as single-select options
	Title     string
	StartDate string // YYYY-MM-DD
	Duration  int    // days
}

ProjectV2Iteration is one concrete iteration on an ITERATION field.

type ProjectV2IterationConfiguration

type ProjectV2IterationConfiguration struct {
	StartDate  string // date of the first iteration, YYYY-MM-DD
	Duration   int    // default iteration length in days
	Iterations []*ProjectV2Iteration
}

ProjectV2IterationConfiguration is the schedule of an ITERATION field: a default duration plus the concrete iterations.

type ProjectV2Owner

type ProjectV2Owner struct {
	ID        int
	OwnerType string // "Organization" or "User"
	Login     string
	Org       *Org
	User      *User
}

ProjectV2Owner is a project's resolved owner (org or user). Both the REST and GraphQL layers resolve into this before the shared access predicates.

type ProjectV2SingleSelectOption

type ProjectV2SingleSelectOption struct {
	ID          string // GitHub uses 8-char alnum IDs ("47fc9ee4"); we generate similar
	Name        string
	Color       string // GitHub's option color enum (BLUE, GRAY, GREEN, ...)
	Description string
}

ProjectV2SingleSelectOption is one selectable value on a SINGLE_SELECT field (e.g. Status: Todo / In Progress / Done).

type ProjectV2StatusUpdate

type ProjectV2StatusUpdate struct {
	ID         int
	NodeID     string
	ProjectID  int
	CreatorID  int
	Body       string
	Status     string // ProjectV2StatusUpdateStatus enum, "" when unset
	StartDate  string // YYYY-MM-DD, "" when unset
	TargetDate string // YYYY-MM-DD, "" when unset
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

ProjectV2StatusUpdate is a dated progress note posted on a project.

type ProjectV2StatusUpdatePatch

type ProjectV2StatusUpdatePatch struct {
	Body       *string
	Status     *string
	StartDate  *string
	TargetDate *string
}

ProjectV2StatusUpdatePatch is the patch updateProjectV2StatusUpdate applies.

type ProjectV2Store

type ProjectV2Store struct {
	Mu       sync.RWMutex     `json:"-"`
	ClockMu  sync.RWMutex     `json:"-"`
	ClockNow func() time.Time `json:"-"`

	FieldsByProj map[int][]*ProjectV2Field `json:"-"`

	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

ProjectV2Store is the in-memory store. Concurrency-safe via mu.

func NewProjectV2Store

func NewProjectV2Store(p *Persistence) *ProjectV2Store

func (*ProjectV2Store) AddDraftItem

func (s *ProjectV2Store) AddDraftItem(projectID int, title, body string, creatorID int) *ProjectV2Item

AddDraftItem adds a draft issue to a project.

func (*ProjectV2Store) AddItem

func (s *ProjectV2Store) AddItem(projectID int, contentType string, contentID, creatorID int) *ProjectV2Item

AddItem adds an Issue or PullRequest to a project. contentID is the issue or PR database ID; contentType is "Issue" or "PullRequest".

func (*ProjectV2Store) ArchiveItem

func (s *ProjectV2Store) ArchiveItem(id int, archived bool) *ProjectV2Item

ArchiveItem archives or unarchives a project item, returning the updated snapshot. Re-archiving keeps the original ArchivedAt timestamp.

func (*ProjectV2Store) ClearFieldValue

func (s *ProjectV2Store) ClearFieldValue(itemID, fieldID int) (*ProjectV2Item, error)

ClearFieldValue removes an item's value for one field. Clearing an unset field is not an error.

func (*ProjectV2Store) CollaboratorRole

func (s *ProjectV2Store) CollaboratorRole(projectID, userID int) string

CollaboratorRole returns the role explicitly granted to a user, or "".

func (*ProjectV2Store) ConvertDraftToIssue

func (s *ProjectV2Store) ConvertDraftToIssue(itemID, issueID int) (*ProjectV2Item, error)

ConvertDraftToIssue repoints a draft item at a real issue, clearing the draft title and body so the two cannot drift.

func (*ProjectV2Store) CopyProject

func (s *ProjectV2Store) CopyProject(sourceID, ownerID int, ownerType, title string, includeDraftIssues bool, creatorID int) *ProjectV2

CopyProject duplicates a project under a (possibly different) owner. Fields and views are always copied; items only when includeDraftIssues asks for it.

func (*ProjectV2Store) CreateField

func (s *ProjectV2Store) CreateField(projectID int, name string, dataType ProjectV2FieldDataType, options []*ProjectV2SingleSelectOption, iteration *ProjectV2IterationConfiguration) *ProjectV2Field

CreateField adds a field column to a project. options applies to SINGLE_SELECT and iteration to ITERATION; their IDs are assigned here.

func (*ProjectV2Store) CreateProject

func (s *ProjectV2Store) CreateProject(ownerID int, ownerType, title string, creatorID int) *ProjectV2

CreateProject creates a new ProjectV2 owned by the given user or org, recording the creating user.

func (*ProjectV2Store) CreateStatusUpdate

func (s *ProjectV2Store) CreateStatusUpdate(projectID, creatorID int, body, status, startDate, targetDate string) *ProjectV2StatusUpdate

CreateStatusUpdate posts a status update on a project.

func (*ProjectV2Store) CreateView

func (s *ProjectV2Store) CreateView(projectID int, name, layout string, filter *string, visibleFields []int, creatorID int) *ProjectV2View

CreateView adds a view to a project.

func (*ProjectV2Store) CreateWorkflow

func (s *ProjectV2Store) CreateWorkflow(projectID int, name string, enabled bool) *ProjectV2Workflow

CreateWorkflow records an automation rule on a project. GitHub has no create-workflow mutation, so this is the seam the UI and seeded defaults use.

func (*ProjectV2Store) CurrentTime

func (s *ProjectV2Store) CurrentTime() time.Time

func (*ProjectV2Store) DeleteContentItems

func (s *ProjectV2Store) DeleteContentItems(contentType string, contentIDs map[int]bool)

DeleteContentItems removes every item whose content is one of the supplied issue or PR database IDs.

func (*ProjectV2Store) DeleteContentItemsBatch

func (s *ProjectV2Store) DeleteContentItemsBatch(contentType string, contentIDs map[int]bool, batch *PersistBatch)

func (*ProjectV2Store) DeleteField

func (s *ProjectV2Store) DeleteField(id int) bool

DeleteField removes a field from a project.

func (*ProjectV2Store) DeleteItem

func (s *ProjectV2Store) DeleteItem(id int) bool

DeleteItem removes an item from a project.

func (*ProjectV2Store) DeleteProject

func (s *ProjectV2Store) DeleteProject(id int) bool

DeleteProject removes a project and every entity it owns: fields, items, views, status updates and workflows.

func (*ProjectV2Store) DeleteStatusUpdate

func (s *ProjectV2Store) DeleteStatusUpdate(id int) *ProjectV2StatusUpdate

DeleteStatusUpdate removes a status update, returning the deleted snapshot.

func (*ProjectV2Store) DeleteView

func (s *ProjectV2Store) DeleteView(id int) *ProjectV2View

DeleteView removes a view, returning the deleted snapshot.

func (*ProjectV2Store) DeleteWorkflow

func (s *ProjectV2Store) DeleteWorkflow(id int) *ProjectV2Workflow

DeleteWorkflow removes an automation rule, returning the deleted snapshot.

func (*ProjectV2Store) FieldByNameOnProject

func (s *ProjectV2Store) FieldByNameOnProject(projectID int, name string) *ProjectV2Field

FieldByNameOnProject returns the named field on the project, or nil.

func (*ProjectV2Store) FieldsForProject

func (s *ProjectV2Store) FieldsForProject(projectID int) []*ProjectV2Field

FieldsForProject returns every field defined on the project.

func (*ProjectV2Store) GetField

func (s *ProjectV2Store) GetField(id int) *ProjectV2Field

GetField returns the field by id.

func (*ProjectV2Store) GetItem

func (s *ProjectV2Store) GetItem(id int) *ProjectV2Item

GetItem returns a project item by id.

func (*ProjectV2Store) GetProject

func (s *ProjectV2Store) GetProject(id int) *ProjectV2

GetProject returns a project by ID or nil.

func (*ProjectV2Store) GetProjectByOwnerNumber

func (s *ProjectV2Store) GetProjectByOwnerNumber(ownerID int, ownerType string, number int) *ProjectV2

GetProjectByOwnerNumber returns the owner's project with the given per-owner number, or nil.

func (*ProjectV2Store) GetStatusUpdate

func (s *ProjectV2Store) GetStatusUpdate(id int) *ProjectV2StatusUpdate

GetStatusUpdate returns one status update by database ID.

func (*ProjectV2Store) GetView

func (s *ProjectV2Store) GetView(id int) *ProjectV2View

GetView returns a view by id.

func (*ProjectV2Store) GetViewByNumber

func (s *ProjectV2Store) GetViewByNumber(projectID, number int) *ProjectV2View

GetViewByNumber returns the project's view with the given per-project number, or nil.

func (*ProjectV2Store) GetWorkflow

func (s *ProjectV2Store) GetWorkflow(id int) *ProjectV2Workflow

GetWorkflow returns one workflow by database ID.

func (*ProjectV2Store) GetWorkflowByNumber

func (s *ProjectV2Store) GetWorkflowByNumber(projectID, number int) *ProjectV2Workflow

GetWorkflowByNumber returns the project's workflow with the given per-project number.

func (*ProjectV2Store) LinkRepository

func (s *ProjectV2Store) LinkRepository(projectID, repoID int) *ProjectV2

LinkRepository links a repository to a project. Linking one already linked is a no-op, returning the project either way.

func (*ProjectV2Store) LinkTeam

func (s *ProjectV2Store) LinkTeam(projectID, teamID int) *ProjectV2

LinkTeam links a team to a project.

func (*ProjectV2Store) ListItemsForIssue

func (s *ProjectV2Store) ListItemsForIssue(issueID int) []*ProjectV2Item

ListItemsForIssue returns every project item wrapping the issue with the given database ID.

func (*ProjectV2Store) ListItemsForPR

func (s *ProjectV2Store) ListItemsForPR(prID int) []*ProjectV2Item

ListItemsForPR returns every project item wrapping the PR with the given database ID.

func (*ProjectV2Store) ListItemsForProject

func (s *ProjectV2Store) ListItemsForProject(projectID int) []*ProjectV2Item

ListItemsForProject returns every item on a project.

func (*ProjectV2Store) ListProjectsForOwner

func (s *ProjectV2Store) ListProjectsForOwner(ownerID int, ownerType string) []*ProjectV2

ListProjectsForOwner returns all projects owned by a user or organization.

func (*ProjectV2Store) LookupFieldByNodeID

func (s *ProjectV2Store) LookupFieldByNodeID(nodeID string) *ProjectV2Field

LookupFieldByNodeID returns the field with the given GraphQL node id.

func (*ProjectV2Store) LookupItemByNodeID

func (s *ProjectV2Store) LookupItemByNodeID(nodeID string) *ProjectV2Item

LookupItemByNodeID returns the item with the given GraphQL node id.

func (*ProjectV2Store) LookupProjectByNodeID

func (s *ProjectV2Store) LookupProjectByNodeID(nodeID string) *ProjectV2

LookupProjectByNodeID returns the project with the given global node id.

func (*ProjectV2Store) LookupStatusUpdateByNodeID

func (s *ProjectV2Store) LookupStatusUpdateByNodeID(nodeID string) *ProjectV2StatusUpdate

LookupStatusUpdateByNodeID returns the status update with the given node id.

func (*ProjectV2Store) LookupViewByNodeID

func (s *ProjectV2Store) LookupViewByNodeID(nodeID string) *ProjectV2View

LookupViewByNodeID returns the view with the given node id.

func (*ProjectV2Store) LookupWorkflowByNodeID

func (s *ProjectV2Store) LookupWorkflowByNodeID(nodeID string) *ProjectV2Workflow

LookupWorkflowByNodeID returns the workflow with the given node id.

func (*ProjectV2Store) MoveItem

func (s *ProjectV2Store) MoveItem(id, afterID int) (*ProjectV2Item, error)

MoveItem places an item directly after afterID within its project, or at the head when afterID is 0. Positions are renumbered densely to stay total.

func (*ProjectV2Store) SeedProjectDefaults

func (s *ProjectV2Store) SeedProjectDefaults(projectID, creatorID int)

SeedProjectDefaults gives a fresh project the fields, view and workflows github.com creates it with, attributing the default view to creatorID. Called by CreateProject.

func (*ProjectV2Store) SetFieldValue

func (s *ProjectV2Store) SetFieldValue(itemID, fieldID int, optionID, textValue string, numberValue float64) (*ProjectV2ItemFieldValue, error)

SetFieldValue writes a value for (item, field). For SINGLE_SELECT, optionID must match one of the field's options; for TEXT/NUMBER it is ignored.

func (*ProjectV2Store) SetFieldValueAny

func (s *ProjectV2Store) SetFieldValueAny(itemID, fieldID int, value interface{}) error

SetFieldValueAny writes a REST field value, dispatching on data type: string for TEXT/DATE, float64 for NUMBER, option/iteration ID string for SINGLE_SELECT/ITERATION. A nil value clears the field.

func (*ProjectV2Store) SetFieldValuesAny

func (s *ProjectV2Store) SetFieldValuesAny(itemID int, updates []ProjectV2ItemFieldUpdate) error

SetFieldValuesAny applies a batch of field writes to one item atomically: every field is resolved and validated first, and nothing is mutated or persisted unless all of them pass — so a later invalid field can no longer leave earlier writes committed while the request reports 422.

func (*ProjectV2Store) SetMultiSelectValue

func (s *ProjectV2Store) SetMultiSelectValue(itemID, fieldID int, optionIDs []string) error

SetMultiSelectValue writes a MULTI_SELECT value, validating every option ID against the field's options.

func (*ProjectV2Store) SetProjectTemplate

func (s *ProjectV2Store) SetProjectTemplate(id int, template bool) *ProjectV2

SetProjectTemplate marks or unmarks a project as a template.

func (*ProjectV2Store) StatusUpdatesForProject

func (s *ProjectV2Store) StatusUpdatesForProject(projectID int) []*ProjectV2StatusUpdate

StatusUpdatesForProject returns a project's status updates, newest first.

func (*ProjectV2Store) TouchProject

func (s *ProjectV2Store) TouchProject(id int)

TouchProject stamps a project's updatedAt. Content mutations move it on GitHub and views ordered by UPDATED_AT depend on it, so content write paths call this.

func (*ProjectV2Store) UnlinkRepository

func (s *ProjectV2Store) UnlinkRepository(projectID, repoID int) *ProjectV2

UnlinkRepository removes a repository link.

func (*ProjectV2Store) UnlinkTeam

func (s *ProjectV2Store) UnlinkTeam(projectID, teamID int) *ProjectV2

UnlinkTeam removes a team link.

func (*ProjectV2Store) UpdateCollaborators

func (s *ProjectV2Store) UpdateCollaborators(projectID int, grants []*ProjectV2Collaborator) *ProjectV2

UpdateCollaborators applies role grants. Role "NONE" revokes the grant (how GitHub spells revocation on this mutation).

func (*ProjectV2Store) UpdateField

func (s *ProjectV2Store) UpdateField(id int, name *string, options []*ProjectV2SingleSelectOption) *ProjectV2Field

UpdateField patches a field's name/options.

func (*ProjectV2Store) UpdateFieldDetails

func (s *ProjectV2Store) UpdateFieldDetails(id int, patch ProjectV2FieldUpdate) *ProjectV2Field

UpdateFieldDetails patches a field's name and, for option-bearing data types, its options. Option IDs survive a rename-free edit so item values stay valid.

func (*ProjectV2Store) UpdateItem

func (s *ProjectV2Store) UpdateItem(id int, draftTitle, draftBody *string) *ProjectV2Item

UpdateItem patches an item's draft title/body or field values.

func (*ProjectV2Store) UpdateProject

func (s *ProjectV2Store) UpdateProject(id int, title *string, closed, public *bool) *ProjectV2

UpdateProject patches a project's title/closed/public fields.

func (*ProjectV2Store) UpdateProjectDetails

func (s *ProjectV2Store) UpdateProjectDetails(id int, patch ProjectV2Update) *ProjectV2

UpdateProjectDetails applies a patch and returns the updated snapshot, or nil when no such project exists.

func (*ProjectV2Store) UpdateStatusUpdate

func (s *ProjectV2Store) UpdateStatusUpdate(id int, patch ProjectV2StatusUpdatePatch) *ProjectV2StatusUpdate

UpdateStatusUpdate patches a status update.

func (*ProjectV2Store) UpdateView

func (s *ProjectV2Store) UpdateView(id int, patch ProjectV2ViewUpdate) *ProjectV2View

UpdateView patches a view's name, layout and configuration.

func (*ProjectV2Store) ViewsForProject

func (s *ProjectV2Store) ViewsForProject(projectID int) []*ProjectV2View

ViewsForProject returns every view on a project.

func (*ProjectV2Store) WorkflowsForProject

func (s *ProjectV2Store) WorkflowsForProject(projectID int) []*ProjectV2Workflow

WorkflowsForProject returns a project's automation rules by number.

type ProjectV2Update

type ProjectV2Update struct {
	Title            *string
	ShortDescription *string
	Readme           *string
	Closed           *bool
	Public           *bool
}

ProjectV2Update is the patch updateProjectV2 applies. A nil member leaves the stored value alone (GraphQL's "not supplied" vs. "set to empty").

type ProjectV2View

type ProjectV2View struct {
	ID            int
	NodeID        string
	ProjectID     int
	Number        int // per-project sequential
	Name          string
	Layout        string // "table", "board", or "roadmap"
	CreatorID     int
	Filter        *string // the view's filter query, nil when unset
	VisibleFields []int   // field IDs shown in the view
	CreatedAt     time.Time
	UpdatedAt     time.Time

	// GroupBy / VerticalGroupBy are field IDs the view groups rows and
	// columns by; SortBy is the ordered sort specification.
	GroupBy         []int
	VerticalGroupBy []int
	SortBy          []*ProjectV2ViewSort
}

ProjectV2View is a board/table/roadmap view inside a project.

type ProjectV2ViewSort

type ProjectV2ViewSort struct {
	FieldID   int
	Direction string // "ASC" or "DESC"
}

ProjectV2ViewSort is one entry of a view's sort specification.

type ProjectV2ViewUpdate

type ProjectV2ViewUpdate struct {
	Name            *string
	Layout          *string
	Filter          *string
	VisibleFields   []int
	GroupBy         []int
	VerticalGroupBy []int
	SortBy          []*ProjectV2ViewSort
}

ProjectV2ViewUpdate is the patch updateProjectV2View applies.

type ProjectV2Workflow

type ProjectV2Workflow struct {
	ID        int
	NodeID    string
	ProjectID int
	Number    int // per-project sequential
	Name      string
	Enabled   bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

ProjectV2Workflow is one automation rule on a project.

type PullRequest

type PullRequest struct {
	ID                      int
	NodeID                  string
	Number                  int // per-repo, SHARED with issues via NextIssueNumber
	RepoID                  int
	Title                   string
	Body                    string
	State                   string // "OPEN", "CLOSED", "MERGED"
	IsDraft                 bool
	HeadRefName             string // source branch name
	HeadRepoID              int    // source repository; zero on legacy rows means RepoID
	BaseRefName             string // target branch name
	BaseSHA                 string // base branch commit at PR creation ("" when the repo had no git objects)
	MergeCommitSHA          string // merge result commit ("" until merged, or when merged without git refs)
	PotentialMergeCommitSHA string // test-merge of head into base for an open PR ("" if unmergeable/no git); reported to pull_request workflow runs (ACT-027)
	MaintainerCanModify     bool
	AuthorID                int
	AssigneeIDs             []int
	LabelIDs                []int
	RequestedReviewerIDs    []int
	RequestedTeamIDs        []int
	MilestoneID             int    // 0 = none
	Mergeable               string // "MERGEABLE", "CONFLICTING", "UNKNOWN"
	Additions               int
	Deletions               int
	ChangedFiles            int
	MergedByID              int // 0 = not merged
	Locked                  bool
	ActiveLockReason        LockReason // empty = locked without a stated reason
	CreatedAt               time.Time
	UpdatedAt               time.Time
	ClosedAt                *time.Time
	MergedAt                *time.Time
	// AutoMerge is the armed auto-merge request, nil when off. Cleared whenever
	// the PR leaves the OPEN state.
	AutoMerge *PullRequestAutoMerge
	// Archived hides the PR from default views while keeping its state.
	Archived bool
	// ViewedFiles is the per-reviewer set of file paths marked viewed in the
	// diff, keyed by reviewer account id.
	ViewedFiles map[int][]string
	// MergeQueuePosition is the 1-based place in the base branch's merge queue;
	// zero means not queued.
	MergeQueuePosition   int
	MergeQueueEnqueuedAt *time.Time
	// RevertedByID is the PR opened to revert this one, zero until one is.
	RevertedByID int
	// RevertsID is the PR this one reverts, zero when it reverts nothing.
	RevertsID int
}

PullRequest represents a GitHub pull request.

func FindPullRequestByNodeID

func FindPullRequestByNodeID(st *Store, nodeID string) *PullRequest

type PullRequestAutoMerge

type PullRequestAutoMerge struct {
	EnabledByID    int
	MergeMethod    string // "MERGE", "SQUASH", "REBASE"
	CommitHeadline string
	CommitBody     string
	AuthorEmail    string
	EnabledAt      time.Time
}

PullRequestAutoMerge captures who armed auto-merge on a pull request and the merge parameters to use once its blocking conditions clear.

type PullRequestMergeAsync

type PullRequestMergeAsync struct {
	UUID            string           `json:"uuid"`
	RepoID          int              `json:"repo_id"`
	PRNumber        int              `json:"pr_number"`
	Status          MergeAsyncStatus `json:"status"`
	MergeMethod     string           `json:"merge_method"`
	MergeAction     string           `json:"merge_action"`
	Message         string           `json:"message"`
	SHA             string           `json:"sha"`
	ExpectedHeadSHA string           `json:"expected_head_sha"`
	CreatedAt       time.Time        `json:"created_at"`
}

PullRequestMergeAsync records an async merge outcome for the GET .../merge-async/{uuid} poll. GitHub enqueues onto the merge queue; bleephub merges synchronously and stores the terminal result by UUID.

type PullRequestOptions

type PullRequestOptions struct {
	HeadRepoID          int
	MaintainerCanModify bool
}

type PullRequestReview

type PullRequestReview struct {
	ID               int
	NodeID           string
	PRID             int // PullRequest.ID
	AuthorID         int
	State            string // "APPROVED", "CHANGES_REQUESTED", "COMMENTED", "PENDING", "DISMISSED"
	Body             string
	SubmittedAt      *time.Time
	DismissedAt      *time.Time
	DismissalMessage string
	// PreviousState is the state held before dismissal ("" if never dismissed).
	// Dismissal overwrites State; ReviewDismissedEvent.previousReviewState needs
	// the overturned standing.
	PreviousState string
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

PullRequestReview represents a review on a pull request.

func FindReviewByNodeID

func FindReviewByNodeID(st *Store, nodeID string) *PullRequestReview

FindReviewByNodeID resolves a PR review (PRR_kgDO…); reviews lack a fast-path index, so this scans.

type PullRequestStack

type PullRequestStack struct {
	ID           int       `json:"id"`
	Number       int       `json:"number"`
	RepoID       int       `json:"repo_id"`
	BaseRef      string    `json:"base_ref"`
	PullRequests []int     `json:"pull_requests"`
	CreatedAt    time.Time `json:"created_at"`
}

type PullWithRepo

type PullWithRepo struct {
	Pull *PullRequest `json:"-"`
	Repo *Repo        `json:"-"`
}

type Reaction

type Reaction struct {
	ID         int       `json:"id"`
	ParentType string    `json:"parent_type"`
	ParentID   int       `json:"parent_id"`
	Content    string    `json:"content"`
	UserID     int       `json:"user_id"`
	CreatedAt  time.Time `json:"created_at"`
}

Reaction is one user reaction on a parent entity. ParentType/ParentID/UserID carry real json names so the reload path re-indexes byParent from them; client responses go through reactionToJSON, not this struct.

type ReactionStore

type ReactionStore struct {
	Mu sync.RWMutex `json:"-"`

	ByID    map[int]*Reaction `json:"-"`
	NextID  int               `json:"-"`
	Persist *Persistence      `json:"-"`
	// contains filtered or unexported fields
}

ReactionStore holds reactions keyed by (parentType, parentID).

func (*ReactionStore) AddReaction

func (rs *ReactionStore) AddReaction(parentType string, parentID int, userID int, content string) (*Reaction, bool, error)

AddReaction creates or returns the existing (userID, content) reaction. GitHub returns the same id on repeat POST (idempotent).

func (*ReactionStore) DeleteParentsBatch

func (rs *ReactionStore) DeleteParentsBatch(parentType string, parentIDs map[int]bool, batch *PersistBatch)

DeleteParentsBatch removes every reaction on the given parents. A non-nil batch stages the deletes into the caller's transaction so they commit with the parent rows (STORE-001/002); a nil batch commits each independently.

func (*ReactionStore) DeleteReactionByUser

func (rs *ReactionStore) DeleteReactionByUser(parentType string, parentID, reactionID, userID int) bool

DeleteReactionByUser removes a reaction only when it belongs to userID. The ownership check and deletion happen under one lock so a stale authorization check cannot delete a replaced record.

func (*ReactionStore) ListReactions

func (rs *ReactionStore) ListReactions(parentType string, parentID int, contentFilter string) []*Reaction

ListReactions returns reactions on a parent, optionally filtered by content.

func (*ReactionStore) SummarizeReactions

func (rs *ReactionStore) SummarizeReactions(parentType string, parentID int) map[string]interface{}

SummarizeReactions computes the per-content counts and total for GitHub's reactions{url, total_count, +1, ...} block.

type ReapOptions

type ReapOptions struct {
	// Delete removes the orphans found; false (the default) only reports them.
	Delete bool
	// GracePeriod protects objects younger than this from being treated as
	// orphans, so a byte-first upload whose metadata is still committing is safe.
	GracePeriod time.Duration
}

ReapOptions configures one reaper pass.

type ReapReport

type ReapReport struct {
	Scanned      int
	OrphanCount  int
	OrphanBytes  int64
	DeletedCount int
	DeleteErrors int
	SampleKeys   []string // up to a handful of orphan keys, for the operator's log
	ObjectBacked bool     // false when the object store is not S3-backed (no-op)
}

ReapReport summarizes one pass.

type RecoveryCode

type RecoveryCode struct {
	Hash   string    `json:"hash"`
	UsedAt time.Time `json:"used_at,omitempty"`
}

RecoveryCode is one single-use fallback credential; only its digest is retained. UsedAt is zero while unused.

func (RecoveryCode) Used

func (c RecoveryCode) Used() bool

type RefNameCondition

type RefNameCondition struct {
	Include []string `json:"include"`
	Exclude []string `json:"exclude"`
}

RefNameCondition matches ref names.

type RefreshToken

type RefreshToken struct {
	Token            string
	UserID           int
	AppID            int
	OAuthAppClientID string
	Scopes           string
	ExpiresAt        time.Time // typically 6 months
	CreatedAt        time.Time
}

RefreshToken mints a fresh user token past its expiry without re-running the OAuth flow.

type Release

type Release struct {
	ID              int             `json:"id"`
	NodeID          string          `json:"node_id"`
	TagName         string          `json:"tag_name"`
	TargetCommitish string          `json:"target_commitish"`
	Name            string          `json:"name"`
	Body            string          `json:"body"`
	Draft           bool            `json:"draft"`
	Prerelease      bool            `json:"prerelease"`
	AuthorID        int             `json:"author_id"`
	RepoID          int             `json:"repo_id"`
	Assets          []*ReleaseAsset `json:"-"`
	CreatedAt       time.Time       `json:"created_at"`
	PublishedAt     *time.Time      `json:"published_at"`
	// ExcludeFromLatest (make_latest:"false") drops the release from Latest().
	// Persisted, but absent from the API response, as on GitHub.
	ExcludeFromLatest bool `json:"exclude_from_latest,omitempty"`
	// DiscussionNumber links to a discussion (via discussion_category_name),
	// zero when none; surfaced as discussion_url.
	DiscussionNumber int `json:"discussion_number,omitempty"`
}

Release is a tagged release on a repo. AuthorID/RepoID carry json names so persistence round-trips the linkage; client responses never marshal this struct (releaseToJSON emits an explicit map).

func FindReleaseByNodeID

func FindReleaseByNodeID(st *Store, nodeID string) *Release

FindReleaseByNodeID resolves a release (RE_kgDO…).

type ReleaseAsset

type ReleaseAsset struct {
	ID            int       `json:"id"`
	NodeID        string    `json:"node_id"`
	Name          string    `json:"name"`
	Label         string    `json:"label"`
	State         string    `json:"state"`
	ContentType   string    `json:"content_type"`
	Digest        string    `json:"digest"`
	Size          int       `json:"size"`
	DownloadCount int       `json:"download_count"`
	UploaderID    int       `json:"-"`
	ReleaseID     int       `json:"-"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

type ReleaseStore

type ReleaseStore struct {
	Mu     sync.RWMutex       `json:"-"`
	ByID   map[int]*Release   `json:"-"`
	ByRepo map[int][]*Release `json:"-"`

	ByteStore ActionsByteStore `json:"-"`
	NextID    int              `json:"-"`

	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

func (*ReleaseStore) Create

func (rs *ReleaseStore) Create(repoID, authorID int, tagName, target, name, body string, draft, prerelease, excludeFromLatest bool) *Release

func (*ReleaseStore) CreateReleaseAsset

func (rs *ReleaseStore) CreateReleaseAsset(releaseID, uploaderID int, name, label, contentType string, data []byte) (*ReleaseAsset, error)

func (*ReleaseStore) CreateReleaseAssetStream

func (rs *ReleaseStore) CreateReleaseAssetStream(releaseID, uploaderID int, name, label, contentType string, r io.Reader, size int64, sum []byte) (*ReleaseAsset, error)

CreateReleaseAssetStream stores an asset from a reader whose size and SHA-256 are already known (a handler stages the upload to a temp file first), so the bytes stream to the object store without ever residing whole on the heap.

func (*ReleaseStore) Delete

func (rs *ReleaseStore) Delete(id int, reactions *ReactionStore) (bool, error)

Delete removes a release, its asset rows, and its reactions in one transaction, so a crash can't drop the reactions while the release survives (STORE-001/002).

func (*ReleaseStore) DeleteAllForRepo

func (rs *ReleaseStore) DeleteAllForRepo(repoID int) error

DeleteAllForRepo purges every release for a repo, in memory and on disk, so a recreated same-name repo can't inherit them after a restart.

func (*ReleaseStore) DeleteReleaseAsset

func (rs *ReleaseStore) DeleteReleaseAsset(id int) (bool, error)

func (*ReleaseStore) Get

func (rs *ReleaseStore) Get(id int) *Release

func (*ReleaseStore) GetAssetData

func (rs *ReleaseStore) GetAssetData(id int) ([]byte, bool)

func (*ReleaseStore) GetByTag

func (rs *ReleaseStore) GetByTag(repoID int, tag string) *Release

func (*ReleaseStore) GetReleaseAsset

func (rs *ReleaseStore) GetReleaseAsset(id int) *ReleaseAsset

func (*ReleaseStore) IDsForRepo

func (rs *ReleaseStore) IDsForRepo(repoID int) map[int]bool

func (*ReleaseStore) IncrementAssetDownloads

func (rs *ReleaseStore) IncrementAssetDownloads(id int) bool

func (*ReleaseStore) Latest

func (rs *ReleaseStore) Latest(repoID int) *Release

Latest returns the newest non-draft non-prerelease release.

func (*ReleaseStore) List

func (rs *ReleaseStore) List(repoID int) []*Release

func (*ReleaseStore) ListReleaseAssets

func (rs *ReleaseStore) ListReleaseAssets(releaseID int) []*ReleaseAsset

func (*ReleaseStore) Update

func (rs *ReleaseStore) Update(id int, fn func(*Release)) bool

func (*ReleaseStore) UpdateReleaseAsset

func (rs *ReleaseStore) UpdateReleaseAsset(id int, name, label string) (*ReleaseAsset, error)

type Repo

type Repo struct {
	ID                        int        `json:"id"`
	NodeID                    string     `json:"node_id"`
	Name                      string     `json:"name"`
	FullName                  string     `json:"full_name"`
	Description               string     `json:"description"`
	Homepage                  string     `json:"homepage"`
	DefaultBranch             string     `json:"default_branch"`
	Visibility                string     `json:"visibility"`
	Language                  string     `json:"language"`
	Owner                     *User      `json:"-"`
	OwnerID                   int        `json:"owner_id"`   // serialized so Owner can be relinked on reload
	OwnerType                 string     `json:"owner_type"` // "User" or "Organization"
	Private                   bool       `json:"private"`
	Fork                      bool       `json:"fork"`
	Archived                  bool       `json:"archived"`
	ArchivedAt                *time.Time `json:"archived_at,omitempty"`
	IsTemplate                bool       `json:"is_template"`
	WebCommitSignoffRequired  bool       `json:"web_commit_signoff_required"`
	HasIssues                 bool       `json:"has_issues"`
	HasProjects               bool       `json:"has_projects"`
	HasWiki                   bool       `json:"has_wiki"`
	WikiEditsUnrestricted     bool       `json:"wiki_edits_unrestricted"` // inverse of github's "restrict editing to collaborators", so the zero value is the checked default (see viewerMayEditWiki)
	HasDiscussions            *bool      `json:"has_discussions"`
	HasPullRequests           bool       `json:"has_pull_requests"`
	AllowSquashMerge          bool       `json:"allow_squash_merge"`
	AllowMergeCommit          bool       `json:"allow_merge_commit"`
	AllowRebaseMerge          bool       `json:"allow_rebase_merge"`
	AllowAutoMerge            bool       `json:"allow_auto_merge"`
	AllowUpdateBranch         bool       `json:"allow_update_branch"`
	DeleteBranchOnMerge       bool       `json:"delete_branch_on_merge"`
	UseSquashPRTitleAsDefault bool       `json:"use_squash_pr_title_as_default"`
	SquashMergeCommitTitle    string     `json:"squash_merge_commit_title"`
	SquashMergeCommitMessage  string     `json:"squash_merge_commit_message"`
	MergeCommitTitle          string     `json:"merge_commit_title"`
	MergeCommitMessage        string     `json:"merge_commit_message"`
	PullRequestCreationPolicy string     `json:"pull_request_creation_policy"`
	IssueCreationPolicy       string     `json:"issue_creation_policy"`
	// HasSponsorships shows a sponsor button; nil derives the answer from the owner's Sponsors listing and FUNDING file.
	HasSponsorships *bool `json:"has_sponsorships,omitempty"`
	// DeclinedTopics are topics an admin declined; never re-suggested nor applied.
	DeclinedTopics                           []string          `json:"declined_topics,omitempty"`
	LicenseKey                               string            `json:"license_key"`
	LicenseName                              string            `json:"license_name"`
	LicenseSPDX                              string            `json:"license_spdx"`
	StargazersCount                          int               `json:"stargazers_count"`
	Topics                                   []string          `json:"topics"`
	Stargazers                               map[int]time.Time `json:"stargazers,omitempty"`
	ParentID                                 int               `json:"parent_id"`
	SourceID                                 int               `json:"source_id"`
	TemplateRepoID                           int               `json:"template_repo_id,omitempty"`
	NextIssueNumber                          int               `json:"-"`
	NextMilestoneNumber                      int               `json:"-"`
	AutomatedSecurityFixesEnabled            bool              `json:"automated_security_fixes_enabled"`
	AdvancedSecurityEnabled                  bool              `json:"advanced_security_enabled"`
	SecretScanningEnabled                    bool              `json:"secret_scanning_enabled"`
	SecretScanningPushProtectionEnabled      bool              `json:"secret_scanning_push_protection_enabled"`
	SecretScanningNonProviderPatternsEnabled bool              `json:"secret_scanning_non_provider_patterns_enabled"`
	PrivateVulnerabilityReportingEnabled     bool              `json:"private_vulnerability_reporting_enabled"`
	VulnerabilityAlertsEnabled               bool              `json:"vulnerability_alerts_enabled"`
	InteractionLimit                         string            `json:"interaction_limit"`
	InteractionLimitExpiry                   *time.Time        `json:"interaction_limit_expiry,omitempty"`
	LFSEnabled                               bool              `json:"lfs_enabled,omitempty"`
	CreatedAt                                time.Time         `json:"created_at"`
	UpdatedAt                                time.Time         `json:"updated_at"`
	PushedAt                                 time.Time         `json:"pushed_at"`
}

func FilterSortRepos

func FilterSortRepos(repos []*Repo, opts RepoListOptions) []*Repo

FilterSortRepos applies filtering and sorting without pagination.

func FindRepoByNodeID

func FindRepoByNodeID(st *Store, nodeID string) *Repo

func PullRequestHeadRepo

func PullRequestHeadRepo(st *Store, pr *PullRequest) *Repo

PullRequestHeadRepo resolves the PR's head repository (locking).

func PullRequestHeadRepoLocked

func PullRequestHeadRepoLocked(st *Store, pr *PullRequest) *Repo

PullRequestHeadRepoLocked resolves the PR's head repository; the caller holds st.Mu.

func ResolvePullRequestHead

func ResolvePullRequestHead(st *Store, baseRepo *Repo, head string) (*Repo, string)

ResolvePullRequestHead resolves a PR head spec ("branch" or "owner:branch") to the repository holding that branch within the base repository's fork network, and the branch name.

type RepoActionsPermissions

type RepoActionsPermissions struct {
	Enabled                     bool            `json:"enabled"`
	AllowedActions              string          `json:"allowed_actions"`
	SelectedActionsURL          string          `json:"selected_actions_url,omitempty"`
	ActionsAllowed              *ActionsAllowed `json:"actions_allowed,omitempty"`
	AccessLevel                 string          `json:"access_level"`
	WorkflowPermissions         *WorkflowPermissions
	ForkPRContributorApproval   string                       `json:"fork_pull_request_member_approval"`
	ForkPRWorkflowsPrivateRepos *ForkPRWorkflowsPrivateRepos `json:"fork_pull_request_workflows_private_repos,omitempty"`
	ArtifactAndLogRetentionDays int                          `json:"artifact_and_log_retention_days"`
	CacheRetentionLimitDays     int
	CacheStorageLimitGB         int64
}

func DefaultRepoActionsPermissions

func DefaultRepoActionsPermissions() *RepoActionsPermissions

DefaultRepoActionsPermissions returns the GitHub-default repo settings.

type RepoActivity

type RepoActivity struct {
	ID           int       `json:"id"`
	RepoID       int       `json:"repo_id"`
	Ref          string    `json:"ref"`    // full reference name (refs/heads/…)
	Before       string    `json:"before"` // SHA before the update (all-zero for creations)
	After        string    `json:"after"`  // SHA after the update (all-zero for deletions)
	ActorID      int       `json:"actor_id"`
	ActivityType string    `json:"activity_type"` // push, force_push, branch_creation, branch_deletion
	Timestamp    time.Time `json:"timestamp"`
}

RepoActivity is one recorded ref update served by the repo activity and events APIs, written on every git receive-pack ref command.

type RepoAutolink struct {
	ID             int       `json:"id"`
	NodeID         string    `json:"node_id"`
	RepoKey        string    `json:"-"`
	KeyPrefix      string    `json:"key_prefix"`
	URLTemplate    string    `json:"url_template"`
	IsAlphanumeric bool      `json:"is_alphanumeric"`
	CreatedAt      time.Time `json:"created_at"`
}

RepoAutolink represents a GitHub autolink reference configured on a repository.

type RepoDeployKey

type RepoDeployKey struct {
	ID        int       `json:"id"`
	NodeID    string    `json:"node_id"`
	RepoID    int       `json:"repo_id"`
	Title     string    `json:"title"`
	Key       string    `json:"key"`
	ReadOnly  bool      `json:"read_only"`
	Verified  bool      `json:"verified"`
	CreatedAt time.Time `json:"created_at"`
}

RepoDeployKey represents a deploy key configured on a repository.

type RepoImport

type RepoImport struct {
	RepoID          int             `json:"repo_id"`
	VCS             string          `json:"vcs"` // empty until detected/declared
	VCSURL          string          `json:"vcs_url"`
	VCSUsername     string          `json:"vcs_username,omitempty"`
	VCSPassword     string          `json:"vcs_password,omitempty"`
	TFVCProject     string          `json:"tfvc_project,omitempty"`
	Status          string          `json:"status"`
	StatusText      string          `json:"status_text,omitempty"`
	FailedStep      string          `json:"failed_step,omitempty"`
	ErrorMessage    string          `json:"error_message,omitempty"`
	ImportPercent   *int            `json:"import_percent"`
	CommitCount     *int            `json:"commit_count"`
	AuthorsCount    *int            `json:"authors_count"`
	UseLFS          bool            `json:"use_lfs"`
	HasLargeFiles   bool            `json:"has_large_files"`
	LargeFilesSize  int             `json:"large_files_size"`
	LargeFilesCount int             `json:"large_files_count"`
	Authors         []*PorterAuthor `json:"authors"`
	NextAuthorID    int             `json:"next_author_id"`
	CreatedAt       time.Time       `json:"created_at"`
	UpdatedAt       time.Time       `json:"updated_at"`
}

RepoImport backs the Source Import API (sunset on github.com, still real on GitHub Enterprise Server). The import is a real synchronous git fetch: PUT (and PATCH restarts) fetch vcs_url's refs into the repository's git storage. Status reflects what happened — "complete" only after a successful fetch, "auth_failed"/"error" on transport failure, and "error" for VCS types other than git, which bleephub cannot import.

type RepoInvitation

type RepoInvitation struct {
	ID           int       `json:"id"`
	NodeID       string    `json:"node_id"`
	RepoKey      string    `json:"-"`
	InviteeLogin string    `json:"invitee_login,omitempty"`
	InviteeEmail string    `json:"invitee_email,omitempty"`
	InviterID    int       `json:"inviter_id"`
	Permissions  string    `json:"permissions"`
	CreatedAt    time.Time `json:"created_at"`
	Status       string    `json:"status"`
}

RepoInvitation represents a pending invitation to collaborate on a repository.

type RepoListOptions

type RepoListOptions struct {
	Type        string // org: all/public/private/forks/sources/member; user: all/owner/member
	Visibility  string // all/public/private
	Affiliation string // owner,collaborator,organization_member
	Sort        string // created/updated/pushed/full_name
	Direction   string // asc/desc
	PerPage     int
	Page        int
	NoPaginate  bool
}

RepoListOptions controls filtering, sorting and pagination for repo list endpoints. A zero value applies GitHub's defaults. Set NoPaginate when the caller will paginate itself (e.g. REST handlers use paginateAndLink).

type RepoPermission

type RepoPermission string

RepoPermission is the access level a collaborator has on a repo.

const (
	RepoPermPull  RepoPermission = "pull"
	RepoPermPush  RepoPermission = "push"
	RepoPermAdmin RepoPermission = "admin"
)

type RepoSubscription

type RepoSubscription struct {
	UserID     int       `json:"user_id"`
	RepoID     int       `json:"repo_id"`
	Subscribed bool      `json:"subscribed"`
	Ignored    bool      `json:"ignored"`
	CreatedAt  time.Time `json:"created_at"`
}

RepoSubscription records a user's watch subscription for a repo.

type RepoTrafficBucket

type RepoTrafficBucket struct {
	RepoID int             `json:"repo_id"`
	Day    string          `json:"day"` // YYYY-MM-DD, UTC
	Count  int             `json:"count"`
	Actors map[string]bool `json:"actors"`
}

RepoTrafficBucket accumulates one repository's clone traffic for one UTC day. Actors holds distinct cloner identities (login, or remote host for anonymous clones) so uniques are counted, not estimated.

type RepositoryMigration

type RepositoryMigration struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`
	// OwnerOrgID is the organization the imported repository lands in.
	OwnerOrgID     int    `json:"owner_org_id"`
	SourceID       int    `json:"source_id"`
	RepositoryName string `json:"repository_name"`
	SourceURL      string `json:"source_url"`
	State          string `json:"state"`
	FailureReason  string `json:"failure_reason,omitempty"`
	// WarningsCount is len(WarningLog): recoverable problems continued past.
	WarningsCount   int      `json:"warnings_count"`
	WarningLog      []string `json:"warning_log,omitempty"`
	ContinueOnError bool     `json:"continue_on_error"`
	LockSource      bool     `json:"lock_source"`
	SkipReleases    bool     `json:"skip_releases"`
	// TargetRepoVisibility is public/private/internal; empty keeps the
	// source's visibility, which for an un-interrogable source means private.
	TargetRepoVisibility string `json:"target_repo_visibility,omitempty"`
	GitArchiveURL        string `json:"git_archive_url,omitempty"`
	MetadataArchiveURL   string `json:"metadata_archive_url,omitempty"`
	// MigrationLogKey is empty until the migration reaches a terminal state.
	MigrationLogKey string `json:"migration_log_key,omitempty"`
	// OrgMigrationID links back to the org migration that fanned this out; 0
	// if standalone.
	OrgMigrationID int `json:"org_migration_id,omitempty"`
	// StartedByUserID owns everything the migration creates in the target.
	StartedByUserID int `json:"started_by_user_id,omitempty"`
	// TargetRepoID is the repository this migration created. A resumed migration
	// continues by ID, not name: name-matching would let someone pre-plant a repo
	// under a queued migration's name and receive its contents.
	TargetRepoID int `json:"target_repo_id,omitempty"`
	// SourceRepoLock is the full name of the repo on *this* instance that
	// lock_source froze, or "" when the source is elsewhere. Held until the
	// migration is terminal, so its state is the only thing that releases it.
	SourceRepoLock string    `json:"source_repo_lock,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

RepositoryMigration is one repository coming across from a MigrationSource.

func FindRepositoryMigrationByNodeID

func FindRepositoryMigrationByNodeID(st *Store, nodeID string) *RepositoryMigration

FindRepositoryMigrationByNodeID resolves a repository migration global id to the LIVE row.

type ResolvedDependency

type ResolvedDependency struct {
	// PackageURL is the dependency's purl, as submitted.
	PackageURL string
	// Ecosystem is the purl's type folded onto a canonical ecosystem key.
	Ecosystem string
	// Name and Version are the purl's remaining coordinates.
	Name    string
	Version string
	// Relationship is "direct", "indirect" or "" when unsaid; GraphQL renders
	// the unsaid case as "unknown".
	Relationship string
	// Scope is "runtime", "development" or "" when unsaid.
	Scope string
	// DependsOn names the purls this dependency itself pulls in.
	DependsOn []string
}

ResolvedDependency is one package a manifest resolves to.

type ResolvedManifest

type ResolvedManifest struct {
	Name           string
	SourceLocation string
	Dependencies   []ResolvedDependency
}

ResolvedManifest is one manifest of the repository's current dependency set.

type Result

type Result string

Result is the terminal outcome of a workflow or job; empty means in-flight.

const (
	ResultNone      Result = ""
	ResultSuccess   Result = "success"
	ResultFailure   Result = "failure"
	ResultCancelled Result = "cancelled"
	ResultSkipped   Result = "skipped"
	// ResultStartupFailure marks runs that produced no jobs (invalid
	// reusable-workflow ref, unparseable definition), matching GitHub.
	ResultStartupFailure Result = "startup_failure"
)

type ReviewThread

type ReviewThread struct {
	ID           int                `json:"id"`
	IsResolved   bool               `json:"isResolved"`
	ResolvedByID int                `json:"-"` // user who resolved (0 when unresolved)
	Comments     []*PRReviewComment `json:"comments"`
}

ReviewThread groups PR review comments by thread root.

type Rule

type Rule struct {
	Type       string                 `json:"type"`
	Parameters map[string]interface{} `json:"parameters,omitempty"`
}

Rule is a single rule inside a ruleset.

type Ruleset

type Ruleset struct {
	ID                   int                    `json:"id"`
	NodeID               string                 `json:"node_id"`
	RepoID               int                    `json:"repo_id"`
	OrgID                int                    `json:"org_id"`
	Enterprise           string                 `json:"enterprise,omitempty"`
	Name                 string                 `json:"name"`
	Target               string                 `json:"target"` // branch, tag
	SourceType           string                 `json:"source_type"`
	Source               string                 `json:"source"`
	Enforcement          string                 `json:"enforcement"` // active, evaluate, disabled
	BypassActors         []RulesetBypassActor   `json:"bypass_actors"`
	CurrentUserCanBypass string                 `json:"current_user_can_bypass"`
	Conditions           RulesetConditions      `json:"conditions"`
	Rules                []Rule                 `json:"rules"`
	CreatedAt            time.Time              `json:"created_at"`
	UpdatedAt            time.Time              `json:"updated_at"`
	Versions             map[int]RulesetVersion `json:"versions,omitempty"`
	NextVersionID        int                    `json:"next_version_id,omitempty"`
}

Ruleset is a GitHub repository or organization ruleset.

func FindRulesetByNodeID

func FindRulesetByNodeID(st *Store, nodeID string) *Ruleset

FindRulesetByNodeID resolves a RepositoryRuleset global id to the LIVE row (repository-, organization- or enterprise-scoped — they share one table).

type RulesetBypassActor

type RulesetBypassActor struct {
	ActorID    int    `json:"actor_id"`
	ActorType  string `json:"actor_type"`
	BypassMode string `json:"bypass_mode"`
}

RulesetBypassActor represents an actor that can bypass a ruleset.

type RulesetConditions

type RulesetConditions struct {
	RefName RefNameCondition `json:"ref_name,omitempty"`
}

RulesetConditions holds the conditions under which a ruleset applies.

type RulesetEvaluation

type RulesetEvaluation struct {
	RuleSource  RulesetEvaluationSource `json:"rule_source"`
	Enforcement string                  `json:"enforcement"`
	Result      string                  `json:"result"`
	RuleType    string                  `json:"rule_type"`
	Details     *string                 `json:"details"`
}

RulesetEvaluation is the result of one rule inside a rule suite.

type RulesetEvaluationSource

type RulesetEvaluationSource struct {
	Type string  `json:"type"`
	ID   *int    `json:"id"`
	Name *string `json:"name"`
}

RulesetEvaluationSource identifies the repository or organization ruleset that contributed a rule to an evaluation.

type RulesetSuite

type RulesetSuite struct {
	ID               int                 `json:"id"`
	ActorID          *int                `json:"actor_id"`
	ActorName        *string             `json:"actor_name"`
	BeforeSHA        string              `json:"before_sha"`
	AfterSHA         string              `json:"after_sha"`
	Ref              string              `json:"ref"`
	RepositoryID     int                 `json:"repository_id"`
	RepositoryName   string              `json:"repository_name"`
	OrganizationID   int                 `json:"organization_id,omitempty"`
	PushedAt         time.Time           `json:"pushed_at"`
	Result           string              `json:"result"`
	EvaluationResult *string             `json:"evaluation_result"`
	RuleEvaluations  []RulesetEvaluation `json:"rule_evaluations"`
}

RulesetSuite is a single ruleset evaluation run.

type RulesetVersion

type RulesetVersion struct {
	VersionID int       `json:"version_id"`
	Ruleset   Ruleset   `json:"ruleset"`
	ActorID   int       `json:"actor_id"`
	CreatedAt time.Time `json:"created_at"`
}

RulesetVersion is a historical snapshot of a ruleset. ActorID is the user whose update superseded this version.

type RunDefaults

type RunDefaults struct {
	Shell            string `yaml:"shell" json:"shell,omitempty"`
	WorkingDirectory string `yaml:"working-directory" json:"working_directory,omitempty"`
}

RunDefaults is the defaults.run block inherited by script steps that supply no more specific value.

type RunnerGroup

type RunnerGroup struct {
	ID                       int         `json:"id"`
	Name                     string      `json:"name"`
	Visibility               string      `json:"visibility"` // all | selected | private
	Default                  bool        `json:"default"`
	AllowsPublicRepositories bool        `json:"allows_public_repositories"`
	SelectedRepoIDs          []int       `json:"selected_repository_ids,omitempty"`
	SelectedOrgIDs           []int       `json:"selected_organization_ids,omitempty"`
	RestrictedToWorkflows    bool        `json:"restricted_to_workflows,omitempty"`
	SelectedWorkflows        []string    `json:"selected_workflows,omitempty"`
	NetworkConfigurationID   string      `json:"network_configuration_id,omitempty"`
	Scope                    RunnerScope `json:"scope"`
	CreatedAt                time.Time   `json:"created_at"`
}

RunnerGroup models an organization or enterprise runner group. Scope is part of the persisted identity: ids are globally unique, so a group must never become visible through a different owner sharing the backing store.

type RunnerScope

type RunnerScope struct {
	Repo       string `json:"repo,omitempty"` // owner/repo
	Org        string `json:"org,omitempty"`
	Enterprise string `json:"enterprise,omitempty"`
}

RunnerScope names the repository, organization, or enterprise a runner credential acts for; exactly one field is set.

func (RunnerScope) CoversRepo

func (sc RunnerScope) CoversRepo(repoFullName string) bool

CoversRepo reports whether the scope entitles its holder to act for repoFullName. Repository names are case-insensitive on GitHub.

func (RunnerScope) Empty

func (sc RunnerScope) Empty() bool

func (RunnerScope) String

func (sc RunnerScope) String() string

type S3ActionsByteStore

type S3ActionsByteStore struct {
	Fs *gitstore.S3FS `json:"-"`
}

func (*S3ActionsByteStore) Delete

func (s *S3ActionsByteStore) Delete(ctx context.Context, key string) error

func (*S3ActionsByteStore) Get

func (s *S3ActionsByteStore) Get(ctx context.Context, key string) ([]byte, error)

func (*S3ActionsByteStore) GetStream

func (s *S3ActionsByteStore) GetStream(ctx context.Context, key string) (io.ReadCloser, error)

func (*S3ActionsByteStore) Key

func (s *S3ActionsByteStore) Key(key string) string

func (*S3ActionsByteStore) Put

func (s *S3ActionsByteStore) Put(ctx context.Context, key string, data []byte) error

func (*S3ActionsByteStore) PutStream

func (s *S3ActionsByteStore) PutStream(ctx context.Context, key string, r io.Reader) error

PutStream buffers the reader to a temp file (never the heap) while hashing it, then uploads with the SHA-256 in metadata (STORE-019).

func (*S3ActionsByteStore) PutStreamHashed

func (s *S3ActionsByteStore) PutStreamHashed(ctx context.Context, key string, r io.Reader, size int64, sha256Sum []byte) error

PutStreamHashed uploads r directly with a caller-computed size and checksum, skipping the temp-file staging PutStream does (the caller already staged it).

type SARIFUpload

type SARIFUpload struct {
	ID        string    `json:"id"`
	RepoKey   string    `json:"repo_key"`
	Status    string    `json:"status"`
	Errors    []string  `json:"errors"`
	CreatedAt time.Time `json:"created_at"`
}

SARIFUpload tracks a SARIF upload request. GitHub processes asynchronously; bleephub processes synchronously and stores the upload as complete.

type SBOMExport

type SBOMExport struct {
	UUID      string    `json:"uuid"`
	RepoID    int       `json:"repo_id"`
	CreatedAt time.Time `json:"created_at"`
}

SBOMExport is a generated SBOM report export addressed by UUID.

type Secret

type Secret struct {
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Value     string    `json:"value"`
}

Secret is an Actions secret at repository or environment scope (OrgSecret embeds it for org scope).

Value is persisted (workflow runs need the plaintext after a restart) but never marshaled to clients: the handlers emit only name/created_at/updated_at, matching GitHub's never-return-the-value contract. Clients send the value as a libsodium sealed box, which the server opens once at PUT time.

type SecretScanningAlert

type SecretScanningAlert struct {
	ID                    int                      `json:"id"`
	NodeID                string                   `json:"node_id"`
	Number                int                      `json:"number"`
	RepoKey               string                   `json:"repo_key"`
	SecretType            string                   `json:"secret_type"`
	SecretTypeDisplayName string                   `json:"secret_type_display_name"`
	State                 SecretScanningState      `json:"state"`
	Resolution            SecretScanningResolution `json:"resolution"`
	ResolutionComment     string                   `json:"resolution_comment"`
	Locations             []SecretScanningLocation `json:"locations"`
	HTMLURL               string                   `json:"html_url"`
	URL                   string                   `json:"url"`
	LocationsURL          string                   `json:"locations_url"`
	CreatedAt             time.Time                `json:"created_at"`
	UpdatedAt             time.Time                `json:"updated_at"`
	ResolvedAt            *time.Time               `json:"resolved_at"`
}

SecretScanningAlert is a repo-scoped secret scanning alert.

type SecretScanningCustomPattern

type SecretScanningCustomPattern struct {
	ID                    int       `json:"id"`
	Name                  string    `json:"name"`
	Pattern               string    `json:"pattern"`
	Slug                  string    `json:"slug"`
	State                 string    `json:"state"`
	PushProtectionEnabled bool      `json:"push_protection_enabled"`
	StartDelimiter        *string   `json:"start_delimiter"`
	EndDelimiter          *string   `json:"end_delimiter"`
	MustMatch             []string  `json:"must_match"`
	MustNotMatch          []string  `json:"must_not_match"`
	Version               string    `json:"custom_pattern_version"`
	CreatedAt             time.Time `json:"created_at"`
	UpdatedAt             time.Time `json:"updated_at"`
}

type SecretScanningLocation

type SecretScanningLocation struct {
	Type    string                        `json:"type"`
	Details SecretScanningLocationDetails `json:"details"`
}

SecretScanningLocation describes where a secret was detected.

type SecretScanningLocationDetails

type SecretScanningLocationDetails struct {
	Path        string `json:"path"`
	StartLine   int    `json:"start_line"`
	EndLine     int    `json:"end_line"`
	StartColumn int    `json:"start_column"`
	EndColumn   int    `json:"end_column"`
	BlobSHA     string `json:"blob_sha"`
	BlobURL     string `json:"blob_url"`
	CommitSHA   string `json:"commit_sha"`
	CommitURL   string `json:"commit_url"`
	HTMLURL     string `json:"html_url"`
}

SecretScanningLocationDetails holds the commit-level details for a location.

type SecretScanningPatternCreate

type SecretScanningPatternCreate struct {
	Name           string   `json:"name"`
	Pattern        string   `json:"pattern"`
	StartDelimiter *string  `json:"start_delimiter"`
	EndDelimiter   *string  `json:"end_delimiter"`
	MustMatch      []string `json:"must_match"`
	MustNotMatch   []string `json:"must_not_match"`
}

type SecretScanningPatternDelete

type SecretScanningPatternDelete struct {
	PatternID int    `json:"pattern_id"`
	Version   string `json:"custom_pattern_version"`
}

type SecretScanningPatternUpdate

type SecretScanningPatternUpdate struct {
	Pattern        *string   `json:"pattern"`
	StartDelimiter *string   `json:"start_delimiter"`
	EndDelimiter   *string   `json:"end_delimiter"`
	MustMatch      *[]string `json:"must_match"`
	MustNotMatch   *[]string `json:"must_not_match"`
	Version        string    `json:"custom_pattern_version"`
}

type SecretScanningPushProtectionBypass

type SecretScanningPushProtectionBypass struct {
	PlaceholderID string    `json:"placeholder_id"`
	RepoKey       string    `json:"repo_key"`
	Reason        string    `json:"reason"`
	TokenType     string    `json:"token_type"`
	ExpireAt      time.Time `json:"expire_at"`
	CreatedAt     time.Time `json:"created_at"`
}

SecretScanningPushProtectionBypass is a granted push protection bypass.

type SecretScanningPushProtectionPlaceholder

type SecretScanningPushProtectionPlaceholder struct {
	ID        string    `json:"id"`
	RepoKey   string    `json:"repo_key"`
	TokenType string    `json:"token_type"`
	CreatedAt time.Time `json:"created_at"`
}

SecretScanningPushProtectionPlaceholder is the identity a pusher presents when requesting a push protection bypass.

type SecretScanningResolution

type SecretScanningResolution string

SecretScanningResolution is the reason recorded when an alert is resolved; only these six values are accepted.

const (
	SecretScanningResolutionFalsePositive  SecretScanningResolution = "false_positive"
	SecretScanningResolutionWontFix        SecretScanningResolution = "wont_fix"
	SecretScanningResolutionRevoked        SecretScanningResolution = "revoked"
	SecretScanningResolutionUsedInTests    SecretScanningResolution = "used_in_tests"
	SecretScanningResolutionPatternDeleted SecretScanningResolution = "pattern_deleted"
	SecretScanningResolutionPatternEdited  SecretScanningResolution = "pattern_edited"
)

type SecretScanningScanRecord

type SecretScanningScanRecord struct {
	Type        string
	Status      string
	StartedAt   time.Time
	CompletedAt time.Time
}

SecretScanningScanRecord is one scan in the repository's scan history.

type SecretScanningState

type SecretScanningState string

SecretScanningState is the lifecycle state of a secret-scanning alert; GitHub only ever emits these two.

const (
	SecretScanningStateOpen     SecretScanningState = "open"
	SecretScanningStateResolved SecretScanningState = "resolved"
)

type SecretsKeyPair

type SecretsKeyPair struct {
	KeyID      string `json:"key_id"`
	PublicKey  string `json:"public_key"`  // base64 32-byte X25519 public key
	PrivateKey string `json:"private_key"` // base64 32-byte X25519 private key
}

SecretsKeyPair is the X25519 keypair backing the Actions sealed-box contract. Persisted so key_id stays stable across restarts for clients caching the public key.

type SecurityAdvisory

type SecurityAdvisory struct {
	ID                     int                             `json:"id"`
	NodeID                 string                          `json:"node_id"`
	GHSAID                 string                          `json:"ghsa_id"`
	RepoID                 int                             `json:"repo_id"`
	AuthorID               int                             `json:"author_id"`
	Title                  string                          `json:"title,omitempty"`
	Summary                string                          `json:"summary"`
	Description            string                          `json:"description"`
	Severity               string                          `json:"severity"`
	CVSSScore              float64                         `json:"cvss_score"`
	CVSSVector             string                          `json:"cvss_vector"`
	CWEs                   []string                        `json:"cwes"`
	State                  string                          `json:"state"`
	CreatedAt              time.Time                       `json:"created_at"`
	UpdatedAt              time.Time                       `json:"updated_at"`
	PublishedAt            *time.Time                      `json:"published_at,omitempty"`
	CVEID                  string                          `json:"cve_id"`
	HTMLURL                string                          `json:"html_url"`
	URL                    string                          `json:"url"`
	SubmissionAccepted     bool                            `json:"submission_accepted"`
	PrivateForkID          int                             `json:"private_fork_id"`
	CollaboratingUsers     []string                        `json:"collaborating_users,omitempty"`
	CollaboratingTeams     []string                        `json:"collaborating_teams,omitempty"`
	VulnerableVersionRange string                          `json:"vulnerable_version_range"`
	Vulnerabilities        []SecurityAdvisoryVulnerability `json:"vulnerabilities,omitempty"`
	Credits                []SecurityAdvisoryCredit        `json:"credits,omitempty"`
}

SecurityAdvisory is a repository-scoped security advisory.

type SecurityAdvisoryCredit

type SecurityAdvisoryCredit struct {
	Login string `json:"login"`
	Type  string `json:"type"`
}

SecurityAdvisoryCredit is one credited participant ({login, type}). bleephub auto-accepts credits, so no per-credit state is stored; rendered credits_detailed state is always "accepted".

type SecurityAdvisoryReport

type SecurityAdvisoryReport struct {
	ID                     int       `json:"id"`
	AdvisoryID             int       `json:"advisory_id"`
	ReporterID             int       `json:"reporter_id"`
	Summary                string    `json:"summary"`
	Description            string    `json:"description"`
	Severity               string    `json:"severity"`
	CVSSScore              float64   `json:"cvss_score"`
	CVSSVector             string    `json:"cvss_vector"`
	CWEs                   []string  `json:"cwes"`
	VulnerableVersionRange string    `json:"vulnerable_version_range"`
	CreatedAt              time.Time `json:"created_at"`
}

SecurityAdvisoryReport records a vulnerability report that spawned an advisory.

type SecurityAdvisoryVulnerability

type SecurityAdvisoryVulnerability struct {
	PackageName            string   `json:"package_name"`
	PackageEcosystem       string   `json:"package_ecosystem"`
	VulnerableVersionRange string   `json:"vulnerable_version_range"`
	FirstPatchedVersion    string   `json:"first_patched_version,omitempty"`
	VulnerableFunctions    []string `json:"vulnerable_functions,omitempty"`
}

type SecurityReviewRequest

type SecurityReviewRequest struct {
	ID               int                      `json:"id"`
	Number           int                      `json:"number"`
	RepoKey          string                   `json:"repo_key"`
	OrgLogin         string                   `json:"org_login"`
	Kind             string                   `json:"kind"`
	RequesterID      int                      `json:"requester_id"`
	ResourceID       string                   `json:"resource_identifier"`
	Status           string                   `json:"status"`
	RequesterComment *string                  `json:"requester_comment"`
	Data             []map[string]interface{} `json:"data"`
	Responses        []SecurityReviewResponse `json:"responses"`
	ExpiresAt        time.Time                `json:"expires_at"`
	CreatedAt        time.Time                `json:"created_at"`
}

func CopySecurityReviewRequest

func CopySecurityReviewRequest(request *SecurityReviewRequest) *SecurityReviewRequest

type SecurityReviewResponse

type SecurityReviewResponse struct {
	ID         int       `json:"id"`
	ReviewerID int       `json:"reviewer_id"`
	Message    string    `json:"message"`
	Status     string    `json:"status"`
	CreatedAt  time.Time `json:"created_at"`
}

type ServiceDef

type ServiceDef struct {
	Image       string            `yaml:"image"`
	Env         map[string]string `yaml:"env"`
	Ports       []interface{}     `yaml:"ports"`
	Volumes     []string          `yaml:"volumes"`
	Options     string            `yaml:"options"`
	Credentials struct {
		Username string `yaml:"username"`
		Password string `yaml:"password"`
	} `yaml:"credentials"`
}

ServiceDef represents a service container configuration.

type Session

type Session struct {
	SessionID string                 `json:"sessionId"`
	OwnerName string                 `json:"ownerName"`
	Agent     *Agent                 `json:"agent"`
	MsgCh     chan *TaskAgentMessage `json:"-"`
}

Session represents a runner's active session.

type SnapshotDependency

type SnapshotDependency struct {
	PackageURL   string   `json:"package_url"`
	Relationship string   `json:"relationship,omitempty"`
	Scope        string   `json:"scope,omitempty"`
	Dependencies []string `json:"dependencies,omitempty"`
}

type SnapshotDetector

type SnapshotDetector struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	URL     string `json:"url"`
}

type SnapshotJob

type SnapshotJob struct {
	ID         string `json:"id"`
	Correlator string `json:"correlator"`
	HTMLURL    string `json:"html_url,omitempty"`
}

type SnapshotManifest

type SnapshotManifest struct {
	Name string `json:"name"`
	File *struct {
		SourceLocation string `json:"source_location"`
	} `json:"file,omitempty"`
	Resolved map[string]*SnapshotDependency `json:"resolved,omitempty"`
}

type SponsorLifetimeValue

type SponsorLifetimeValue struct {
	SponsorLogin     string
	SponsorType      string
	SponsorableLogin string
	AmountInCents    int
}

SponsorLifetimeValue is one row of lifetimeReceivedSponsorshipValues.

type SponsorsActivity

type SponsorsActivity struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`
	Action string `json:"action"`

	SponsorableID    int    `json:"sponsorable_id"`
	SponsorableType  string `json:"sponsorable_type"`
	SponsorableLogin string `json:"sponsorable_login"`

	SponsorID    int    `json:"sponsor_id"`
	SponsorType  string `json:"sponsor_type"`
	SponsorLogin string `json:"sponsor_login"`

	SponsorshipID          int       `json:"sponsorship_id"`
	SponsorsTierID         int       `json:"sponsors_tier_id,omitempty"`
	PreviousSponsorsTierID int       `json:"previous_sponsors_tier_id,omitempty"`
	CurrentPrivacyLevel    string    `json:"current_privacy_level,omitempty"`
	PaymentSource          string    `json:"payment_source,omitempty"`
	ViaBulkSponsorship     bool      `json:"via_bulk_sponsorship"`
	Timestamp              time.Time `json:"timestamp"`
}

SponsorsActivity is one entry in a sponsorable's activity feed.

type SponsorsGoal

type SponsorsGoal struct {
	Kind        string `json:"kind"`
	TargetValue int    `json:"target_value"`
	Description string `json:"description,omitempty"`
}

SponsorsGoal is the target a maintainer has set on their listing. TargetValue is cents for MONTHLY_SPONSORSHIP_AMOUNT and a sponsor count for TOTAL_SPONSORS_COUNT.

type SponsorsInvoice

type SponsorsInvoice struct {
	ID               int       `json:"id"`
	SponsorshipID    int       `json:"sponsorship_id"`
	ListingID        int       `json:"listing_id"`
	SponsorLogin     string    `json:"sponsor_login"`
	SponsorableLogin string    `json:"sponsorable_login"`
	TierID           int       `json:"tier_id"`
	AmountInCents    int       `json:"amount_in_cents"`
	PeriodStart      time.Time `json:"period_start"`
	PeriodEnd        time.Time `json:"period_end"`
	OneTime          bool      `json:"one_time"`
	Prorated         bool      `json:"prorated"`
	Status           string    `json:"status"` // paid | refunded
	PayoutID         int       `json:"payout_id,omitempty"`
	CreatedAt        time.Time `json:"created_at"`
}

SponsorsInvoice records one billed period. It is the ledger every reported money figure derives from, so totals cannot drift from what was billed.

type SponsorsListing

type SponsorsListing struct {
	ID               int    `json:"id"`
	NodeID           string `json:"node_id"`
	Slug             string `json:"slug"`
	SponsorableID    int    `json:"sponsorable_id"`
	SponsorableType  string `json:"sponsorable_type"` // User | Organization
	SponsorableLogin string `json:"sponsorable_login"`
	Name             string `json:"name"`
	ShortDescription string `json:"short_description"`
	FullDescription  string `json:"full_description"`
	ContactEmail     string `json:"contact_email,omitempty"`
	// Payout settings (no money moves, but the maintainer's real config).
	BillingCountryOrRegion          string        `json:"billing_country_or_region,omitempty"`
	ResidenceCountryOrRegion        string        `json:"residence_country_or_region,omitempty"`
	FiscalHostLogin                 string        `json:"fiscal_host_login,omitempty"`
	FiscallyHostedProjectProfileURL string        `json:"fiscally_hosted_project_profile_url,omitempty"`
	PayoutMinimumInCents            int           `json:"payout_minimum_in_cents"`
	NextPayoutDate                  string        `json:"next_payout_date,omitempty"` // YYYY-MM-DD
	IsPublic                        bool          `json:"is_public"`
	PatreonSponsorshipsEnabled      bool          `json:"patreon_sponsorships_enabled"`
	ActiveGoal                      *SponsorsGoal `json:"active_goal,omitempty"`
	CreatedAt                       time.Time     `json:"created_at"`
	UpdatedAt                       time.Time     `json:"updated_at"`
}

SponsorsListing is a sponsorable account's GitHub Sponsors profile.

type SponsorsListingFeaturedItem

type SponsorsListingFeaturedItem struct {
	ID              int       `json:"id"`
	NodeID          string    `json:"node_id"`
	ListingID       int       `json:"listing_id"`
	FeatureableType string    `json:"featureable_type"` // REPOSITORY | USER
	FeatureableID   int       `json:"featureable_id"`
	Description     string    `json:"description,omitempty"`
	Position        int       `json:"position"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

SponsorsListingFeaturedItem promotes a repository or a user on a listing.

type SponsorsListingInput

type SponsorsListingInput struct {
	SponsorableID                   int
	SponsorableType                 string
	SponsorableLogin                string
	Name                            string
	ShortDescription                string
	FullDescription                 string
	ContactEmail                    string
	BillingCountryOrRegion          string
	ResidenceCountryOrRegion        string
	FiscalHostLogin                 string
	FiscallyHostedProjectProfileURL string
}

SponsorsListingInput is the maintainer-supplied half of a listing.

type SponsorsListingUpdate

type SponsorsListingUpdate struct {
	Name                     *string
	ShortDescription         *string
	FullDescription          *string
	ContactEmail             *string
	BillingCountryOrRegion   *string
	ResidenceCountryOrRegion *string
	FiscalHostLogin          *string
	IsPublic                 *bool
	PatreonEnabled           *bool
	Goal                     *SponsorsGoal
	ClearGoal                bool
}

SponsorsListingUpdate is a sparse patch: a nil member is left alone.

type SponsorsPayout

type SponsorsPayout struct {
	ID            int       `json:"id"`
	ListingID     int       `json:"listing_id"`
	AmountInCents int       `json:"amount_in_cents"`
	PeriodStart   time.Time `json:"period_start"`
	PeriodEnd     time.Time `json:"period_end"`
	Status        string    `json:"status"` // pending | paid
	ScheduledDate string    `json:"scheduled_date"`
	CreatedAt     time.Time `json:"created_at"`
}

SponsorsPayout is one maintainer payout run: the invoices billed in a period, rolled up into the amount that would be transferred.

type SponsorsStore

type SponsorsStore struct {
	Mu      sync.RWMutex `json:"-"`
	Persist *Persistence `json:"-"`
	// contains filtered or unexported fields
}

SponsorsStore holds the whole Sponsors object graph behind one mutex so a lifecycle transition is atomic across the records it touches.

func NewSponsorsStore

func NewSponsorsStore(now func() time.Time) *SponsorsStore

NewSponsorsStore builds an empty Sponsors store sharing the given clock, so freezing time freezes billing.

func (*SponsorsStore) AdvanceSponsorshipBillingCycles

func (ss *SponsorsStore) AdvanceSponsorshipBillingCycles(now time.Time) []*SponsorsTransition

AdvanceSponsorshipBillingCycles rolls every recurring sponsorship whose next billing date has arrived (pending cancellation ends it, pending tier change applies, otherwise bills another period) and returns one transition each.

func (*SponsorsStore) CancelSponsorship

func (ss *SponsorsStore) CancelSponsorship(sponsorshipID int) (*SponsorsTransition, error)

CancelSponsorship ends a sponsorship. A recurring one stops at the end of the paid-for period; a one-time payment cancels immediately.

func (*SponsorsStore) ChangeSponsorshipTier

func (ss *SponsorsStore) ChangeSponsorshipTier(sponsorshipID, tierID int) (*SponsorsTransition, error)

ChangeSponsorshipTier moves a recurring sponsorship to another tier. An upgrade takes effect now and bills the prorated difference (multiply by remaining days before dividing, so no rounding accumulates); a downgrade is deferred to the next billing date, as GitHub does.

func (*SponsorsStore) CreateSponsorsListing

func (ss *SponsorsStore) CreateSponsorsListing(in SponsorsListingInput) (*SponsorsListing, error)

CreateSponsorsListing opens a listing for the sponsorable. An account may hold only one.

func (*SponsorsStore) CreateSponsorsTier

func (ss *SponsorsStore) CreateSponsorsTier(in SponsorsTierInput) (*SponsorsTier, error)

CreateSponsorsTier adds a tier to a listing. A tier is created as a draft unless Publish is set; a draft tier cannot back a sponsorship.

func (*SponsorsStore) CreateSponsorship

func (ss *SponsorsStore) CreateSponsorship(in SponsorshipInput) (*SponsorsTransition, error)

CreateSponsorship opens a sponsorship and bills its first period. Recurring gets a next billing date one month out; a one-time payment gets one invoice.

func (*SponsorsStore) CreateSponsorshipNewsletter

func (ss *SponsorsStore) CreateSponsorshipNewsletter(listingID, authorID int, subject, body string, publish bool) (*SponsorshipNewsletter, error)

CreateSponsorshipNewsletter drafts (or publishes) an update to sponsors.

func (*SponsorsStore) EstimatedNextSponsorsPayoutInCents

func (ss *SponsorsStore) EstimatedNextSponsorsPayoutInCents(sponsorableLogin string) int

EstimatedNextSponsorsPayoutInCents is the money already billed for this sponsorable that has not yet been rolled into a payout.

func (*SponsorsStore) FeatureSponsorsListingItem

func (ss *SponsorsStore) FeatureSponsorsListingItem(listingID int, featureableType string, featureableID int, description string) (*SponsorsListingFeaturedItem, error)

FeatureSponsorsListingItem promotes a repository or user on a listing, appending it at the end of the featured order.

func (*SponsorsStore) FindSponsorsActivityByNodeID

func (ss *SponsorsStore) FindSponsorsActivityByNodeID(nodeID string) *SponsorsActivity

FindSponsorsActivityByNodeID returns the live activity row.

func (*SponsorsStore) FindSponsorsFeaturedItemByNodeID

func (ss *SponsorsStore) FindSponsorsFeaturedItemByNodeID(nodeID string) *SponsorsListingFeaturedItem

FindSponsorsFeaturedItemByNodeID returns the live featured-item row.

func (*SponsorsStore) FindSponsorsListingByNodeID

func (ss *SponsorsStore) FindSponsorsListingByNodeID(nodeID string) *SponsorsListing

FindSponsorsListingByNodeID returns the live listing row (STORE-021 node lookup exception).

func (*SponsorsStore) FindSponsorsTierByNodeID

func (ss *SponsorsStore) FindSponsorsTierByNodeID(nodeID string) *SponsorsTier

FindSponsorsTierByNodeID returns the live tier row for a global id.

func (*SponsorsStore) FindSponsorshipByNodeID

func (ss *SponsorsStore) FindSponsorshipByNodeID(nodeID string) *Sponsorship

FindSponsorshipByNodeID returns the live sponsorship row.

func (*SponsorsStore) FindSponsorshipNewsletterByNodeID

func (ss *SponsorsStore) FindSponsorshipNewsletterByNodeID(nodeID string) *SponsorshipNewsletter

FindSponsorshipNewsletterByNodeID returns the live newsletter row.

func (*SponsorsStore) GetSponsorsListing

func (ss *SponsorsStore) GetSponsorsListing(id int) *SponsorsListing

GetSponsorsListing returns the listing by database id.

func (*SponsorsStore) GetSponsorsListingForAccount

func (ss *SponsorsStore) GetSponsorsListingForAccount(login string) *SponsorsListing

GetSponsorsListingForAccount returns the sponsorable's listing, or nil.

func (*SponsorsStore) GetSponsorsTier

func (ss *SponsorsStore) GetSponsorsTier(id int) *SponsorsTier

GetSponsorsTier returns a tier by database id.

func (*SponsorsStore) GetSponsorship

func (ss *SponsorsStore) GetSponsorship(id int) *Sponsorship

GetSponsorship returns a sponsorship by database id.

func (*SponsorsStore) GetSponsorshipBetween

func (ss *SponsorsStore) GetSponsorshipBetween(sponsorLogin, sponsorableLogin string, activeOnly bool) *Sponsorship

GetSponsorshipBetween returns the sponsorship from sponsorLogin to sponsorableLogin, optionally only while it is still active.

func (*SponsorsStore) LifetimeReceivedSponsorshipValues

func (ss *SponsorsStore) LifetimeReceivedSponsorshipValues(sponsorableLogin string) []*SponsorLifetimeValue

LifetimeReceivedSponsorshipValues totals, per sponsor, everything ever billed for this sponsorable. Refunded invoices are excluded.

func (*SponsorsStore) ListSponsorsActivities

func (ss *SponsorsStore) ListSponsorsActivities(login string, includeAsSponsor bool) []*SponsorsActivity

ListSponsorsActivities returns a sponsorable's activity feed, newest first. includeAsSponsor also returns the events where the account was the sponsor rather than the recipient.

func (*SponsorsStore) ListSponsorsInvoices

func (ss *SponsorsStore) ListSponsorsInvoices(listingID int) []*SponsorsInvoice

ListSponsorsInvoices returns the invoices billed for a listing, newest first.

func (*SponsorsStore) ListSponsorsInvoicesForSponsor

func (ss *SponsorsStore) ListSponsorsInvoicesForSponsor(sponsorLogin string) []*SponsorsInvoice

ListSponsorsInvoicesForSponsor returns what an account has been billed.

func (*SponsorsStore) ListSponsorsListingFeaturedItems

func (ss *SponsorsStore) ListSponsorsListingFeaturedItems(listingID int, types []string) []*SponsorsListingFeaturedItem

ListSponsorsListingFeaturedItems returns a listing's featured items in promotion order, optionally filtered to the given featureable types.

func (*SponsorsStore) ListSponsorsListings

func (ss *SponsorsStore) ListSponsorsListings() []*SponsorsListing

ListSponsorsListings returns every listing, ordered by sponsorable login.

func (*SponsorsStore) ListSponsorsPayouts

func (ss *SponsorsStore) ListSponsorsPayouts(listingID int) []*SponsorsPayout

ListSponsorsPayouts returns a listing's payout history, newest first.

func (*SponsorsStore) ListSponsorsTiers

func (ss *SponsorsStore) ListSponsorsTiers(listingID int, includeUnpublished bool) []*SponsorsTier

ListSponsorsTiers returns a listing's tiers ordered by monthly price, including drafts and retired tiers only when asked.

func (*SponsorsStore) ListSponsorshipNewsletters

func (ss *SponsorsStore) ListSponsorshipNewsletters(listingID int, includeDrafts bool) []*SponsorshipNewsletter

ListSponsorshipNewsletters returns a listing's newsletters newest first; unpublished drafts are included only for the maintainer.

func (*SponsorsStore) ListSponsorshipsAsMaintainer

func (ss *SponsorsStore) ListSponsorshipsAsMaintainer(sponsorableLogin string, activeOnly bool) []*Sponsorship

ListSponsorshipsAsMaintainer returns the sponsorships funding the sponsorable, newest first.

func (*SponsorsStore) ListSponsorshipsAsSponsor

func (ss *SponsorsStore) ListSponsorshipsAsSponsor(sponsorLogin string, activeOnly bool) []*Sponsorship

ListSponsorshipsAsSponsor returns the sponsorships the account funds.

func (*SponsorsStore) ListSponsorshipsForTier

func (ss *SponsorsStore) ListSponsorshipsForTier(tierID int, activeOnly bool) []*Sponsorship

ListSponsorshipsForTier returns the sponsorships currently on a tier.

func (*SponsorsStore) MonthlyEstimatedSponsorsIncomeInCents

func (ss *SponsorsStore) MonthlyEstimatedSponsorsIncomeInCents(sponsorableLogin string) int

MonthlyEstimatedSponsorsIncomeInCents sums every active recurring sponsorship's locked-in amount, with pending downgrades applied (they take effect before the next payout).

func (*SponsorsStore) PublishSponsorsTier

func (ss *SponsorsStore) PublishSponsorsTier(id int) (*SponsorsTier, error)

PublishSponsorsTier moves a draft tier to published.

func (*SponsorsStore) PublishSponsorshipNewsletter

func (ss *SponsorsStore) PublishSponsorshipNewsletter(id int) (*SponsorshipNewsletter, error)

PublishSponsorshipNewsletter sends a drafted newsletter to sponsors.

func (*SponsorsStore) RetireSponsorsTier

func (ss *SponsorsStore) RetireSponsorsTier(id int) (*SponsorsTier, error)

RetireSponsorsTier retires a tier: existing sponsorships keep billing at the amount they locked in, but no new sponsorship may select it.

func (*SponsorsStore) RunSponsorsPayout

func (ss *SponsorsStore) RunSponsorsPayout(listingID int, now time.Time) *SponsorsPayout

RunSponsorsPayout rolls every unpaid invoice for a listing into one payout and advances its next payout date, or nil when nothing is owed.

func (*SponsorsStore) SetClock

func (ss *SponsorsStore) SetClock(now func() time.Time)

SetClock rebinds the Sponsors store's clock to the owning store's.

func (*SponsorsStore) SponsorsGoalProgress

func (ss *SponsorsStore) SponsorsGoalProgress(listingID int) (kind string, target, percent int, ok bool)

SponsorsGoalProgress reports a listing's goal progress as an integer percent clamped to 0..100.

func (*SponsorsStore) TotalSponsorshipAmountAsSponsorInCents

func (ss *SponsorsStore) TotalSponsorshipAmountAsSponsorInCents(sponsorLogin string, since, until *time.Time, sponsorableLogins []string) int

TotalSponsorshipAmountAsSponsorInCents is what an account has spent funding sponsorships, optionally filtered by window and recipient.

func (*SponsorsStore) UnfeatureSponsorsListingItem

func (ss *SponsorsStore) UnfeatureSponsorsListingItem(id int) bool

UnfeatureSponsorsListingItem removes a featured item and closes the gap its position left, so positions stay 1..n with no holes.

func (*SponsorsStore) UpdateSponsorsListing

func (ss *SponsorsStore) UpdateSponsorsListing(id int, patch SponsorsListingUpdate) *SponsorsListing

UpdateSponsorsListing applies a sparse patch and returns the new state.

func (*SponsorsStore) UpdateSponsorshipPreferences

func (ss *SponsorsStore) UpdateSponsorshipPreferences(sponsorshipID int, privacy string, receiveEmails bool) (*SponsorsTransition, error)

UpdateSponsorshipPreferences changes a sponsorship's privacy level and email preference.

type SponsorsTier

type SponsorsTier struct {
	ID                  int       `json:"id"`
	NodeID              string    `json:"node_id"`
	ListingID           int       `json:"listing_id"`
	Name                string    `json:"name"`
	Description         string    `json:"description"`
	MonthlyPriceInCents int       `json:"monthly_price_in_cents"`
	IsOneTime           bool      `json:"is_one_time"`
	IsCustomAmount      bool      `json:"is_custom_amount"`
	IsDraft             bool      `json:"is_draft"`
	IsPublished         bool      `json:"is_published"`
	IsRetired           bool      `json:"is_retired"`
	WelcomeMessage      string    `json:"welcome_message,omitempty"`
	RepositoryID        int       `json:"repository_id,omitempty"`
	CreatedAt           time.Time `json:"created_at"`
	UpdatedAt           time.Time `json:"updated_at"`
}

SponsorsTier is one price point on a listing.

func (*SponsorsTier) ListingIDOrZero

func (t *SponsorsTier) ListingIDOrZero() int

ListingIDOrZero is nil-safe so a tier lookup miss reads as "no listing" rather than panicking in the change path.

type SponsorsTierInput

type SponsorsTierInput struct {
	ListingID      int
	Name           string
	Description    string
	AmountInCents  int
	IsOneTime      bool
	IsCustomAmount bool
	Publish        bool
	WelcomeMessage string
	RepositoryID   int
}

SponsorsTierInput is the maintainer-supplied half of a tier.

type SponsorsTransition

type SponsorsTransition struct {
	Sponsorship  *Sponsorship
	Previous     *Sponsorship
	Activity     *SponsorsActivity
	Invoice      *SponsorsInvoice
	Tier         *SponsorsTier
	PreviousTier *SponsorsTier
}

SponsorsTransition is what a lifecycle call reports back: the sponsorship after the change, its activity, any invoice, and the tiers on either side. The server renders the `sponsorship` webhook from it.

type Sponsorship

type Sponsorship struct {
	ID     int    `json:"id"`
	NodeID string `json:"node_id"`

	SponsorID    int    `json:"sponsor_id"`
	SponsorType  string `json:"sponsor_type"` // User | Organization
	SponsorLogin string `json:"sponsor_login"`

	SponsorableID    int    `json:"sponsorable_id"`
	SponsorableType  string `json:"sponsorable_type"`
	SponsorableLogin string `json:"sponsorable_login"`

	TierID                  int    `json:"tier_id"`
	PrivacyLevel            string `json:"privacy_level"`
	PaymentSource           string `json:"payment_source"`
	IsOneTimePayment        bool   `json:"is_one_time_payment"`
	IsActive                bool   `json:"is_active"`
	IsSponsorOptedIntoEmail bool   `json:"is_sponsor_opted_into_email"`
	ViaBulkSponsorship      bool   `json:"via_bulk_sponsorship"`

	// AmountInCents is copied off the tier at selection time so a later tier
	// edit cannot reprice an existing sponsor.
	AmountInCents int `json:"amount_in_cents"`

	PendingTierID        int        `json:"pending_tier_id,omitempty"`
	PendingCancellation  bool       `json:"pending_cancellation,omitempty"`
	PendingEffectiveDate *time.Time `json:"pending_effective_date,omitempty"`
	NextBillingDate      *time.Time `json:"next_billing_date,omitempty"`

	TierSelectedAt time.Time  `json:"tier_selected_at"`
	CreatedAt      time.Time  `json:"created_at"`
	UpdatedAt      time.Time  `json:"updated_at"`
	CancelledAt    *time.Time `json:"cancelled_at,omitempty"`
}

Sponsorship is one sponsor's funding relationship with one sponsorable.

The billing state machine lives in these fields:

IsActive && NextBillingDate != nil && no pending change → ACTIVE
PendingTierID != 0                                      → PENDING_TIER_CHANGE
PendingCancellation                                     → PENDING_CANCELLATION
!IsActive                                               → CANCELLED

A one-time payment has IsOneTimePayment set, no NextBillingDate, and exactly one invoice.

type SponsorshipInput

type SponsorshipInput struct {
	SponsorID        int
	SponsorType      string
	SponsorLogin     string
	SponsorableID    int
	SponsorableType  string
	SponsorableLogin string
	TierID           int
	// AmountInCents is honoured only for a custom-amount tier; otherwise
	// the tier's price is authoritative.
	AmountInCents      int
	PrivacyLevel       string
	ReceiveEmails      bool
	IsRecurring        bool
	ViaBulkSponsorship bool
	PaymentSource      string
}

SponsorshipInput opens a sponsorship.

type SponsorshipNewsletter

type SponsorshipNewsletter struct {
	ID          int       `json:"id"`
	NodeID      string    `json:"node_id"`
	ListingID   int       `json:"listing_id"`
	AuthorID    int       `json:"author_id"`
	Subject     string    `json:"subject"`
	Body        string    `json:"body"`
	IsPublished bool      `json:"is_published"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

SponsorshipNewsletter is a maintainer's update to their sponsors.

type StepDef

type StepDef struct {
	ID               string            `yaml:"id"`
	Name             string            `yaml:"name"`
	Uses             string            `yaml:"uses"`
	Run              string            `yaml:"run"`
	With             map[string]string `yaml:"with"`
	Env              map[string]string `yaml:"env"`
	If               string            `yaml:"if"`
	Shell            string            `yaml:"shell"`
	WorkingDirectory string            `yaml:"working-directory"`
	ContinueOnError  interface{}       `yaml:"continue-on-error"`
	TimeoutMinutes   int               `yaml:"timeout-minutes"`
}

StepDef represents a single step in a job.

type Store

type Store struct {
	Agents                       map[int]*Agent
	Sessions                     map[string]*Session
	Jobs                         map[string]*Job
	Users                        map[int]*User
	UsersByLogin                 map[string]*User
	UsersByExternalID            map[string]*User // issuer\x00subject → user (stable federated identity index)
	Tokens                       map[string]*Token
	DeviceCodes                  map[string]*DeviceCode
	AuthCodes                    map[string]*AuthCode     // OAuth web-flow codes
	LoginSessions                map[string]*LoginSession // _gh_sess cookie value → session
	OIDCLogoutClaims             map[string]time.Time     // replay key → expiry (ephemeral stores only)
	Repos                        map[int]*Repo
	ReposByName                  map[string]*Repo                       // "owner/name" → repo
	RepoRedirects                map[string]int                         // FoldName("owner/old-name") → repo id, for a renamed or transferred repository
	GitStorages                  map[string]gitStorage.Storer           // "owner/name" → go-git storage (memory or filesystem)
	Orgs                         map[int]*Org                           // id → org
	OrgsByLogin                  map[string]*Org                        // login → org
	Teams                        map[int]*Team                          // id → team
	TeamsBySlug                  map[string]*Team                       // "org/slug" → team
	Memberships                  map[string]*Membership                 // "org/user" → membership
	Issues                       map[int]*Issue                         // id → issue
	IssuesByRepo                 map[int]map[int]*Issue                 // repoID → number → issue (secondary index)
	IssueOrderByRepo             map[int][]*Issue                       // repoID → issues ordered by (CreatedAt, Number) asc (secondary index; maintained by indexIssueLocked/unindexIssueLocked)
	Labels                       map[int]*IssueLabel                    // id → label
	UserLists                    map[int]*UserList                      // id → user list (the profile "lists" a user sorts starred repositories into)
	Milestones                   map[int]*Milestone                     // id → milestone
	Comments                     map[int]*Comment                       // id → comment
	CommentCounts                map[string]int                         // "parentType\x1fparentID" → comment count (index)
	CommentsByParent             map[string][]*Comment                  // "parentType\x1fparentID" → comments (index, avoids scanning every comment per parent)
	IssueEvents                  map[int]*IssueEvent                    // id → issue event
	PullRequests                 map[int]*PullRequest                   // id → PR
	PullsByRepo                  map[int]map[int]*PullRequest           // repoID → number → PR (secondary index)
	PRReviews                    map[int]*PullRequestReview             // id → review
	PRReviewsByPR                map[int][]*PullRequestReview           // PR id → reviews (secondary index)
	Workflows                    map[string]*Workflow                   // id → workflow (run-level)
	WorkflowFiles                map[int64]*WorkflowFile                // id → workflow file (file-level)
	PendingMessages              []*TaskAgentMessage                    // messages awaiting delivery
	RepoSecrets                  map[string]map[string]*Secret          // "owner/repo" → name → secret
	RepoVariables                map[string]map[string]*ActionsVariable // "owner/repo" → NAME → variable
	RepoCollaborators            map[string]map[string]string           // "owner/repo" → login → permission (pull/push/admin)
	RepoAutolinks                map[string]map[int]*RepoAutolink       // "owner/repo" → id → autolink
	WikiGitStorages              map[string]gitStorage.Storer           // "owner/repo" → go-git storage of that repository's wiki
	WikiProjections              map[string]*WikiProjection             // "owner/repo" → pages/history derived from the wiki tip
	WikiMu                       sync.Mutex                             `json:"-"` // serializes wiki git I/O and projection rebuilds
	LFSObjects                   map[string]map[string]int64            // "owner/repo" → Git LFS oid (sha256 hex) → size in bytes (bytes live in the object store)
	LFSLocks                     map[string]map[int]*LFSLock            // "owner/repo" → lock id → Git LFS file lock
	RepoInvitations              map[string]map[int]*RepoInvitation     // "owner/repo" → id → invitation
	RepoDeployKeys               map[string]map[int]*RepoDeployKey      // "owner/repo" → id → deploy key
	RepoSubscriptions            map[string]*RepoSubscription           // "userID:repoID" → subscription
	OrgSecrets                   map[string]map[string]*OrgSecret       // org login → NAME → org secret
	OrgVariables                 map[string]map[string]*ActionsVariable // org login → NAME → org variable
	EnvSecrets                   map[string]map[string]*Secret          // envScopeKey(repo, env) → NAME → secret
	EnvVariables                 map[string]map[string]*ActionsVariable // envScopeKey(repo, env) → NAME → variable
	TimelineRecords              map[string][]*TimelineRecord           // planID → runner-uploaded timeline records
	LogFiles                     map[int][]byte                         // logID → uploaded runner log content
	LogMasks                     map[string][]string                    // planID → exact values scrubbed from every log surface
	WorkflowAttempts             map[int][]*Workflow                    // runID → prior attempts (oldest first)
	RunnerGroups                 map[int]*RunnerGroup                   // org runner groups (global pool overlay)
	NextRunnerGroupID            int
	Hooks                        map[string][]*Webhook         // "owner/repo" → hooks
	OrgHooks                     map[string][]*Webhook         // org login → org-level hooks
	HookDeliveries               map[int][]*WebhookDelivery    // hookID → deliveries
	Apps                         map[int]*App                  // id → app
	AppsBySlug                   map[string]*App               // slug → app
	AppsByClientID               map[string]*App               // OAuth client_id → app
	OAuthApps                    map[string]*OAuthApp          // OAuth client_id → OAuth app (distinct from GitHub App)
	Installations                map[int]*Installation         // id → installation
	InstallationTokens           map[string]*InstallationToken // token value → token
	UserToServerTokens           map[string]*UserToServerToken // gho_/ghu_ token value → token
	RefreshTokens                map[string]*RefreshToken      // ghr_ token value → refresh token
	AppHookDeliveries            map[int][]*WebhookDelivery    // appID → app-level webhook deliveries
	ManifestCodes                map[string]int                // code → appID (one-time-use)
	CheckRuns                    map[int64]*CheckRun           // id → check run
	CheckSuites                  map[int64]*CheckSuite         // id → check suite
	CheckSuitePrefs              map[string][]*CheckSuitePref  // repoKey → autoTrigger prefs
	CommitStatuses               *CommitStatusStore            // commit status contexts per repo+ref
	CommitComments               *CommitCommentStore           // commit comments per repo/commit
	Reactions                    *ReactionStore                // reactions across all parent types
	Releases                     *ReleaseStore                 // release CRUD
	Deployments                  *DeploymentStore              // deployments + statuses + environments
	PRReviewComments             *PRReviewCommentStore         // PR review comments (inline / threads)
	Misc                         *MiscStore                    // long-tail surfaces
	ProjectsV2                   *ProjectV2Store               // GitHub Projects v2
	NotificationsState           map[int]*UserNotificationsState
	Rulesets                     map[int]*Ruleset
	RulesetSuites                map[int]*RulesetSuite
	ProjectClassic               map[int]*ProjectClassic                // id → project
	ProjectColumns               map[int]*ProjectColumn                 // id → column
	ProjectCards                 map[int]*ProjectCard                   // id → card
	UserMigrations               map[int]*UserMigration                 // id → user migration
	OrgMigrations                map[int]*OrgMigration                  // id → org migration
	MigrationSources             map[int]*MigrationSource               // id → GEI migration source
	RepositoryMigrations         map[int]*RepositoryMigration           // id → GEI repository migration
	OrganizationMigrations       map[int]*OrganizationMigration         // id → GEI organization migration
	OrgMigratorRoles             map[string]*OrgMigratorRole            // org/type/actor → migrator grant
	Codespaces                   map[int]*Codespace                     // id → codespace
	CodespacesByName             map[string]*Codespace                  // name → codespace
	CodespaceSecrets             map[string]map[string]*CodespaceSecret // scope\x1fname → secret
	NextCodespaceID              int
	NextCodespaceSecretID        int
	LogLines                     map[string][]string     // jobID → captured console log lines
	Gists                        map[string]*Gist        // id → gist
	GistComments                 map[int]*GistComment    // id → gist comment
	StarredGists                 map[int]map[string]bool // userID → gistID → starred
	SecretScanningAlerts         map[int]*SecretScanningAlert
	SecretScanningAlertsByRepo   map[string]map[int]*SecretScanningAlert // repoKey → alertNumber → alert
	SecretScanningNextNumber     map[string]int                          // repoKey → next alert number
	CodeScanningAlerts           map[int]*CodeScanningAlert
	CodeScanningAlertsByRepo     map[string]map[int]*CodeScanningAlert // repoKey → alertNumber → alert
	CodeScanningNextNumber       map[string]int                        // repoKey → next alert number
	CodeScanningAnalyses         map[int]*CodeScanningAnalysis
	CodeScanningAnalysesByRepo   map[string]map[int]*CodeScanningAnalysis // repoKey → analysisID → analysis
	CodeScanningDefaultSetups    map[string]*CodeScanningDefaultSetup     // repoKey → default setup
	SARIFUploads                 map[string]*SARIFUpload                  // uploadID → upload
	DependabotAlerts             map[int]*DependabotAlert
	DependabotAlertsByRepo       map[string]map[int]*DependabotAlert         // repoKey → alertNumber → alert
	DependabotNextNumber         map[string]int                              // repoKey → next alert number
	DependabotSecrets            map[string]map[string]*DependabotSecret     // repoKey → name → secret
	DependabotOrgSecrets         map[string]map[string]*DependabotOrgSecret  // orgLogin → name → secret
	DependabotUserSecrets        map[string]map[string]*DependabotUserSecret // userLogin → name → secret
	DependabotRepositoryAccess   map[string][]int                            // orgLogin → repo IDs
	SecurityAdvisories           map[int]*SecurityAdvisory
	SecurityAdvisoriesByRepo     map[string]map[string]*SecurityAdvisory // repoKey → GHSA ID → advisory
	SecurityAdvisoryReports      map[int]*SecurityAdvisoryReport
	Packages                     map[int]*Package
	PackageVersions              map[int]*PackageVersion
	PackageFiles                 map[int]*PackageFile
	PackagesByOwnerKey           map[string]map[string]*Package  // ownerKey → PackageKey → package
	PackageVersionsByPackage     map[int]map[int]*PackageVersion // packageID → versionID → version
	PackageFilesByVersion        map[int]map[int]*PackageFile    // versionID → fileID → file
	PackageDataDir               string                          // directory for package file bytes
	ObjectByteStore              ActionsByteStore                // object storage for durable service bytes
	NextGistID                   int
	NextGistCommentID            int
	NextAgent                    int
	NextSecretScanningAlertID    int
	NextCodeScanningAlertID      int
	NextCodeScanningAnalysisID   int
	NextDependabotAlertID        int
	NextPackageID                int
	NextPackageVersionID         int
	NextPackageFileID            int
	NextMsg                      int64
	NextLog                      int
	NextReqID                    int64
	NextUser                     int
	NextRepo                     int
	NextOrg                      int
	NextTeam                     int
	NextIssue                    int
	NextLabel                    int
	NextUserListID               int
	NextMilestone                int
	NextComment                  int
	NextIssueEventID             int
	NextPR                       int
	NextPRReview                 int
	NextRunID                    int
	NextHookID                   int
	NextDeliveryID               int
	NextAppID                    int
	NextInstallationID           int
	NextCheckRunID               int64
	NextCheckSuiteID             int64
	NextRulesetID                int
	NextRulesetSuiteID           int
	NextProjectClassicID         int
	NextProjectColumnID          int
	NextProjectCardID            int
	NextUserMigrationID          int
	NextOrgMigrationID           int
	NextMigrationSourceID        int
	NextRepositoryMigrationID    int
	NextOrganizationMigrationID  int
	NextAutolinkID               int
	NextLFSLockID                int
	NextInvitationID             int
	NextDeployKeyID              int
	NextSecurityAdvisoryID       int
	NextSecurityAdvisoryReportID int
	Discussions                  map[int]*Discussion
	DiscussionPolls              map[int]*DiscussionPoll
	UserNamespaceGrants          map[int]*UserNamespaceAccessGrant
	Mannequins                   map[int]*Mannequin
	AttributionInvitations       map[int]*AttributionInvitation
	DiscussionCategories         map[int]*DiscussionCategory
	DiscussionComments           map[int]*DiscussionComment
	PinnedDiscussions            map[int][]int // repoID → ordered pinned discussion IDs (≤ MaxPinnedDiscussions)
	NextDiscussionID             int
	NextDiscussionPollID         int
	NextUserNamespaceGrantID     int
	NextMannequinID              int
	NextAttributionInvitationID  int
	NextDiscussionPollOptionID   int
	NextDiscussionNumber         map[int]int // repoID → next per-repo discussion number (high-water; monotonic across tombstones)
	NextDiscussionCategoryID     int
	NextDiscussionCommentID      int
	OrgActionsPermissions        map[string]*OrgActionsPermissions
	RepoActionsPermissions       map[string]*RepoActionsPermissions

	ActionsArtifacts *ArtifactStore `json:"-"`
	Persist          *Persistence   `json:"-"`
	Logger           zerolog.Logger `json:"-"` // structured logger; NewServer wires the configured one, else a nop

	PersistenceRecoveryRequired bool `json:"-"`

	CodespaceRuntimeDelete    func(*Codespace) error                                                 `json:"-"`
	CodespaceWorkspacePrepare func(string, *Repo, gitStorage.Storer, string) (string, func(), error) `json:"-"`
	RepoStorageOpen           func(context.Context, string) (gitStorage.Storer, error)               `json:"-"`
	// repoPrefixCopy/repoPrefixDelete run the S3 rename's slow prefix moves
	// outside the store lock (STORE-013). Nil in production; a test injects a
	// blocking copy to prove the lock is released.
	RepoPrefixCopy       func(oldFull, newFull string) error `json:"-"`
	RepoPrefixDelete     func(fullName string) error         `json:"-"`
	PendingRepoCreations map[string]bool                     `json:"-"`

	// mu guards the Store's maps and counters. RWMutex read locks are NOT
	// reentrant: once a writer queues on Lock, new RLock calls block, so
	// re-acquiring mu while holding it deadlocks. The invariants that prevent it:
	//   - Public Store methods and JSON serializers acquire mu themselves and
	//     must never be called with mu held.
	//   - xxxLocked helpers (and those documented "callers hold st.Mu") never
	//     acquire mu; they run under the caller's lock.
	//   - Code needing both a coherent scan AND rendered JSON gathers rows under
	//     one RLock, releases, then renders with the self-locking serializers.
	//   - Lock order: Store.Mu before any sub-store mutex (Misc.Mu, Reactions.Mu,
	//     Releases.Mu, persistence), never the reverse.
	Mu       sync.RWMutex     `json:"-"`
	ClockMu  sync.RWMutex     `json:"-"`
	ClockNow func() time.Time `json:"-"`

	// enterprises
	EnterpriseTeams                    map[int]*EnterpriseTeam
	EnterpriseTeamsBySlug              map[string]*EnterpriseTeam
	EnterpriseCodeSecurityConfigs      map[int]*EnterpriseCodeSecurityConfiguration
	EnterpriseCodeSecurityRepoConfigs  map[int]int // repoID → attached config ID
	EnterpriseSettings                 *EnterpriseSettings
	NextEnterpriseTeamID               int
	NextEnterpriseCodeSecurityConfigID int

	// enterprise accounts (store_enterprise_accounts.go), keyed by enterprise id
	// so no read crosses between enterprises.
	Enterprises           map[int]*Enterprise
	EnterprisesBySlug     map[string]*Enterprise           // lower-cased slug → enterprise
	EnterpriseMemberships map[string]*EnterpriseMembership // "<enterpriseID>/<userID>" → membership
	EnterpriseOrgs        map[int]*EnterpriseOrganization  // org id → owning enterprise link
	EnterpriseInvitations map[int]*EnterpriseInvitation
	IPAllowListEntries    map[int]*IPAllowListEntry
	VerifiableDomains     map[int]*VerifiableDomain

	NextEnterpriseID           int
	NextEnterpriseMembershipID int
	NextEnterpriseInvitationID int
	NextIPAllowListEntryID     int
	NextVerifiableDomainID     int

	// attestations + org artifact metadata
	Attestations                   map[int]*Attestation // id → attestation
	NextAttestationID              int
	ArtifactStorageRecords         map[int]*ArtifactStorageRecord // id → storage record
	NextArtifactStorageRecordID    int
	ArtifactDeploymentRecords      map[int]*ArtifactDeploymentRecord // id → deployment record
	NextArtifactDeploymentRecordID int
	ArtifactDeploymentJobs         map[int]*ArtifactDeploymentJob // id → asynchronous cluster job
	NextArtifactDeploymentJobID    int

	// copilot + code quality (gh_copilot.go, gh_copilot_spaces.go, gh_code_quality.go)
	CopilotSeats             map[string]map[int]*CopilotSeat           // org login → user ID → seat
	CopilotContentExclusions map[string]*CopilotContentExclusion       // org login → rules
	CopilotCodingAgentPerms  map[string]*CopilotCodingAgentPermissions // org login → policy
	CopilotSpaces            map[int64]*CopilotSpace                   // space ID → space
	NextCopilotSpaceID       int64
	CodeQualitySetups        map[string]*CodeQualitySetup           // repo full name → setup
	CodeQualityFindings      map[string]map[int]*CodeQualityFinding // repo full name → finding number → finding

	// GitHub Copilot subscription policy, seat activity and the usage
	// ledger the metrics endpoints aggregate (store_copilot_policy.go).
	CopilotPolicies *CopilotPolicyStore

	// GitHub Marketplace publication state (store_marketplace_categories.go):
	// the category taxonomy and each listing's marketing profile, beside the
	// billing state in store_marketplace.go.
	MarketplaceProfiles *MarketplaceProfileStore

	// GitHub Sponsors (store_sponsors.go). Listings, tiers, sponsorships,
	// the activity feed, newsletters and the invoice/payout ledger live
	// behind their own mutex so a billing-cycle transition is atomic across
	// every record it touches.
	Sponsors *SponsorsStore

	// Current GitHub REST resource families introduced after the original
	// OpenAPI pin. They are first-class durable state, not route-only shims.
	SecretScanningCustomPatterns map[string]map[int]*SecretScanningCustomPattern // "org:<login>" or "repo:<full>" → id → pattern
	NextSecretScanningPatternID  int
	PRCreationCaps               map[string]*PRCreationCap           // repo full name → cap
	OrgPRCreationCaps            map[string]*PRCreationCap           // org login → cap
	PullRequestMergeAsync        map[string]*PullRequestMergeAsync   // uuid → async merge record
	PRCreationBypass             map[string]map[string]bool          // repo full name → login set
	IssueSuggestions             map[string]map[int]*IssueSuggestion // "owner/repo#issueID" → id → suggestion
	NextIssueSuggestionID        int
	PullRequestStacks            map[string]map[int]*PullRequestStack // repo full name → stack number → stack
	NextPullRequestStackID       int

	// org governance surfaces (code security configurations, custom
	// properties, issue types, issue fields, security campaigns, private
	// registries, hosted compute network configurations, immutable releases)
	CodeSecurityConfigs         map[string]map[int]*CodeSecurityConfiguration // org login → id → configuration
	CodeSecurityRepoAttachments map[string]map[int]int                        // org login → repo ID → configuration ID
	NextCodeSecurityConfigID    int
	OrgCustomProperties         map[string]map[string]*CustomProperty // org login → property name → definition
	RepoCustomPropertyValues    map[string]map[string]interface{}     // "owner/repo" → property name → value
	OrgIssueTypes               map[string]map[int]*IssueType         // org login → id → issue type
	IssueTypesByID              map[int]*IssueType                    // id → issue type (GQL-024 O(1) node-ID lookup; ids are globally unique)
	NextIssueTypeID             int
	OrgIssueFields              map[string]map[int]*IssueField // org login → id → issue field
	NextIssueFieldID            int
	NextIssueFieldOptionID      int
	IssueFieldValues            map[int]map[int]interface{}                         // issue ID → field ID → raw value
	OrgCampaigns                map[string]map[int]*Campaign                        // org login → campaign number → campaign
	OrgPrivateRegistries        map[string]map[string]*PrivateRegistryConfiguration // org login → name → configuration
	OrgNetworkConfigurations    map[string]map[string]*NetworkConfiguration         // org login → id → configuration
	OrgNetworkSettings          map[string]map[string]*NetworkSettingsResource      // org login → id → settings resource
	OrgImmutableReleases        map[string]*OrgImmutableReleasesSettings            // org login → enforcement policy
	RepoImmutableReleases       map[string]bool                                     // "owner/repo" → repo-level enablement

	// hosted-runners
	HostedRunners            map[int]*HostedRunner
	NextHostedRunnerID       int
	HostedRunnerCustomImages map[int]*HostedRunnerCustomImage
	NextHostedRunnerImageID  int
	// actions-oidc-properties
	OrgOIDCPropertyInclusions map[string][]string

	// agents-codescan: GitHub Copilot coding agent secrets/variables/tasks
	// and CodeQL databases/variant analyses.
	AgentsRepoSecrets           map[string]map[string]*Secret          // "owner/repo" → NAME → secret
	AgentsOrgSecrets            map[string]map[string]*OrgSecret       // org login → NAME → org secret
	AgentsRepoVariables         map[string]map[string]*ActionsVariable // "owner/repo" → NAME → variable
	AgentsOrgVariables          map[string]map[string]*ActionsVariable // org login → NAME → org variable
	AgentTasks                  map[string]*AgentTask                  // task ID (UUID) → task
	CodeScanningAutofixes       map[string]*CodeScanningAutofix        // autofixKey(repoKey, number) → autofix
	CodeQLDatabases             map[int]*CodeQLDatabase                // id → database
	CodeQLDatabasesByRepo       map[string]map[string]*CodeQLDatabase  // repoKey → language → database
	CodeQLVariantAnalyses       map[int]*CodeQLVariantAnalysis         // id → variant analysis
	NextCodeQLDatabaseID        int
	NextCodeQLVariantAnalysisID int
	// teams-people
	OrgInvitations         map[int]*OrgInvitation // id → org invitation
	NextOrgInvitationID    int
	OrgBlocks              map[string]map[int]time.Time    // orgLogin → blocked userID → blocked-at
	OrgInteractionLimits   map[string]*OrgInteractionLimit // orgLogin → active interaction limit
	OrgRoleTeamAssignments map[string]map[int][]int        // orgLogin → roleID → team IDs
	OrgRoleUserAssignments map[string]map[int][]int        // orgLogin → roleID → user IDs
	OrgAnnouncements       map[string]*EnterpriseAnnouncement
	OrgCustomRepoRoles     map[string]map[int]*OrgCustomRepositoryRole // orgLogin → role ID → role
	OrgCustomRoles         map[string]map[int]*OrgCustomOrganizationRole
	NextOrgCustomRoleID    int
	OrgSCIMUsers           map[string]map[string]*EnterpriseSCIMUser // orgLogin → SCIM ID → identity
	OrgExternalGroups      map[string]map[string]*OrgExternalIdentityGroup
	TeamExternalGroupIDs   map[int][]string // team ID → external group IDs
	NextOrgExternalGroupID int
	// org billing budgets (gh_org_billing.go)
	OrgBudgets map[string]map[string]*OrgBudget // org login → budget ID → budget
	// API insights (gh_api_insights.go)
	APIRequestRecords []*APIRequestRecord // ordered by ID (oldest first)
	NextAPIRequestID  int64
	// apiRequestRecordCap bounds both the in-memory log and its durable bucket;
	// defaults to maxAPIRequestRecords, kept as a field so tests can exercise
	// FIFO eviction and durable reclamation with a small cap.
	ApiRequestRecordCap int `json:"-"`
	// fine-grained personal access token administration (gh_org_pat_admin.go)
	OrgPATGrantRequests map[string]map[int]*OrgPATGrantRequest // org login → request ID → request
	OrgPATGrants        map[string]map[int]*OrgPATGrant        // org login → grant ID → grant
	NextPATRequestID    int
	NextPATGrantID      int
	NextPATTokenID      int
	// org codespaces access settings (gh_codespaces.go)
	OrgCodespacesAccess map[string]*OrgCodespacesAccess // org login → access settings
	// Dependabot repository access default level (gh_dependabot.go)
	DependabotRepoAccessDefaultLevel map[string]string // org login → "public" | "internal"
	// secret scanning pattern configurations + push protection (gh_secret_scanning.go)
	SecretScanningPatternConfigs   map[string]*OrgSecretScanningPatternConfig                     // org login → config
	SecretScanningPushPlaceholders map[string]map[string]*SecretScanningPushProtectionPlaceholder // repoKey → placeholder ID → placeholder
	SecretScanningPushBypasses     map[string][]*SecretScanningPushProtectionBypass               // repoKey → bypasses
	SecurityReviewRequests         map[string]map[int]*SecurityReviewRequest                      // "repo|kind" → number → request
	NextSecurityReviewRequestID    int
	NextSecurityReviewResponseID   int

	// repo-write surfaces
	PagesDeployments         map[int]map[int]*PagesDeploymentRecord // repoID → deployment ID → record
	NextPagesDeploymentID    int
	EnvBranchPolicies        map[int][]*DeploymentBranchPolicyRule // environment ID → ordered branch/tag policies
	NextEnvBranchPolicyID    int
	EnvProtectionRules       map[int][]*EnvCustomProtectionRule // environment ID → enabled custom protection rules
	NextEnvProtectionRuleID  int
	SubIssueLists            map[int][]int                 // parent issue ID → ordered sub-issue IDs
	SubIssueParent           map[int]int                   // sub-issue ID → parent issue ID
	IssueBlockedBy           map[int][]int                 // issue ID → IDs of the issues blocking it
	RepoImports              map[int]*RepoImport           // repoID → source import
	DependencySnapshots      map[int][]*DependencySnapshot // repoID → submitted snapshots (oldest first)
	NextDependencySnapshotID int
	SBOMExports              map[string]*SBOMExport // export uuid → SBOM report export

	// GitHub Classroom
	Classrooms                   map[int]*Classroom
	ClassroomAssignments         map[int]*ClassroomAssignment
	ClassroomAcceptedAssignments map[int]*ClassroomAcceptedAssignment
	NextClassroomID              int
	NextClassroomAssignmentID    int
	NextClassroomAcceptedID      int

	// repo-reads
	RepoActivities   map[int]*RepoActivity         // id → recorded ref update (push activity)
	NextRepoActivity int                           // next RepoActivity ID
	RepoCloneTraffic map[string]*RepoTrafficBucket // "repoID:YYYY-MM-DD" → clone counters

	// Actions hot-path indexes (actions_indexes.go)
	//
	// Unexported on purpose: the replica-refresh field copy skips unexported
	// fields, so a snapshot swap can never smuggle stale pointers through them.
	// They mirror the Jobs and Workflows maps and are rebuilt wherever those
	// reload (load, replica refresh).
	JobsByPlanID map[string]*Job `json:"-"` // Job.PlanID → job

	PlanScopes       map[string]planScope `json:"-"` // Job.PlanID → plan scope identity (survives Message GC)
	PlanIDByScope    map[string]string    `json:"-"` // plan scopeIdentifier → Job.PlanID
	WorkflowsByRunID map[int]*Workflow    `json:"-"` // Workflow.RunID → workflow
	// contains filtered or unexported fields
}

Store holds all in-memory state for bleephub.

func NewStore

func NewStore() *Store

NewStore creates an initialized store.

func (*Store) AbortQueuedRepositoryMigrations

func (st *Store) AbortQueuedRepositoryMigrations(ownerOrgID int, reason string) int

AbortQueuedRepositoryMigrations fails every QUEUED migration of an org and returns how many. In-progress migrations are left alone (GitHub's abortQueuedMigrations names the queue).

func (*Store) AcceptEnterpriseInvitation

func (st *Store) AcceptEnterpriseInvitation(id, userID int) *EnterpriseInvitation

AcceptEnterpriseInvitation consumes an invitation and installs its membership in one batch write, so an accepted invitation cannot survive a crash without its membership. Returns the consumed snapshot, or nil when none exists.

func (*Store) AcceptRepoInvitation

func (st *Store) AcceptRepoInvitation(id int, user *User) (string, bool)

AcceptRepoInvitation consumes a pending invitation and adds the user to the repo's collaborators. It returns the repo's full name (for the `member` webhook) and whether an invitation was accepted.

func (*Store) AccountAuthenticationFor

func (st *Store) AccountAuthenticationFor(userID int) (AccountAuthentication, bool)

AccountAuthenticationFor returns a detached description of the account's credential source; the second result is false when the user does not exist.

func (*Store) ActionsBillingUsageForOwner

func (st *Store) ActionsBillingUsageForOwner(ownerLogin string) []BillingUsageItem

ActionsBillingUsageForOwner derives Actions usage line items from completed workflow-run jobs. Quantities are per-job minutes rounded up (GitHub's metering).

func (*Store) ActionsKeyPair

func (st *Store) ActionsKeyPair() (*SecretsKeyPair, error)

ActionsKeyPair returns the server-wide sealed-box keypair, generating and persisting it on first use.

func (*Store) ActiveEnterpriseIPAllowList

func (st *Store) ActiveEnterpriseIPAllowList() (values []string, forInstalledApps bool)

ActiveEnterpriseIPAllowList returns the enterprise's active allow-list entries when its IP allow list is on, else nil. Keeps the per-request gate to one read lock and no allocation when the feature is off.

func (*Store) ActiveOrgLoginsForUser

func (st *Store) ActiveOrgLoginsForUser(userID int) []string

ActiveOrgLoginsForUser returns the logins of every org where the user holds an active membership.

func (*Store) ActiveUserIPAllowList

func (st *Store) ActiveUserIPAllowList(userID int) []string

ActiveUserIPAllowList returns the active entries of one account's own IP allow list when the enterprise has turned user-level enforcement on, else nil. The enterprise decides whether it is enforced; the account decides its contents.

func (*Store) AddAppDelivery

func (st *Store) AddAppDelivery(appID int, d *WebhookDelivery)

AddAppDelivery records an app-level webhook delivery.

func (*Store) AddCodespaceSecretSelectedRepo

func (st *Store) AddCodespaceSecretSelectedRepo(scope, name string, repoID int) bool

AddCodespaceSecretSelectedRepo adds a repository to a secret's selected list; a duplicate is a no-op.

func (*Store) AddCopilotCodingAgentSelectedRepo

func (st *Store) AddCopilotCodingAgentSelectedRepo(orgLogin string, repoID int)

AddCopilotCodingAgentSelectedRepo adds a repository to the selected list (no-op when already present).

func (*Store) AddCopilotSeats

func (st *Store) AddCopilotSeats(orgLogin string, userIDs []int, teamSlug string) int

AddCopilotSeats grants seats to the users, assigned through teamSlug when non-empty. Active seats are skipped; pending-cancellation seats are reinstated. Returns the count created or reinstated (what GitHub bills). The expiry prune and every seat write commit in one transaction (STORE-001/002).

func (*Store) AddDelivery

func (st *Store) AddDelivery(delivery *WebhookDelivery)

AddDelivery records a webhook delivery.

func (*Store) AddDependencySnapshot

func (st *Store) AddDependencySnapshot(snap *DependencySnapshot) *DependencySnapshot

AddDependencySnapshot appends a snapshot for the repository.

func (*Store) AddEnterpriseCopilotCodingAgentOrgs

func (st *Store) AddEnterpriseCopilotCodingAgentOrgs(logins []string)

AddEnterpriseCopilotCodingAgentOrgs enables the Copilot coding agent for the given organization logins (idempotent, sorted).

func (*Store) AddEnterpriseOIDCCustomProperty

func (st *Store) AddEnterpriseOIDCCustomProperty(name string) bool

AddEnterpriseOIDCCustomProperty records an OIDC custom property inclusion. Returns false when the property is already included.

func (*Store) AddEnterpriseOrganization

func (st *Store) AddEnterpriseOrganization(enterpriseID, orgID int) bool

AddEnterpriseOrganization binds an organization to an enterprise. It returns false when the organization already belongs to a different enterprise; re-adding to the same enterprise is a no-op that returns true.

func (*Store) AddEnterpriseTeamMember

func (st *Store) AddEnterpriseTeamMember(t *EnterpriseTeam, userID int)

AddEnterpriseTeamMember adds a user to the team (idempotent).

func (*Store) AddEnterpriseTeamOrg

func (st *Store) AddEnterpriseTeamOrg(t *EnterpriseTeam, orgLogin string)

AddEnterpriseTeamOrg records an organization assignment (idempotent).

func (*Store) AddHostedRunnerCustomImageVersion

func (st *Store) AddHostedRunnerCustomImageVersion(imageID int, version string, sizeGB int) bool

AddHostedRunnerCustomImageVersion appends a version. Returns false when the image doesn't exist or the version is already present.

func (*Store) AddInstallationRepo

func (st *Store) AddInstallationRepo(id, repoID int) (bool, bool)

func (*Store) AddIssueAssignees

func (st *Store) AddIssueAssignees(repoID int, issueNumber int, assigneeIDs []int, actorID int) bool

func (*Store) AddIssueBlockedBy

func (st *Store) AddIssueBlockedBy(issueID, blockerID int) bool

AddIssueBlockedBy records that issue is blocked by blocker. Returns false when the link already exists.

func (*Store) AddIssueFieldValues

func (st *Store) AddIssueFieldValues(issueID int, values map[int]interface{})

AddIssueFieldValues merges field values into an issue's existing set.

func (*Store) AddIssueLabels

func (st *Store) AddIssueLabels(repoKey string, issueNumber int, labelIDs []int) bool

AddIssueLabels adds labels (ignoring duplicates) with a "labeled" event each. Returns true when the issue exists.

func (*Store) AddMarketplaceDelivery

func (st *Store) AddMarketplaceDelivery(listingSlug string, delivery *WebhookDelivery)

func (*Store) AddOrgImmutableReleasesRepo

func (st *Store) AddOrgImmutableReleasesRepo(orgLogin string, repoID int)

AddOrgImmutableReleasesRepo adds one repository to the selected list.

func (*Store) AddOrgSelectedRepo

func (st *Store) AddOrgSelectedRepo(orgLogin string, repoID int)

AddOrgSelectedRepo adds a repository to the org's selected list.

func (*Store) AddPullRequestAssignees

func (st *Store) AddPullRequestAssignees(repoID, prNumber int, assigneeIDs []int, actorID int) bool

AddPullRequestAssignees mirrors AddIssueAssignees for a pull request (a PR is an issue on GitHub, served by the shared issues endpoint). Non-assignable users are dropped and the total is capped at 10.

func (*Store) AddPullRequestLabels

func (st *Store) AddPullRequestLabels(repoID, prNumber int, labelIDs []int, actorID int) bool

AddPullRequestLabels adds labels to a pull request, recording a labeled event per new attachment. Returns true when the PR exists; duplicate IDs are ignored.

func (*Store) AddPullRequestsToStack

func (st *Store) AddPullRequestsToStack(repoKey string, stackNumber int, pulls []*PullRequest) (*PullRequestStack, error)

func (*Store) AddRepoCollaborator

func (st *Store) AddRepoCollaborator(owner, name, login, permission string) bool

AddRepoCollaborator grants login the given permission (pull/push/admin) on the repo. Returns true when both repo and user exist.

func (*Store) AddSBOMExport

func (st *Store) AddSBOMExport(repoID int) *SBOMExport

AddSBOMExport records a generated SBOM export.

func (*Store) AddSubIssue

func (st *Store) AddSubIssue(parentID, childID int, replaceParent bool) error

AddSubIssue links child under parent. replaceParent detaches the child from a previous parent first.

func (*Store) AddTeamRepo

func (st *Store) AddTeamRepo(orgLogin, slug, repoFullName string) bool

AddTeamRepo adds a repository to a team's access list.

func (*Store) AddUserEmails

func (st *Store) AddUserEmails(userID int, emails []string) ([]UserEmail, bool)

AddUserEmails appends new email addresses to the user's account, returning (nil, false) when any address is already registered (GitHub's 422).

func (*Store) AddUserSSHSigningKey

func (st *Store) AddUserSSHSigningKey(userID int, key string) map[string]interface{}

AddUserSSHSigningKey adds an SSH signing key for a user.

func (*Store) ApiInsightsRecords

func (st *Store) ApiInsightsRecords(orgLogin string, minT, maxT time.Time) []*APIRequestRecord

ApiInsightsRecords returns the org's records inside [minT, maxT], oldest first.

func (*Store) ApplicableRulesets

func (st *Store) ApplicableRulesets(repo *Repo, ref string) []Ruleset

ApplicableRulesets snapshots every repository and organization ruleset that targets ref. It returns values, not live map entries, so push evaluation can run without holding the store lock across Git reads.

func (*Store) ApproveVerifiableDomain

func (st *Store) ApproveVerifiableDomain(id int) *VerifiableDomain

ApproveVerifiableDomain marks the domain approved: an owner vouching for it without DNS verification.

func (*Store) AssignOrgRoleToTeam

func (st *Store) AssignOrgRoleToTeam(orgLogin string, roleID, teamID int)

AssignOrgRoleToTeam grants an organization role to a team. Idempotent.

func (*Store) AssignOrgRoleToUser

func (st *Store) AssignOrgRoleToUser(orgLogin string, roleID, userID int)

AssignOrgRoleToUser grants an organization role to a user directly. Idempotent.

func (*Store) AttachCodeSecurityConfiguration

func (st *Store) AttachCodeSecurityConfiguration(orgLogin string, id int, scope string, selectedIDs []int) bool

AttachCodeSecurityConfiguration applies the configuration to the repos the scope selects. Returns false when a selected repository ID is not an org repository.

func (*Store) AttachEnterpriseCodeSecurityConfig

func (st *Store) AttachEnterpriseCodeSecurityConfig(c *EnterpriseCodeSecurityConfiguration, scope string)

AttachEnterpriseCodeSecurityConfig attaches the configuration to every organization-owned repository on the instance ("all"), or only to those without an attached configuration ("all_without_configurations").

func (*Store) BeginTwoFactorEnrollment

func (st *Store) BeginTwoFactorEnrollment(userID int, now time.Time) (string, AccountSecurityResult)

BeginTwoFactorEnrollment provisions a fresh TOTP secret and returns it — the one moment it is legible outside the store. The secret stays pending until ConfirmTwoFactorEnrollment sees a code computed from it. Restarting replaces any previous pending secret.

func (*Store) BlockUser

func (st *Store) BlockUser(userID, targetID int) bool

BlockUser blocks targetID for userID.

func (*Store) BlockUserForOrg

func (st *Store) BlockUserForOrg(orgLogin string, userID int)

BlockUserForOrg records a block of the user by the organization. Idempotent.

func (*Store) BranchProtectedByRuleset

func (st *Store) BranchProtectedByRuleset(repo *Repo, branch string) bool

BranchProtectedByRuleset reports whether an enforced (active, not evaluate) branch-targeting repo or org ruleset applies to the branch. Evaluate-mode rulesets are observable through the rules API but do not protect the branch.

func (*Store) BuildIssueTimeline

func (st *Store) BuildIssueTimeline(repo *Repo, issueID int, baseURL string) []map[string]interface{}

BuildIssueTimeline synthesizes an issue's timeline by interleaving events and comments by created_at.

func (*Store) BuildNotificationThreads

func (st *Store) BuildNotificationThreads(rows []NotificationThreadRow, baseURL string) []*NotificationThread

BuildNotificationThreads renders rows into notification threads. buildThread is expensive per row (embeds RepoToJSON, scans comments), so paginate rows before calling.

func (*Store) BulkUpdateSecretScanningAlerts

func (st *Store) BulkUpdateSecretScanningAlerts(repoKey, stateFilter, secretTypeFilter, resolutionFilter, newResolution, resolutionComment string) ([]*SecretScanningAlert, error)

BulkUpdateSecretScanningAlerts resolves every alert matching the repo filters.

func (*Store) CampaignAlertCounts

func (st *Store) CampaignAlertCounts(c *Campaign) (open, closed int)

CampaignAlertCounts derives open/closed counts from the states of the campaign's linked alerts.

func (*Store) CanCreatePullRequest

func (st *Store) CanCreatePullRequest(repoID, userID int, login string) bool

func (*Store) CancelCopilotSeatsForTeam

func (st *Store) CancelCopilotSeatsForTeam(orgLogin, teamSlug string) int

CancelCopilotSeatsForTeam marks every team-assigned seat pending cancellation and returns the count affected. Prune and marks commit in one transaction (STORE-001/002).

func (*Store) CancelCopilotSeatsForUsers

func (st *Store) CancelCopilotSeatsForUsers(orgLogin string, userIDs []int) (cancelled int, teamAssigned []int)

CancelCopilotSeatsForUsers marks the users' directly-assigned seats pending cancellation. If any user holds a team-assigned seat, nothing is cancelled and those user IDs are returned — GitHub rejects the whole request with 422.

func (*Store) CancelOrgInvitation

func (st *Store) CancelOrgInvitation(orgLogin string, id int) bool

CancelOrgInvitation removes a live invitation and its pending membership. Returns false when no such invitation exists.

func (*Store) CancelTwoFactorEnrollment

func (st *Store) CancelTwoFactorEnrollment(userID int, now time.Time) AccountSecurityResult

CancelTwoFactorEnrollment discards a pending (unconfirmed) secret; no proof is required since the account was never protected by it.

func (*Store) CastDiscussionPollVote

func (st *Store) CastDiscussionPollVote(pollID, optionID, userID int) bool

CastDiscussionPollVote records userID's vote, replacing any earlier vote in the same poll (github lets a voter change their mind, not vote twice).

func (*Store) ChangePRCreationBypass

func (st *Store) ChangePRCreationBypass(repoKey string, logins []string, add bool)

func (*Store) ClaimMigrationForExport

func (st *Store) ClaimMigrationForExport(scope MigrationScope, id int) bool

ClaimMigrationForExport moves a pending migration into "exporting" and reports whether this caller claimed it. Only pending migrations are claimable, so two workers cannot export the same migration twice.

func (*Store) ClaimOIDCLogoutAndDeleteSessions

func (st *Store) ClaimOIDCLogoutAndDeleteSessions(provider, issuer, clientID, jti string, expiresAt, now time.Time, sid, subject string) (bool, error)

ClaimOIDCLogoutAndDeleteSessions atomically claims a Back-Channel Logout token and revokes the sessions it selects — in one DB transaction with persistence, otherwise under the map mutex.

func (*Store) ClaimOrganizationMigration

func (st *Store) ClaimOrganizationMigration(id int) bool

ClaimOrganizationMigration moves a queued organization migration into IN_PROGRESS and reports whether this caller claimed it.

func (*Store) ClaimRepositoryMigration

func (st *Store) ClaimRepositoryMigration(id int) bool

ClaimRepositoryMigration moves a queued migration into IN_PROGRESS and reports whether this caller claimed it.

func (*Store) ClassroomAcceptedFor

func (st *Store) ClassroomAcceptedFor(assignmentID int) []*ClassroomAcceptedAssignment

ClassroomAcceptedFor returns an assignment's accepted assignments, oldest first.

func (*Store) CleanupDeletedRepo

func (st *Store) CleanupDeletedRepo(record PendingDeletion) error

func (*Store) ClearAgentAssignmentLocked

func (st *Store) ClearAgentAssignmentLocked(job *Job)

ClearAgentAssignmentLocked clears the AssignedJobID of the agent holding a job that no longer binds it. EverAssigned stays set: it keeps a used ephemeral agent disqualified after its job's stub is swept. Callers hold the write lock.

func (*Store) ClearIssueLabels

func (st *Store) ClearIssueLabels(repoID int, issueNumber int, actorID int) bool

ClearIssueLabels removes every label from an issue with an "unlabeled" event each.

func (*Store) ClearMigrationArchive

func (st *Store) ClearMigrationArchive(scope MigrationScope, id int) (string, bool)

ClearMigrationArchive marks the archive deleted and returns its key so the caller can delete the bytes, or "" when there is no archive.

func (*Store) ClearPullRequestLabels

func (st *Store) ClearPullRequestLabels(repoID, prNumber, actorID int) bool

ClearPullRequestLabels removes every label from a pull request, recording an unlabeled event for each previously-attached label. Returns true when the PR exists.

func (*Store) ClearRunJobMessagesLocked

func (st *Store) ClearRunJobMessagesLocked(wf *Workflow)

ClearRunJobMessagesLocked drops the secret-bearing job messages of a finalized run and stamps each job's retirement time. Late runner calls keep authenticating through planScopes. Callers hold the write lock and must call this only once the run has completed.

func (*Store) CommentRepoID

func (st *Store) CommentRepoID(c *Comment) int

CommentRepoID returns the repo ID owning the comment's parent, or 0 when the parent no longer exists.

func (*Store) CompleteMigrationExport

func (st *Store) CompleteMigrationExport(scope MigrationScope, id int, archiveKey string, size int64, sha256Hex string) bool

CompleteMigrationExport records a successful export's archive key, size, and hash.

func (*Store) ComputeContributions

func (st *Store) ComputeContributions(userID int, from, to time.Time, orgID int) *ContributionData

ComputeContributions aggregates the user's contributions over [from, to]. A non-zero orgID restricts the aggregate to that organization's repositories.

func (*Store) ComputeRepoLanguages

func (st *Store) ComputeRepoLanguages(repo *Repo) map[string]int64

ComputeRepoLanguages walks the default-branch tree and returns language name to byte size.

func (*Store) ConfirmTwoFactorEnrollment

func (st *Store) ConfirmTwoFactorEnrollment(userID int, code string, now time.Time) ([]string, TwoFactorStatus, AccountSecurityResult)

ConfirmTwoFactorEnrollment completes enrolment when code is a valid TOTP for the pending secret. It returns the generated recovery codes in the clear — the single time they are legible.

func (*Store) ConsumeManifestCode

func (st *Store) ConsumeManifestCode(code string) (int, bool)

ConsumeManifestCode redeems a manifest code, returning the app ID. One-time use.

func (*Store) ConvertProjectCardToIssue

func (st *Store) ConvertProjectCardToIssue(card *ProjectCard, issueID int) *ProjectCard

ConvertProjectCardToIssue replaces a note card with an issue card in the same column/position, preserving the card ID.

func (*Store) CountActiveOrgOwners

func (st *Store) CountActiveOrgOwners(orgID int) int

CountActiveOrgOwners returns how many active owners (admin role) the org has. Used to refuse removing or demoting the last owner, which would orphan the organization (GitHub rejects both).

func (*Store) CountAppInstallations

func (st *Store) CountAppInstallations(appID int) int

CountAppInstallations returns the number of installations for a given app.

func (*Store) CountCommentsFor

func (st *Store) CountCommentsFor(parentType string, parentID int) int

CountCommentsFor returns the comment count on a parent via the maintained index. Caller must NOT hold st.Mu.

func (*Store) CountCommentsForLocked

func (st *Store) CountCommentsForLocked(parentType string, parentID int) int

CountCommentsForLocked is the variant for callers already holding st.Mu.

func (*Store) CountFineGrainedPATs

func (st *Store) CountFineGrainedPATs(userID int) int

func (*Store) CountFollowers

func (st *Store) CountFollowers(login string) int

CountFollowers returns how many users follow the given login.

func (*Store) CountFollowing

func (st *Store) CountFollowing(login string) int

CountFollowing returns how many users the given login follows.

func (*Store) CountForks

func (st *Store) CountForks(sourceRepoID int) int

CountForks counts repos forked from sourceRepoID.

func (*Store) CountOpenIssues

func (st *Store) CountOpenIssues(repoID int) int

CountOpenIssues returns open issues plus open PRs in a repo; GitHub's open_issues_count counts both, since PRs are issues internally.

func (*Store) CountPrivateRepos

func (st *Store) CountPrivateRepos(login string) int

CountPrivateRepos returns the number of private repositories owned by login.

func (*Store) CountPublicRepos

func (st *Store) CountPublicRepos(login string) int

CountPublicRepos returns the number of non-private repositories owned by the given account login (user or organization).

func (*Store) CountRepoCollaboratorsForOwner

func (st *Store) CountRepoCollaboratorsForOwner(login string) int

CountRepoCollaboratorsForOwner returns the number of distinct collaborators across the account's repositories.

func (*Store) CountSecretGists

func (st *Store) CountSecretGists(userID int) int

CountSecretGists returns the number of non-public gists the user owns.

func (*Store) CreateAgentTask

func (st *Store) CreateAgentTask(repo *Repo, creator *User, prompt, model string, createPR bool, baseRef, headRef string) *AgentTask

CreateAgentTask stores a new task with its initial session.

func (*Store) CreateApp

func (st *Store) CreateApp(ownerID int, name, description string, perms map[string]string, events []string) *App

CreateApp generates a new GitHub App with an RSA key pair.

func (*Store) CreateAppE

func (st *Store) CreateAppE(ownerID int, name, description string, perms map[string]string, events []string) (*App, error)

func (*Store) CreateArtifactDeploymentJob

func (st *Store) CreateArtifactDeploymentJob(job *ArtifactDeploymentJob) *ArtifactDeploymentJob

func (*Store) CreateArtifactStorageRecord

func (st *Store) CreateArtifactStorageRecord(rec *ArtifactStorageRecord) *ArtifactStorageRecord

CreateArtifactStorageRecord appends a storage record for the org.

func (*Store) CreateAttestation

func (st *Store) CreateAttestation(repoID int, bundle json.RawMessage, subjects []string, predicateType, initiator string) (*Attestation, error)

CreateAttestation stores an uploaded bundle for a repository.

func (*Store) CreateAttributionInvitation

func (st *Store) CreateAttributionInvitation(orgID int, sourceNodeID, targetNodeID string) (*AttributionInvitation, error)

CreateAttributionInvitation records that source's work be claimed by target. GitHub allows only one open invitation per source.

func (*Store) CreateCampaign

func (st *Store) CreateCampaign(orgLogin, name, description string, managers, teamManagers []string, endsAt time.Time, contactLink *string, alerts map[int][]int) *Campaign

CreateCampaign creates an open campaign with the next per-org number.

func (*Store) CreateCheckRun

func (st *Store) CreateCheckRun(repoKey, headSHA, name string, appID int, suiteID int64) *CheckRun

CreateCheckRun inserts a new check run. If suiteID is 0, finds-or-creates a suite for the SHA.

func (*Store) CreateCheckSuite

func (st *Store) CreateCheckSuite(repoKey, headBranch, headSHA string, appID int) *CheckSuite

CreateCheckSuite creates or returns an existing suite for the (repoKey, headSHA, appID) tuple.

func (*Store) CreateClassroom

func (st *Store) CreateClassroom(name string, orgID int, archived bool) *Classroom

func (*Store) CreateClassroomAcceptedAssignment

func (st *Store) CreateClassroomAcceptedAssignment(a *ClassroomAcceptedAssignment) *ClassroomAcceptedAssignment

func (*Store) CreateClassroomAssignment

func (st *Store) CreateClassroomAssignment(a *ClassroomAssignment) *ClassroomAssignment

func (*Store) CreateCodeQLVariantAnalysis

func (st *Store) CreateCodeQLVariantAnalysis(controllerRepoKey string, actorID int, language string, queryPack []byte, repoFullNames []string) (*CodeQLVariantAnalysis, error)

CreateCodeQLVariantAnalysis resolves the requested repos and stores a completed variant analysis. Nonexistent repos go to NotFoundRepos, those without a CodeQL database for the language to NoCodeQLDBRepos, the rest are scanned; when none is scannable the analysis fails with no_repos_queried.

func (*Store) CreateCodeScanningAlert

func (st *Store) CreateCodeScanningAlert(repoKey, ruleID, severity, description, toolName, toolGUID, state string, instances []CodeScanningAlertInstance) *CodeScanningAlert

CreateCodeScanningAlert seeds an alert through the operator surface.

func (*Store) CreateCodeScanningAnalysis

func (st *Store) CreateCodeScanningAnalysis(repoKey, ref, commitSHA, analysisKey, category, toolName, toolGUID string) *CodeScanningAnalysis

CreateCodeScanningAnalysis records a new analysis run.

func (*Store) CreateCodeScanningAutofix

func (st *Store) CreateCodeScanningAutofix(a *CodeScanningAlert) (*CodeScanningAutofix, bool)

CreateCodeScanningAutofix generates and stores the autofix for an alert. created is false when one already existed, returned unchanged.

func (*Store) CreateCodeSecurityConfiguration

func (st *Store) CreateCodeSecurityConfiguration(orgLogin string, req *CodeSecurityConfigurationRequest) *CodeSecurityConfiguration

CreateCodeSecurityConfiguration materializes a configuration with the per-field creation defaults, then applies the request.

func (*Store) CreateCodespace

func (st *Store) CreateCodespace(ownerLogin, repoKey, gitRef, location string, opts CodespaceCreateOptions) (*Codespace, error)

CreateCodespace records a new codespace and starts its runtime. The image pull and container start run with the store lock released; if Docker cannot provision the image, the prepared workspace is promoted to the built-in runtime instead.

func (*Store) CreateCodespaceSecret

func (st *Store) CreateCodespaceSecret(scope, name, value, visibility string, selectedRepoIDs []int) *CodespaceSecret

CreateCodespaceSecret creates or updates a codespaces secret in a scope.

func (*Store) CreateComment

func (st *Store) CreateComment(issueID, authorID int, body string) *Comment

CreateComment creates a conversation comment on an issue; use CreateCommentFor for PRs.

func (*Store) CreateCommentFor

func (st *Store) CreateCommentFor(parentType string, parentID, authorID int, body string) *Comment

CreateCommentFor creates a comment on an "issue" or "pull_request" parent, which must already exist. Returns nil otherwise.

func (*Store) CreateCopilotSpace

func (st *Store) CreateCopilotSpace(ownerType, ownerLogin string, creatorID int, name, description, instructions, baseRole string) *CopilotSpace

CreateCopilotSpace creates a space, numbering it past the owner's highest existing space so numbers are never reused within an owner.

func (*Store) CreateDependabotAlertIfNew

func (st *Store) CreateDependabotAlertIfNew(repoKey, pkgName, ecosystem, manifest, vulnID, cveID, severity, summary, description, vulnRange, patched string) *DependabotAlert

func (*Store) CreateDependabotAlertIfNewReported

func (st *Store) CreateDependabotAlertIfNewReported(repoKey, pkgName, ecosystem, manifest, vulnID, cveID, severity, summary, description, vulnRange, patched string) (*DependabotAlert, bool)

CreateDependabotAlertIfNewReported is CreateDependabotAlertIfNew that also reports whether this call minted the alert. Derivation runs on every dependency submission and advisory publication, so the flag lets the caller deliver a "created" webhook only for genuinely new alerts, not on every re-derivation.

func (*Store) CreateDependabotAlertLocked

func (st *Store) CreateDependabotAlertLocked(repoKey, pkgName, ecosystem, manifest, vulnID, cveID, severity, state, summary, description, vulnRange, patched string) *DependabotAlert

func (*Store) CreateDiscussion

func (st *Store) CreateDiscussion(repoID, categoryID, authorID int, title, body string) *Discussion

CreateDiscussion creates a new discussion in the given repository.

func (*Store) CreateDiscussionCategory

func (st *Store) CreateDiscussionCategory(repoID int, name, emoji, description string, isAnswerable bool) *DiscussionCategory

CreateDiscussionCategory creates a discussion category.

func (*Store) CreateDiscussionComment

func (st *Store) CreateDiscussionComment(discussionID, authorID int, body string, parentID int) *DiscussionComment

CreateDiscussionComment creates a new top-level comment or reply on a discussion.

func (*Store) CreateDiscussionCommentAt

func (st *Store) CreateDiscussionCommentAt(discussionID, authorID int, body string, parentID int, createdAt time.Time) *DiscussionComment

CreateDiscussionCommentAt is CreateDiscussionComment with a caller-supplied timestamp, so issue→discussion conversion preserves original authorship times.

func (*Store) CreateDiscussionPoll

func (st *Store) CreateDiscussionPoll(discussionID int, question string, options []string) *DiscussionPoll

CreateDiscussionPoll attaches a poll to a discussion, refusing a second so cast votes are never replaced.

func (*Store) CreateEnterprise

func (st *Store) CreateEnterprise(slug, name, billingEmail string) *Enterprise

CreateEnterprise creates an enterprise account with GitHub's default policy set, or returns nil when the slug is taken.

func (*Store) CreateEnterpriseCodeSecurityConfig

func (st *Store) CreateEnterpriseCodeSecurityConfig(c *EnterpriseCodeSecurityConfiguration) *EnterpriseCodeSecurityConfiguration

CreateEnterpriseCodeSecurityConfig stores a new configuration.

func (*Store) CreateEnterpriseHostedRunnerCustomImage

func (st *Store) CreateEnterpriseHostedRunnerCustomImage(enterprise, name, platform string) *HostedRunnerCustomImage

func (*Store) CreateEnterpriseInvitation

func (st *Store) CreateEnterpriseInvitation(enterpriseID, inviterID, inviteeID int, email, kind string, role EnterpriseRole) *EnterpriseInvitation

CreateEnterpriseInvitation records an invitation ("admin" or "member"; role applies to "admin" only) and returns a detached snapshot, or nil when the enterprise is gone or an equivalent invitation is already outstanding.

func (*Store) CreateEnterpriseRuleset

func (st *Store) CreateEnterpriseRuleset(enterprise string, input *Ruleset) *Ruleset

CreateEnterpriseRuleset creates a ruleset that applies across every repository in the enterprise.

func (*Store) CreateEnterpriseTeam

func (st *Store) CreateEnterpriseTeam(name, description, selectionType string, groupID *string, notificationSetting string) *EnterpriseTeam

CreateEnterpriseTeam creates an enterprise team. Returns nil when a team with the same slug already exists.

func (*Store) CreateEnvBranchPolicy

func (st *Store) CreateEnvBranchPolicy(envID int, name, policyType string) (created, existing *DeploymentBranchPolicyRule)

CreateEnvBranchPolicy appends a branch/tag policy. Returns (nil, existing) on a duplicate name+type (the API answers 303 pointing at it).

func (*Store) CreateEnvProtectionRule

func (st *Store) CreateEnvProtectionRule(envID, appID int) *EnvCustomProtectionRule

CreateEnvProtectionRule enables a GitHub App protection rule. Returns nil when the app already has one on the environment.

func (*Store) CreateGistComment

func (st *Store) CreateGistComment(gistID string, user *User, body string) *GistComment

CreateGistComment adds a comment to a gist.

func (*Store) CreateGistE

func (st *Store) CreateGistE(owner *User, description string, public bool, files map[string]*GistFile) (*Gist, error)

CreateGistE creates a new gist owned by the given user.

func (*Store) CreateHook

func (st *Store) CreateHook(repoKey, url, secret, contentType, insecureSSL string, events []string, active bool) *Webhook

CreateHook creates a new webhook for a repository.

func (*Store) CreateHostedRunnerCustomImage

func (st *Store) CreateHostedRunnerCustomImage(org, name, platform string) *HostedRunnerCustomImage

CreateHostedRunnerCustomImage registers a custom image for an org. The REST v3 surface only lists/reads/deletes them, so creation lives here.

func (*Store) CreateIPAllowListEntry

func (st *Store) CreateIPAllowListEntry(ownerType string, ownerID int, allowListValue, name string, isActive bool) *IPAllowListEntry

CreateIPAllowListEntry appends an entry to an owner's allow list.

func (*Store) CreateInstallation

func (st *Store) CreateInstallation(appID int, targetType string, targetID int, targetLogin string, perms map[string]string, events []string) *Installation

CreateInstallation creates a new installation for an app.

func (*Store) CreateInstallationToken

func (st *Store) CreateInstallationToken(installationID, appID int, perms map[string]string, repoIDs []int) *InstallationToken

CreateInstallationToken generates a ghs_-prefixed token with 1h expiry, scoped to repoIDs when non-empty.

func (*Store) CreateInstallationTokenE

func (st *Store) CreateInstallationTokenE(installationID, appID int, perms map[string]string, repoIDs []int) (*InstallationToken, error)

func (*Store) CreateIssue

func (st *Store) CreateIssue(repoID, authorID int, title, body string, labelIDs, assigneeIDs []int, milestoneID int) *Issue

func (*Store) CreateIssueField

func (st *Store) CreateIssueField(orgLogin, name string, description *string, dataType, visibility string, options []IssueFieldOptionRequest) *IssueField

CreateIssueField creates a new organization issue field.

func (*Store) CreateIssueSuggestion

func (st *Store) CreateIssueSuggestion(repoKey string, issueID int, suggestion IssueSuggestion) *IssueSuggestion

CreateIssueSuggestion is the ingestion seam for coding agents; the public REST surface exposes only review, approval, and dismissal.

func (*Store) CreateIssueType

func (st *Store) CreateIssueType(orgLogin, name string, description, color *string, isEnabled bool) *IssueType

CreateIssueType creates a new organization issue type.

func (*Store) CreateLFSLock

func (st *Store) CreateLFSLock(repoKey, path, ref string, ownerID int, ownerName string) (*LFSLock, bool)

CreateLFSLock locks a path for a user. An already-locked path returns the existing lock and false (the locking API reports a 409 naming the holder).

func (*Store) CreateLabel

func (st *Store) CreateLabel(repoID int, name, description, color string) *IssueLabel

CreateLabel creates a label in the repo, or returns nil on a duplicate name.

func (*Store) CreateMarketplacePlan

func (st *Store) CreateMarketplacePlan(plan *MarketplacePlan) (*MarketplacePlan, error)

func (*Store) CreateMarketplacePurchase

func (st *Store) CreateMarketplacePurchase(listing *MarketplaceListing, account MarketplaceBuyerAccount, purchase *MarketplacePurchase) (*Installation, bool, error)

CreateMarketplacePurchase atomically creates a subscription and, for a GitHub App listing, its account installation. Reports whether the installation was newly created, so webhook delivery begins only after both records are durable.

func (*Store) CreateMigrationSource

func (st *Store) CreateMigrationSource(ownerOrgID int, name, sourceType, url, accessToken, githubPAT string) *MigrationSource

CreateMigrationSource records a place to migrate from and returns a detached snapshot.

func (*Store) CreateMilestone

func (st *Store) CreateMilestone(repoID, creatorID int, title, description, state string, dueOn *time.Time) *Milestone

CreateMilestone creates a milestone in the repo on behalf of creatorID.

func (*Store) CreateNetworkConfiguration

func (st *Store) CreateNetworkConfiguration(orgLogin string, req *NetworkConfigurationRequest) (*NetworkConfiguration, error)

CreateNetworkConfiguration creates a configuration and links its settings resources.

func (*Store) CreateNetworkSettings

func (st *Store) CreateNetworkSettings(orgLogin, name, subnetID, region string) (*NetworkSettingsResource, error)

CreateNetworkSettings provisions a settings resource for the org.

func (*Store) CreateOAuthApp

func (st *Store) CreateOAuthApp(ownerID int, name, description, url, callbackURL string) *OAuthApp

CreateOAuthApp registers a classic OAuth App. Its web-flow tokens are gho_ (versus ghu_ for a GitHub App's user-to-server tokens).

func (*Store) CreateOAuthAppE

func (st *Store) CreateOAuthAppE(ownerID int, name, description, appURL, callbackURL string) (*OAuthApp, error)

func (*Store) CreateOrg

func (st *Store) CreateOrg(creator *User, login, name, description string) *Org

CreateOrg creates an organization and adds the creator as an admin member.

func (*Store) CreateOrgBudget

func (st *Store) CreateOrgBudget(orgLogin string, b *OrgBudget)

func (*Store) CreateOrgHook

func (st *Store) CreateOrgHook(orgLogin, url, secret, contentType, insecureSSL string, events []string, active bool) *Webhook

func (*Store) CreateOrgInvitation

func (st *Store) CreateOrgInvitation(org *Org, inviter *User, invitee *User, email, role string, teamIDs []int) (*OrgInvitation, string)

CreateOrgInvitation creates an invitation and, when the invitee resolves to an account, the pending membership they later accept. Returns nil and a reason when the invitation is invalid (already a member or already invited).

func (*Store) CreateOrgMigration

func (st *Store) CreateOrgMigration(orgLogin string, repos []string, lock, exMeta, exGit, exAttach, exRel, exOwnerProj, orgMetaOnly bool) *OrgMigration

CreateOrgMigration starts a new organization migration export.

func (*Store) CreateOrgPATGrantRequest

func (st *Store) CreateOrgPATGrantRequest(orgLogin string, ownerUserID int, tokenName string, reason *string, repositorySelection string, repositoryIDs []int, perms OrgPATPermissions, expiresAt *time.Time) (*OrgPATGrantRequest, error)

CreateOrgPATGrantRequest mints a fine-grained token and files the pending grant request referencing it.

func (*Store) CreateOrgRepo

func (st *Store) CreateOrgRepo(org *Org, creator *User, name, description string, private bool) *Repo

CreateOrgRepo creates a repository owned by an org.

func (*Store) CreateOrgRuleset

func (st *Store) CreateOrgRuleset(orgID int, name string, target string, enforcement string, conditions RulesetConditions, rules []Rule, bypassActors []RulesetBypassActor) *Ruleset

CreateOrgRuleset creates and persists a new organization-level ruleset.

func (*Store) CreateOrganizationMigration

func (st *Store) CreateOrganizationMigration(enterpriseID int, sourceOrgURL, sourceOrgName, targetOrgName, sourceAccessToken string, startedByUserID int) *OrganizationMigration

CreateOrganizationMigration queues an organization migration and returns a detached snapshot.

func (*Store) CreatePRReview

func (st *Store) CreatePRReview(prID, authorID int, state, body string) *PullRequestReview

CreatePRReview creates a new review on a pull request (legacy prID-based API).

func (*Store) CreatePackage

func (st *Store) CreatePackage(ownerType, ownerKey, pkgType, name, visibility string) (*Package, bool)

CreatePackage creates or returns an existing package.

func (*Store) CreatePackageVersion

func (st *Store) CreatePackageVersion(ownerType, ownerKey, pkgType, pkgName, version, description string, metadata map[string]interface{}, files []PackageFileInput) (*PackageVersion, error)

CreatePackageVersion creates a new version of a package and persists files.

func (*Store) CreatePagesDeployment

func (st *Store) CreatePagesDeployment(repoID int, environment, buildVersion, status string, artifactSize int64, artifactSHA, artifactKey string) *PagesDeploymentRecord

CreatePagesDeployment records a Pages deployment for a repository.

func (*Store) CreatePrivateRegistry

func (st *Store) CreatePrivateRegistry(orgLogin string, req *PrivateRegistryRequest, authType string) *PrivateRegistryConfiguration

CreatePrivateRegistry materializes a configuration, naming it from the registry type as GitHub does (MAVEN_REPOSITORY_SECRET, ...), suffixed on collision.

func (*Store) CreateProjectCard

func (st *Store) CreateProjectCard(columnID, creatorID int, note string, issueID, pullRequestID int) *ProjectCard

CreateProjectCard creates a card in a column. Exactly one of note, issueID or pullRequestID must be provided.

func (*Store) CreateProjectClassic

func (st *Store) CreateProjectClassic(repo *Repo, creatorID int, name, body, state string) *ProjectClassic

CreateProjectClassic creates a new repo-scoped project.

func (*Store) CreateProjectClassicForOwner

func (st *Store) CreateProjectClassicForOwner(ownerType, ownerLogin string, creatorID int, name, body string, public bool) *ProjectClassic

CreateProjectClassicForOwner creates an account-owned project (ownerType "User" or "Organization").

func (*Store) CreateProjectColumn

func (st *Store) CreateProjectColumn(projectID int, name string) *ProjectColumn

CreateProjectColumn creates a column in a project, appending it last.

func (*Store) CreatePullRequest

func (st *Store) CreatePullRequest(repoID, authorID int, title, body, headRefName, baseRefName string, isDraft bool, labelIDs, assigneeIDs []int, milestoneID int, opts ...PullRequestOptions) *PullRequest

CreatePullRequest creates a pull request. Numbering shares the repo's NextIssueNumber counter with issues.

func (*Store) CreatePullRequestChecked

func (st *Store) CreatePullRequestChecked(repoID, authorID int, title, body, headRefName, baseRefName string, isDraft bool, labelIDs, assigneeIDs []int, milestoneID int, opts ...PullRequestOptions) (*PullRequest, error)

CreatePullRequestChecked atomically enforces GitHub's invariant that a repository cannot have two open pull requests with the same source repository/ref and base ref.

func (*Store) CreatePullRequestReview

func (st *Store) CreatePullRequestReview(repoKey string, pullNumber int, userID int, body string, state string) *PullRequestReview

CreatePullRequestReview creates a review addressed by repo key and PR number.

func (*Store) CreatePullRequestStack

func (st *Store) CreatePullRequestStack(repo *Repo, pulls []*PullRequest) (*PullRequestStack, error)

func (*Store) CreateRepo

func (st *Store) CreateRepo(owner *User, name, description string, private bool) *Repo
func (st *Store) CreateRepoAutolink(repoKey, keyPrefix, urlTemplate string, isAlphanumeric bool) *RepoAutolink

CreateRepoAutolink creates a new autolink reference on the repository.

func (*Store) CreateRepoDeployKey

func (st *Store) CreateRepoDeployKey(repoID int, title, key string, readOnly bool) *RepoDeployKey

CreateRepoDeployKey adds a deploy key to a repo.

func (*Store) CreateRepoInvitation

func (st *Store) CreateRepoInvitation(repoKey, inviteeLogin, inviteeEmail string, inviterID int, permission string) *RepoInvitation

CreateRepoInvitation creates a pending collaborator invitation.

func (*Store) CreateRepositoryMigration

func (st *Store) CreateRepositoryMigration(in NewRepositoryMigration) *RepositoryMigration

CreateRepositoryMigration queues a repository migration and returns a detached snapshot.

func (*Store) CreateRuleset

func (st *Store) CreateRuleset(repo *Repo, rs *Ruleset) *Ruleset

CreateRuleset creates and persists a new ruleset for a repository.

func (*Store) CreateSARIFUpload

func (st *Store) CreateSARIFUpload(repoKey string, payload map[string]interface{}) (*SARIFUpload, error)

CreateSARIFUpload parses a base64-encoded SARIF payload, creates analyses and alerts, and returns the (always "complete") upload record. Every analysis, alert, and the upload row commit in one transaction (STORE-001/002).

func (*Store) CreateSecretScanningAlert

func (st *Store) CreateSecretScanningAlert(repoKey, secretType string, locations []SecretScanningLocation) *SecretScanningAlert

CreateSecretScanningAlert seeds a new alert. The real API has no create endpoint; this is bleephub's internal seeding path.

func (*Store) CreateSecretScanningAlertIfNew

func (st *Store) CreateSecretScanningAlertIfNew(repoKey, secretType string, locations []SecretScanningLocation) *SecretScanningAlert

CreateSecretScanningAlertIfNew records an alert unless the repo already has the same secret type at the same blob location.

func (*Store) CreateSecretScanningAlertLocked

func (st *Store) CreateSecretScanningAlertLocked(repoKey, secretType string, locations []SecretScanningLocation) *SecretScanningAlert

func (*Store) CreateSecretScanningCustomPatterns

func (st *Store) CreateSecretScanningCustomPatterns(scope string, specs []SecretScanningPatternCreate) []*SecretScanningCustomPattern

func (*Store) CreateSecretScanningPushProtectionBypass

func (st *Store) CreateSecretScanningPushProtectionBypass(repoKey, placeholderID, reason string) *SecretScanningPushProtectionBypass

CreateSecretScanningPushProtectionBypass consumes a placeholder and grants the bypass, returning nil when the placeholder does not exist for the repo.

func (*Store) CreateSecretScanningPushProtectionPlaceholder

func (st *Store) CreateSecretScanningPushProtectionPlaceholder(repoKey, tokenType string) *SecretScanningPushProtectionPlaceholder

CreateSecretScanningPushProtectionPlaceholder records a blocked push's placeholder.

func (*Store) CreateSecurityAdvisory

func (st *Store) CreateSecurityAdvisory(repoID, authorID int, req CreateAdvisoryReq) *SecurityAdvisory

func (*Store) CreateSecurityAdvisoryE

func (st *Store) CreateSecurityAdvisoryE(repoID, authorID int, req CreateAdvisoryReq) (*SecurityAdvisory, error)

func (*Store) CreateSecurityAdvisoryReport

func (st *Store) CreateSecurityAdvisoryReport(report SecurityAdvisoryReport) *SecurityAdvisoryReport

func (*Store) CreateTeam

func (st *Store) CreateTeam(orgLogin, name string, opts TeamOptions) *Team

CreateTeam creates a team within an org. A non-zero ParentID must reference an existing team in the same org.

func (*Store) CreateTemporaryFork

func (st *Store) CreateTemporaryFork(repoID int, ghsaID string) *Repo

CreateTemporaryFork creates the private fork maintainers collaborate on.

func (*Store) CreateToken

func (st *Store) CreateToken(userID int, scopes string) *Token

CreateToken generates a new token for the given user.

func (*Store) CreateTokenLocked

func (st *Store) CreateTokenLocked(userID int, scopes string) *Token

CreateTokenLocked generates a new token; caller holds st.Mu write lock.

func (*Store) CreateUserFineGrainedPAT

func (st *Store) CreateUserFineGrainedPAT(userID int, body CreatePersonalAccessTokenWebRequest) (*Token, error)

func (*Store) CreateUserList

func (st *Store) CreateUserList(userID int, name, description string, private bool) *UserList

CreateUserList adds a list to the account, or nil when the account is missing, the name is blank, or a list with the same slug already exists (a list is addressed by slug, so two would collide).

func (*Store) CreateUserMigration

func (st *Store) CreateUserMigration(userID int, repos []string, lock, exMeta, exGit, exAttach, exRel, exOwnerProj, orgMetaOnly bool) *UserMigration

CreateUserMigration starts a new user migration export.

func (*Store) CreateUserToServerToken

func (st *Store) CreateUserToServerToken(userID, appID int, oauthClientID, scopes string, ttl time.Duration, withRefresh bool) (*UserToServerToken, *RefreshToken)

CreateUserToServerToken mints a gho_/ghu_ token (+ optional ghr_ pair). appID > 0 yields ghu_; otherwise oauthClientID yields gho_.

func (*Store) CreateUserToServerTokenE

func (st *Store) CreateUserToServerTokenE(userID, appID int, oauthClientID, scopes string, ttl time.Duration, withRefresh bool) (*UserToServerToken, *RefreshToken, error)

func (*Store) CreateUserToServerTokenLocked

func (st *Store) CreateUserToServerTokenLocked(userID, appID int, oauthClientID, scopes string, ttl time.Duration, withRefresh bool) (*UserToServerToken, *RefreshToken, error)

func (*Store) CreateVerifiableDomain

func (st *Store) CreateVerifiableDomain(ownerType string, ownerID int, domain string) (*VerifiableDomain, error)

CreateVerifiableDomain adds a domain with a fresh token, erroring when it does not normalize or the owner already carries it.

func (*Store) CurrentTime

func (st *Store) CurrentTime() time.Time

func (*Store) CustomImagesLocked

func (st *Store) CustomImagesLocked(target RunnerScope) []*HostedRunnerCustomImage

CustomImagesLocked returns the target's custom images sorted by id. Callers hold the lock.

func (*Store) DeclineRepoInvitation

func (st *Store) DeclineRepoInvitation(id int, user *User) bool

DeclineRepoInvitation removes an invitation addressed to the user.

func (*Store) DeleteApp

func (st *Store) DeleteApp(appID int) bool

DeleteApp removes an app and every credential or installation derived from it. Marketplace deletion stays in the settings layer (separate lock, may refuse while purchases exist).

func (*Store) DeleteAttestation

func (st *Store) DeleteAttestation(id int) (bool, error)

DeleteAttestation removes an attestation by ID, returning true if it existed.

func (*Store) DeleteCampaign

func (st *Store) DeleteCampaign(orgLogin string, number int)

DeleteCampaign removes a campaign.

func (*Store) DeleteClassroom

func (st *Store) DeleteClassroom(id int) bool

DeleteClassroom removes the Classroom metadata and its assignments; the assignment repositories survive as ordinary org repositories, per GitHub Classroom.

func (*Store) DeleteClassroomAssignment

func (st *Store) DeleteClassroomAssignment(id int) bool

func (*Store) DeleteCodeQLDatabase

func (st *Store) DeleteCodeQLDatabase(repoKey, language string) (bool, error)

DeleteCodeQLDatabase removes the CodeQL database for a repo + language.

func (*Store) DeleteCodeScanningAnalysis

func (st *Store) DeleteCodeScanningAnalysis(repoKey string, id int) bool

DeleteCodeScanningAnalysis removes an analysis from the store.

func (*Store) DeleteCodeSecurityConfiguration

func (st *Store) DeleteCodeSecurityConfiguration(orgLogin string, id int)

DeleteCodeSecurityConfiguration removes a configuration; attached repositories retain their settings but lose the association.

func (*Store) DeleteCodespace

func (st *Store) DeleteCodespace(id int) (bool, error)

DeleteCodespace stops and removes the backing container and deletes the record.

func (*Store) DeleteCodespaceSecret

func (st *Store) DeleteCodespaceSecret(scope, name string) bool

func (*Store) DeleteComment

func (st *Store) DeleteComment(id int) bool

DeleteComment removes a comment and its reactions in one transaction (STORE-001/002). Returns true if removed.

func (*Store) DeleteCopilotSpace

func (st *Store) DeleteCopilotSpace(id int64) bool

DeleteCopilotSpace removes a space. Returns true if it existed.

func (*Store) DeleteCustomProperty

func (st *Store) DeleteCustomProperty(orgLogin, name string) bool

DeleteCustomProperty removes a property definition and every repo value assigned under it, returning true when the definition existed.

func (*Store) DeleteDependabotOrgSecret

func (st *Store) DeleteDependabotOrgSecret(orgLogin, name string) bool

func (*Store) DeleteDependabotSecret

func (st *Store) DeleteDependabotSecret(repoKey, name string) bool

func (*Store) DeleteDependabotUserSecret

func (st *Store) DeleteDependabotUserSecret(userLogin, name string) bool

func (*Store) DeleteDiscussion

func (st *Store) DeleteDiscussion(id int) bool

DeleteDiscussion soft-deletes a discussion.

func (*Store) DeleteDiscussionComment

func (st *Store) DeleteDiscussionComment(id int) bool

DeleteDiscussionComment soft-deletes a comment.

func (*Store) DeleteEnterpriseCodeSecurityConfig

func (st *Store) DeleteEnterpriseCodeSecurityConfig(id int) (deleted, conflict bool)

DeleteEnterpriseCodeSecurityConfig removes a configuration and detaches its repositories. Returns false when the configuration is a default for new repositories (GitHub refuses with 409 in that state).

func (*Store) DeleteEnterpriseCustomProperty

func (st *Store) DeleteEnterpriseCustomProperty(name string) bool

DeleteEnterpriseCustomProperty removes an enterprise-level property definition, returning true when it existed.

func (*Store) DeleteEnterpriseInvitation

func (st *Store) DeleteEnterpriseInvitation(id int) bool

DeleteEnterpriseInvitation removes an invitation and reports whether one was removed.

func (*Store) DeleteEnterpriseTeam

func (st *Store) DeleteEnterpriseTeam(slug string) bool

DeleteEnterpriseTeam removes an enterprise team by slug. Returns true if it existed.

func (*Store) DeleteEnvBranchPolicy

func (st *Store) DeleteEnvBranchPolicy(envID, policyID int) bool

DeleteEnvBranchPolicy removes a policy, returning whether it existed.

func (*Store) DeleteEnvProtectionRule

func (st *Store) DeleteEnvProtectionRule(envID, ruleID int) bool

DeleteEnvProtectionRule removes a rule, returning whether it existed.

func (*Store) DeleteFineGrainedPAT

func (st *Store) DeleteFineGrainedPAT(userID, tokenID int) bool

func (*Store) DeleteGist

func (st *Store) DeleteGist(id string) bool

DeleteGist deletes a gist and all its comments.

func (*Store) DeleteGistComment

func (st *Store) DeleteGistComment(id int) bool

DeleteGistComment deletes a comment and decrements the gist comment count.

func (*Store) DeleteHook

func (st *Store) DeleteHook(repoKey string, hookID int) bool

DeleteHook removes a webhook. Returns false if not found.

func (*Store) DeleteIPAllowListEntry

func (st *Store) DeleteIPAllowListEntry(id int) *IPAllowListEntry

DeleteIPAllowListEntry removes an entry and returns a detached snapshot of what was removed.

func (*Store) DeleteInstallation

func (st *Store) DeleteInstallation(id int) bool

DeleteInstallation removes an installation by ID.

func (*Store) DeleteIssue

func (st *Store) DeleteIssue(issueID int) bool

DeleteIssue removes an issue and everything parented to it — comments (and their reactions), timeline events, sub-issue links, blocked-by references, project items, field values, notification threads, and the issue's own reactions — in one transaction (STORE-001/002).

func (*Store) DeleteIssueComment

func (st *Store) DeleteIssueComment(id int) bool

func (*Store) DeleteIssueField

func (st *Store) DeleteIssueField(orgLogin string, id int) bool

DeleteIssueField removes an issue field and any per-issue values that reference it. Returns true when the field existed.

func (*Store) DeleteIssueFieldValue

func (st *Store) DeleteIssueFieldValue(issueID, fieldID int) bool

func (*Store) DeleteIssueType

func (st *Store) DeleteIssueType(orgLogin string, id int) bool

DeleteIssueType removes an issue type. Returns true when it existed.

func (*Store) DeleteLFSLock

func (st *Store) DeleteLFSLock(repoKey string, id int) *LFSLock

DeleteLFSLock releases a lock, returning it or nil when no such lock exists.

func (*Store) DeleteLabel

func (st *Store) DeleteLabel(id int) bool

DeleteLabel removes a label and detaches it from every issue in one transaction, so no issue persists referencing a deleted label.

func (*Store) DeleteLoginSession

func (st *Store) DeleteLoginSession(id string) error

func (*Store) DeleteLoginSessionByHandle

func (st *Store) DeleteLoginSessionByHandle(userID int, handle string, now time.Time) (bool, error)

DeleteLoginSessionByHandle revokes one of the user's sessions by its public handle. The handle is scoped to the user, so one account cannot revoke another's by guessing. Reports whether a session matched.

func (*Store) DeleteLoginSessionsForOIDC

func (st *Store) DeleteLoginSessionsForOIDC(provider, issuer, sid, subject string) error

DeleteLoginSessionsForOIDC revokes the sessions selected by an OpenID Connect Back-Channel Logout token: sid selects one provider session, otherwise sub selects every session for that provider identity.

func (*Store) DeleteLoginSessionsForUser

func (st *Store) DeleteLoginSessionsForUser(userID int) error

func (*Store) DeleteMarketplaceListing

func (st *Store) DeleteMarketplaceListing(slug string) error

func (*Store) DeleteMarketplacePlan

func (st *Store) DeleteMarketplacePlan(listingSlug string, planID int) error

func (*Store) DeleteMarketplacePurchase

func (st *Store) DeleteMarketplacePurchase(listingSlug, accountType string, accountID int) error

func (*Store) DeleteMilestone

func (st *Store) DeleteMilestone(id int) bool

DeleteMilestone removes a milestone and detaches it from every issue in one transaction, so no issue persists referencing a deleted milestone.

func (*Store) DeleteNetworkConfiguration

func (st *Store) DeleteNetworkConfiguration(orgLogin, id string) bool

DeleteNetworkConfiguration removes a configuration and unlinks its settings resources. Returns true when it existed.

func (*Store) DeleteOAuthApp

func (st *Store) DeleteOAuthApp(clientID string) bool

func (*Store) DeleteOrg

func (st *Store) DeleteOrg(login string) bool

DeleteOrg removes an organization and everything scoped to it.

func (*Store) DeleteOrgBudget

func (st *Store) DeleteOrgBudget(orgLogin, id string) bool

DeleteOrgBudget removes a budget. Returns true if it existed.

func (*Store) DeleteOrgHook

func (st *Store) DeleteOrgHook(orgLogin string, hookID int) bool

DeleteOrgHook removes an org webhook. Returns false if not found.

func (*Store) DeleteOrgInteractionLimit

func (st *Store) DeleteOrgInteractionLimit(orgLogin string)

DeleteOrgInteractionLimit removes the org's interaction limit. Idempotent.

func (*Store) DeleteOrgMigrationArchive

func (st *Store) DeleteOrgMigrationArchive(id int) bool

DeleteOrgMigrationArchive marks an organization migration archive as deleted.

func (*Store) DeleteOrgRuleset

func (st *Store) DeleteOrgRuleset(id int) bool

DeleteOrgRuleset removes an organization ruleset by ID.

func (*Store) DeleteOrgWithError

func (st *Store) DeleteOrgWithError(login string) (bool, error)

DeleteOrgWithError removes an organization, its memberships, its teams and its repositories. Repos are part of the cascade: an org row that goes away while its repos remain makes every later start reject them as an unknown owner.

func (*Store) DeletePackage

func (st *Store) DeletePackage(ownerKey, pkgType, name string) bool

DeletePackage soft-deletes a package: it leaves the by-owner map (freeing the name) but keeps the row, versions, and files so it stays restorable, per GitHub's delete/restore contract.

func (*Store) DeletePackageVersion

func (st *Store) DeletePackageVersion(id int) bool

DeletePackageVersion marks a version deleted. The version row and the package's recomputed count commit in one transaction (STORE-001/002).

func (*Store) DeletePagesPublicationData

func (st *Store) DeletePagesPublicationData(ctx context.Context, repoID int) error

func (*Store) DeletePrivateRegistry

func (st *Store) DeletePrivateRegistry(orgLogin, name string) bool

DeletePrivateRegistry removes a configuration, returning true when it existed.

func (*Store) DeleteProjectCard

func (st *Store) DeleteProjectCard(id int) bool

DeleteProjectCard deletes a card.

func (*Store) DeleteProjectClassic

func (st *Store) DeleteProjectClassic(id int) bool

DeleteProjectClassic deletes a project and all its columns and cards.

func (*Store) DeleteProjectColumn

func (st *Store) DeleteProjectColumn(id int) bool

DeleteProjectColumn deletes a column and all its cards.

func (*Store) DeletePullRequestReview

func (st *Store) DeletePullRequestReview(id int) bool

DeletePullRequestReview deletes a pending review.

func (*Store) DeletePullRequestStack

func (st *Store) DeletePullRequestStack(repoKey string, number int) bool

func (*Store) DeleteRepo

func (st *Store) DeleteRepo(owner, name string) (bool, error)

DeleteRepo removes a repo, its cascade and its bytes. Metadata goes first and atomically; the bytes go afterwards outside the lock, guarded by a recorded deletion intent that a later start can finish.

func (st *Store) DeleteRepoAutolink(repoKey string, id int) bool

DeleteRepoAutolink removes an autolink by ID. Returns true if it existed.

func (*Store) DeleteRepoDeployKey

func (st *Store) DeleteRepoDeployKey(id int) bool

DeleteRepoDeployKey removes a deploy key by ID.

func (*Store) DeleteRepoImport

func (st *Store) DeleteRepoImport(repoID int) bool

DeleteRepoImport removes the repo's import record. Returns true if it existed.

func (*Store) DeleteRepoInvitation

func (st *Store) DeleteRepoInvitation(repoKey string, id int) bool

DeleteRepoInvitation removes an invitation, returning true if it existed.

func (*Store) DeleteRepoSubscription

func (st *Store) DeleteRepoSubscription(userID int, repoID int) bool

DeleteRepoSubscription removes a subscription.

func (*Store) DeleteRuleset

func (st *Store) DeleteRuleset(id int) bool

DeleteRuleset removes a ruleset.

func (*Store) DeleteSecretScanningCustomPatterns

func (st *Store) DeleteSecretScanningCustomPatterns(scope string, deletes []SecretScanningPatternDelete) (found, versionsOK bool)

func (*Store) DeleteTeam

func (st *Store) DeleteTeam(orgLogin, slug string) bool

DeleteTeam removes a team from an organization.

func (*Store) DeleteTokenMapKeyLocked

func (st *Store) DeleteTokenMapKeyLocked(mapKey string)

func (*Store) DeleteUserEmails

func (st *Store) DeleteUserEmails(userID int, emails []string) deleteEmailsResult

DeleteUserEmails removes email addresses; the primary address cannot be removed.

func (*Store) DeleteUserList

func (st *Store) DeleteUserList(id int) bool

DeleteUserList removes a list.

func (*Store) DeleteUserMigrationArchive

func (st *Store) DeleteUserMigrationArchive(id int) bool

DeleteUserMigrationArchive marks a user migration archive as deleted.

func (*Store) DeleteUserOwnedResourcesLocked

func (st *Store) DeleteUserOwnedResourcesLocked(u *User) ([]PendingDeletion, PendingDeletion, error)

DeleteUserOwnedResourcesLocked cascades a deleted user's repositories, directly-owned packages (with file bytes), Marketplace purchases and org memberships, mirroring the org cascade so no orphaned rows or object bytes remain (STORE-028). Caller holds st.Mu; returns the repo and package-byte intents to drain after releasing the lock.

func (*Store) DeleteUserSSHSigningKey

func (st *Store) DeleteUserSSHSigningKey(userID, keyID int) bool

DeleteUserSSHSigningKey deletes an SSH signing key for a user.

func (*Store) DeleteVerifiableDomain

func (st *Store) DeleteVerifiableDomain(id int) *VerifiableDomain

DeleteVerifiableDomain removes a domain, returning a detached snapshot of what was removed, or nil.

func (*Store) DeleteWikiPage

func (st *Store) DeleteWikiPage(repoKey, slug string) bool

DeleteWikiPage removes a wiki page by committing the removal of its file. Returns true if the page existed.

func (*Store) DeleteWorkflowRecord

func (st *Store) DeleteWorkflowRecord(id string)

func (*Store) DequeuePullRequest

func (st *Store) DequeuePullRequest(prID int) *PullRequest

DequeuePullRequest removes a PR from its queue and closes the gap. Returns the row as it was while queued (for rendering), or nil when it was not queued.

func (*Store) DetachCodeSecurityConfigurations

func (st *Store) DetachCodeSecurityConfigurations(orgLogin string, repoIDs []int)

DetachCodeSecurityConfigurations removes the configuration association from the given repositories.

func (*Store) DetectCodeQLLanguages

func (st *Store) DetectCodeQLLanguages(repo *Repo) []string

DetectCodeQLLanguages derives a repo's sorted CodeQL default-setup languages from its default-branch content: the CodeQL mapping of every Linguist-detected language, plus "actions" when the repo carries Actions workflow files.

func (*Store) DisableTwoFactor

func (st *Store) DisableTwoFactor(userID int, code string, now time.Time, disallowed []TwoFactorMethod) AccountSecurityResult

DisableTwoFactor turns the second factor off, only on proof of possession.

func (*Store) DiscoverWorkflowFilesFromGit

func (st *Store) DiscoverWorkflowFilesFromGit(repoFullName string) int

DiscoverWorkflowFilesFromGit walks the repo's default branch and registers every `.github/workflows/*.{yml,yaml}` file with source="discovered", re-discovering on every call. No-ops without git storage, a default-branch ref, or a tree; returns the count registered.

func (*Store) DiskUsageKBForOwner

func (st *Store) DiskUsageKBForOwner(login string) int64

DiskUsageKBForOwner sums the account's repository sizes in kilobytes (memory-backed git storage occupies no disk).

func (*Store) DismissPullRequestReview

func (st *Store) DismissPullRequestReview(id int, message string) bool

DismissPullRequestReview marks a review as dismissed.

func (*Store) DropJobStateLocked

func (st *Store) DropJobStateLocked(job *Job) (planID string)

DropJobStateLocked deletes every piece of replica-local state held for one job. The caller releases the returned plan id's in-memory log bytes outside the store lock (releaseJobLogFiles). Callers hold the write lock.

func (*Store) DropWikiGitStorage

func (st *Store) DropWikiGitStorage(repoKey string)

DropWikiGitStorage forgets a wiki's handle and projection; the bytes are removed by the caller that removes the repository's own storage.

func (*Store) DropWorkflowJobStateLocked

func (st *Store) DropWorkflowJobStateLocked(wf *Workflow) (planIDs []string)

DropWorkflowJobStateLocked tears down the replica-local job state of every job in a run. Returns the plan ids whose in-memory log bytes to release via releaseJobLogFiles once the lock is dropped. Callers hold the write lock.

func (*Store) EffectiveEnterpriseRole

func (st *Store) EffectiveEnterpriseRole(enterpriseID int, user *User) EnterpriseRole

EffectiveEnterpriseRole reports the role a user holds in an enterprise. An explicit membership row wins; failing that, two enterprise-scoped derivations apply:

  • In the instance's own (GHES) enterprise, every account is a member and every site administrator is an owner.
  • In any enterprise, a member of one of its organizations is a member, and an owner of one is an owner.

A user with neither an explicit membership nor an organization in the enterprise holds no role, keeping one enterprise's people out of another's.

func (*Store) EffectiveNotificationPreferences

func (st *Store) EffectiveNotificationPreferences(userID int) (NotificationPreferences, bool)

EffectiveNotificationPreferences applies the enterprise delivery restriction: the saved document with every email channel cleared when the address is undeliverable.

func (*Store) EffectiveRepoCustomPropertyValues

func (st *Store) EffectiveRepoCustomPropertyValues(orgLogin, repoKey string) []map[string]interface{}

EffectiveRepoCustomPropertyValues renders the repo's property values: the explicitly set value, else the property's default. Properties with no effective value are omitted, matching GitHub.

func (*Store) EnqueuePullRequest

func (st *Store) EnqueuePullRequest(prID int, jump bool) *PullRequest

EnqueuePullRequest puts an open PR at the back of its base branch's queue, or the front when jump is set. Returns nil when the PR is not open or is queued.

func (*Store) EnsureEnterprise

func (st *Store) EnsureEnterprise(slug, name, billingEmail string) *Enterprise

EnsureEnterprise returns the enterprise with the given slug, creating it when absent. It brings the instance's own enterprise into being at boot.

func (*Store) EnsureMannequin

func (st *Store) EnsureMannequin(orgID int, login, email string) *Mannequin

EnsureMannequin returns the org's mannequin for login, minting one if absent. Idempotent by (org, login) so a resumed migration does not duplicate.

func (*Store) EnterpriseBandwidthBytes

func (st *Store) EnterpriseBandwidthBytes(orgIDs map[int]bool) int64

EnterpriseBandwidthBytes sums the bytes the enterprise's repositories served: each release asset's size times its download count.

func (*Store) EnterpriseClampedBasePermission

func (st *Store) EnterpriseClampedBasePermission(org *Org) string

EnterpriseClampedBasePermission is the exported base-permission clamp. The organization settings response reports this rather than the org's own setting, so what the API reports matches what the access check grants.

func (*Store) EnterpriseIDForOrg

func (st *Store) EnterpriseIDForOrg(orgID int) int

EnterpriseIDForOrg reports the enterprise an organization belongs to, or 0.

func (*Store) EnterprisePolicyForOrg

func (st *Store) EnterprisePolicyForOrg(orgID int) (EnterprisePolicy, *Enterprise)

EnterprisePolicyForOrg returns the policy governing an organization — that of the enterprise that owns it, or the instance's own enterprise for an unclaimed organization. The second return names the source enterprise so a caller can exempt its owners.

func (*Store) EnterprisePolicyForRepo

func (st *Store) EnterprisePolicyForRepo(repo *Repo) (EnterprisePolicy, *Enterprise)

EnterprisePolicyForRepo returns the policy governing a repository through its owning organization; a user-owned repo is governed by the instance's own enterprise.

func (*Store) EnterprisePolicyForbids

func (st *Store) EnterprisePolicyForbids(e *Enterprise, setting string, user *User) bool

EnterprisePolicyForbids reports whether a DISABLED policy blocks user. Blank and NO_POLICY impose nothing, ENABLED permits, and DISABLED blocks everyone but an owner of the enterprise that imposed it.

func (*Store) EnterpriseRoleOf

func (st *Store) EnterpriseRoleOf(enterpriseID, userID int) EnterpriseRole

EnterpriseRoleOf reports a user's role in an enterprise, or "" when the user is not a member.

func (*Store) EnterpriseStorageBytes

func (st *Store) EnterpriseStorageBytes(orgIDs map[int]bool) int64

EnterpriseStorageBytes sums the release-asset and package-file bytes held by repositories owned by the given organizations.

func (*Store) ExportCodespace

func (st *Store) ExportCodespace(id int) (*CodespaceExport, error)

ExportCodespace exports the codespace's git ref to a new branch (codespace-<name>) in its repository and records the export under id "latest".

func (*Store) FailMigrationExport

func (st *Store) FailMigrationExport(scope MigrationScope, id int, reason string) bool

FailMigrationExport records why an export failed. Repositories stay locked, as on GitHub: the operator may retry the frozen state and owns the unlock call.

func (*Store) FindCheckRunByNodeID

func (st *Store) FindCheckRunByNodeID(repoKey, nodeID string) *CheckRun

FindCheckRunByNodeID resolves a check run within one repository, or nil. The repository is required: run ids are global, so it ties the id to a tenant as the REST {owner}/{repo}/check-runs/{id} path does.

func (*Store) FindCheckSuiteByNodeID

func (st *Store) FindCheckSuiteByNodeID(repoKey, nodeID string) *CheckSuite

FindCheckSuiteByNodeID is FindCheckRunByNodeID for check suites.

func (*Store) FindPRByRepoNumberLocked

func (st *Store) FindPRByRepoNumberLocked(repoKey string, pullNumber int) *PullRequest

func (*Store) FollowerLoginsOf

func (st *Store) FollowerLoginsOf(login string) []string

FollowerLoginsOf returns the logins that follow the given account.

func (*Store) FollowingLoginsOf

func (st *Store) FollowingLoginsOf(login string) []string

FollowingLoginsOf returns the logins the given account follows.

func (*Store) ForgetExternalIdentitiesLocked

func (st *Store) ForgetExternalIdentitiesLocked(user *User)

ForgetExternalIdentitiesLocked removes every (issuer, subject) binding for user from the federated-identity index, so it can't resurrect a deleted account when its provider logs in again. Callers hold st.Mu.

func (*Store) ForkGistE

func (st *Store) ForkGistE(user *User, gistID string) (*Gist, bool, error)

ForkGistE forks a gist for the given user.

func (*Store) ForkRepo

func (st *Store) ForkRepo(owner *User, sourceRepo *Repo, name string) *Repo

ForkRepo forks sourceRepo under owner, copying git storage and recording parent/source linkage. Returns nil if the source is gone or the name is taken.

func (*Store) GetActorByID

func (st *Store) GetActorByID(id int) *User

GetActorByID is the lock-safe form of ActorUserLocked.

func (*Store) GetAgentTask

func (st *Store) GetAgentTask(id string) *AgentTask

GetAgentTask returns a task by ID, or nil.

func (*Store) GetApp

func (st *Store) GetApp(id int) *App

GetApp returns an app by ID, or nil.

func (*Store) GetAppByClientID

func (st *Store) GetAppByClientID(clientID string) *App

GetAppByClientID returns the GitHub App with the given client_id, or nil.

func (*Store) GetAppBySlug

func (st *Store) GetAppBySlug(slug string) *App

GetAppBySlug returns an app by slug, or nil.

func (*Store) GetAppDelivery

func (st *Store) GetAppDelivery(appID, deliveryID int) *WebhookDelivery

GetAppDelivery returns a delivery by id, or nil. Returns the live row: deliveries are write-once, so a reader never races a writer (STORE-021 exception).

func (*Store) GetArtifactDeploymentJob

func (st *Store) GetArtifactDeploymentJob(orgID, id int, cluster string) *ArtifactDeploymentJob

func (*Store) GetAssignableIssueTypeForRepo

func (st *Store) GetAssignableIssueTypeForRepo(repo *Repo, id int) *IssueType

GetAssignableIssueTypeForRepo returns an enabled issue type owned by the repository's organization. User-owned repositories do not have issue types.

func (*Store) GetAttestation

func (st *Store) GetAttestation(id int) *Attestation

GetAttestation returns an attestation by ID, or nil.

func (*Store) GetBranchProtection

func (st *Store) GetBranchProtection(repoID int, branch string) *BranchProtection

GetBranchProtection returns a detached copy of the branch's exact-name protection rule, or nil.

func (*Store) GetBranchProtectionExtras

func (st *Store) GetBranchProtectionExtras(repoID int, pattern string) *BranchProtectionRuleExtras

GetBranchProtectionExtras returns a detached copy of the rule's GraphQL-only members, or nil.

func (*Store) GetCampaign

func (st *Store) GetCampaign(orgLogin string, number int) *Campaign

GetCampaign returns a campaign by org and number, or nil.

func (*Store) GetCheckRun

func (st *Store) GetCheckRun(id int64) *CheckRun

GetCheckRun returns a check run by ID, or nil.

func (*Store) GetCheckSuite

func (st *Store) GetCheckSuite(id int64) *CheckSuite

GetCheckSuite returns a suite by ID, or nil.

func (*Store) GetCheckSuitePreferences

func (st *Store) GetCheckSuitePreferences(repoKey string) []*CheckSuitePref

GetCheckSuitePreferences returns the configured auto-trigger flags, or empty.

func (*Store) GetClassroom

func (st *Store) GetClassroom(id int) *Classroom

func (*Store) GetClassroomAssignment

func (st *Store) GetClassroomAssignment(id int) *ClassroomAssignment

func (*Store) GetCodeQLDatabase

func (st *Store) GetCodeQLDatabase(repoKey, language string) *CodeQLDatabase

GetCodeQLDatabase returns the live row, not a snapshot: a stored database is write-once (Upsert swaps a fresh row under the write lock), so a reader never races a writer, and its Content blob would be needlessly copied on every read (STORE-021 documented exception).

func (*Store) GetCodeQLVariantAnalysis

func (st *Store) GetCodeQLVariantAnalysis(controllerRepoKey string, id int) *CodeQLVariantAnalysis

GetCodeQLVariantAnalysis returns a variant analysis scoped to its controller repo.

func (*Store) GetCodeQualityFinding

func (st *Store) GetCodeQualityFinding(repoKey string, number int) *CodeQualityFinding

func (*Store) GetCodeQualitySetup

func (st *Store) GetCodeQualitySetup(repoFullName string) *CodeQualitySetup

GetCodeQualitySetup returns the repository's code quality setup, or the unconfigured default.

func (*Store) GetCodeScanningAlert

func (st *Store) GetCodeScanningAlert(repoKey string, number int) *CodeScanningAlert

GetCodeScanningAlert returns an alert by repo + alert number.

func (*Store) GetCodeScanningAlertForCampaign

func (st *Store) GetCodeScanningAlertForCampaign(repoKey string, number int) *CodeScanningAlert

GetCodeScanningAlertForCampaign returns the repo's code scanning alert by number, or nil.

func (*Store) GetCodeScanningAnalysis

func (st *Store) GetCodeScanningAnalysis(repoKey string, id int) *CodeScanningAnalysis

GetCodeScanningAnalysis returns an analysis by ID scoped to the repo.

func (*Store) GetCodeScanningAutofix

func (st *Store) GetCodeScanningAutofix(repoKey string, number int) *CodeScanningAutofix

GetCodeScanningAutofix returns the autofix for an alert, or nil.

func (*Store) GetCodeScanningDefaultSetup

func (st *Store) GetCodeScanningDefaultSetup(repoKey string) *CodeScanningDefaultSetup

GetCodeScanningDefaultSetup returns a repo's default-setup configuration, or nil when never configured.

func (*Store) GetCodeSecurityConfiguration

func (st *Store) GetCodeSecurityConfiguration(orgLogin string, id int) *CodeSecurityConfiguration

GetCodeSecurityConfiguration returns a configuration by org and ID, or nil.

func (*Store) GetCodeSecurityConfigurationByName

func (st *Store) GetCodeSecurityConfigurationByName(orgLogin, name string) *CodeSecurityConfiguration

GetCodeSecurityConfigurationByName returns a configuration by name, or nil.

func (*Store) GetCodespace

func (st *Store) GetCodespace(id int) *Codespace

func (*Store) GetCodespaceByName

func (st *Store) GetCodespaceByName(name string) *Codespace

func (*Store) GetCodespaceSecret

func (st *Store) GetCodespaceSecret(scope, name string) *CodespaceSecret

func (*Store) GetComment

func (st *Store) GetComment(id int) *Comment

func (*Store) GetCopilotCodingAgentPermissions

func (st *Store) GetCopilotCodingAgentPermissions(orgLogin string) *CopilotCodingAgentPermissions

GetCopilotCodingAgentPermissions returns the org's coding-agent policy.

func (*Store) GetCopilotContentExclusion

func (st *Store) GetCopilotContentExclusion(orgLogin string) map[string][]interface{}

GetCopilotContentExclusion returns the org's content exclusion rules, empty when unconfigured.

func (*Store) GetCopilotSeat

func (st *Store) GetCopilotSeat(orgLogin string, userID int) *CopilotSeat

GetCopilotSeat returns the org's seat for the user, or nil. An expired seat reads as absent; its durable removal happens on the next seat write.

func (*Store) GetCopilotSpace

func (st *Store) GetCopilotSpace(ownerType, ownerLogin string, number int) *CopilotSpace

GetCopilotSpace returns the owner's space with the given number, or nil.

func (*Store) GetCustomProperty

func (st *Store) GetCustomProperty(orgLogin, name string) *CustomProperty

GetCustomProperty returns a detached snapshot of a property definition by name, or nil (STORE-021).

func (*Store) GetDeletedPackage

func (st *Store) GetDeletedPackage(ownerKey, pkgType, name string) *Package

GetDeletedPackage returns a soft-deleted package, or nil.

func (*Store) GetDependabotAlert

func (st *Store) GetDependabotAlert(repoKey string, number int) *DependabotAlert

func (*Store) GetDependabotRepositoryAccess

func (st *Store) GetDependabotRepositoryAccess(orgLogin string) []int

func (*Store) GetDependabotRepositoryAccessDefaultLevel

func (st *Store) GetDependabotRepositoryAccessDefaultLevel(orgLogin string) string

GetDependabotRepositoryAccessDefaultLevel returns the org's default access level for Dependabot updates ("public" until changed).

func (*Store) GetDependabotUserSecret

func (st *Store) GetDependabotUserSecret(userLogin, name string) *DependabotUserSecret

func (*Store) GetDiscussion

func (st *Store) GetDiscussion(id int) *Discussion

GetDiscussion returns a discussion by global ID.

func (*Store) GetDiscussionByNumber

func (st *Store) GetDiscussionByNumber(repoID, number int) *Discussion

GetDiscussionByNumber returns a discussion by repo and number.

func (*Store) GetDiscussionCategory

func (st *Store) GetDiscussionCategory(id int) *DiscussionCategory

GetDiscussionCategory returns a category by global ID.

func (*Store) GetDiscussionCategoryByName

func (st *Store) GetDiscussionCategoryByName(repoID int, name string) *DiscussionCategory

GetDiscussionCategoryByName returns a category by repo and name.

func (*Store) GetDiscussionComment

func (st *Store) GetDiscussionComment(id int) *DiscussionComment

GetDiscussionComment returns a comment by global ID.

func (*Store) GetDiscussionPoll

func (st *Store) GetDiscussionPoll(discussionID int) *DiscussionPoll

GetDiscussionPoll returns a discussion's poll as a detached snapshot, or nil.

func (*Store) GetEnterprise

func (st *Store) GetEnterprise(slug string) *Enterprise

GetEnterprise returns a detached snapshot of the enterprise with the given slug, or nil.

func (*Store) GetEnterpriseByID

func (st *Store) GetEnterpriseByID(id int) *Enterprise

GetEnterpriseByID returns a detached snapshot of the enterprise with the given database id, or nil.

func (*Store) GetEnterpriseCodeSecurityConfig

func (st *Store) GetEnterpriseCodeSecurityConfig(id int) *EnterpriseCodeSecurityConfiguration

GetEnterpriseCodeSecurityConfig returns a configuration by ID, or nil.

func (*Store) GetEnterpriseCustomProperty

func (st *Store) GetEnterpriseCustomProperty(name string) *CustomProperty

GetEnterpriseCustomProperty returns a detached snapshot of the enterprise-level property definition by name, or nil.

func (*Store) GetEnterpriseInvitation

func (st *Store) GetEnterpriseInvitation(id int) *EnterpriseInvitation

GetEnterpriseInvitation returns a detached snapshot by database id.

func (*Store) GetEnterpriseMembership

func (st *Store) GetEnterpriseMembership(enterpriseID, userID int) *EnterpriseMembership

GetEnterpriseMembership returns a detached snapshot of a user's membership in one enterprise, or nil when the user is not a member of it.

func (*Store) GetEnterpriseRuleset

func (st *Store) GetEnterpriseRuleset(enterprise string, id int) *Ruleset

func (*Store) GetEnterpriseTeam

func (st *Store) GetEnterpriseTeam(slug string) *EnterpriseTeam

GetEnterpriseTeam returns an enterprise team by slug, or nil.

func (*Store) GetEnvBranchPolicy

func (st *Store) GetEnvBranchPolicy(envID, policyID int) *DeploymentBranchPolicyRule

GetEnvBranchPolicy returns one policy by ID, or nil.

func (*Store) GetEnvProtectionRule

func (st *Store) GetEnvProtectionRule(envID, ruleID int) *EnvCustomProtectionRule

GetEnvProtectionRule returns one rule by ID, or nil.

func (*Store) GetGist

func (st *Store) GetGist(id string) *Gist

GetGist returns the gist with the given ID, or nil.

func (*Store) GetGistAtRevision

func (st *Store) GetGistAtRevision(gistID, sha string) *Gist

GetGistAtRevision returns the gist state at a specific revision.

func (*Store) GetGistComment

func (st *Store) GetGistComment(id int) *GistComment

GetGistComment returns a comment by ID.

func (*Store) GetGitStorage

func (st *Store) GetGitStorage(owner, name string) gitStorage.Storer

func (*Store) GetGlobalAdvisoryByGHSA

func (st *Store) GetGlobalAdvisoryByGHSA(ghsaID string) *SecurityAdvisory

GetGlobalAdvisoryByGHSA returns one published advisory by its GHSA ID as a detached snapshot, or nil. Drafted advisories are invisible here.

func (*Store) GetHook

func (st *Store) GetHook(repoKey string, hookID int) *Webhook

GetHook returns a webhook by repo key and hook ID, or nil.

func (*Store) GetInstallation

func (st *Store) GetInstallation(id int) *Installation

GetInstallation returns an installation by ID, or nil.

func (*Store) GetIssue

func (st *Store) GetIssue(id int) *Issue

func (*Store) GetIssueByNumber

func (st *Store) GetIssueByNumber(repoID, number int) *Issue

func (*Store) GetIssueComment

func (st *Store) GetIssueComment(id int) *Comment

func (*Store) GetIssueEvent

func (st *Store) GetIssueEvent(id int) *IssueEvent

GetIssueEvent returns a detached copy of an issue event by global ID (STORE-021).

func (*Store) GetIssueField

func (st *Store) GetIssueField(orgLogin string, id int) *IssueField

GetIssueField returns an issue field by org and ID, or nil.

func (*Store) GetLFSLock

func (st *Store) GetLFSLock(repoKey string, id int) *LFSLock

GetLFSLock returns one lock as a detached snapshot (STORE-021), or nil.

func (*Store) GetLabel

func (st *Store) GetLabel(id int) *IssueLabel

GetLabel returns a detached copy of a label by global ID (STORE-021).

func (*Store) GetLabelByName

func (st *Store) GetLabelByName(repoID int, name string) *IssueLabel

func (*Store) GetLoginSession

func (st *Store) GetLoginSession(id string) (*LoginSession, error)

func (*Store) GetMarketplaceListing

func (st *Store) GetMarketplaceListing(slug string) *MarketplaceListing

func (*Store) GetMarketplacePlanForListing

func (st *Store) GetMarketplacePlanForListing(listingSlug string, planID int) *MarketplacePlan

func (*Store) GetMarketplacePurchase

func (st *Store) GetMarketplacePurchase(listingSlug, accountType string, accountID int) *MarketplacePurchase

func (*Store) GetMembership

func (st *Store) GetMembership(orgLogin string, userID int) *Membership

GetMembership returns a user's membership in an organization, or nil.

func (*Store) GetMigrationCommon

func (st *Store) GetMigrationCommon(scope MigrationScope, id int) *MigrationCommon

GetMigrationCommon returns a detached snapshot of a migration's shared fields, whichever family it belongs to, or nil.

func (*Store) GetMigrationSource

func (st *Store) GetMigrationSource(id int) *MigrationSource

GetMigrationSource returns a detached snapshot by database id, or nil.

func (*Store) GetMilestone

func (st *Store) GetMilestone(id int) *Milestone

func (*Store) GetMilestoneByNumber

func (st *Store) GetMilestoneByNumber(repoID, number int) *Milestone

func (*Store) GetNetworkConfiguration

func (st *Store) GetNetworkConfiguration(orgLogin, id string) *NetworkConfiguration

GetNetworkConfiguration returns a configuration by ID, or nil.

func (*Store) GetNetworkSettings

func (st *Store) GetNetworkSettings(orgLogin, id string) *NetworkSettingsResource

GetNetworkSettings returns a settings resource by ID, or nil.

func (*Store) GetNotificationPreferences

func (st *Store) GetNotificationPreferences(userID int) (NotificationPreferences, bool)

GetNotificationPreferences returns a detached copy of the user's preferences (defaults when unset); false if the user does not exist.

func (*Store) GetNotificationThreadFor

func (st *Store) GetNotificationThreadFor(user *User, baseURL, threadID string, canRead func(*Repo) bool) *NotificationThread

GetNotificationThreadFor is the credential-aware form for HTTP handlers. The callback runs only after st.Mu is released; nil denies access.

func (*Store) GetOAuthApp

func (st *Store) GetOAuthApp(clientID string) *OAuthApp

GetOAuthApp returns the OAuth App with the given client_id, or nil.

func (*Store) GetOrg

func (st *Store) GetOrg(login string) *Org

func (*Store) GetOrgActionsPermissions

func (st *Store) GetOrgActionsPermissions(orgLogin string) *OrgActionsPermissions

GetOrgActionsPermissions returns the org's Actions settings, materializing defaults on first read.

func (*Store) GetOrgActionsPermissionsLocked

func (st *Store) GetOrgActionsPermissionsLocked(orgLogin string) *OrgActionsPermissions

GetOrgActionsPermissionsLocked materializes an org's Actions settings, filling defaults for fields whose zero value is invalid. Writes to the store, so the caller must hold the WRITE lock (a read lock is a fatal map write).

func (*Store) GetOrgBudget

func (st *Store) GetOrgBudget(orgLogin, id string) *OrgBudget

GetOrgBudget returns a budget by ID, or nil.

func (*Store) GetOrgByID

func (st *Store) GetOrgByID(id int) *Org

func (*Store) GetOrgHook

func (st *Store) GetOrgHook(orgLogin string, hookID int) *Webhook

GetOrgHook returns an org webhook by org login and hook ID, or nil.

func (*Store) GetOrgImmutableReleasesSettings

func (st *Store) GetOrgImmutableReleasesSettings(orgLogin string) *OrgImmutableReleasesSettings

GetOrgImmutableReleasesSettings returns the org policy; an org that never configured one holds the "none" default.

func (*Store) GetOrgInteractionLimit

func (st *Store) GetOrgInteractionLimit(orgLogin string) *OrgInteractionLimit

GetOrgInteractionLimit returns the org's active interaction limit, or nil. An expired limit is removed on read, matching GitHub's automatic lapse.

func (*Store) GetOrgInvitation

func (st *Store) GetOrgInvitation(orgLogin string, id int) *OrgInvitation

func (*Store) GetOrgMigration

func (st *Store) GetOrgMigration(id int) *OrgMigration

GetOrgMigration returns an org migration by ID, or nil.

func (*Store) GetOrgPATGrant

func (st *Store) GetOrgPATGrant(orgLogin string, id int) *OrgPATGrant

GetOrgPATGrant returns an active grant by ID, or nil.

func (*Store) GetOrgPATGrantRequest

func (st *Store) GetOrgPATGrantRequest(orgLogin string, id int) *OrgPATGrantRequest

GetOrgPATGrantRequest returns a pending grant request by ID, or nil.

func (*Store) GetOrgPRCreationCap

func (st *Store) GetOrgPRCreationCap(orgLogin string) PRCreationCap

func (*Store) GetOrgRuleset

func (st *Store) GetOrgRuleset(id int) *Ruleset

GetOrgRuleset returns a ruleset by ID.

func (*Store) GetOrgRulesetSuite

func (st *Store) GetOrgRulesetSuite(orgID int, suiteID int) *RulesetSuite

GetOrgRulesetSuite returns a single rule suite for an organization.

func (*Store) GetOrganizationMigration

func (st *Store) GetOrganizationMigration(id int) *OrganizationMigration

GetOrganizationMigration returns a detached snapshot by database id, or nil.

func (*Store) GetPRCreationCap

func (st *Store) GetPRCreationCap(repoKey string) PRCreationCap

func (*Store) GetPackage

func (st *Store) GetPackage(ownerKey, pkgType, name string) *Package

func (*Store) GetPackageFile

func (st *Store) GetPackageFile(id int) *PackageFile

GetPackageFile returns a package file by ID, or nil.

func (*Store) GetPackageVersion

func (st *Store) GetPackageVersion(id int) *PackageVersion

func (*Store) GetPagesDeployment

func (st *Store) GetPagesDeployment(repoID, id int) *PagesDeploymentRecord

GetPagesDeployment returns a Pages deployment by repo and ID, or nil.

func (*Store) GetPagesDeploymentByIdentifier

func (st *Store) GetPagesDeploymentByIdentifier(repoID int, ident string) *PagesDeploymentRecord

GetPagesDeploymentByIdentifier returns a Pages deployment by its internal numeric record ID or by GitHub's public pages_build_version identifier.

func (*Store) GetPrivateRegistry

func (st *Store) GetPrivateRegistry(orgLogin, name string) *PrivateRegistryConfiguration

GetPrivateRegistry returns a registry by configuration name, or nil.

func (*Store) GetProjectCard

func (st *Store) GetProjectCard(id int) *ProjectCard

GetProjectCard returns a card by ID.

func (*Store) GetProjectClassic

func (st *Store) GetProjectClassic(id int) *ProjectClassic

GetProjectClassic returns a project by ID.

func (*Store) GetProjectColumn

func (st *Store) GetProjectColumn(id int) *ProjectColumn

GetProjectColumn returns a column by ID.

func (*Store) GetPullRequest

func (st *Store) GetPullRequest(id int) *PullRequest

func (*Store) GetPullRequestByNumber

func (st *Store) GetPullRequestByNumber(repoID, number int) *PullRequest

GetPullRequestByNumber returns a pull request by repo ID and number.

func (*Store) GetPullRequestMergeAsync

func (st *Store) GetPullRequestMergeAsync(uuid string) *PullRequestMergeAsync

GetPullRequestMergeAsync returns the async merge result for a UUID, or nil.

func (*Store) GetPullRequestReview

func (st *Store) GetPullRequestReview(id int) *PullRequestReview

GetPullRequestReview returns a review by global ID.

func (*Store) GetPullRequestStack

func (st *Store) GetPullRequestStack(repoKey string, number int) *PullRequestStack

func (*Store) GetRepo

func (st *Store) GetRepo(owner, name string) *Repo

func (*Store) GetRepoActionsPermissions

func (st *Store) GetRepoActionsPermissions(repoKey string) *RepoActionsPermissions

GetRepoActionsPermissions returns the repo's Actions settings, materializing defaults on first read.

func (st *Store) GetRepoAutolink(repoKey string, id int) *RepoAutolink

GetRepoAutolink returns an autolink by ID, or nil.

func (*Store) GetRepoByFullName

func (st *Store) GetRepoByFullName(fullName string) *Repo

GetRepoByFullName resolves an "owner/name" key under the read lock. Handlers must use this rather than indexing ReposByName directly: an unsynchronized read racing a create/rename/delete write is a fatal concurrent map access.

func (*Store) GetRepoByID

func (st *Store) GetRepoByID(id int) *Repo

func (*Store) GetRepoByName

func (st *Store) GetRepoByName(fullName string) *Repo

func (*Store) GetRepoCodeSecurityConfiguration

func (st *Store) GetRepoCodeSecurityConfiguration(orgLogin string, repoID int) *CodeSecurityConfiguration

GetRepoCodeSecurityConfiguration returns the configuration attached to the repository, or nil.

func (*Store) GetRepoCollaboratorPermission

func (st *Store) GetRepoCollaboratorPermission(owner, name, login string) string

GetRepoCollaboratorPermission returns the collaborator's permission, or "".

func (*Store) GetRepoDeployKey

func (st *Store) GetRepoDeployKey(id int) *RepoDeployKey

GetRepoDeployKey returns a deploy key by ID.

func (*Store) GetRepoImport

func (st *Store) GetRepoImport(repoID int) *RepoImport

GetRepoImport returns the repo's import record, or nil.

func (*Store) GetRepoInstallation

func (st *Store) GetRepoInstallation(ownerLogin string) *Installation

GetRepoInstallation finds an installation by target login.

func (*Store) GetRepoInvitation

func (st *Store) GetRepoInvitation(repoKey string, id int) *RepoInvitation

GetRepoInvitation returns an invitation by repository key and ID, or nil.

func (*Store) GetRepoRulesetSuite

func (st *Store) GetRepoRulesetSuite(repoID int, suiteID int) *RulesetSuite

GetRepoRulesetSuite returns a single rule suite for a repository.

func (*Store) GetRepoSubscription

func (st *Store) GetRepoSubscription(userID int, repoID int) *RepoSubscription

GetRepoSubscription returns a subscription or nil.

func (*Store) GetRepositoryMigration

func (st *Store) GetRepositoryMigration(id int) *RepositoryMigration

GetRepositoryMigration returns a detached snapshot by database id, or nil.

func (*Store) GetRuleset

func (st *Store) GetRuleset(id int) *Ruleset

GetRuleset returns a ruleset by ID.

func (*Store) GetRulesetHistory

func (st *Store) GetRulesetHistory(rs *Ruleset) []RulesetVersion

GetRulesetHistory returns prior versions of a ruleset.

func (*Store) GetRulesetVersion

func (st *Store) GetRulesetVersion(rs *Ruleset, versionID int) *RulesetVersion

GetRulesetVersion returns a specific historical version.

func (*Store) GetSARIFUpload

func (st *Store) GetSARIFUpload(repoKey, id string) *SARIFUpload

GetSARIFUpload returns a SARIF upload by ID.

func (*Store) GetSBOMExport

func (st *Store) GetSBOMExport(uuid string) *SBOMExport

GetSBOMExport returns an export by UUID, or nil.

func (*Store) GetSecretScanningAlert

func (st *Store) GetSecretScanningAlert(repoKey string, number int) *SecretScanningAlert

func (*Store) GetSecurityAdvisoryByGHSA

func (st *Store) GetSecurityAdvisoryByGHSA(repoID int, ghsaID string) *SecurityAdvisory

func (*Store) GetSubIssueParent

func (st *Store) GetSubIssueParent(issueID int) int

func (*Store) GetTeam

func (st *Store) GetTeam(orgLogin, slug string) *Team

func (*Store) GetTeamByID

func (st *Store) GetTeamByID(id int) *Team

func (*Store) GetTeamMembership

func (st *Store) GetTeamMembership(orgLogin, slug string, userID int) (TeamRole, bool)

GetTeamMembership returns a user's team role and whether they are a member; the role is empty for a non-member.

func (*Store) GetTeamRepoPermission

func (st *Store) GetTeamRepoPermission(orgLogin, slug, fullName string) (TeamPermission, bool)

GetTeamRepoPermission returns the effective permission a team confers on a repo; the second value is false when the repo is not linked. A missing per-repo override falls back to the team's default Permission.

func (*Store) GetThreadSubscription

func (st *Store) GetThreadSubscription(userID int, threadID string) *ThreadSubscription

GetThreadSubscription returns the user's subscription for a thread.

func (*Store) GetUserByID

func (st *Store) GetUserByID(id int) *User

GetUserByID returns the user with the given ID, or nil.

func (*Store) GetUserInteractionLimit

func (st *Store) GetUserInteractionLimit(userID int) (string, time.Time)

GetUserInteractionLimit returns the active limit and its expiry, or ("", zero) when no unexpired limit is set.

func (*Store) GetUserList

func (st *Store) GetUserList(id int) *UserList

GetUserList returns a detached copy of one list.

func (*Store) GetUserMigration

func (st *Store) GetUserMigration(id int) *UserMigration

GetUserMigration returns a user migration by ID, or nil.

func (*Store) GetUserStatus

func (st *Store) GetUserStatus(userID int) *UserStatus

GetUserStatus returns a detached copy of the user's status, or nil when there is none or it has expired.

func (*Store) GetWikiPage

func (st *Store) GetWikiPage(repoKey, slug string) *WikiPage

GetWikiPage returns a detached copy of one wiki page, or nil if absent.

func (*Store) GetWikiPageRevision

func (st *Store) GetWikiPageRevision(repoKey, slug string, id int) *WikiPageRevision

GetWikiPageRevision returns one revision by ID (detached), or nil if absent.

func (*Store) GetWorkflowFile

func (st *Store) GetWorkflowFile(repoFullName string, id int64) *WorkflowFile

GetWorkflowFile returns the WorkflowFile keyed by (repo, id), or nil. The repo check guards against a cross-repo FNV ID collision.

func (*Store) GetWorkflowFileLocked

func (st *Store) GetWorkflowFileLocked(repoFullName string, id int64) *WorkflowFile

GetWorkflowFileLocked is GetWorkflowFile for callers that already hold st.Mu. Calling the locking GetWorkflowFile from a `...Locked` render path recursively read-locks st.Mu, which deadlocks the moment a writer is queued (Go's RWMutex gives writers priority over new readers).

func (*Store) GistStargazerIDs

func (st *Store) GistStargazerIDs(gistID string) []int

GistStargazerIDs returns the ids of the users who starred the gist, oldest account first. Star bookkeeping has no reverse index, so this scans. The result is a fresh slice.

func (*Store) GitStorageForRepoID

func (st *Store) GitStorageForRepoID(repoID int) (gitStorage.Storer, string)

func (*Store) GrantTeamRepoAccessAsCollaborator

func (st *Store) GrantTeamRepoAccessAsCollaborator(orgLogin string, user *User)

GrantTeamRepoAccessAsCollaborator materializes a member's team-derived repo access as direct collaborator grants — the access a member keeps when converted to an outside collaborator. Stronger existing direct grants are kept.

func (*Store) GrantUserNamespaceAccess

func (st *Store) GrantUserNamespaceAccess(enterpriseID, repoID, granteeID int) time.Time

GrantUserNamespaceAccess records the grant and returns its expiry. The window is GitHub's two hours.

func (*Store) HasActiveSecretScanningPushProtectionBypass

func (st *Store) HasActiveSecretScanningPushProtectionBypass(repoKey, tokenType string, now time.Time) bool

HasActiveSecretScanningPushProtectionBypass reports whether a granted bypass still permits a protected write for this token type.

func (*Store) HasPagesSite

func (st *Store) HasPagesSite(repoID int) bool

func (*Store) HookLastResp

func (st *Store) HookLastResp(h *Webhook) *HookLastResponse

HookLastResp reads the hook's last_response under the lock. A direct h.LastResponse read races SetHookLastResponse on the async deliverWebhook goroutine, so every JSON-rendering path must use this.

func (*Store) HostedRunnersLocked

func (st *Store) HostedRunnersLocked(target RunnerScope) []*HostedRunner

HostedRunnersLocked returns the target's hosted runners sorted by id. Callers hold the store lock.

func (*Store) IndexOrgLoginLocked

func (st *Store) IndexOrgLoginLocked(login string)

IndexOrgLoginLocked records login in the folded org-login index. Caller holds st.Mu and has inserted the org into OrgsByLogin under login.

func (*Store) IndexPullLocked

func (st *Store) IndexPullLocked(pr *PullRequest)

IndexPullLocked records the PR in the per-repo secondary index so lookups resolve in O(PRs-in-repo) instead of a full store scan. Caller holds st.Mu.

func (*Store) IndexRepoNameLocked

func (st *Store) IndexRepoNameLocked(fullName string)

IndexRepoNameLocked records the "owner/name" key in the folded repo index. Caller holds st.Mu and has inserted the repo into ReposByName under fullName.

func (*Store) IndexUserLoginLocked

func (st *Store) IndexUserLoginLocked(login string)

IndexUserLoginLocked records login in the folded login index. Caller holds st.Mu and has inserted the user into UsersByLogin under login.

func (*Store) IsEnterpriseBillingReader

func (st *Store) IsEnterpriseBillingReader(enterpriseID int, user *User) bool

func (*Store) IsEnterpriseMember

func (st *Store) IsEnterpriseMember(enterpriseID int, user *User) bool

func (*Store) IsEnterpriseOwner

func (st *Store) IsEnterpriseOwner(enterpriseID int, user *User) bool

IsEnterpriseOwner, IsEnterpriseMember and IsEnterpriseBillingReader are the three standing questions every enterprise read and write is authorized against.

func (*Store) IsEnterpriseTeamMember

func (st *Store) IsEnterpriseTeamMember(t *EnterpriseTeam, userID int) bool

IsEnterpriseTeamMember reports whether the user belongs to the team.

func (*Store) IsGistStarred

func (st *Store) IsGistStarred(userID int, gistID string) bool

IsGistStarred reports whether the user has starred the gist.

func (*Store) IsRepoStarredBy

func (st *Store) IsRepoStarredBy(userID int, owner, name string) bool

IsRepoStarredBy reports whether userID has starred the repo.

func (*Store) IsUserBlocked

func (st *Store) IsUserBlocked(userID, targetID int) bool

IsUserBlocked reports whether userID has blocked targetID.

func (*Store) IsUserBlockedByOrg

func (st *Store) IsUserBlockedByOrg(orgLogin string, userID int) bool

IsUserBlockedByOrg reports whether the organization blocks the user.

func (*Store) IsUserFollowing

func (st *Store) IsUserFollowing(userID, targetID int) bool

IsUserFollowing reports whether userID follows targetID.

func (*Store) IssueTypeForIssueLocked

func (st *Store) IssueTypeForIssueLocked(issue *Issue) *IssueType

IssueTypeForIssueLocked resolves the issue's assigned type; call with st.Mu held. Returns nil when the repo is gone, not org-owned, or the type was removed.

func (*Store) JobByPlanIDLocked

func (st *Store) JobByPlanIDLocked(planID string) *Job

JobByPlanIDLocked resolves a job by plan id, falling back to a scan for jobs seeded outside the dispatch path. Callers hold the store lock.

func (*Store) JobByRequestIDLocked

func (st *Store) JobByRequestIDLocked(reqID int64) *Job

JobByRequestIDLocked resolves a job by request id, falling back to a scan for jobs seeded outside the dispatch path. Callers hold the store lock.

func (*Store) JobConcurrencyPeersLocked

func (st *Store) JobConcurrencyPeersLocked(repoFullName, group string) []jobConcurrencyPeer

JobConcurrencyPeersLocked snapshots the non-terminal jobs in a job concurrency group, lazily pruning entries gone terminal since indexing. Callers hold the write lock.

func (*Store) LFSObjectSize

func (st *Store) LFSObjectSize(repoKey, oid string) (int64, bool)

LFSObjectSize reports an object's size and whether this repository holds it.

func (*Store) LFSObjectStoredAnywhere

func (st *Store) LFSObjectStoredAnywhere(oid string) (int64, bool)

LFSObjectStoredAnywhere reports whether any repository holds this oid, i.e. whether verified bytes are already in the byte store. The upload path checks this before writing so a second upload claiming the same oid cannot overwrite already-verified bytes.

func (*Store) LatestPublishedPagesDeployment

func (st *Store) LatestPublishedPagesDeployment(repoID int) *PagesDeploymentRecord

func (*Store) LinkIssueBranch

func (st *Store) LinkIssueBranch(issueID, repoID int, ref string) (found, created bool)

LinkIssueBranch links a branch to an issue, reporting whether the issue exists and whether this call created the link. Relinking is idempotent.

func (*Store) LinkRepoToProjectClassic

func (st *Store) LinkRepoToProjectClassic(projectID, repoID int) bool

LinkRepoToProjectClassic records a repository link (idempotent). Reports false only when the project does not exist.

func (*Store) ListAccountSSHKeys

func (st *Store) ListAccountSSHKeys(userID int) []*UserKey

ListAccountSSHKeys returns a detached snapshot of the account's SSH authentication keys, oldest first. The traversal lives here because the index is guarded by Misc.Mu.

func (*Store) ListAgentTasks

func (st *Store) ListAgentTasks(f AgentTaskFilter) (tasks []*AgentTask, totalActive, totalArchived int)

ListAgentTasks returns the tasks matching the filter, sorted, plus the active/archived totals within the filter's repo/creator scope.

func (*Store) ListAppDeliveries

func (st *Store) ListAppDeliveries(appID int) []*WebhookDelivery

ListAppDeliveries returns app deliveries newest-first as live rows: they are write-once, so a reader never races a writer (STORE-021 exception).

func (*Store) ListAppInstallations

func (st *Store) ListAppInstallations(appID int) []*Installation

ListAppInstallations returns all installations for a given app.

func (*Store) ListArtifactDeploymentRecords

func (st *Store) ListArtifactDeploymentRecords(orgID int, digest string) []*ArtifactDeploymentRecord

ListArtifactDeploymentRecords returns the org's deployment records for a digest (any digest when empty), ascending by ID.

func (*Store) ListArtifactStorageRecords

func (st *Store) ListArtifactStorageRecords(orgID int, digest string) []*ArtifactStorageRecord

ListArtifactStorageRecords returns the org's storage records for a digest (any digest when empty), ascending by ID.

func (*Store) ListAssignableUsers

func (st *Store) ListAssignableUsers(repo *Repo) []*User

ListAssignableUsers returns the users assignable to a repo's issues — owner, direct collaborators, and (for org repos) active org members — ordered by login.

func (*Store) ListAttestations

func (st *Store) ListAttestations(repoIDs map[int]bool, subjectDigest, predicateType string) []*Attestation

ListAttestations returns attestations across the given repos that cover subjectDigest (any when empty) and pass the predicate-type filter, sorted by ID.

func (*Store) ListBlockedUsers

func (st *Store) ListBlockedUsers(userID int) []string

ListBlockedUsers returns the logins of users blocked by userID.

func (*Store) ListBranchProtectedBranches

func (st *Store) ListBranchProtectedBranches(repoID int) []string

ListBranchProtectedBranches returns the sorted names of branches carrying an exact-name protection rule.

func (*Store) ListBranchProtectionPatterns

func (st *Store) ListBranchProtectionPatterns(repoID int) []*BranchProtectionPatternRule

ListBranchProtectionPatterns returns the repo's ordered pattern rules as a detached snapshot.

func (*Store) ListCampaigns

func (st *Store) ListCampaigns(orgLogin string) []*Campaign

ListCampaigns returns the org's campaigns sorted by number.

func (*Store) ListCheckRunsForCommit

func (st *Store) ListCheckRunsForCommit(repoKey, headSHA, status, conclusion string, appID int) []*CheckRun

ListCheckRunsForCommit returns every CheckRun for (repoKey, headSHA), optional filters.

func (*Store) ListCheckRunsForSuite

func (st *Store) ListCheckRunsForSuite(suiteID int64) []*CheckRun

ListCheckRunsForSuite returns every CheckRun in a suite.

func (*Store) ListCheckSuitesForCommit

func (st *Store) ListCheckSuitesForCommit(repoKey, headSHA string, appID int) []*CheckSuite

ListCheckSuitesForCommit returns every suite recorded against (repoKey, headSHA), optionally filtered by appID (0 = no filter).

func (*Store) ListChildTeams

func (st *Store) ListChildTeams(orgLogin string, parentID int) []*Team

ListChildTeams returns the teams whose parent is parentID.

func (*Store) ListCodeQLDatabases

func (st *Store) ListCodeQLDatabases(repoKey string) []*CodeQLDatabase

ListCodeQLDatabases returns a repo's CodeQL databases sorted by language, as live rows for the same write-once reason as GetCodeQLDatabase (STORE-021 documented exception).

func (*Store) ListCodeQualityFindings

func (st *Store) ListCodeQualityFindings(repoKey, state string) []*CodeQualityFinding

func (*Store) ListCodeScanningAlerts

func (st *Store) ListCodeScanningAlerts(repoKey, state, severity, toolName, rule, sortField, direction string) []*CodeScanningAlert

ListCodeScanningAlerts returns repo alerts filtered and sorted per GitHub's list endpoint.

func (*Store) ListCodeScanningAlertsByOrg

func (st *Store) ListCodeScanningAlertsByOrg(orgID int, state, severity, toolName, sortField, direction string) []*CodeScanningAlert

ListCodeScanningAlertsByOrg returns all alerts for repos owned by the org, sorted per GitHub's organization list endpoint.

func (*Store) ListCodeScanningAnalyses

func (st *Store) ListCodeScanningAnalyses(repoKey, ref, toolName string) []*CodeScanningAnalysis

ListCodeScanningAnalyses returns a repo's analyses, optionally filtered by ref and tool_name.

func (*Store) ListCodeSecurityConfigurationRepos

func (st *Store) ListCodeSecurityConfigurationRepos(orgLogin string, id int) []*Repo

ListCodeSecurityConfigurationRepos returns the repositories attached to the configuration, sorted by repo ID.

func (*Store) ListCodeSecurityConfigurations

func (st *Store) ListCodeSecurityConfigurations(orgLogin string) []*CodeSecurityConfiguration

ListCodeSecurityConfigurations returns the org's configurations sorted by ID.

func (*Store) ListCodespaceSecrets

func (st *Store) ListCodespaceSecrets(scope string) []*CodespaceSecret

ListCodespaceSecrets returns a scope's secrets sorted by name.

func (*Store) ListCodespacesByOwner

func (st *Store) ListCodespacesByOwner(ownerLogin string) []*Codespace

func (*Store) ListCodespacesByRepo

func (st *Store) ListCodespacesByRepo(repoKey string) []*Codespace

func (*Store) ListComments

func (st *Store) ListComments(issueID int) []*Comment

func (*Store) ListCommentsFor

func (st *Store) ListCommentsFor(parentType string, parentID int) []*Comment

ListCommentsFor returns the conversation comments on an "issue" or "pull_request" parent.

func (*Store) ListCopilotSeats

func (st *Store) ListCopilotSeats(orgLogin string) []*CopilotSeat

ListCopilotSeats returns the org's seats by creation time (user ID tie-break) so pagination is stable.

func (*Store) ListCopilotSpaces

func (st *Store) ListCopilotSpaces(ownerType, ownerLogin string) []*CopilotSpace

ListCopilotSpaces returns the owner's spaces sorted by number.

func (*Store) ListCustomProperties

func (st *Store) ListCustomProperties(orgLogin string) []*CustomProperty

ListCustomProperties returns the org's property definitions sorted by name.

func (*Store) ListDeletedPackages

func (st *Store) ListDeletedPackages(ownerKey string) []*Package

ListDeletedPackages returns an owner's soft-deleted packages, newest first. Deleted rows leave PackagesByOwnerKey but stay in st.Packages, so this scans that directly.

func (*Store) ListDeliveries

func (st *Store) ListDeliveries(hookID int) []*WebhookDelivery

ListDeliveries returns the hook's deliveries newest-first. Rows are shared live, not cloned: they are write-once and carry large payloads (STORE-021 exception, as for ListAppDeliveries).

func (*Store) ListDependabotAlerts

func (st *Store) ListDependabotAlerts(repoKey, state, severity, packageName, ecosystem, manifest, sortField, direction string) []*DependabotAlert

ListDependabotAlerts returns repo alerts filtered and sorted per GitHub's list endpoint.

func (*Store) ListDependabotAlertsByOrg

func (st *Store) ListDependabotAlertsByOrg(orgID int, state, ecosystem, packageName, sortField, direction string) []*DependabotAlert

ListDependabotAlertsByOrg returns alerts for an org's repos, filtered and sorted per GitHub's query parameters. Unknown filter values match nothing rather than 400.

func (*Store) ListDependabotUserSecrets

func (st *Store) ListDependabotUserSecrets(userLogin string) []*DependabotUserSecret

ListDependabotUserSecrets returns a user's Dependabot secrets sorted by name.

func (*Store) ListDependencySnapshots

func (st *Store) ListDependencySnapshots(repoID int) []*DependencySnapshot

ListDependencySnapshots returns the repo's snapshots, oldest first.

func (*Store) ListDiscussionCategories

func (st *Store) ListDiscussionCategories(repoID int) []*DiscussionCategory

ListDiscussionCategories returns all categories for a repository.

func (*Store) ListDiscussionComments

func (st *Store) ListDiscussionComments(discussionID, parentID int) []*DiscussionComment

ListDiscussionComments returns a discussion's comments, optionally scoped to a parent.

func (*Store) ListDiscussions

func (st *Store) ListDiscussions(repoID, categoryID int) []*Discussion

ListDiscussions returns a repository's discussions, optionally filtered by category.

func (*Store) ListEnterpriseCodeSecurityConfigRepos

func (st *Store) ListEnterpriseCodeSecurityConfigRepos(configID int) []*Repo

ListEnterpriseCodeSecurityConfigRepos returns the repositories attached to the configuration, sorted by repo ID.

func (*Store) ListEnterpriseCodeSecurityConfigs

func (st *Store) ListEnterpriseCodeSecurityConfigs() []*EnterpriseCodeSecurityConfiguration

ListEnterpriseCodeSecurityConfigs returns all configurations sorted by ID.

func (*Store) ListEnterpriseCustomProperties

func (st *Store) ListEnterpriseCustomProperties() []*CustomProperty

ListEnterpriseCustomProperties returns detached snapshots of the enterprise-level repository custom property definitions, ordered by name.

func (*Store) ListEnterpriseInvitations

func (st *Store) ListEnterpriseInvitations(enterpriseID int, kind string) []*EnterpriseInvitation

ListEnterpriseInvitations returns detached snapshots of the outstanding invitations of one kind for one enterprise, oldest first.

func (*Store) ListEnterpriseMemberships

func (st *Store) ListEnterpriseMemberships(enterpriseID int) []*EnterpriseMembership

ListEnterpriseMemberships returns detached snapshots of every membership in one enterprise, ordered by user id.

func (*Store) ListEnterpriseOrgIDs

func (st *Store) ListEnterpriseOrgIDs(enterpriseID int) []int

ListEnterpriseOrgIDs returns the ids of the organizations in an enterprise, ascending.

func (*Store) ListEnterpriseTeamMembers

func (st *Store) ListEnterpriseTeamMembers(t *EnterpriseTeam) []*User

ListEnterpriseTeamMembers returns the team's members sorted by user ID.

func (*Store) ListEnterpriseTeamOrgs

func (st *Store) ListEnterpriseTeamOrgs(t *EnterpriseTeam) []*Org

ListEnterpriseTeamOrgs resolves the team's organization assignments from its selection type: "all" assigns every organization on the instance, "selected" the recorded list, "disabled" none. Sorted by org ID.

func (*Store) ListEnterpriseTeams

func (st *Store) ListEnterpriseTeams() []*EnterpriseTeam

ListEnterpriseTeams returns all enterprise teams sorted by ID.

func (*Store) ListEnterprises

func (st *Store) ListEnterprises() []*Enterprise

ListEnterprises returns detached snapshots of every enterprise, ordered by slug.

func (*Store) ListEnterprisesForUser

func (st *Store) ListEnterprisesForUser(userID int) []*Enterprise

ListEnterprisesForUser returns detached snapshots of every enterprise the user belongs to in any role, ordered by slug.

func (*Store) ListEnvBranchPolicies

func (st *Store) ListEnvBranchPolicies(envID int) []*DeploymentBranchPolicyRule

ListEnvBranchPolicies returns an environment's branch/tag policies in creation order.

func (*Store) ListEnvProtectionRules

func (st *Store) ListEnvProtectionRules(envID int) []*EnvCustomProtectionRule

ListEnvProtectionRules returns an environment's custom protection rules in creation order.

func (*Store) ListEveryRepo

func (st *Store) ListEveryRepo() []*Repo

ListEveryRepo returns a detached snapshot of every repository on the instance, ordered by full name (STORE-021). The traversal lives here behind the store lock because reading st.ReposByName from a caller is a process-fatal map race (AUTH-043).

func (*Store) ListFailedOrgInvitations

func (st *Store) ListFailedOrgInvitations(orgLogin string) []*OrgInvitation

ListFailedOrgInvitations returns the org's failed invitations sorted by ID.

func (*Store) ListForks

func (st *Store) ListForks(sourceRepoID int, opts RepoListOptions) []*Repo

ListForks returns repos forked from sourceRepoID, sorted/paged per opts.

func (*Store) ListGistComments

func (st *Store) ListGistComments(gistID string) []*GistComment

ListGistComments returns comments for a gist, oldest first.

func (*Store) ListGistCommits

func (st *Store) ListGistCommits(gistID string) []*GistHistory

ListGistCommits returns the revision history for a gist.

func (*Store) ListGistForks

func (st *Store) ListGistForks(gistID string) []*Gist

ListGistForks returns forks of a gist.

func (*Store) ListGistsForUser

func (st *Store) ListGistsForUser(userID int, since time.Time) []*Gist

ListGistsForUser returns gists owned by the user, optionally filtered by since.

func (*Store) ListGlobalAdvisories

func (st *Store) ListGlobalAdvisories() []*SecurityAdvisory

ListGlobalAdvisories returns every published repository advisory.

func (*Store) ListGlobalAdvisoriesFiltered

func (st *Store) ListGlobalAdvisoriesFiltered(filter GlobalAdvisoryFilter) []*SecurityAdvisory

ListGlobalAdvisoriesFiltered returns the published advisories matching the filter as detached snapshots (STORE-021), newest publication first.

func (*Store) ListGlobalVulnerabilities

func (st *Store) ListGlobalVulnerabilities(filter GlobalAdvisoryFilter) []GlobalSecurityVulnerability

ListGlobalVulnerabilities flattens the published advisories into their individual package vulnerabilities, filtered the same way.

func (*Store) ListHooks

func (st *Store) ListHooks(repoKey string) []*Webhook

ListHooks returns all webhooks for a repository.

func (*Store) ListIPAllowListEntries

func (st *Store) ListIPAllowListEntries(ownerType string, ownerID int) []*IPAllowListEntry

ListIPAllowListEntries returns detached snapshots of one owner's entries, ordered by database id.

func (*Store) ListIPAllowListEntryByID

func (st *Store) ListIPAllowListEntryByID(id int) *IPAllowListEntry

ListIPAllowListEntryByID returns a detached snapshot of one entry by database id, or nil.

func (*Store) ListInstallationsForTarget

func (st *Store) ListInstallationsForTarget(login string) []*Installation

ListInstallationsForTarget returns every App installation on the account, to fan an account-scoped event out to the apps that subscribed.

func (*Store) ListIssueBlockedBy

func (st *Store) ListIssueBlockedBy(issueID int) []int

ListIssueBlockedBy returns the IDs of the issues blocking issueID.

func (*Store) ListIssueBlocking

func (st *Store) ListIssueBlocking(issueID int) []int

ListIssueBlocking returns the IDs of the issues issueID blocks (the reverse of the blocked-by links).

func (*Store) ListIssueComments

func (st *Store) ListIssueComments(repoKey string, issueNumber int) []*Comment

ListIssueComments returns an issue's conversation comments by repo key and number.

func (*Store) ListIssueEvents

func (st *Store) ListIssueEvents(repoID, issueID int) []*IssueEvent

ListIssueEvents returns a repo's issue events, ordered by event ID. issueID 0 spans all events including PR events (GitHub's repo-level listing does too); a specific issueID excludes PR events, whose global IDs can collide with issues'.

func (*Store) ListIssueFieldValues

func (st *Store) ListIssueFieldValues(orgLogin string, issueID int) []map[string]interface{}

ListIssueFieldValues renders an issue's field values in the REST issue-field-value shape, sorted by field ID. Values whose field definition no longer exists are skipped.

func (*Store) ListIssueFields

func (st *Store) ListIssueFields(orgLogin string) []*IssueField

ListIssueFields returns the org's issue fields sorted by ID.

func (*Store) ListIssueSuggestions

func (st *Store) ListIssueSuggestions(repoKey string, issueID int) []*IssueSuggestion

func (*Store) ListIssueTypes

func (st *Store) ListIssueTypes(orgLogin string) []*IssueType

ListIssueTypes returns the org's issue types sorted by ID.

func (*Store) ListIssues

func (st *Store) ListIssues(repoID int, state string) []*Issue

ListIssues returns a repo's issues oldest-created first. state matches "OPEN"/"CLOSED"; empty or "all" returns all.

func (*Store) ListIssuesOrderedByCreation

func (st *Store) ListIssuesOrderedByCreation(repoID int, state string, desc bool) []*Issue

ListIssuesOrderedByCreation returns a repo's issues by creation time (number tie-break), descending (GitHub's default) when desc is true. Detached snapshots (STORE-021).

func (*Store) ListLFSLocks

func (st *Store) ListLFSLocks(repoKey string) []*LFSLock

ListLFSLocks returns a repository's locks by id, as detached snapshots (STORE-021).

func (*Store) ListLabels

func (st *Store) ListLabels(repoID int) []*IssueLabel

ListLabels returns a repository's labels in creation order.

func (*Store) ListLinkedBranches

func (st *Store) ListLinkedBranches(issueID int) []LinkedBranch

ListLinkedBranches returns an issue's links as a detached snapshot (STORE-021).

func (*Store) ListLoginSessionsForUser

func (st *Store) ListLoginSessionsForUser(userID int, now time.Time) ([]LoginSessionSummary, error)

ListLoginSessionsForUser returns the user's live browser sessions, newest first. Sessions predating the handle are reported with an empty handle and are not revocable by name.

func (*Store) ListMannequins

func (st *Store) ListMannequins(orgID int) []*Mannequin

ListMannequins returns an org's mannequins as detached snapshots.

func (*Store) ListMarketplaceDeliveries

func (st *Store) ListMarketplaceDeliveries(listingSlug string) []*WebhookDelivery

ListMarketplaceDeliveries returns live rows: webhook deliveries are write-once (STORE-021 documented exception, as for ListAppDeliveries).

func (*Store) ListMarketplaceListings

func (st *Store) ListMarketplaceListings(publishedOnly bool) []*MarketplaceListing

func (*Store) ListMarketplacePlans

func (st *Store) ListMarketplacePlans(listingSlug string, publishedOnly bool) []*MarketplacePlan

func (*Store) ListMarketplacePurchasesForAccount

func (st *Store) ListMarketplacePurchasesForAccount(accountType string, accountID int) []*MarketplacePurchase

func (*Store) ListMarketplacePurchasesForListing

func (st *Store) ListMarketplacePurchasesForListing(listingSlug string) []*MarketplacePurchase

func (*Store) ListMembershipsByUser

func (st *Store) ListMembershipsByUser(userID int, state MembershipState) []*Membership

ListMembershipsByUser returns the user's memberships across all orgs, optionally filtered by state ("" = all).

func (*Store) ListMigrationLockedRepos

func (st *Store) ListMigrationLockedRepos(scope MigrationScope, id int) []string

ListMigrationLockedRepos returns the full names of every repository a migration currently locks.

func (*Store) ListMigrationSources

func (st *Store) ListMigrationSources(ownerOrgID int) []*MigrationSource

ListMigrationSources returns detached snapshots of one organization's sources, ordered by database id.

func (*Store) ListMilestones

func (st *Store) ListMilestones(repoID int, state string) []*Milestone

ListMilestones returns milestones for a repository, optionally filtered by state.

func (*Store) ListNetworkConfigurations

func (st *Store) ListNetworkConfigurations(orgLogin string) []*NetworkConfiguration

ListNetworkConfigurations returns the org's configurations sorted by creation time then ID.

func (*Store) ListOAuthApps

func (st *Store) ListOAuthApps() []*OAuthApp

ListOAuthApps returns all OAuth Apps.

func (*Store) ListOrgAuditEntries

func (st *Store) ListOrgAuditEntries(org string) []*AuditEntry

ListOrgAuditEntries returns detached snapshots (STORE-021) of the audit entries the org's log surfaces: org-scoped entries plus the org-less instance-wide entries GitHub also lists. Mirrors handleOrgAuditLog's filter so REST and GraphQL answer from the same rows.

func (*Store) ListOrgBlockedUsers

func (st *Store) ListOrgBlockedUsers(orgLogin string) []*User

ListOrgBlockedUsers returns the users the organization blocks, sorted by user ID.

func (*Store) ListOrgBudgets

func (st *Store) ListOrgBudgets(orgLogin string) []*OrgBudget

ListOrgBudgets returns the org's budgets ordered by creation time then ID.

func (*Store) ListOrgHooks

func (st *Store) ListOrgHooks(orgLogin string) []*Webhook

func (*Store) ListOrgImmutableReleasesRepos

func (st *Store) ListOrgImmutableReleasesRepos(orgLogin string) []*Repo

ListOrgImmutableReleasesRepos returns the selected repositories sorted by ID.

func (*Store) ListOrgMembers

func (st *Store) ListOrgMembers(orgLogin string) []*User

ListOrgMembers returns all active members of an org.

func (*Store) ListOrgMigrations

func (st *Store) ListOrgMigrations(orgLogin string) []*OrgMigration

ListOrgMigrations returns an organization's migrations, newest first.

func (*Store) ListOrgMigratorRoles

func (st *Store) ListOrgMigratorRoles(orgID int) []*OrgMigratorRole

ListOrgMigratorRoles returns detached snapshots of one organization's migrator grants, ordered by actor type then actor.

func (*Store) ListOrgPinnedRepos

func (st *Store) ListOrgPinnedRepos(orgLogin string) ([]string, bool)

ListOrgPinnedRepos returns a detached copy of the org's ordered pinned-repo full names, or an empty slice. The bool reports whether the org exists.

func (*Store) ListOrgReposForProperties

func (st *Store) ListOrgReposForProperties(orgLogin, query string) []*Repo

ListOrgReposForProperties returns the org's repositories, optionally filtered by a repository_query keyword against the repo name (the `repo:owner/name` qualifier is honored as an exact match).

func (*Store) ListOrgRulesetSuites

func (st *Store) ListOrgRulesetSuites(orgID int) []RulesetSuite

ListOrgRulesetSuites returns rule suites for an organization, newest first.

func (*Store) ListOrgRulesets

func (st *Store) ListOrgRulesets(orgID int) []*Ruleset

ListOrgRulesets returns all rulesets for an organization, sorted by ID.

func (*Store) ListOrgSelectedRepos

func (st *Store) ListOrgSelectedRepos(orgLogin string) []int

ListOrgSelectedRepos returns the org's selected repository IDs. Uses the non-materializing lookup so a read lock never writes to the store.

func (*Store) ListOrganizationMigrations

func (st *Store) ListOrganizationMigrations(enterpriseID int) []*OrganizationMigration

ListOrganizationMigrations returns detached snapshots of one enterprise's organization migrations, oldest first.

func (*Store) ListOrgsAll

func (st *Store) ListOrgsAll(since int) []*Org

ListOrgsAll returns every org with ID greater than since, ordered by ID ascending — the GET /organizations contract.

func (*Store) ListOrgsByUser

func (st *Store) ListOrgsByUser(userID int) []*Org

ListOrgsByUser returns the user's orgs in ascending id order. The order must be stable: offset pagination in /user/orgs over the random-order memberships map would otherwise skip or duplicate orgs across pages.

func (*Store) ListOutsideCollaborators

func (st *Store) ListOutsideCollaborators(orgLogin string) []*User

ListOutsideCollaborators returns users who collaborate on at least one of the org's repositories without an active org membership, sorted by user ID.

func (*Store) ListPRReviews

func (st *Store) ListPRReviews(prID int) []*PullRequestReview

ListPRReviews returns all reviews for a pull request.

func (*Store) ListPackageFiles

func (st *Store) ListPackageFiles(versionID int) []*PackageFile

ListPackageFiles returns files for a version.

func (*Store) ListPackageVersions

func (st *Store) ListPackageVersions(pkgID int, includeDeleted bool) []*PackageVersion

ListPackageVersions returns versions for a package, newest first, omitting deleted ones unless includeDeleted.

func (*Store) ListPackages

func (st *Store) ListPackages(ownerKey string) []*Package

ListPackages returns packages for an owner, newest first.

func (*Store) ListPendingOrgInvitations

func (st *Store) ListPendingOrgInvitations(orgLogin string) []*OrgInvitation

ListPendingOrgInvitations returns the org's live invitations sorted by ID.

func (*Store) ListPendingOrgInvitationsForTeam

func (st *Store) ListPendingOrgInvitationsForTeam(orgLogin string, teamID int) []*OrgInvitation

ListPendingOrgInvitationsForTeam returns the org's live invitations carrying the given team, sorted by ID.

func (*Store) ListPendingRepoInvitations

func (st *Store) ListPendingRepoInvitations(repoKey string) []*RepoInvitation

ListPendingRepoInvitations returns a repository's pending invitations, sorted by ID.

func (*Store) ListPinnedDiscussions

func (st *Store) ListPinnedDiscussions(repoID int) []int

ListPinnedDiscussions returns the repo's ordered pinned discussion IDs (detached, STORE-021), dropping any whose discussion was deleted.

func (*Store) ListPinnedIssues

func (st *Store) ListPinnedIssues(repoID int) []*Issue

ListPinnedIssues returns a repository's pinned issues, oldest pin first (GitHub's order).

func (*Store) ListPinnedRepos

func (st *Store) ListPinnedRepos(userID int) []string

ListPinnedRepos returns a detached copy of the user's ordered pinned-repo full names, or an empty slice.

func (*Store) ListPrivateRegistries

func (st *Store) ListPrivateRegistries(orgLogin string) []*PrivateRegistryConfiguration

ListPrivateRegistries returns the org's registries sorted by name.

func (*Store) ListProjectCards

func (st *Store) ListProjectCards(columnID int) []*ProjectCard

ListProjectCards returns cards in a column in visual order.

func (*Store) ListProjectClassicsForOwner

func (st *Store) ListProjectClassicsForOwner(ownerType, ownerLogin string) []*ProjectClassic

ListProjectClassicsForOwner returns all account-owned projects under a user or organization login, newest first.

func (*Store) ListProjectClassicsForRepo

func (st *Store) ListProjectClassicsForRepo(repoKey string) []*ProjectClassic

ListProjectClassicsForRepo returns all projects in a repo, newest first.

func (*Store) ListProjectColumns

func (st *Store) ListProjectColumns(projectID int) []*ProjectColumn

ListProjectColumns returns columns for a project in visual order.

func (*Store) ListPublicGists

func (st *Store) ListPublicGists(since time.Time) []*Gist

ListPublicGists returns all public gists, newest first.

func (*Store) ListPublicOrgMembers

func (st *Store) ListPublicOrgMembers(orgLogin string) []*User

ListPublicOrgMembers returns active members who publicized their membership.

func (*Store) ListPublicOrgsByUser

func (st *Store) ListPublicOrgsByUser(userID int) []*Org

ListPublicOrgsByUser returns only active memberships the user has publicized, the visibility contract behind GET /users/{username}/orgs (unlike /user/orgs, which includes concealed memberships via ListOrgsByUser).

func (*Store) ListPublicRepos

func (st *Store) ListPublicRepos(since int) []*Repo

ListPublicRepos returns public repositories with an ID greater than since, ordered by ID ascending — the contract of GET /repositories.

func (*Store) ListPullRequestEvents

func (st *Store) ListPullRequestEvents(repoID, prID int) []*IssueEvent

ListPullRequestEvents returns a PR's issue events, ordered by event ID.

func (*Store) ListPullRequestReviews

func (st *Store) ListPullRequestReviews(repoKey string, pullNumber int) []*PullRequestReview

ListPullRequestReviews returns all reviews for a repo/PR number.

func (*Store) ListPullRequestStacks

func (st *Store) ListPullRequestStacks(repoID int) []*PullRequestStack

func (*Store) ListPullRequests

func (st *Store) ListPullRequests(repoID int, state string) []*PullRequest

ListPullRequests returns pull requests for a repository, optionally filtered by state. State filter: "OPEN", "CLOSED" (includes MERGED), "MERGED", "" or "all" returns all.

func (*Store) ListRepoActivity

func (st *Store) ListRepoActivity(repoID int) []*RepoActivity

ListRepoActivity returns a repository's recorded ref updates, oldest first.

func (st *Store) ListRepoAutolinks(repoKey string) []*RepoAutolink

ListRepoAutolinks returns all autolinks for a repository, sorted by ID.

func (*Store) ListRepoCloneTraffic

func (st *Store) ListRepoCloneTraffic(repoID int, since time.Time) []*RepoTrafficBucket

ListRepoCloneTraffic returns a repository's clone buckets on or after the given day, oldest first.

func (*Store) ListRepoCollaborators

func (st *Store) ListRepoCollaborators(owner, name string) map[string]string

ListRepoCollaborators returns the collaborators of a repo.

func (*Store) ListRepoDeployKeys

func (st *Store) ListRepoDeployKeys(repoID int) []*RepoDeployKey

ListRepoDeployKeys returns deploy keys for a repo, sorted by ID.

func (*Store) ListRepoFullNamesByOwner

func (st *Store) ListRepoFullNamesByOwner(owner string) []string

ListRepoFullNamesByOwner returns the sorted full names of every repo owned by the login. Backs the CodeQL variant-analysis repository_owners selector.

func (*Store) ListRepoIssueComments

func (st *Store) ListRepoIssueComments(repoID int) []*Comment

ListRepoIssueComments returns all of a repo's issue comments, oldest first.

func (*Store) ListRepoIssueEvents

func (st *Store) ListRepoIssueEvents(repoID int) []*IssueEvent

func (*Store) ListRepoRulesetSuites

func (st *Store) ListRepoRulesetSuites(repoID int) []RulesetSuite

ListRepoRulesetSuites returns rule suites for a repository, newest first.

func (*Store) ListRepoStargazers

func (st *Store) ListRepoStargazers(owner, name string) []int

ListRepoStargazers returns the user IDs who starred the repo, sorted ascending.

func (*Store) ListRepoSubscribers

func (st *Store) ListRepoSubscribers(repoID int) []*User

ListRepoSubscribers returns the users holding a watch subscription on the repository, ordered by user ID.

func (*Store) ListRepoSubscriptionsForUser

func (st *Store) ListRepoSubscriptionsForUser(userID int) []*Repo

ListRepoSubscriptionsForUser returns the repositories subscribed by userID.

func (*Store) ListReposByOwner

func (st *Store) ListReposByOwner(login string) []*Repo

func (*Store) ListReposForAuthUser

func (st *Store) ListReposForAuthUser(user *User, opts RepoListOptions) []*Repo

ListReposForAuthUser returns repos the authenticated user can access. Affiliation controls owner/collaborator/org-member inclusion.

func (*Store) ListReposForOrg

func (st *Store) ListReposForOrg(org string, opts RepoListOptions) []*Repo

ListReposForOrg returns repos owned by an organization, filtered/sorted/paged.

func (*Store) ListReposForUser

func (st *Store) ListReposForUser(user *User, opts RepoListOptions) []*Repo

ListReposForUser returns public repos owned by a user, filtered/sorted/paged.

func (*Store) ListRepositoryMigrations

func (st *Store) ListRepositoryMigrations(ownerOrgID int) []*RepositoryMigration

ListRepositoryMigrations returns detached snapshots of one organization's repository migrations, oldest first.

func (*Store) ListRepositoryMigrationsForOrgMigration

func (st *Store) ListRepositoryMigrationsForOrgMigration(orgMigrationID int) []*RepositoryMigration

ListRepositoryMigrationsForOrgMigration returns detached snapshots of the repository migrations one organization migration fanned out into.

func (*Store) ListRulesForBranch

func (st *Store) ListRulesForBranch(repo *Repo, branch string) []map[string]interface{}

ListRulesForBranch evaluates active branch-targeting rulesets against a branch and returns the flattened rule objects GitHub's "list rules for a branch" endpoint produces.

func (*Store) ListRulesetsForRepository

func (st *Store) ListRulesetsForRepository(repo *Repo, includeParents bool) []*Ruleset

ListRulesetsForRepository returns repository rulesets and, when requested, organization rulesets that apply to the repository, sorted by ID.

func (*Store) ListSecretScanningAlerts

func (st *Store) ListSecretScanningAlerts(repoKey, state, secretType, resolution, sortField, direction string) []*SecretScanningAlert

ListSecretScanningAlerts returns repo alerts filtered/sorted per GitHub's list endpoint.

func (*Store) ListSecretScanningAlertsByOrg

func (st *Store) ListSecretScanningAlertsByOrg(orgID int, state, secretType, resolution, sortField, direction string) []*SecretScanningAlert

ListSecretScanningAlertsByOrg returns alerts for the org's repos, filtered and sorted per GitHub's org-alerts query parameters. Unknown filter values yield no matches rather than a 400, matching GitHub's lenient behavior.

func (*Store) ListSecretScanningAlertsByUser

func (st *Store) ListSecretScanningAlertsByUser(userID int) []*SecretScanningAlert

ListSecretScanningAlertsByUser returns alerts for the user's repos, newest first.

func (*Store) ListSecretScanningCustomPatterns

func (st *Store) ListSecretScanningCustomPatterns(scope string) []*SecretScanningCustomPattern

func (*Store) ListSecretScanningPatternConfigurations

func (st *Store) ListSecretScanningPatternConfigurations(orgLogin string) map[string]interface{}

ListSecretScanningPatternConfigurations returns the org's pattern overrides for GitHub's pattern-configurations endpoint, reflecting stored push-protection settings and computing alert totals from real alerts.

func (*Store) ListSecurityAdvisories

func (st *Store) ListSecurityAdvisories(repoID int) []*SecurityAdvisory

ListSecurityAdvisories returns a repo's advisories, newest first.

func (*Store) ListSecurityReviewRequests

func (st *Store) ListSecurityReviewRequests(repoKey, orgLogin, kind string) []*SecurityReviewRequest

func (*Store) ListStarredGists

func (st *Store) ListStarredGists(userID int) []*Gist

ListStarredGists returns gists starred by the user.

func (*Store) ListStarredRepos

func (st *Store) ListStarredRepos(userID int) []string

ListStarredRepos returns the full names of repos starred by userID.

func (*Store) ListSubIssues

func (st *Store) ListSubIssues(parentID int) []int

ListSubIssues returns parent's sub-issue IDs in priority order.

func (*Store) ListTeamMembers

func (st *Store) ListTeamMembers(orgLogin, slug string) []*User

ListTeamMembers returns the users who are members of a team.

func (*Store) ListTeamRepos

func (st *Store) ListTeamRepos(orgLogin, slug string) []*Repo

ListTeamRepos returns the repositories linked to a team.

func (*Store) ListTeams

func (st *Store) ListTeams(orgLogin string) []*Team

ListTeams returns all teams in an organization.

func (*Store) ListTeamsByUser

func (st *Store) ListTeamsByUser(userID int) []*Team

ListTeamsByUser returns every team across all orgs the user is a member of.

func (*Store) ListTeamsForRepo

func (st *Store) ListTeamsForRepo(fullName string) []*Team

ListTeamsForRepo returns the org teams granted access to the repository, ordered by team ID.

func (*Store) ListTeamsWithOrgRole

func (st *Store) ListTeamsWithOrgRole(orgLogin string, roleID int) []*Team

ListTeamsWithOrgRole returns the org's existing teams holding the role, sorted by team ID. Assignments to since-deleted teams are skipped.

func (*Store) ListUnfinishedMigrations

func (st *Store) ListUnfinishedMigrations() []UnfinishedMigration

ListUnfinishedMigrations returns every non-terminal migration, oldest first within each family. Called at boot to resume a previous process's work.

func (*Store) ListUnfinishedOrganizationMigrations

func (st *Store) ListUnfinishedOrganizationMigrations() []int

ListUnfinishedOrganizationMigrations returns the ids of every organization migration not in a terminal state, ascending.

func (*Store) ListUnfinishedRepositoryMigrations

func (st *Store) ListUnfinishedRepositoryMigrations() []int

ListUnfinishedRepositoryMigrations returns the ids of every repository migration not in a terminal state, ascending.

func (*Store) ListUserBlocks

func (st *Store) ListUserBlocks(userID int) []*User

ListUserBlocks returns users blocked by userID.

func (*Store) ListUserEmails

func (st *Store) ListUserEmails(userID int) []UserEmail

ListUserEmails returns the user's email addresses, primary first.

func (*Store) ListUserFilteredIssues

func (st *Store) ListUserFilteredIssues(user *User, filter string) []IssueWithRepo

ListUserFilteredIssues returns issues visible through GET /user/issues for the given filter. Repository read access is checked by the caller.

func (*Store) ListUserFilteredPulls

func (st *Store) ListUserFilteredPulls(user *User, filter string) []PullWithRepo

ListUserFilteredPulls is the pull-request analogue of ListUserFilteredIssues. GitHub's issues endpoints return pull requests too (every PR is an issue), so the cross-repository issue listings merge these rows in. The `filter` values carry the same meaning as for issues.

func (*Store) ListUserLists

func (st *Store) ListUserLists(userID int) []*UserList

ListUserLists returns the account's lists in creation order.

func (*Store) ListUserMigrations

func (st *Store) ListUserMigrations(userID int) []*UserMigration

ListUserMigrations returns a user's migrations, newest first.

func (*Store) ListUserRepoInvitations

func (st *Store) ListUserRepoInvitations(user *User) []*RepoInvitation

ListUserRepoInvitations returns pending invitations addressed to the user.

func (*Store) ListUserSSHSigningKeys

func (st *Store) ListUserSSHSigningKeys(userID int) []map[string]interface{}

ListUserSSHSigningKeys returns SSH signing keys for a user.

func (*Store) ListUserSocialAccounts

func (st *Store) ListUserSocialAccounts(userID int) []map[string]interface{}

ListUserSocialAccounts returns social accounts for a user.

func (*Store) ListUsers

func (st *Store) ListUsers() []*User

ListUsers returns all users.

func (*Store) ListUsersWithOrgRole

func (st *Store) ListUsersWithOrgRole(orgLogin string, roleID int) map[int]string

ListUsersWithOrgRole maps each user holding the role to its assignment kind: "direct", "indirect" (via a team), or "mixed". Users without an active membership are skipped.

func (*Store) ListVerifiableDomains

func (st *Store) ListVerifiableDomains(ownerType string, ownerID int) []*VerifiableDomain

ListVerifiableDomains returns detached snapshots of one owner's domains, ordered by database id.

func (*Store) ListWikiPageRevisions

func (st *Store) ListWikiPageRevisions(repoKey, slug string) []*WikiPageRevision

ListWikiPageRevisions returns a page's history newest-first (detached). It starts at the commit the file was last created in, so a deleted-and-rewritten page reads as new.

func (*Store) ListWikiPages

func (st *Store) ListWikiPages(repoKey string) []*WikiPage

ListWikiPages returns a repository's wiki pages: "Home" first (GitHub's landing page), the rest alphabetically.

func (*Store) ListWorkflowFiles

func (st *Store) ListWorkflowFiles(repoFullName string) []*WorkflowFile

ListWorkflowFiles returns the repo's WorkflowFiles ordered by ID for stable pagination.

func (*Store) LockIssue

func (st *Store) LockIssue(repoKey string, issueNumber int, lockReason string) bool

LockIssue locks an issue, optionally recording a lock reason. Returns true when the issue exists.

func (*Store) LoginFollows

func (st *Store) LoginFollows(follower, target string) bool

LoginFollows reports whether follower follows target. Unlike IsUserFollowing it takes logins, so it answers for organization targets too.

func (*Store) LookupAgentByClientID

func (st *Store) LookupAgentByClientID(clientID string) *Agent

LookupAgentByClientID returns the agent whose Authorization.ClientID matches, or nil.

func (*Store) LookupCommentByNodeID

func (st *Store) LookupCommentByNodeID(nodeID string) *Comment

LookupCommentByNodeID returns the comment with the given GraphQL node ID, or nil.

func (*Store) LookupDependabotAlertByNodeID

func (st *Store) LookupDependabotAlertByNodeID(nodeID string) *DependabotAlert

LookupDependabotAlertByNodeID returns a detached snapshot of the alert. Not spelt Find*ByNodeID (which signals a LIVE row) because the dismissal mutation reads pre-change state to decide the webhook action; a live row would report post-change state instead.

func (*Store) LookupInstallationToken

func (st *Store) LookupInstallationToken(tokenStr string) (*InstallationToken, *Installation)

LookupInstallationToken returns the token and its installation, or nil if not found/expired.

func (*Store) LookupOrgActionsPermissionsLocked

func (st *Store) LookupOrgActionsPermissionsLocked(orgLogin string) *OrgActionsPermissions

LookupOrgActionsPermissionsLocked returns an org's stored Actions settings without creating them; safe under a read lock. Returns nil when the org has never been configured.

func (*Store) LookupResolvedDependency

func (st *Store) LookupResolvedDependency(repoID int, ref, manifestPath, ecosystem, packageName string) (ResolvedDependency, bool)

LookupResolvedDependency finds one dependency by manifest path, ecosystem and package name, reporting false when the repository no longer declares it. The false is load-bearing: a Dependabot alert outlives the dependency it was raised on, and a zero value would misread as "runtime, direct".

func (*Store) LookupToken

func (st *Store) LookupToken(tokenStr string) (*Token, *User)

LookupToken returns the token and associated user, or nil if not found.

func (*Store) LookupUserByEmail

func (st *Store) LookupUserByEmail(email string) *User

LookupUserByEmail returns the user whose email matches case-insensitively, or nil. Git commit signatures carry emails, not logins, so this resolves authors.

func (*Store) LookupUserByLogin

func (st *Store) LookupUserByLogin(login string) *User

LookupUserByLogin returns the user for a login, or nil. The login resolves case-insensitively (GitHub parity); the result carries its canonical casing.

func (*Store) LookupUserBySSHKey

func (st *Store) LookupUserBySSHKey(key ssh.PublicKey) *User

LookupUserBySSHKey resolves a registered account SSH auth key, comparing parsed SSH wire encodings so comment/spacing differences in the key text cannot forge a different identity. Keys whose text never parsed carry no cached form and cannot match.

func (*Store) LookupUserToServerToken

func (st *Store) LookupUserToServerToken(tokenStr string) (*UserToServerToken, *User)

LookupUserToServerToken returns the token and bearing user, or nil if not found or expired.

func (*Store) MarkDiscussionCommentAsAnswer

func (st *Store) MarkDiscussionCommentAsAnswer(id int) bool

MarkDiscussionCommentAsAnswer marks a comment as the answer. The unmark of any prior answer and the new answer commit in one transaction, so a crash cannot leave zero or two answers (STORE-001/002).

func (*Store) MarkJobCompletedLocked

func (st *Store) MarkJobCompletedLocked(job *Job)

MarkJobCompletedLocked stamps a job's terminal transition and releases the broker's busy bookkeeping for its non-ephemeral agent. Callers hold the write lock.

func (*Store) MarkLoginSessionSudo

func (st *Store) MarkLoginSessionSudo(id string, now time.Time, withSecondFactor bool) (bool, error)

MarkLoginSessionSudo records that the session just satisfied a proof-of-presence challenge, reporting whether such a session existed (an expired one is not resurrected). It writes through PutLoginSession so the grant is durable and survives a replica switch.

func (*Store) MarkNotificationsRead

func (st *Store) MarkNotificationsRead(userID int, at time.Time, repoScope string)

MarkNotificationsRead sets the global last-read timestamp for the user.

func (*Store) MarkThreadDone

func (st *Store) MarkThreadDone(userID int, threadID string)

MarkThreadDone dismisses a thread. Done threads are retained (not deleted) so the Done view can list them.

func (*Store) MarkThreadRead

func (st *Store) MarkThreadRead(userID int, threadID string, at time.Time)

MarkThreadRead records a thread as read for the user.

func (*Store) MergeQueuePullRequests

func (st *Store) MergeQueuePullRequests(repoID int, baseRef string) []*PullRequest

MergeQueuePullRequests returns the PRs queued against one base branch, in queue order.

func (*Store) MigrationRepoExportData

func (st *Store) MigrationRepoExportData(repoID int) map[string]interface{}

MigrationRepoExportData gathers lightweight metadata for a migration archive.

func (*Store) ModifyOrgCodespacesAccessUsers

func (st *Store) ModifyOrgCodespacesAccessUsers(orgLogin string, add bool, usernames []string) bool

ModifyOrgCodespacesAccessUsers adds or removes usernames from the org's selected-members list. Returns false when visibility is not selected_members.

func (*Store) MoveBranchProtectionExtras

func (st *Store) MoveBranchProtectionExtras(repoID int, oldPattern, newPattern string)

MoveBranchProtectionExtras rekeys a rule's GraphQL-only members from one pattern to another (a pattern edit or branch rename).

func (*Store) MoveProjectCard

func (st *Store) MoveProjectCard(card *ProjectCard, targetColumnID int, position string) error

MoveProjectCard moves a card to a column and/or a new position within it.

func (*Store) MoveProjectColumn

func (st *Store) MoveProjectColumn(col *ProjectColumn, position string) error

MoveProjectColumn repositions a column within its project.

func (*Store) NewLabelsAssignable

func (st *Store) NewLabelsAssignable(repoID int, current, requested []int) bool

NewLabelsAssignable reports whether every requested label not already on a subject belongs to the repository and remains available for assignment.

func (*Store) NotificationDeliveryRestriction

func (st *Store) NotificationDeliveryRestriction() (bool, []string)

NotificationDeliveryRestriction reports whether the instance's enterprise restricts notification delivery to its verified domains, and which those are. A restriction with no verified domain restricts everything, as on GitHub.

func (*Store) NotificationEmailDeliveryAllowed

func (st *Store) NotificationEmailDeliveryAllowed(userID int) (allowed, restricted bool)

NotificationEmailDeliveryAllowed reports whether email delivery to this account is permitted and whether a restriction is in force. Under the restriction only an address in a verified domain is deliverable — a property of the address, not the account's authority, so an enterprise owner outside the domains is undeliverable too.

func (*Store) NotificationRowsFor

func (st *Store) NotificationRowsFor(user *User, opts NotificationListOptions, canRead func(*Repo) bool) []NotificationThreadRow

NotificationRowsFor applies a request-credential reach check after the read lock releases. A nil predicate exposes no rows, so a caller cannot request a credential-blind view.

func (*Store) OpenSealedSecret

func (st *Store) OpenSealedSecret(encryptedValue string) (string, error)

OpenSealedSecret decrypts a base64 libsodium sealed-box ciphertext produced against the server's Actions public key.

func (*Store) OrgActionsUsageLines

func (st *Store) OrgActionsUsageLines(orgLogin string, year, month, day int) []ActionsUsageLine

OrgActionsUsageLines bills every completed job per started minute, rounded up, as GitHub meters Actions, over current runs plus archived attempts. Zero month/day mean "whole year"/"whole month".

func (*Store) OrgByLoginLocked

func (st *Store) OrgByLoginLocked(login string) *Org

OrgByLoginLocked resolves an org login case-insensitively to the live org row, or nil. Caller holds st.Mu.

func (*Store) OrgCodespacesInvalidUsers

func (st *Store) OrgCodespacesInvalidUsers(org *Org, usernames []string) []string

OrgCodespacesInvalidUsers returns usernames that are neither active org members nor collaborators on any of the org's repositories.

func (*Store) OrgMigrationLocksRepo

func (st *Store) OrgMigrationLocksRepo(id int, repoName string) bool

OrgMigrationLocksRepo reports whether an org migration still locks a repo. It acquires st.Mu itself; the name avoids the "…Locked" suffix (caller-holds-the-lock helpers) to prevent a self-deadlock on the non-reentrant mutex.

func (*Store) OrgOwnsCustomProperty

func (st *Store) OrgOwnsCustomProperty(orgLogin, name string) bool

OrgOwnsCustomProperty reports whether the definition is the org's own rather than inherited from the enterprise schema. Editing an enterprise-level definition is the enterprise owner's call, not the org's.

func (*Store) PATIdentityByTokenValue

func (st *Store) PATIdentityByTokenValue(value string) (int, string, bool)

PATIdentityByTokenValue resolves a fine-grained PAT value to its token ID and name.

func (*Store) PRCreationBypassUsers

func (st *Store) PRCreationBypassUsers(repoKey string) []*User

func (*Store) ParseAndVerifyAppJWT

func (st *Store) ParseAndVerifyAppJWT(tokenStr string) (*App, error)

ParseAndVerifyAppJWT validates an RS256 JWT against stored app keys.

func (*Store) PendingIssueSuggestion

func (st *Store) PendingIssueSuggestion(repoFullName string, issueID, suggestionID int) *IssueSuggestion

PendingIssueSuggestion returns the issue's pending suggestion with this id, or nil when it is absent or already resolved.

func (*Store) PendingReviewForAuthor

func (st *Store) PendingReviewForAuthor(prID, authorID int) *PullRequestReview

PendingReviewForAuthor returns the author's still-pending review on a PR (at most one), or nil.

func (*Store) PerformIssueSuggestion

func (st *Store) PerformIssueSuggestion(repo *Repo, issue *Issue, suggestion *IssueSuggestion, userID int) (*IssueEvent, error)

PerformIssueSuggestion applies one pending suggestion and returns the issue event it recorded. It does not touch the suggestion's own state — that is ResolveIssueSuggestion's job — so the two steps stay separately committable.

func (*Store) PersistCodespaceSecretScopeLocked

func (st *Store) PersistCodespaceSecretScopeLocked(scope string)

PersistCodespaceSecretScopeLocked writes a whole secret scope through; the scope map is the bucket row. Caller holds st.Mu.

func (*Store) PersistEnterpriseSettings

func (st *Store) PersistEnterpriseSettings()

func (*Store) PersistEnterpriseTeam

func (st *Store) PersistEnterpriseTeam(t *EnterpriseTeam)

func (*Store) PersistHostedRunnerCustomImageLocked

func (st *Store) PersistHostedRunnerCustomImageLocked(img *HostedRunnerCustomImage)

func (*Store) PersistHostedRunnerLocked

func (st *Store) PersistHostedRunnerLocked(hr *HostedRunner)

func (*Store) PersistPrivateRegistries

func (st *Store) PersistPrivateRegistries(orgLogin string)

PersistPrivateRegistries saves the org's registry map via the persist shape, which serializes EncryptedValue.

func (*Store) PersistTokenLocked

func (st *Store) PersistTokenLocked(token *Token)

func (*Store) PersistWorkflowAttemptsRecord

func (st *Store) PersistWorkflowAttemptsRecord(runID int)

func (*Store) PersistWorkflowRecord

func (st *Store) PersistWorkflowRecord(wf *Workflow)

func (*Store) PersistenceReady

func (st *Store) PersistenceReady(ctx context.Context) error

func (*Store) PinIssue

func (st *Store) PinIssue(issueID, actorID int) error

PinIssue pins an issue on behalf of actorID; already-pinned is a no-op. The cap check and pin happen under one lock so two concurrent pins cannot both squeeze under the cap.

func (*Store) PinIssueComment

func (st *Store) PinIssueComment(commentID int) bool

PinIssueComment marks a comment pinned. Returns true when it exists.

func (*Store) PlanScopeForJobLocked

func (st *Store) PlanScopeForJobLocked(job *Job) planScope

PlanScopeForJobLocked answers a job's plan scope: the dispatch-time record first, else the job's message. Callers hold the store lock.

func (*Store) PrimaryEnterpriseSlug

func (st *Store) PrimaryEnterpriseSlug() string

PrimaryEnterpriseSlug names the instance's own enterprise account (configured via BLEEPHUB_ENTERPRISE_SLUG, set once at boot): the enterprise every account on the instance belongs to.

func (*Store) PromoteCustomProperty

func (st *Store) PromoteCustomProperty(orgLogin, name string) *CustomProperty

PromoteCustomProperty copies an org's property definition into the enterprise schema and returns the promoted definition, or nil when the org holds no such definition.

func (*Store) PruneEnvironmentPolicies

func (st *Store) PruneEnvironmentPolicies(envID int)

PruneEnvironmentPolicies drops all policies and protection rules for a deleted environment.

func (*Store) PublishCodespace

func (st *Store) PublishCodespace(id int, owner *User, name string, private bool) (*Codespace, error)

PublishCodespace creates a repository for an unpublished codespace and links them. The repo and codespace rows commit in one transaction (STORE-001/002): a crash between them would durably take the repo name yet leave the codespace permanently unpublishable.

func (*Store) PullRequestViewedFiles

func (st *Store) PullRequestViewedFiles(prID, reviewerID int) []string

PullRequestViewedFiles returns the paths a reviewer has marked viewed.

func (*Store) PurgeDeletedRepoBytes

func (st *Store) PurgeDeletedRepoBytes(fullName string, fallback PendingDeletion) error

PurgeDeletedRepoBytes destroys the git bytes of an already-unregistered repo and clears its deletion intent. Nothing can reach the repo now, so the object-store round trip needs no lock.

func (*Store) PutCodeQualityFinding

func (st *Store) PutCodeQualityFinding(finding *CodeQualityFinding)

PutCodeQualityFinding ingests a finding. Numbers are repository-scoped.

func (*Store) PutLoginSession

func (st *Store) PutLoginSession(id string, session *LoginSession) error

func (*Store) PutRepoImport

func (st *Store) PutRepoImport(imp *RepoImport)

PutRepoImport creates or replaces the repo's import record.

func (*Store) ReadAttestationBundle

func (st *Store) ReadAttestationBundle(ctx context.Context, a *Attestation) (json.RawMessage, error)

ReadAttestationBundle reads the Sigstore bundle bytes for an attestation.

func (*Store) ReadCodeQLDatabaseContent

func (st *Store) ReadCodeQLDatabaseContent(ctx context.Context, db *CodeQLDatabase) ([]byte, error)

ReadCodeQLDatabaseContent reads the archive bytes for a CodeQL database.

func (*Store) ReadCodeQLVariantAnalysisQueryPack

func (st *Store) ReadCodeQLVariantAnalysisQueryPack(ctx context.Context, va *CodeQLVariantAnalysis) ([]byte, error)

ReadCodeQLVariantAnalysisQueryPack reads the uploaded query-pack tarball for a CodeQL variant analysis.

func (*Store) ReapExpiredLoginSessions

func (st *Store) ReapExpiredLoginSessions(now time.Time) error

ReapExpiredLoginSessions bounds the in-memory index and durable bucket, reaping sessions past expiry and those orphaned by user deletion (whose durable rows would otherwise linger until natural expiry). Deletions are idempotent, so it is replica-safe. The caller supplies time for determinism.

func (*Store) ReapOrphanObjects

func (st *Store) ReapOrphanObjects(ctx context.Context, opts ReapOptions) (ReapReport, error)

ReapOrphanObjects performs one reaper pass. It is a no-op unless the object store is S3-backed.

func (*Store) ReconcileAllOrgInvitations

func (st *Store) ReconcileAllOrgInvitations(now time.Time)

ReconcileAllOrgInvitations runs the invitation state machine across every org on the background dispatcher tick, so a GET never takes the write lock or does a durable delete on a read (STORE-034).

func (*Store) RecordAPIRequest

func (st *Store) RecordAPIRequest(rec *APIRequestRecord)

RecordAPIRequest appends an attributed request record and persists it, with FIFO eviction at the cap.

func (*Store) RecordAuditEntry

func (st *Store) RecordAuditEntry(action, actor, org string, data map[string]interface{}) *AuditEntry

RecordAuditEntry appends an audit-log entry and returns it. Both the REST handlers and GraphQL resolvers write through it, so either surface's actions land in the same log with the same shape.

func (*Store) RecordIssueEvent

func (st *Store) RecordIssueEvent(repoID, issueID, actorID int, event string, payload map[string]interface{}) *IssueEvent

RecordIssueEvent records a public issue event. payload may carry optional related IDs under GitHub's keys: label_id, assignee_id, assigner_id, milestone_id, comment_id, commit_id, commit_url.

func (*Store) RecordIssueOrPREvent

func (st *Store) RecordIssueOrPREvent(repoID, number, actorID int, event string, payload map[string]interface{}) *IssueEvent

RecordIssueOrPREvent records a timeline event against whichever of the issue or PR in repoID carries `number`, stamping the correct ParentType. Shared issue+PR endpoints (lock/unlock) must use this, not RecordIssueEvent: a PR event parented to "issue" is dropped from the PR timeline and can collide into an unrelated issue's.

func (*Store) RecordPullRequestEvent

func (st *Store) RecordPullRequestEvent(repoID, prID, actorID int, event, commitID string, requestedReviewerID int) *IssueEvent

RecordPullRequestEvent records a public issue event attached to a PR.

func (*Store) RecordPullRequestMergeAsync

func (st *Store) RecordPullRequestMergeAsync(rec *PullRequestMergeAsync)

RecordPullRequestMergeAsync stores an async merge result keyed by its UUID.

func (*Store) RecordRepoActivity

func (st *Store) RecordRepoActivity(repoID int, ref, before, after string, actorID int, activityType string) *RepoActivity

func (*Store) RecordRepoClone

func (st *Store) RecordRepoClone(repoID int, actor string)

RecordRepoClone counts one clone of a repository by the given actor in today's UTC day bucket.

func (*Store) RecordRepositoryMigrationWarning

func (st *Store) RecordRepositoryMigrationWarning(id int, warning string) bool

RecordRepositoryMigrationWarning appends one recoverable problem to a migration's log and bumps its warning count.

func (*Store) RecordRulesetSuite

func (st *Store) RecordRulesetSuite(repo *Repo, actor *User, ref, beforeSHA, afterSHA, result string, evaluationResult *string, evaluations []RulesetEvaluation, pushedAt time.Time) *RulesetSuite

RecordRulesetSuite persists one completed evaluation. pushedAt is supplied by the caller so tests and importers never need to consult the wall clock.

func (*Store) RedactLogBytesLocked

func (st *Store) RedactLogBytesLocked(planID string, data []byte) []byte

func (*Store) RedactLogLinesLocked

func (st *Store) RedactLogLinesLocked(planID string, lines []string) []string

func (*Store) RedirectedRepo

func (st *Store) RedirectedRepo(fullName string) *Repo

RedirectedRepo resolves a repository by a name it used to answer to, returning a detached snapshot (STORE-021) or nil. A live name wins over its own redirect, so this reports a move only for a name nothing occupies.

func (*Store) RefreshCodespaceState

func (st *Store) RefreshCodespaceState(id int) string

RefreshCodespaceState queries Docker for a codespace's current state.

func (*Store) RefreshFromPersistenceBeforeApply

func (st *Store) RefreshFromPersistenceBeforeApply(force bool, beforeApply func()) error

func (*Store) RefreshFromPersistenceIfStale

func (st *Store) RefreshFromPersistenceIfStale() error

RefreshFromPersistenceIfStale propagates writes made through another dqlite connection. Exclusively-owned local SQLite has no peer and skips the query.

func (*Store) RegenerateEnterpriseIdentityProviderRecoveryCodes

func (st *Store) RegenerateEnterpriseIdentityProviderRecoveryCodes(enterpriseID int, codes []string) *EnterpriseSAMLIdentityProvider

RegenerateEnterpriseIdentityProviderRecoveryCodes replaces the binding's recovery codes and returns a detached snapshot, or nil when the enterprise has no identity provider.

func (*Store) RegenerateRecoveryCodes

func (st *Store) RegenerateRecoveryCodes(userID int, code string, now time.Time, disallowed []TwoFactorMethod) ([]string, TwoFactorStatus, AccountSecurityResult)

RegenerateRecoveryCodes replaces the whole set, invalidating every previous code, and returns the new codes once. Costs a valid second factor.

func (*Store) RegenerateVerifiableDomainToken

func (st *Store) RegenerateVerifiableDomainToken(id int) *VerifiableDomain

RegenerateVerifiableDomainToken replaces the token and restarts its expiry, leaving verified/approved status intact — the recovery path from an expired token.

func (*Store) RegisterDispatchedJobLocked

func (st *Store) RegisterDispatchedJobLocked(job *Job, msg map[string]interface{}, repo string)

RegisterDispatchedJobLocked indexes a dispatched job and records its plan scope. msg is the pre-marshal job message. Callers hold the write lock.

func (*Store) RegisterJobLogMasksLocked

func (st *Store) RegisterJobLogMasksLocked(planID string, message map[string]interface{})

RegisterJobLogMasksLocked records every secret variable in a job message: a server-side backstop so uploaded logs stay masked even against a buggy or hostile runner. Caller holds Store.Mu.

func (*Store) RegisterLFSObject

func (st *Store) RegisterLFSObject(repoKey, oid string, size int64)

RegisterLFSObject records that a repository holds an LFS object of the given size. Idempotent: a second repository adds a membership row and shares the bytes.

func (*Store) RegisterManifestCode

func (st *Store) RegisterManifestCode(appID int) string

RegisterManifestCode creates a one-time-use code that maps to an app ID.

func (*Store) RegisterWorkflowFile

func (st *Store) RegisterWorkflowFile(repoFullName, path, name, yamlBody, source string) *WorkflowFile

RegisterWorkflowFile creates or updates the WorkflowFile keyed by (repo, path). The latest call wins on YAML/Name; CreatedAt is preserved across updates.

func (*Store) RekeyFollowLogin

func (st *Store) RekeyFollowLogin(oldLogin, newLogin string)

RekeyFollowLogin re-points every follow edge that names oldLogin at newLogin after an account rename: the accounts oldLogin followed (its outgoing set) and its membership in every other account's following set (its followers). The graph is keyed by login on both sides, so a rename that only re-keyed the user row would strand both directions — the renamed account would show no followers or following, and its old followers' counts would name a login that no longer resolves. A pre-existing dangling edge to newLogin is dropped rather than turned into a self-follow.

func (*Store) RekeyWikiGitStorage

func (st *Store) RekeyWikiGitStorage(oldKey, newKey string)

RekeyWikiGitStorage follows a repository rename, dropping the wiki handle and projection so the next access reopens them against the new key. The bytes are moved by MoveWikiGitStorageBytes.

func (*Store) ReloadFromPersistence

func (st *Store) ReloadFromPersistence() error

ReloadFromPersistence discards durable in-memory mutations after a failed write, preserving process-local runner state as peer refreshes do.

func (*Store) RemoveCodespaceSecretSelectedRepo

func (st *Store) RemoveCodespaceSecretSelectedRepo(scope, name string, repoID int) bool

RemoveCodespaceSecretSelectedRepo removes a repository from a secret's selected list; an absent one is a no-op.

func (*Store) RemoveCopilotCodingAgentSelectedRepo

func (st *Store) RemoveCopilotCodingAgentSelectedRepo(orgLogin string, repoID int)

RemoveCopilotCodingAgentSelectedRepo drops a repository from the selected list.

func (*Store) RemoveEnterpriseCopilotCodingAgentOrgs

func (st *Store) RemoveEnterpriseCopilotCodingAgentOrgs(logins []string)

RemoveEnterpriseCopilotCodingAgentOrgs disables the Copilot coding agent for the given organization logins.

func (*Store) RemoveEnterpriseIdentityProvider

func (st *Store) RemoveEnterpriseIdentityProvider(enterpriseID int) *EnterpriseSAMLIdentityProvider

RemoveEnterpriseIdentityProvider clears the binding and returns a detached snapshot of what was removed, or nil when there was none.

func (*Store) RemoveEnterpriseMembership

func (st *Store) RemoveEnterpriseMembership(enterpriseID, userID int) bool

RemoveEnterpriseMembership drops a user's membership. It reports whether a membership was removed.

func (*Store) RemoveEnterpriseOIDCCustomProperty

func (st *Store) RemoveEnterpriseOIDCCustomProperty(name string) bool

RemoveEnterpriseOIDCCustomProperty removes an OIDC custom property inclusion. Returns true if it existed.

func (*Store) RemoveEnterpriseOrganization

func (st *Store) RemoveEnterpriseOrganization(enterpriseID, orgID int) bool

RemoveEnterpriseOrganization unbinds an organization from its enterprise.

func (*Store) RemoveEnterpriseTeamMember

func (st *Store) RemoveEnterpriseTeamMember(t *EnterpriseTeam, userID int) bool

RemoveEnterpriseTeamMember removes a user from the team. Returns true if the user was a member.

func (*Store) RemoveEnterpriseTeamOrg

func (st *Store) RemoveEnterpriseTeamOrg(t *EnterpriseTeam, orgLogin string) bool

RemoveEnterpriseTeamOrg removes an organization assignment. Returns true if it was assigned.

func (*Store) RemoveInstallationRepo

func (st *Store) RemoveInstallationRepo(id, repoID int) (bool, bool)

RemoveInstallationRepo removes a repo from a "selected" installation's allow-list. Returns (removed, ok).

func (*Store) RemoveIssueAssignees

func (st *Store) RemoveIssueAssignees(repoID int, issueNumber int, assigneeIDs []int, actorID int) bool

RemoveIssueAssignees removes assignees with an "unassigned" event each. Returns true when the issue exists.

func (*Store) RemoveIssueBlockedBy

func (st *Store) RemoveIssueBlockedBy(issueID, blockerID int) bool

RemoveIssueBlockedBy removes a blocked-by link. Returns false when the link does not exist.

func (*Store) RemoveIssueLabel

func (st *Store) RemoveIssueLabel(repoKey string, issueNumber int, labelName string) bool

RemoveIssueLabel removes a single label from an issue by name. Returns true when the issue and label exist.

func (*Store) RemoveMembership

func (st *Store) RemoveMembership(orgLogin string, userID int) bool

RemoveMembership removes a user's membership from an org.

func (*Store) RemoveOrgImmutableReleasesRepo

func (st *Store) RemoveOrgImmutableReleasesRepo(orgLogin string, repoID int)

RemoveOrgImmutableReleasesRepo removes one repository from the selected list.

func (*Store) RemoveOrgSelectedRepo

func (st *Store) RemoveOrgSelectedRepo(orgLogin string, repoID int)

RemoveOrgSelectedRepo drops a repository from the org's selected list.

func (*Store) RemoveOutsideCollaborator

func (st *Store) RemoveOutsideCollaborator(orgLogin, login string)

RemoveOutsideCollaborator strips the user's collaborator grants and pending invitations across every repository of the org.

func (*Store) RemovePullRequestAssignees

func (st *Store) RemovePullRequestAssignees(repoID, prNumber int, assigneeIDs []int, actorID int) bool

RemovePullRequestAssignees mirrors RemoveIssueAssignees for a pull request.

func (*Store) RemovePullRequestLabel

func (st *Store) RemovePullRequestLabel(repoID, prNumber, labelID, actorID int) bool

RemovePullRequestLabel removes a single label from a pull request by id, recording an unlabeled event. Returns true when the PR exists (whether or not the label was attached), false when it does not.

func (*Store) RemoveRepoCollaborator

func (st *Store) RemoveRepoCollaborator(owner, name, login string) bool

RemoveRepoCollaborator removes a collaborator, returning true if one was.

func (*Store) RemoveRequestedReviewers

func (st *Store) RemoveRequestedReviewers(repoKey string, pullNumber int, reviewerIDs []int, actorID int) bool

RemoveRequestedReviewers removes reviewer IDs from a PR and records a review_request_removed event per reviewer removed, attributed to actorID.

func (*Store) RemoveRequestedTeamReviewers

func (st *Store) RemoveRequestedTeamReviewers(repoKey string, pullNumber int, teamIDs []int) bool

func (*Store) RemoveSubIssue

func (st *Store) RemoveSubIssue(parentID, childID int) error

RemoveSubIssue unlinks child from parent.

func (*Store) RemoveTeamMembership

func (st *Store) RemoveTeamMembership(orgLogin, slug string, userID int) bool

RemoveTeamMembership removes a user from a team.

func (*Store) RemoveTeamRepo

func (st *Store) RemoveTeamRepo(orgLogin, slug, repoFullName string) bool

RemoveTeamRepo removes a repository from a team's access list.

func (*Store) RenameBranch

func (st *Store) RenameBranch(repoID int, branch, newName string) bool

RenameBranch renames a git branch in a repository.

func (*Store) RenameRepo

func (st *Store) RenameRepo(owner, name, newName string) bool

RenameRepo renames owner/name to owner/newName, moving its git bytes. The filesystem/in-memory move is constant-time under the store lock; the S3 object-prefix copy is slow, so it runs outside the lock behind a target reservation and a crash-recoverable intent (STORE-013).

func (*Store) RepairWikiHead

func (st *Store) RepairWikiHead(repoKey string)

RepairWikiHead points a wiki's HEAD at a branch that exists, so a clone checks something out. A client may push any branch name to a fresh wiki, so HEAD must follow the branch that actually landed rather than the one the server guessed.

func (*Store) ReplaceRepoImportIfCurrent

func (st *Store) ReplaceRepoImportIfCurrent(previous, next *RepoImport) bool

ReplaceRepoImportIfCurrent publishes a fetch outcome only while the record it started from is still on file, so a fetch finishing after a cancel or restart cannot resurrect the superseded record.

func (*Store) RepoBelongsToOrg

func (st *Store) RepoBelongsToOrg(repo *Repo, orgLogin string) bool

RepoBelongsToOrg reports whether the repository lives under the org's namespace.

func (*Store) RepoByNameLocked

func (st *Store) RepoByNameLocked(fullName string) *Repo

RepoByNameLocked resolves an "owner/name" key case-insensitively to the live repo row, or nil. Caller holds st.Mu.

func (*Store) RepoIDsOwnedBy

func (st *Store) RepoIDsOwnedBy(login string) map[int]bool

RepoIDsOwnedBy returns the IDs of every repository owned by login.

func (*Store) RepoImmutableReleasesState

func (st *Store) RepoImmutableReleasesState(repo *Repo) (enabled, enforcedByOwner bool)

RepoImmutableReleasesState reports whether immutable releases are enabled for the repo and whether the owner's policy enforces them.

func (*Store) RepoLockedForMigration

func (st *Store) RepoLockedForMigration(fullName string) bool

RepoLockedForMigration reports whether any migration still locks the repository with this full name. It stays locked until the last of any overlapping migrations releases it.

func (*Store) RepoSize

func (st *Store) RepoSize(fullName string) int64

RepoSize returns the git storage size in kilobytes (GitHub's `size` unit). In-memory and S3-backed storage report 0 (S3 until a list-objects sum lands).

func (*Store) RepoStargazersAt

func (st *Store) RepoStargazersAt(owner, name string) map[int]time.Time

RepoStargazersAt returns a detached copy of the stargazers with the instant each starred, backing starredAt. Empty when the repo is unknown.

func (*Store) ReprioritizeSubIssue

func (st *Store) ReprioritizeSubIssue(parentID, childID int, afterID, beforeID *int) error

ReprioritizeSubIssue moves child within parent's list, placing it after afterID or before beforeID.

func (*Store) RequestCVE

func (st *Store) RequestCVE(id int) bool

RequestCVE assigns a CVE ID to the advisory.

func (*Store) RequestCVEE

func (st *Store) RequestCVEE(id int) (bool, error)

func (*Store) RequestReviewers

func (st *Store) RequestReviewers(repoKey string, pullNumber int, reviewerIDs []int, actorID int) bool

RequestReviewers adds reviewer IDs to a PR and records a review_requested event per newly added reviewer, attributed to actorID.

func (*Store) RequestTeamReviewers

func (st *Store) RequestTeamReviewers(repoKey string, pullNumber int, teamIDs []int) bool

RequestTeamReviewers adds team review requests to a pull request. Team IDs, not slugs, so a later team rename preserves the request.

func (*Store) RequeueOrganizationMigration

func (st *Store) RequeueOrganizationMigration(id int) bool

RequeueOrganizationMigration returns a mid-flight organization migration to the queue so a restarted process picks it up again.

func (*Store) RequeueRepositoryMigration

func (st *Store) RequeueRepositoryMigration(id int) bool

RequeueRepositoryMigration returns an in-progress migration to the queue, so work a dead process left behind becomes claimable again.

func (*Store) ReserveCodespace

func (st *Store) ReserveCodespace(ownerLogin, repoKey, gitRef, location string, opts CodespaceCreateOptions) (*Codespace, string, func(), error)

func (*Store) ReserveGlobalID

func (st *Store) ReserveGlobalID(name string, next *int) int

ReserveGlobalID hands out the next durable global-entity ID. Routing through AllocateCounterValue makes the sequence agree across dqlite replicas (minting from in-memory NextX alone let two replicas mint the same ID and overwrite). NextX (max+1 on load) supplies the minimum. Caller holds st.Mu.

func (*Store) ReserveLogID

func (st *Store) ReserveLogID() int

ReserveLogID returns a durable object-store-safe log identifier, so a service replacement cannot reuse a logs/{id} key and overwrite a completed job's bytes.

func (*Store) ReserveMarketplaceHookID

func (st *Store) ReserveMarketplaceHookID() int

func (*Store) ReserveOrgCustomRoleIDLocked

func (st *Store) ReserveOrgCustomRoleIDLocked() int

func (*Store) ReserveRunID

func (st *Store) ReserveRunID() int

ReserveRunID hands out the next workflow run ID and persists the counter. Artifacts are keyed by run ID, so the sequence must never restart from 1 after a reload, or run #1 would inherit the prior epoch's artifacts.

func (*Store) ReserveWorkflowRunNumber

func (st *Store) ReserveWorkflowRunNumber(wf *Workflow) int

ReserveWorkflowRunNumber returns the next number for one workflow file. GitHub numbers each workflow independently; the durable counter also makes replicas agree.

func (*Store) ResetMigrationToPending

func (st *Store) ResetMigrationToPending(scope MigrationScope, id int) bool

ResetMigrationToPending returns an "exporting" migration to "pending". Run at boot: any migration still "exporting" is the remains of a process that died mid-export, and this makes its work claimable again.

func (*Store) ResolveCommentParent

func (st *Store) ResolveCommentParent(repoID, number int) (parentType string, parentID, parentNumber int, locked, found bool)

ResolveCommentParent resolves the issue or PR at repo + number, returning its kind, global ID, number, and locked flag in one read-locked pass. Read Locked here rather than off a shared pointer: SetIssueOrPRLock mutates it under the write lock.

func (*Store) ResolveDependabotAlert

func (st *Store) ResolveDependabotAlert(repoKey string, number int, state DependabotAlertState) (*DependabotAlert, bool)

ResolveDependabotAlert applies platform-driven transitions ("fixed" when the dependency is no longer vulnerable, "open" on reintroduction). Separate from the user-driven UpdateDependabotAlert (open ⇄ dismissed), which must keep refusing a client's own "fixed". Leaves a dismissed alert alone: a human decision outranks a re-derivation.

func (*Store) ResolveIssueSuggestion

func (st *Store) ResolveIssueSuggestion(repoKey string, issueID, suggestionID, userID int, state string, eventID *int) *IssueSuggestion

func (*Store) ResolveUserBySignature

func (st *Store) ResolveUserBySignature(name, email string) *User

ResolveUserBySignature maps a git signature to an account: email first (GitHub's rule), then name matching a login or profile display name. Returns nil when nothing matches.

func (*Store) ResolvedDependencyManifests

func (st *Store) ResolvedDependencyManifests(repoID int, ref, sha string) []ResolvedManifest

ResolvedDependencyManifests returns the repository's current dependency manifests for a ref (or exact commit when sha is given), newest snapshot per detector, manifests ordered by name and dependencies by purl. The ordering is load-bearing: the underlying maps would otherwise yield GraphQL cursors that move between requests.

func (*Store) RestorePackage

func (st *Store) RestorePackage(ownerKey, pkgType, name string) bool

RestorePackage un-deletes a package with its versions and files. Fails when no deleted package exists or a live one has since claimed the name.

func (*Store) RestorePackageVersion

func (st *Store) RestorePackageVersion(id int) bool

RestorePackageVersion unmarks a deleted version. The version row and the package's recomputed count commit in one transaction (STORE-001/002).

func (*Store) ReviewOrgPATGrantRequest

func (st *Store) ReviewOrgPATGrantRequest(orgLogin string, requestID int, approve bool) bool

ReviewOrgPATGrantRequest resolves a pending request: approve converts it into an active grant, deny removes it. Returns false when it does not exist.

func (*Store) RevokeCredentials

func (st *Store) RevokeCredentials(credentials []string) int

RevokeCredentials deletes every listed credential from all token stores and returns how many were revoked.

func (*Store) RevokeInstallationToken

func (st *Store) RevokeInstallationToken(tokenStr string) bool

RevokeInstallationToken drops the token, reporting whether it existed (204 vs 401 for the caller).

func (*Store) RevokeOrgPATGrant

func (st *Store) RevokeOrgPATGrant(orgLogin string, grantID int) bool

RevokeOrgPATGrant removes an active grant. Returns false when it does not exist.

func (*Store) RevokeUserGrant

func (st *Store) RevokeUserGrant(clientID string, userID int) int

RevokeUserGrant deletes every user-to-server and refresh token for (clientID, userID). Mirrors DELETE /applications/{client_id}/grant.

func (*Store) RevokeUserToServerToken

func (st *Store) RevokeUserToServerToken(tokenStr string) bool

RevokeUserToServerToken drops a user-to-server token. Returns true if it existed.

func (*Store) RotateAppClientSecret

func (st *Store) RotateAppClientSecret(appID int) (string, error)

RotateAppClientSecret replaces the client secret and returns it once.

func (*Store) RotateAppPrivateKey

func (st *Store) RotateAppPrivateKey(appID int) (string, error)

RotateAppPrivateKey replaces the signing key and returns its PEM once.

func (*Store) RotateOAuthAppClientSecret

func (st *Store) RotateOAuthAppClientSecret(clientID string) (string, error)

func (*Store) RotateUserToServerToken

func (st *Store) RotateUserToServerToken(refreshTokenStr string) (*UserToServerToken, *RefreshToken)

RotateUserToServerToken mints a fresh token+refresh pair from a valid refresh token, revoking the old pair. Returns nil if refresh is invalid.

func (*Store) RotateUserToServerTokenE

func (st *Store) RotateUserToServerTokenE(refreshTokenStr string) (*UserToServerToken, *RefreshToken, error)

func (*Store) SaveCopilotSpace

func (st *Store) SaveCopilotSpace(space *CopilotSpace)

SaveCopilotSpace bumps UpdatedAt and persists a space the caller mutated.

func (*Store) SaveMarketplaceListing

func (st *Store) SaveMarketplaceListing(listing *MarketplaceListing) error

func (*Store) SaveMarketplacePurchase

func (st *Store) SaveMarketplacePurchase(purchase *MarketplacePurchase) error

func (*Store) ScopeUserToServerToken

func (st *Store) ScopeUserToServerToken(tokenStr string, installationIDs []int, permissions map[string]string, repositoryIDs []int) bool

ScopeUserToServerToken persists a scoped GitHub App user token's capability constraints. Nil permissions/repositoryIDs leave that dimension unrestricted; an explicit empty map/slice scopes to none.

func (*Store) SealSecretValue

func (st *Store) SealSecretValue(plaintext string) (encryptedValue, keyID string, err error)

SealSecretValue encrypts a plaintext against the server's own Actions public key — the client side of the sealed-box contract.

func (*Store) SecretScanningPushProtectionEnabled

func (st *Store) SecretScanningPushProtectionEnabled(repo *Repo, patternID string) bool

SecretScanningPushProtectionEnabled reports whether the org has enabled push protection for a provider pattern on this repo.

func (*Store) SecretScanningScanHistory

func (st *Store) SecretScanningScanHistory(repo *Repo) (incremental, patternUpdate, backfill []*SecretScanningScanRecord)

SecretScanningScanHistory derives the repo's scan history from recorded alert state: each alert-producing event is a completed incremental scan, the earliest is the backfill, and an org pattern-config update is a pattern-update scan. No activity yields an empty history.

func (*Store) SeedApp

func (st *Store) SeedApp(spec AppSeedSpec, pemKey, ownerLogin string) (app *App, created bool, err error)

SeedApp creates a GitHub App from a spec. Idempotent on matching id or slug: returns the existing app unchanged with created=false.

func (*Store) SeedDefaultUser

func (st *Store) SeedDefaultUser()

SeedDefaultUser creates the default admin user and token.

func (*Store) SeedInstallation

func (st *Store) SeedInstallation(appID, explicitID int, targetType string, targetID int, targetLogin string, perms map[string]string, events []string) *Installation

SeedInstallation installs a seeded App on a target. Idempotent per (app, target login). Returns nil if the app doesn't exist.

func (*Store) SetBranchProtection

func (st *Store) SetBranchProtection(repoID int, branch string, bp *BranchProtection)

SetBranchProtection replaces, or for a nil/empty rule removes, the stored exact-name protection rule. The stored rule is a detached copy.

func (*Store) SetBranchProtectionExtras

func (st *Store) SetBranchProtectionExtras(repoID int, pattern string, extras *BranchProtectionRuleExtras)

SetBranchProtectionExtras stores, or for nil removes, the rule's GraphQL-only members keyed by pattern.

func (*Store) SetBranchProtectionPatterns

func (st *Store) SetBranchProtectionPatterns(repoID int, rules []*BranchProtectionPatternRule)

SetBranchProtectionPatterns replaces the repo's pattern rules; an empty list clears them.

func (*Store) SetCheckSuitePreferences

func (st *Store) SetCheckSuitePreferences(repoKey string, prefs []*CheckSuitePref)

SetCheckSuitePreferences replaces the per-app auto-trigger flags for a repo.

func (*Store) SetCodeQualitySetup

func (st *Store) SetCodeQualitySetup(setup *CodeQualitySetup)

func (*Store) SetCodeScanningDefaultSetup

func (st *Store) SetCodeScanningDefaultSetup(setup *CodeScanningDefaultSetup)

SetCodeScanningDefaultSetup records a repo's default-setup configuration, stamping UpdatedAt.

func (*Store) SetCodeSecurityConfigurationAsDefault

func (st *Store) SetCodeSecurityConfigurationAsDefault(orgLogin string, id int, defaultFor string) *CodeSecurityConfiguration

SetCodeSecurityConfigurationAsDefault records the configuration's default-for-new-repositories policy, clearing overlapping defaults from other configurations.

func (*Store) SetCodespaceContainerState

func (st *Store) SetCodespaceContainerState(id int, containerID, state string)

func (*Store) SetCodespaceSecretSelectedRepos

func (st *Store) SetCodespaceSecretSelectedRepos(scope, name string, ids []int) bool

SetCodespaceSecretSelectedRepos replaces an org secret's selected repositories.

func (*Store) SetCodespaceState

func (st *Store) SetCodespaceState(id int, state string, markUsed bool)

SetCodespaceState records a codespace's observed state; markUsed also bumps LastUsedAt.

func (*Store) SetCommentMinimization

func (st *Store) SetCommentMinimization(id, minimizerID int, reason string) *Comment

SetCommentMinimization sets or clears a comment's minimization. reason is OFF_TOPIC / OUTDATED / RESOLVED / DUPLICATE / SPAM / ABUSE to minimize, or empty to unminimize (minimizerID ignored when clearing).

func (*Store) SetCopilotCodingAgentPolicy

func (st *Store) SetCopilotCodingAgentPolicy(orgLogin, policy string)

SetCopilotCodingAgentPolicy sets the enabled_repositories policy.

func (*Store) SetCopilotCodingAgentSelectedRepos

func (st *Store) SetCopilotCodingAgentSelectedRepos(orgLogin string, repoIDs []int)

SetCopilotCodingAgentSelectedRepos replaces the selected repository list.

func (*Store) SetCopilotContentExclusion

func (st *Store) SetCopilotContentExclusion(orgLogin string, rules map[string][]interface{})

SetCopilotContentExclusion replaces the org's content exclusion rules.

func (*Store) SetDependabotOrgSecretSelectedRepos

func (st *Store) SetDependabotOrgSecretSelectedRepos(orgLogin, name string, ids []int) (*DependabotOrgSecret, bool)

SetDependabotOrgSecretSelectedRepos replaces an org secret's selected repository IDs.

func (*Store) SetDependabotRepositoryAccess

func (st *Store) SetDependabotRepositoryAccess(orgLogin string, repoIDs []int) bool

SetDependabotRepositoryAccess replaces an org's repository access list, returning true when no list previously existed.

func (*Store) SetDependabotRepositoryAccessDefaultLevel

func (st *Store) SetDependabotRepositoryAccessDefaultLevel(orgLogin, level string)

func (*Store) SetDiscussionCommentUpvote

func (st *Store) SetDiscussionCommentUpvote(id, userID int, up bool) bool

SetDiscussionCommentUpvote adds (up) or removes userID's upvote, idempotently, reporting whether the comment exists.

func (*Store) SetDiscussionUpvote

func (st *Store) SetDiscussionUpvote(id, userID int, up bool) bool

SetDiscussionUpvote adds (up) or removes userID's upvote, idempotently, reporting whether the discussion exists. A vote is not an edit, so it bumps neither UpdatedAt nor LastEditedAt.

func (*Store) SetEnterpriseActionsCacheRetentionDays

func (st *Store) SetEnterpriseActionsCacheRetentionDays(days int)

SetEnterpriseActionsCacheRetentionDays sets the Actions cache retention limit in days.

func (*Store) SetEnterpriseActionsCacheSizeGB

func (st *Store) SetEnterpriseActionsCacheSizeGB(gb int)

SetEnterpriseActionsCacheSizeGB sets the Actions cache storage limit in GB.

func (*Store) SetEnterpriseActionsCacheUsagePolicy

func (st *Store) SetEnterpriseActionsCacheUsagePolicy(defaultGB, maxGB int)

SetEnterpriseActionsCacheUsagePolicy atomically updates the default and maximum per-repository cache sizes.

func (*Store) SetEnterpriseCodeSecurityConfigDefault

func (st *Store) SetEnterpriseCodeSecurityConfigDefault(c *EnterpriseCodeSecurityConfiguration, defaultForNewRepos string)

SetEnterpriseCodeSecurityConfigDefault marks the configuration as the default for new repositories of the given visibility ("none" clears it).

func (*Store) SetEnterpriseCopilotCodingAgentPolicy

func (st *Store) SetEnterpriseCopilotCodingAgentPolicy(policyState string)

SetEnterpriseCopilotCodingAgentPolicy sets the Copilot coding agent policy state.

func (*Store) SetEnterpriseDependabotDefaultLevel

func (st *Store) SetEnterpriseDependabotDefaultLevel(level DependabotDefaultLevel)

SetEnterpriseDependabotDefaultLevel sets the Dependabot default repository access level (public|internal).

func (*Store) SetEnterpriseDependabotRepoAccess

func (st *Store) SetEnterpriseDependabotRepoAccess(ids []int)

SetEnterpriseDependabotRepoAccess replaces the Dependabot accessible repository ID list.

func (*Store) SetEnterpriseIdentityProvider

func (st *Store) SetEnterpriseIdentityProvider(enterpriseID int, ssoURL, issuer, certificate, signatureMethod, digestMethod string, recoveryCodes []string) *EnterpriseSAMLIdentityProvider

SetEnterpriseIdentityProvider binds (or rebinds) an enterprise's SAML identity provider and returns a detached snapshot. The caller generates recoveryCodes so the store stays free of randomness.

func (*Store) SetEnterpriseMembership

func (st *Store) SetEnterpriseMembership(enterpriseID, userID int, role EnterpriseRole) *EnterpriseMembership

SetEnterpriseMembership creates or re-roles a user's membership and returns a detached snapshot. It returns nil when the enterprise does not exist.

func (*Store) SetEnterpriseMigratorRole

func (st *Store) SetEnterpriseMigratorRole(enterpriseID int, login string, granted bool) bool

SetEnterpriseMigratorRole grants or revokes the organizations-migrator role for a login across the enterprise. It reports whether the enterprise exists.

func (*Store) SetEnterpriseSupportEntitlement

func (st *Store) SetEnterpriseSupportEntitlement(enterpriseID, userID int, entitled bool) bool

SetEnterpriseSupportEntitlement grants or revokes a member's support entitlement. It reports whether the membership existed.

func (*Store) SetEnterpriseVerifiedDomains

func (st *Store) SetEnterpriseVerifiedDomains(enterpriseID int, domains []string) *Enterprise

SetEnterpriseVerifiedDomains replaces the verified domain list and returns a detached snapshot, or nil when the enterprise is gone. Non-domains are dropped so the notification-delivery check never compares against junk.

func (*Store) SetFollow

func (st *Store) SetFollow(follower, target string, following bool)

SetFollow records or removes a follow edge. The graph is keyed by login, not id, because a user may follow an organization.

func (*Store) SetHookLastResponse

func (st *Store) SetHookLastResponse(repoKey string, hookID int, lr *HookLastResponse)

SetHookLastResponse records the outcome of a hook's most recent delivery.

func (*Store) SetInstallationRepositorySelection

func (st *Store) SetInstallationRepositorySelection(id int, mode string, repoIDs []int) bool

SetInstallationRepositorySelection switches between "all" and "selected" modes.

func (*Store) SetIssueFieldValues

func (st *Store) SetIssueFieldValues(issueID int, values map[int]interface{})

SetIssueFieldValues replaces all field values on an issue.

func (*Store) SetIssueLabels

func (st *Store) SetIssueLabels(repoID int, issueNumber int, labelIDs []int, actorID int) bool

SetIssueLabels replaces an issue's labels, recording labeled/unlabeled events for the deltas. Returns true when the issue exists.

func (*Store) SetIssueOrPRLock

func (st *Store) SetIssueOrPRLock(repoID, number int, locked bool, reason string) bool

SetIssueOrPRLock sets the locked flag on the issue or PR at repo + number (reason recorded only when locked). Returns false when none matches.

func (*Store) SetMembership

func (st *Store) SetMembership(orgLogin string, userID int, role OrgRole, state MembershipState) *Membership

SetMembership upserts a user's org membership with the given role and state, preserving an existing membership's Public flag. Returns nil if the org doesn't exist.

func (*Store) SetMembershipPublic

func (st *Store) SetMembershipPublic(orgLogin string, userID int, public bool) bool

SetMembershipPublic sets the membership's public-member flag; false when no active membership exists.

func (*Store) SetNotificationPreferences

func (st *Store) SetNotificationPreferences(userID int, preferences NotificationPreferences, now time.Time) bool

SetNotificationPreferences replaces the user's preferences and persists them. Returns false if the user does not exist.

func (*Store) SetOrgActionsPermissions

func (st *Store) SetOrgActionsPermissions(orgLogin string, p *OrgActionsPermissions)

SetOrgActionsPermissions stores the org's Actions settings and persists.

func (*Store) SetOrgCodespacesAccess

func (st *Store) SetOrgCodespacesAccess(orgLogin, visibility string, selected []string)

func (*Store) SetOrgHookLastResponse

func (st *Store) SetOrgHookLastResponse(orgLogin string, hookID int, lr *HookLastResponse)

SetOrgHookLastResponse records the outcome of an org hook's most recent delivery.

func (*Store) SetOrgImmutableReleasesSettings

func (st *Store) SetOrgImmutableReleasesSettings(orgLogin, enforced string, selectedIDs []int)

SetOrgImmutableReleasesSettings replaces the org policy.

func (*Store) SetOrgInteractionLimit

func (st *Store) SetOrgInteractionLimit(orgLogin, limit string, expiresAt time.Time) *OrgInteractionLimit

SetOrgInteractionLimit stores the org's interaction limit.

func (*Store) SetOrgMigratorRole

func (st *Store) SetOrgMigratorRole(orgID int, actorType, actor string, grantedBy int, granted bool) bool

SetOrgMigratorRole grants or revokes the migrator role for one actor on one organization. It reports whether the grant set changed.

func (*Store) SetOrgPRCreationCap

func (st *Store) SetOrgPRCreationCap(orgLogin string, cap PRCreationCap) PRCreationCap

func (*Store) SetOrgPinnedRepos

func (st *Store) SetOrgPinnedRepos(orgLogin string, fullNames []string) ([]string, bool)

SetOrgPinnedRepos replaces the org's pinned list, mirroring SetPinnedRepos (order preserved, duplicates and nonexistent repos dropped, capped at MaxPinnedRepos) and additionally requiring each repo be owned by the org. Returns the stored list.

func (*Store) SetOrgSelectedRepos

func (st *Store) SetOrgSelectedRepos(orgLogin string, repoIDs []int)

SetOrgSelectedRepos replaces the org's selected repository list.

func (*Store) SetPRCreationCap

func (st *Store) SetPRCreationCap(repoKey string, cap PRCreationCap) PRCreationCap

func (*Store) SetPackageVersionRegistryManifestDigest

func (st *Store) SetPackageVersionRegistryManifestDigest(id int, digest string) bool

func (*Store) SetPagesDeploymentStatus

func (st *Store) SetPagesDeploymentStatus(repoID, id int, status string) bool

SetPagesDeploymentStatus transitions a deployment's status, or false if it does not exist.

func (*Store) SetPersistence

func (st *Store) SetPersistence(p *Persistence) error

SetPersistence wires a Persistence layer onto the Store. Call once at startup before concurrent access; mutations then write through to SQLite. When p is non-nil it also loads existing rows. Idempotent.

invariant: open-failure is caught at MustNewPersistence, so the operator gets a fail-loud signal before reaching here.

func (*Store) SetPinnedDiscussions

func (st *Store) SetPinnedDiscussions(repoID int, ids []int) []int

SetPinnedDiscussions replaces the repo's ordered pinned list. The caller validates membership and the MaxPinnedDiscussions cap; the store keeps a detached copy (STORE-021).

func (*Store) SetPinnedRepos

func (st *Store) SetPinnedRepos(userID int, fullNames []string) ([]string, bool)

SetPinnedRepos replaces the user's pinned list, preserving order, dropping duplicates and nonexistent repos, and capping at MaxPinnedRepos. Returns the stored list.

func (*Store) SetPrimaryEmailLocked

func (st *Store) SetPrimaryEmailLocked(u *User, email string)

SetPrimaryEmailLocked changes the account's primary email address (PATCH /user `email`). Caller must hold st.Mu.

func (*Store) SetPrimaryEmailVisibility

func (st *Store) SetPrimaryEmailVisibility(userID int, visibility string) []UserEmail

SetPrimaryEmailVisibility updates the primary email's visibility, returning the updated entries or nil when the user has no primary email.

func (*Store) SetPrimaryEnterpriseSlug

func (st *Store) SetPrimaryEnterpriseSlug(slug string)

SetPrimaryEnterpriseSlug records which enterprise is the instance's own.

func (*Store) SetPrimaryUserEmail

func (st *Store) SetPrimaryUserEmail(userID int, email string) ([]UserEmail, setPrimaryEmailResult)

SetPrimaryUserEmail promotes a verified address to primary (a web-only action; the REST API cannot change the primary). The promoted address inherits the old primary's visibility when it has none. Returns the updated entries, primary first.

func (*Store) SetPullRequestDiffStats

func (st *Store) SetPullRequestDiffStats(prID, changedFiles, additions, deletions int)

SetPullRequestDiffStats records a pull request's merge-base diff totals. Being derived state, it does not bump UpdatedAt and is a no-op when unchanged.

func (*Store) SetPullRequestFileViewed

func (st *Store) SetPullRequestFileViewed(prID, reviewerID int, path string, viewed bool) bool

SetPullRequestFileViewed sets or clears one reviewer's "viewed" mark on one file of a PR diff. Returns false when the PR does not exist.

func (*Store) SetPullRequestLabels

func (st *Store) SetPullRequestLabels(repoID, prNumber int, labelIDs []int, actorID int) bool

func (*Store) SetPullRequestPotentialMergeSHA

func (st *Store) SetPullRequestPotentialMergeSHA(prID int, sha string)

SetPullRequestPotentialMergeSHA records a pull request's test-merge commit (ACT-027). A no-op when unchanged, to avoid churning persistence.

func (*Store) SetRepoActionsPermissions

func (st *Store) SetRepoActionsPermissions(repoKey string, p *RepoActionsPermissions)

SetRepoActionsPermissions stores the repo's Actions settings and persists.

func (*Store) SetRepoCustomPropertyValues

func (st *Store) SetRepoCustomPropertyValues(repoKey string, values []CustomPropertyValuePayload)

SetRepoCustomPropertyValues applies a validated batch of values to one repo; a null value unsets.

func (*Store) SetRepoFlag

func (st *Store) SetRepoFlag(repoID int, field string, value bool) bool

SetRepoFlag sets a boolean flag field on a repo by name.

func (*Store) SetRepoImmutableReleases

func (st *Store) SetRepoImmutableReleases(repoKey string, enabled bool)

SetRepoImmutableReleases records the repo-level toggle.

func (*Store) SetRepoInteractionLimit

func (st *Store) SetRepoInteractionLimit(repoID int, limit string, expiry *time.Time) bool

SetRepoInteractionLimit sets the interaction limit for a repo.

func (*Store) SetRepoSubscription

func (st *Store) SetRepoSubscription(userID int, repoID int, subscribed, ignored bool) bool

SetRepoSubscription creates or updates a subscription. `ignored` mutes all repo notifications (github's watch "ignore") independently of `subscribed`.

func (*Store) SetRepositoryMigrationLogKey

func (st *Store) SetRepositoryMigrationLogKey(id int, key string) bool

SetRepositoryMigrationLogKey records where the migration's log was stored.

func (*Store) SetRepositoryMigrationSourceLock

func (st *Store) SetRepositoryMigrationSourceLock(id int, fullName string) bool

SetRepositoryMigrationSourceLock records the lock_source freeze. It refuses once terminal, so a late worker cannot re-freeze an unmigrated repository.

func (*Store) SetRepositoryMigrationState

func (st *Store) SetRepositoryMigrationState(id int, state, failureReason string) *RepositoryMigration

SetRepositoryMigrationState records a state and reason. It refuses to leave a terminal state, so a worker finishing after an abort cannot overwrite it.

func (*Store) SetRepositoryMigrationTargetRepo

func (st *Store) SetRepositoryMigrationTargetRepo(id, repoID int) bool

SetRepositoryMigrationTargetRepo records the repository a migration created.

func (*Store) SetTeamMembership

func (st *Store) SetTeamMembership(orgLogin, slug string, userID int, role TeamRole) bool

SetTeamMembership upserts a user's team membership with the given role.

func (*Store) SetTeamRepoPermission

func (st *Store) SetTeamRepoPermission(orgLogin, slug, fullName string, perm TeamPermission) bool

SetTeamRepoPermission links a repo to a team and records a permission override; an empty permission uses the team's default.

func (*Store) SetThreadSaved

func (st *Store) SetThreadSaved(userID int, threadID string, saved bool)

SetThreadSaved adds or removes a thread from the user's saved set.

func (*Store) SetThreadSubscription

func (st *Store) SetThreadSubscription(userID int, threadID string, sub *ThreadSubscription)

SetThreadSubscription sets or clears a thread subscription for the user.

func (*Store) SetUserInteractionLimit

func (st *Store) SetUserInteractionLimit(userID int, limit string, expiresAt *time.Time) bool

SetUserInteractionLimit records, or clears with limit == "", the account-level interaction limit.

func (*Store) SetUserListsForRepo

func (st *Store) SetUserListsForRepo(userID, repoID int, listIDs []int) []*UserList

SetUserListsForRepo puts the repository on exactly the named lists and off the account's others, returning the account's lists after the change.

func (*Store) SetUserPasswordHash

func (st *Store) SetUserPasswordHash(userID int, hash string, now time.Time) AccountSecurityResult

SetUserPasswordHash replaces the account password. Refused on a federated account, which would otherwise gain a second credential path the identity provider knows nothing about.

func (*Store) SetUserSocialAccounts

func (st *Store) SetUserSocialAccounts(userID int, accounts []string) bool

SetUserSocialAccounts replaces a user's social accounts.

func (*Store) SetUserStatus

func (st *Store) SetUserStatus(userID int, status UserStatus) *UserStatus

SetUserStatus writes the account's status and returns the stored row. A status with neither emoji nor message clears it.

func (*Store) SetUserToServerTokenInstallations

func (st *Store) SetUserToServerTokenInstallations(tokenStr string, installationIDs []int) bool

SetUserToServerTokenInstallations binds the token to a set of installation IDs.

func (*Store) SetWorkflowFileState

func (st *Store) SetWorkflowFileState(repoFullName, path, state string) bool

SetWorkflowFileState updates the persisted state of one discovered workflow.

func (*Store) SnapComment

func (st *Store) SnapComment(comment *Comment) *Comment

func (*Store) SnapIssue

func (st *Store) SnapIssue(i *Issue) *Issue

func (*Store) SnapPR

func (st *Store) SnapPR(pr *PullRequest) *PullRequest

func (*Store) SnapPullRequestReview

func (st *Store) SnapPullRequestReview(review *PullRequestReview) *PullRequestReview

func (*Store) SnapRepo

func (st *Store) SnapRepo(r *Repo) *Repo

The Snap* helpers return value copies of a shared store entity taken under the read lock, so webhook payload builders read a private copy rather than the live pointer a concurrent Update* writer mutates. Never call one while holding the read lock — RWMutex read locks are not reentrant.

func (*Store) SnapUser

func (st *Store) SnapUser(u *User) *User

func (*Store) SnapshotAllRepos

func (st *Store) SnapshotAllRepos() []*Repo

SnapshotAllRepos returns every repository as detached snapshots (STORE-021). The two instance-wide advisory sweeps do substantial per-repo work that must not run under the store lock, so they snapshot first.

func (*Store) SnapshotHook

func (st *Store) SnapshotHook(h *Webhook) *Webhook

SnapshotHook copies a hook's config under the store lock. Hook edits mutate the stored *Webhook in place, so a delivery must be addressed and signed by its config as of queue time, not race a concurrent PATCH mid-flight.

func (*Store) StarGist

func (st *Store) StarGist(userID int, gistID string) bool

StarGist stars a gist for the user.

func (*Store) StarRepo

func (st *Store) StarRepo(userID int, owner, name string) bool

StarRepo stars the repo for userID, idempotently. Returns true if newly added.

func (*Store) StarredReposAt

func (st *Store) StarredReposAt(userID int) map[string]time.Time

StarredReposAt returns a detached copy of the repos userID has starred with the instant each was starred, backing the non-null starredAt of the GraphQL StarredRepository edge.

func (*Store) StaticIPUsageLocked

func (st *Store) StaticIPUsageLocked(target RunnerScope) int

StaticIPUsageLocked counts reserved static IPs: each static-IP runner reserves one per concurrent runner (maximum_runners). Callers hold the lock.

func (*Store) SubmitPullRequestReview

func (st *Store) SubmitPullRequestReview(id int, event string) bool

SubmitPullRequestReview transitions a pending review to an event state.

func (*Store) SuspendInstallation

func (st *Store) SuspendInstallation(id int, by *User) bool

SuspendInstallation marks the installation suspended. Returns false if not found or already suspended.

func (*Store) SyncJobConcurrencyEntryLocked

func (st *Store) SyncJobConcurrencyEntryLocked(wf *Workflow, wfJob *WorkflowJob)

SyncJobConcurrencyEntryLocked adds or removes one job's concurrency-group index entry per its status. Callers hold the write lock.

func (*Store) SyncWorkflowIndexesLocked

func (st *Store) SyncWorkflowIndexesLocked(wf *Workflow)

SyncWorkflowIndexesLocked reconciles the derived indexes with one workflow's current state. Callers hold the write lock. A workflow that is no longer the store's entry for its ID is not indexed.

func (*Store) TeamParentWouldCycle

func (st *Store) TeamParentWouldCycle(teamID, parentID int) bool

TeamParentWouldCycle reports whether re-parenting teamID under parentID would create a cycle in the team hierarchy.

func (*Store) TouchEnterpriseCodeSecurityConfig

func (st *Store) TouchEnterpriseCodeSecurityConfig(c *EnterpriseCodeSecurityConfiguration, mutate func())

TouchEnterpriseCodeSecurityConfig runs mutate under the lock, then bumps updated_at and persists.

func (*Store) TransferEnterpriseOrganization

func (st *Store) TransferEnterpriseOrganization(orgID, destinationEnterpriseID int) bool

TransferEnterpriseOrganization moves an organization to another enterprise. It reports whether the organization was bound to an enterprise to begin with.

func (*Store) TransferIssue

func (st *Store) TransferIssue(issueID, targetRepoID, actorID int, createLabelsIfMissing bool) *Issue

TransferIssue moves an issue into targetRepoID with a fresh issue number. Labels re-match by name in the target (created when createLabelsIfMissing, else dropped); milestone and pinned state do not follow; timeline events are re-homed so history survives. Returns nil when the issue or target is missing or the target is the issue's own repo.

func (*Store) TransferRepo

func (st *Store) TransferRepo(owner, name, newOwner string) bool

TransferRepo transfers a repo to a new owner account, returning true on success.

func (*Store) TwoFactorEnabled

func (st *Store) TwoFactorEnabled(userID int) bool

TwoFactorEnabled reports whether the account has a confirmed second factor; a pending (unconfirmed) enrolment is deliberately not "enabled".

func (*Store) TwoFactorStatusFor

func (st *Store) TwoFactorStatusFor(userID int, now time.Time) (TwoFactorStatus, bool)

TwoFactorStatusFor returns a detached snapshot of the account's second-factor state; the second result is false when the user does not exist.

func (*Store) UnassignAllOrgRolesFromTeam

func (st *Store) UnassignAllOrgRolesFromTeam(orgLogin string, teamID int)

UnassignAllOrgRolesFromTeam revokes every organization role from a team. Idempotent.

func (*Store) UnassignAllOrgRolesFromUser

func (st *Store) UnassignAllOrgRolesFromUser(orgLogin string, userID int)

UnassignAllOrgRolesFromUser revokes every organization role from a user. Idempotent.

func (*Store) UnassignOrgRoleFromTeam

func (st *Store) UnassignOrgRoleFromTeam(orgLogin string, roleID, teamID int)

UnassignOrgRoleFromTeam revokes one organization role from a team. Idempotent.

func (*Store) UnassignOrgRoleFromUser

func (st *Store) UnassignOrgRoleFromUser(orgLogin string, roleID, userID int)

UnassignOrgRoleFromUser revokes one organization role from a user. Idempotent.

func (*Store) UnblockUser

func (st *Store) UnblockUser(userID, targetID int) bool

UnblockUser unblocks targetID for userID.

func (*Store) UnblockUserForOrg

func (st *Store) UnblockUserForOrg(orgLogin string, userID int)

UnblockUserForOrg removes an organization's block of the user. Idempotent.

func (*Store) UnindexOrgLoginLocked

func (st *Store) UnindexOrgLoginLocked(login string)

UnindexOrgLoginLocked removes login from the folded org-login index; see UnindexUserLoginLocked for the case-only-rename guard. Caller holds st.Mu.

func (*Store) UnindexRepoNameLocked

func (st *Store) UnindexRepoNameLocked(fullName string)

UnindexRepoNameLocked removes the "owner/name" key from the folded repo index; see UnindexUserLoginLocked for the case-only-rename guard. Caller holds st.Mu.

func (*Store) UnindexUserLoginLocked

func (st *Store) UnindexUserLoginLocked(login string)

UnindexUserLoginLocked removes login from the folded login index, but only if the entry still points at this exact canonical login, so a case-only rename may add the new spelling and remove the old one in either order. Caller holds st.Mu.

func (*Store) UnindexWorkflowLocked

func (st *Store) UnindexWorkflowLocked(wf *Workflow)

UnindexWorkflowLocked removes a deleted workflow from every derived index. Callers hold the write lock.

func (*Store) UnlinkIssueBranch

func (st *Store) UnlinkIssueBranch(issueID int, ref string) bool

UnlinkIssueBranch removes a link, reporting whether one was removed. The branch itself is left in place.

func (*Store) UnlinkRepoFromProjectClassic

func (st *Store) UnlinkRepoFromProjectClassic(projectID, repoID int) bool

UnlinkRepoFromProjectClassic removes a repository link (idempotent). Reports false only when the project does not exist.

func (*Store) UnlockIssue

func (st *Store) UnlockIssue(repoKey string, issueNumber int) bool

UnlockIssue unlocks an issue. Returns true when the issue exists.

func (*Store) UnlockOrgMigrationRepo

func (st *Store) UnlockOrgMigrationRepo(id int, repoName string) bool

UnlockOrgMigrationRepo unlocks a single repository in an org migration.

func (*Store) UnlockUserMigrationRepo

func (st *Store) UnlockUserMigrationRepo(id int, repoName string) bool

UnlockUserMigrationRepo unlocks a single repository in a user migration.

func (*Store) UnmarkDiscussionCommentAsAnswer

func (st *Store) UnmarkDiscussionCommentAsAnswer(id int) bool

UnmarkDiscussionCommentAsAnswer unmarks a comment as the answer.

func (*Store) UnpinIssue

func (st *Store) UnpinIssue(issueID, actorID int) bool

UnpinIssue clears an issue's pinned state on behalf of actorID, reporting whether it had been pinned. Missing or unpinned issue reports false.

func (*Store) UnpinIssueComment

func (st *Store) UnpinIssueComment(commentID int) bool

UnpinIssueComment clears a comment's pinned flag. Returns true when it exists.

func (*Store) UnstarGist

func (st *Store) UnstarGist(userID int, gistID string) bool

UnstarGist unstars a gist for the user.

func (*Store) UnstarRepo

func (st *Store) UnstarRepo(userID int, owner, name string) bool

UnstarRepo unstars the repo for userID, returning true if a star was removed.

func (*Store) UnsuspendInstallation

func (st *Store) UnsuspendInstallation(id int) bool

UnsuspendInstallation clears the suspension. Returns false if not found or wasn't suspended.

func (*Store) UpdateApp

func (st *Store) UpdateApp(appID int, fn func(a *App)) bool

UpdateApp mutates a registered app under the write lock and persists it. Every field-level app edit routes through here.

func (*Store) UpdateAppHookConfig

func (st *Store) UpdateAppHookConfig(appID int, fn func(a *App)) bool

UpdateAppHookConfig mutates the app's hook URL/secret/active flags.

func (*Store) UpdateCampaign

func (st *Store) UpdateCampaign(orgLogin string, number int, fn func(*Campaign)) *Campaign

UpdateCampaign applies fn to the campaign under the store lock.

func (*Store) UpdateCheckRun

func (st *Store) UpdateCheckRun(id int64, fn func(*CheckRun)) bool

UpdateCheckRun mutates a check run via callback. Returns false if not found.

func (*Store) UpdateCheckSuite

func (st *Store) UpdateCheckSuite(id int64, fn func(*CheckSuite)) bool

UpdateCheckSuite mutates a check suite via callback. Returns false if not found.

func (*Store) UpdateClassroom

func (st *Store) UpdateClassroom(id int, update func(*Classroom)) *Classroom

func (*Store) UpdateClassroomAcceptedAssignment

func (st *Store) UpdateClassroomAcceptedAssignment(id int, update func(*ClassroomAcceptedAssignment)) *ClassroomAcceptedAssignment

func (*Store) UpdateClassroomAssignment

func (st *Store) UpdateClassroomAssignment(id int, update func(*ClassroomAssignment)) *ClassroomAssignment

func (*Store) UpdateCodeScanningAlert

func (st *Store) UpdateCodeScanningAlert(a *CodeScanningAlert, state, dismissedReason, dismissedComment string) error

UpdateCodeScanningAlert applies a state/dismissed_reason transition. Since `a` is a detached clone from GetCodeScanningAlert, the mutation hits the LIVE row re-fetched by key, and a fresh snapshot is written back into `a`.

func (*Store) UpdateCodeSecurityConfiguration

func (st *Store) UpdateCodeSecurityConfiguration(orgLogin string, id int, req *CodeSecurityConfigurationRequest) (*CodeSecurityConfiguration, bool)

UpdateCodeSecurityConfiguration applies the request; the bool reports whether anything changed.

func (*Store) UpdateCodespace

func (st *Store) UpdateCodespace(id int, displayName, machineName string, retention int) (*Codespace, bool)

func (*Store) UpdateCommentBody

func (st *Store) UpdateCommentBody(id, editorID int, body string) *Comment

UpdateCommentBody sets a comment's body and edit metadata (LastEditedAt, EditorID). Returns the updated comment or nil when no comment matches.

func (*Store) UpdateDependabotAlert

func (st *Store) UpdateDependabotAlert(a *DependabotAlert, state, dismissedReason, dismissedComment string, dismissedBy *User) error

UpdateDependabotAlert applies a state/dismissed_reason transition to one alert.

func (*Store) UpdateDiscussion

func (st *Store) UpdateDiscussion(id int, fn func(*Discussion)) bool

UpdateDiscussion applies fn to a discussion and bumps UpdatedAt. LastEditedAt is NOT touched here — it reflects only title/body edits, so a content edit stamps it inside fn (see the updateDiscussion resolver); close, reopen and re-categorize must leave it unchanged.

func (*Store) UpdateDiscussionComment

func (st *Store) UpdateDiscussionComment(id int, fn func(*DiscussionComment)) bool

UpdateDiscussionComment applies fn to a comment.

func (*Store) UpdateEnterprisePolicy

func (st *Store) UpdateEnterprisePolicy(enterpriseID int, mutate func(*EnterprisePolicy)) *Enterprise

UpdateEnterprisePolicy mutates the policy set under the store lock and returns a detached snapshot. mutate receives the live policy and must not retain it.

func (*Store) UpdateEnterpriseProfile

func (st *Store) UpdateEnterpriseProfile(enterpriseID int, name, description, location, websiteURL, securityContactEmail, billingEmail *string) *Enterprise

UpdateEnterpriseProfile applies the non-nil profile fields and returns a detached snapshot of the result, or nil when the enterprise is gone.

func (*Store) UpdateEnterpriseTeam

func (st *Store) UpdateEnterpriseTeam(t *EnterpriseTeam, name, description, selectionType, notificationSetting *string, groupID **string) bool

UpdateEnterpriseTeam applies the non-nil fields, re-slugging on rename. Returns false when the new slug collides with a different team.

func (*Store) UpdateEnvBranchPolicy

func (st *Store) UpdateEnvBranchPolicy(envID, policyID int, name string) *DeploymentBranchPolicyRule

UpdateEnvBranchPolicy renames a policy's pattern. Returns nil when not found.

func (*Store) UpdateGistComment

func (st *Store) UpdateGistComment(id int, body string) (*GistComment, bool)

UpdateGistComment updates a comment body.

func (*Store) UpdateGistE

func (st *Store) UpdateGistE(id string, description *string, files map[string]*GistFile, deleteFiles []string) (*Gist, bool, error)

UpdateGistE replaces the gist fields and records a history entry.

func (*Store) UpdateHook

func (st *Store) UpdateHook(repoKey string, hookID int, fn func(h *Webhook)) bool

UpdateHook updates a webhook in place. Returns false if not found.

func (*Store) UpdateIPAllowListEntry

func (st *Store) UpdateIPAllowListEntry(id int, allowListValue, name string, isActive bool) *IPAllowListEntry

UpdateIPAllowListEntry rewrites an entry and returns a detached snapshot.

func (*Store) UpdateIssue

func (st *Store) UpdateIssue(id int, fn func(*Issue)) bool

UpdateIssue applies fn to an issue. Returns false when it does not exist.

func (*Store) UpdateIssueField

func (st *Store) UpdateIssueField(orgLogin string, id int, name, description, visibility *string, options []IssueFieldOptionRequest) *IssueField

UpdateIssueField applies the provided fields; a non-nil options slice replaces the entire option set. Returns nil when the field is unknown.

func (*Store) UpdateIssueType

func (st *Store) UpdateIssueType(orgLogin string, id int, name string, description, color *string, isEnabled bool) *IssueType

UpdateIssueType replaces the mutable fields of an issue type, or returns nil if absent.

func (*Store) UpdateLabel

func (st *Store) UpdateLabel(id int, fn func(*IssueLabel)) bool

UpdateLabel applies fn to a label. Returns false when it does not exist.

func (*Store) UpdateMarketplacePlan

func (st *Store) UpdateMarketplacePlan(plan *MarketplacePlan) error

func (*Store) UpdateMilestone

func (st *Store) UpdateMilestone(id int, fn func(*Milestone)) bool

UpdateMilestone applies fn to a milestone. Returns false when it does not exist.

func (*Store) UpdateNetworkConfiguration

func (st *Store) UpdateNetworkConfiguration(orgLogin, id string, req *NetworkConfigurationRequest) *NetworkConfiguration

UpdateNetworkConfiguration applies provided members and relinks settings.

func (*Store) UpdateOAuthApp

func (st *Store) UpdateOAuthApp(clientID string, fn func(a *OAuthApp)) bool

func (*Store) UpdateOrg

func (st *Store) UpdateOrg(login string, fn func(*Org)) bool

UpdateOrg applies a mutation to an organization.

func (*Store) UpdateOrgBudget

func (st *Store) UpdateOrgBudget(orgLogin, id string, fn func(*OrgBudget)) *OrgBudget

UpdateOrgBudget applies fn to a budget under the write lock, returning it or nil when it does not exist.

func (*Store) UpdateOrgHook

func (st *Store) UpdateOrgHook(orgLogin string, hookID int, fn func(h *Webhook)) bool

UpdateOrgHook updates an org webhook in place. Returns false if not found.

func (*Store) UpdateOrgRuleset

func (st *Store) UpdateOrgRuleset(id int, actorID int, fn func(*Ruleset)) bool

UpdateOrgRuleset applies a mutation to an organization ruleset and records a history snapshot attributed to actorID. Returns true when the ruleset existed.

func (*Store) UpdateOrganizationMigration

func (st *Store) UpdateOrganizationMigration(id int, mutate func(*OrganizationMigration)) *OrganizationMigration

UpdateOrganizationMigration applies a state transition and whatever progress accompanies it. It refuses to move out of a terminal state.

func (*Store) UpdatePrivateRegistry

func (st *Store) UpdatePrivateRegistry(orgLogin, name string, req *PrivateRegistryRequest)

UpdatePrivateRegistry applies the request to an existing configuration.

func (*Store) UpdateProjectCard

func (st *Store) UpdateProjectCard(card *ProjectCard, note *string, archived *bool) *ProjectCard

UpdateProjectCard updates a card's note and/or archived flag. Note→issue conversion goes through ConvertProjectCardToIssue instead.

func (*Store) UpdateProjectClassic

func (st *Store) UpdateProjectClassic(proj *ProjectClassic, name, body, state *string, public *bool) *ProjectClassic

UpdateProjectClassic applies field updates to the live row (proj is a detached clone) and returns a fresh snapshot (STORE-021).

func (*Store) UpdateProjectColumn

func (st *Store) UpdateProjectColumn(col *ProjectColumn, name string) *ProjectColumn

UpdateProjectColumn renames a column.

func (*Store) UpdatePullRequest

func (st *Store) UpdatePullRequest(id int, fn func(*PullRequest)) bool

UpdatePullRequest applies a mutation function to a pull request.

func (*Store) UpdatePullRequestReview

func (st *Store) UpdatePullRequestReview(id int, body string) bool

UpdatePullRequestReview updates a review's body.

func (*Store) UpdateRepo

func (st *Store) UpdateRepo(owner, name string, fn func(*Repo)) bool

func (*Store) UpdateRepoInvitation

func (st *Store) UpdateRepoInvitation(repoKey string, id int, permission string) *RepoInvitation

UpdateRepoInvitation changes the permission on a pending invitation, or returns nil if not found.

func (*Store) UpdateRuleset

func (st *Store) UpdateRuleset(repo *Repo, rs *Ruleset, updates *Ruleset, actorID int) *Ruleset

UpdateRuleset updates an existing ruleset and records a history snapshot attributed to actorID.

func (*Store) UpdateSecretScanningAlert

func (st *Store) UpdateSecretScanningAlert(a *SecretScanningAlert, state, resolution, resolutionComment string) error

UpdateSecretScanningAlert applies a state/resolution transition. The caller's `a` is a detached clone, so the mutation is applied to the live alert re-fetched by key here and a fresh snapshot is written back into `a`.

func (*Store) UpdateSecretScanningCustomPattern

func (st *Store) UpdateSecretScanningCustomPattern(scope string, id int, update SecretScanningPatternUpdate) (*SecretScanningCustomPattern, bool)

func (*Store) UpdateSecretScanningPatternConfig

func (st *Store) UpdateSecretScanningPatternConfig(orgLogin string, expectedVersion *string, provider, custom map[string]string) (string, bool)

UpdateSecretScanningPatternConfig applies push-protection setting changes and returns the new version. A non-nil expectedVersion that mismatches the current version reports a conflict without changing anything.

func (*Store) UpdateSecurityAdvisory

func (st *Store) UpdateSecurityAdvisory(id int, fn func(*SecurityAdvisory)) bool

UpdateSecurityAdvisory applies fn to the advisory and persists it.

func (*Store) UpdateTeam

func (st *Store) UpdateTeam(orgLogin, slug string, fn func(*Team)) bool

UpdateTeam applies a mutation to a team, re-keying the slug index on rename.

func (*Store) UpdateTeamChecked

func (st *Store) UpdateTeamChecked(orgLogin, slug string, fn func(*Team)) error

UpdateTeamChecked applies a team mutation atomically, refusing a rename whose derived slug is occupied. The callback receives a detached copy, so a validation failure cannot partially mutate the live team or its slug index.

func (*Store) UpdateUserList

func (st *Store) UpdateUserList(id int, apply func(*UserList)) *UserList

UpdateUserList applies a change and returns the stored result. A rename that would collide with another of the account's lists is refused.

func (*Store) UpdateUserProfile

func (st *Store) UpdateUserProfile(userID int, fn func(*User)) *User

UpdateUserProfile applies fn to the user under the store lock, bumps UpdatedAt, and persists. Returns nil when the user does not exist.

func (*Store) UpsertArtifactDeploymentRecord

func (st *Store) UpsertArtifactDeploymentRecord(rec *ArtifactDeploymentRecord) *ArtifactDeploymentRecord

UpsertArtifactDeploymentRecord creates or updates the deployment record identified by (org, logical env, physical env, cluster, deployment name).

func (*Store) UpsertCodeQLDatabase

func (st *Store) UpsertCodeQLDatabase(repoKey, language, name, contentType, commitOID string, content []byte, uploaderID int) (*CodeQLDatabase, error)

UpsertCodeQLDatabase creates or replaces the CodeQL database for a repo + language, as a new upload supersedes the previous one on GitHub.

func (*Store) UpsertCodeQLDatabaseStream

func (st *Store) UpsertCodeQLDatabaseStream(repoKey, language, name, contentType, commitOID string, r io.Reader, size int64, sum []byte, uploaderID int) (*CodeQLDatabase, error)

UpsertCodeQLDatabaseStream stores a CodeQL database from a reader whose size and SHA-256 the caller already computed (a handler stages the ZIP to a temp file and validates it there), so a multi-GB database never lands whole on the heap. r must be positioned at the start.

func (*Store) UpsertCustomProperty

func (st *Store) UpsertCustomProperty(orgLogin string, def *CustomProperty)

UpsertCustomProperty creates or replaces a property definition.

func (*Store) UpsertDependabotOrgSecret

func (st *Store) UpsertDependabotOrgSecret(orgLogin, name, value, keyID, visibility string, selectedRepoIDs []int) bool

func (*Store) UpsertDependabotSecret

func (st *Store) UpsertDependabotSecret(repoKey, name, value, keyID string) bool

func (*Store) UpsertDependabotUserSecret

func (st *Store) UpsertDependabotUserSecret(userLogin, name, value, keyID string) bool

func (*Store) UpsertEnterpriseCustomProperty

func (st *Store) UpsertEnterpriseCustomProperty(def *CustomProperty)

UpsertEnterpriseCustomProperty creates or replaces an enterprise-level property definition.

func (*Store) UpsertWikiPage

func (st *Store) UpsertWikiPage(repoKey, slug, title, body, author, message string) *WikiPage

UpsertWikiPage creates or replaces a wiki page by committing its file. A title whose file name differs from the on-disk one renames the page — the new file and removal of the old land in one commit, as on GitHub. message is the commit subject (GitHub's default when empty). Returns a detached copy, or nil when the wiki could not be written.

func (*Store) UserByLoginLocked

func (st *Store) UserByLoginLocked(login string) *User

UserByLoginLocked resolves a login case-insensitively to the live user row, or nil. Caller holds st.Mu; the pointer is only valid under that lock.

func (*Store) UserHoldsOrgMigratorRole

func (st *Store) UserHoldsOrgMigratorRole(orgID int, user *User) bool

UserHoldsOrgMigratorRole reports whether a migrator grant reaches the user on this org — directly, through a team, or through the owning enterprise's grant. Every path is scoped to this org, so a migrator on one tenant is nothing on another.

func (*Store) UserMigrationLocksRepo

func (st *Store) UserMigrationLocksRepo(id int, repoName string) bool

UserMigrationLocksRepo reports whether a user migration still locks a repo. It acquires st.Mu itself; the name avoids the "…Locked" suffix (which marks caller-holds-the-lock helpers) to prevent a self-deadlock on the non-reentrant mutex.

func (*Store) UserPasswordHash

func (st *Store) UserPasswordHash(userID int) (string, bool)

UserPasswordHash returns the account's stored bcrypt hash, empty when the account has no password.

func (*Store) VerifyAppClientSecret

func (st *Store) VerifyAppClientSecret(clientID, clientSecret string) *App

VerifyAppClientSecret returns the GitHub App if client_id+client_secret match, else nil.

func (*Store) VerifyOAuthAppSecret

func (st *Store) VerifyOAuthAppSecret(clientID, clientSecret string) *OAuthApp

VerifyOAuthAppSecret returns the OAuth App if client_id+client_secret match, else nil.

func (*Store) VerifySecondFactor

func (st *Store) VerifySecondFactor(userID int, code string, now time.Time) AccountSecurityResult

VerifySecondFactor spends one TOTP code or one unused recovery code. Verification and consumption happen under the same lock.

func (*Store) VerifySecondFactorExcluding

func (st *Store) VerifySecondFactorExcluding(userID int, code string, now time.Time, disallowed []TwoFactorMethod) (AccountSecurityResult, TwoFactorMethod)

VerifySecondFactorExcluding is VerifySecondFactor with a set of policy-banned methods. A code verifying only through a banned method is refused as SecurityMethodDisallowed and NOT spent, so a policy change cannot burn a user's recovery codes. Returns the method that answered.

func (*Store) VerifyVerifiableDomain

func (st *Store) VerifyVerifiableDomain(id int) (*VerifiableDomain, error)

VerifyVerifiableDomain marks the domain verified (the stand-in for a DNS TXT lookup), erroring when the token has expired.

func (*Store) WikiGitStorage

func (st *Store) WikiGitStorage(repoKey string) gitStorage.Storer

WikiGitStorage is the storer both git transports serve a wiki from, opening the wiki repository on first use so a client can push to an untouched wiki.

func (*Store) WikiHeadBranch

func (st *Store) WikiHeadBranch(repoKey string) string

WikiHeadBranch is the branch a clone of the wiki checks out.

func (*Store) WikiPagesChanged

func (st *Store) WikiPagesChanged(repoKey, before, after string) []WikiPageChange

WikiPagesChanged reports what a wiki commit range did to the wiki's pages, as the gollum webhook carries. github's payload has no vocabulary for a deletion, so a commit that only removes pages produces no entries.

func (*Store) WikiTipSHA

func (st *Store) WikiTipSHA(repoKey string) string

WikiTipSHA is the object id of the wiki's tip commit, or "" when it has none.

func (*Store) WorkflowConcurrencyPeersLocked

func (st *Store) WorkflowConcurrencyPeersLocked(repoFullName, group string) []*Workflow

WorkflowConcurrencyPeersLocked snapshots the non-completed workflows in a concurrency group, lazily pruning entries completed since indexing. Callers hold the write lock.

func (*Store) WorkflowsForRepoLocked

func (st *Store) WorkflowsForRepoLocked(repoFullName string) []*Workflow

WorkflowsForRepoLocked returns the workflow runs belonging to a repository — the per-repo run-listing index instead of a scan of every run in the instance. Operator-submitted runs (empty RepoFullName) match every repository, matching the handler's historical filter, so they are folded in. Callers hold the lock; the returned slice is a fresh list of the live pointers.

type StrategyDef

type StrategyDef struct {
	Matrix      MatrixDef `yaml:"matrix"`
	FailFast    *bool     `yaml:"fail-fast"`
	MaxParallel int       `yaml:"max-parallel"`
}

StrategyDef represents a job's strategy configuration.

type SubjectChange

type SubjectChange struct {
	// Pre-edit values behind an `edited` payload's `changes` member.
	TitleFrom   *string
	BodyFrom    *string
	BaseRefFrom *string

	// Full sets; the emitter diffs them into one action per entry that entered or left.
	LabelsFrom    []int
	LabelsTo      *[]int
	AssigneesFrom []int
	AssigneesTo   *[]int

	// Previous / requested milestone id (0 = none/cleared); To nil when untouched.
	MilestoneFrom int
	MilestoneTo   *int

	// Store states ("OPEN", "CLOSED", "MERGED"); only a real transition acts.
	StateFrom string
	StateTo   string
}

SubjectChange records what one mutation changed on an issue or PR, supplying the before/after pairs the webhook layer diffs to fan a single API call out into per-field actions (`edited`, `labeled`, `closed`, ...). Both REST and GraphQL feed it. A nil pointer or empty state means the field was untouched; *From scalars are set only on a real change, so a no-op delivers nothing.

type TaskAgentMessage

type TaskAgentMessage struct {
	MessageID   int64  `json:"messageId"`
	MessageType string `json:"messageType"`
	IV          string `json:"iv,omitempty"`
	Body        string `json:"body"`
	// Labels carries the job's runs-on requirements for broker routing; JobID
	// links the envelope to its engine job. Neither is serialized to the runner.
	Labels []string `json:"-"`
	JobID  string   `json:"-"`
}

TaskAgentMessage is the message envelope sent to the runner.

type Team

type Team struct {
	ID                  int                       `json:"id"`
	NodeID              string                    `json:"node_id"`
	OrgID               int                       `json:"org_id"`
	Name                string                    `json:"name"`
	Slug                string                    `json:"slug"`
	Description         string                    `json:"description"`
	Privacy             TeamPrivacy               `json:"privacy"`
	Permission          TeamPermission            `json:"permission"`
	NotificationSetting TeamNotificationSetting   `json:"notification_setting"`
	ParentID            int                       `json:"parent_id"` // 0 = no parent team
	MemberIDs           []int                     `json:"member_ids"`
	MaintainerIDs       []int                     `json:"maintainer_ids"`   // subset of MemberIDs with the maintainer role
	RepoNames           []string                  `json:"repo_names"`       // "owner/name" entries
	RepoPermissions     map[string]TeamPermission `json:"repo_permissions"` // per-repo override; nil/missing entry uses Permission
	// ReviewAssignment narrows a review requested from the team to a subset of
	// members when enabled; nil means never configured ("not enabled").
	ReviewAssignment *TeamReviewAssignment `json:"review_assignment,omitempty"`
	CreatedAt        time.Time             `json:"created_at"`
	UpdatedAt        time.Time             `json:"updated_at"`
}

Team represents a team within an organization.

func (*Team) RoleOf

func (t *Team) RoleOf(userID int) (TeamRole, bool)

RoleOf returns the user's team role and whether they're a member.

type TeamNotificationSetting

type TeamNotificationSetting string

TeamNotificationSetting is GitHub's team notification enum.

const (
	TeamNotificationsEnabled  TeamNotificationSetting = "notifications_enabled"
	TeamNotificationsDisabled TeamNotificationSetting = "notifications_disabled"
)

type TeamOptions

type TeamOptions struct {
	Description         string
	Privacy             TeamPrivacy
	Permission          TeamPermission
	NotificationSetting TeamNotificationSetting
	ParentID            int
}

TeamOptions carries the optional attributes of team creation.

type TeamPermission

type TeamPermission string

TeamPermission is the default repository permission a team confers.

const (
	TeamPermissionPull  TeamPermission = "pull"
	TeamPermissionPush  TeamPermission = "push"
	TeamPermissionAdmin TeamPermission = "admin"
)

type TeamPrivacy

type TeamPrivacy string

TeamPrivacy is GitHub's team visibility enum.

const (
	TeamPrivacyClosed TeamPrivacy = "closed"
	TeamPrivacySecret TeamPrivacy = "secret"
)

type TeamReviewAssignment

type TeamReviewAssignment struct {
	Enabled bool `json:"enabled"`
	// Algorithm is ROUND_ROBIN or LOAD_BALANCE.
	Algorithm                    string `json:"algorithm"`
	TeamMemberCount              int    `json:"team_member_count"`
	NotifyTeam                   bool   `json:"notify_team"`
	IncludeChildTeamMembers      bool   `json:"include_child_team_members"`
	RemoveTeamRequest            bool   `json:"remove_team_request"`
	CountMembersAlreadyRequested bool   `json:"count_members_already_requested"`
	ExcludedTeamMemberIDs        []int  `json:"excluded_team_member_ids,omitempty"`
}

TeamReviewAssignment is a team's code-review assignment settings.

type TeamRole

type TeamRole string

TeamRole is a user's role within a team.

const (
	TeamRoleMember     TeamRole = "member"
	TeamRoleMaintainer TeamRole = "maintainer"
)

type ThreadSubscription

type ThreadSubscription struct {
	Subscribed bool      `json:"subscribed"`
	Ignored    bool      `json:"ignored"`
	Reason     string    `json:"reason"`
	CreatedAt  time.Time `json:"created_at"`
}

ThreadSubscription tracks a user's subscription to a notification thread.

type TimelineLogRef

type TimelineLogRef struct {
	ID int `json:"id"`
}

TimelineLogRef points a timeline record at its uploaded log file.

type TimelineRecord

type TimelineRecord struct {
	ID         string          `json:"id"`
	ParentID   string          `json:"parentId"`
	Type       string          `json:"type"`
	Name       string          `json:"name"`
	RefName    string          `json:"refName"`
	Order      int             `json:"order"`
	State      string          `json:"state"`  // pending | inProgress | completed
	Result     string          `json:"result"` // succeeded | failed | skipped | canceled | abandoned
	StartTime  string          `json:"startTime"`
	FinishTime string          `json:"finishTime"`
	Log        *TimelineLogRef `json:"log"`
}

TimelineRecord is the slice of the runner's timeline record bleephub consumes for per-step status, timing and log association. Type is "Job" for the job record and "Task" for each step.

type Token

type Token struct {
	// Value is returned once at mint and held only by the minting process;
	// persistence keys tokens by a digest and never serializes the credential.
	Value               string `json:"-"`
	UserID              int
	Scopes              string
	CreatedAt           time.Time
	FineGrained         bool              `json:"fine_grained,omitempty"`
	FineGrainedID       int               `json:"fine_grained_id,omitempty"`
	Name                string            `json:"name,omitempty"`
	ResourceOwner       string            `json:"resource_owner,omitempty"`
	RepositorySelection string            `json:"repository_selection,omitempty"`
	RepositoryIDs       []int             `json:"repository_ids,omitempty"`
	Permissions         OrgPATPermissions `json:"permissions,omitempty"`
	ExpiresAt           *time.Time        `json:"expires_at,omitempty"`
	// Impersonation marks a GHES site-admin impersonation OAuth token; GHES
	// permits at most one active impersonation authorization per user.
	Impersonation bool   `json:"impersonation,omitempty"`
	Note          string `json:"note,omitempty"`
	NoteURL       string `json:"note_url,omitempty"`
	Fingerprint   string `json:"fingerprint,omitempty"`
}

Token represents a personal access token.

type TwoFactorConfig

type TwoFactorConfig struct {
	Secret string `json:"secret,omitempty"`
	// Pending marks a provisioned-but-unproved secret: the account is NOT
	// protected until a code confirms the authenticator holds it.
	Pending      bool      `json:"pending,omitempty"`
	PendingSince time.Time `json:"pending_since,omitempty"`
	Enabled      bool      `json:"enabled,omitempty"`
	EnrolledAt   time.Time `json:"enrolled_at,omitempty"`
	// LastStep is the highest TOTP counter already spent; replaying one inside
	// its validity window is refused.
	LastStep                 int64          `json:"last_step,omitempty"`
	RecoveryCodes            []RecoveryCode `json:"recovery_codes,omitempty"`
	RecoveryCodesGeneratedAt time.Time      `json:"recovery_codes_generated_at,omitempty"`
}

TwoFactorConfig is the stored second-factor state for one account.

type TwoFactorMethod

type TwoFactorMethod string

TwoFactorMethod names one second factor bleephub implements. The set is closed and reported verbatim by the authentication view.

const (
	TwoFactorMethodTOTP TwoFactorMethod = "totp"
	// TwoFactorMethodRecoveryCode is a static single-use secret the user retypes,
	// so — unlike a TOTP — a phished code stays valid until spent. This is the
	// insecure method GitHub's "insecure 2FA methods" policy targets.
	TwoFactorMethodRecoveryCode TwoFactorMethod = "recovery_code"
)

func InsecureTwoFactorMethods

func InsecureTwoFactorMethods() []TwoFactorMethod

InsecureTwoFactorMethods is the subset of the catalogue an enterprise disallows when its two-factor-disallowed-methods policy is INSECURE.

type TwoFactorMethodDescription

type TwoFactorMethodDescription struct {
	Method   TwoFactorMethod `json:"method"`
	Insecure bool            `json:"insecure"`
	Summary  string          `json:"summary"`
}

TwoFactorMethodDescription is one catalogue entry: the method, whether it is classed insecure, and why.

func SupportedTwoFactorMethods

func SupportedTwoFactorMethods() []TwoFactorMethodDescription

SupportedTwoFactorMethods is the truthful catalogue of second factors bleephub implements. GitHub's insecure method is SMS; this instance has no telephone factor, so it is absent rather than listed and unenforced.

type TwoFactorStatus

type TwoFactorStatus struct {
	Enabled                  bool      `json:"enabled"`
	PendingEnrollment        bool      `json:"pending_enrollment"`
	EnrolledAt               time.Time `json:"enrolled_at,omitzero"`
	RecoveryCodesTotal       int       `json:"recovery_codes_total"`
	RecoveryCodesRemaining   int       `json:"recovery_codes_remaining"`
	RecoveryCodesGeneratedAt time.Time `json:"recovery_codes_generated_at,omitzero"`
}

TwoFactorStatus is the secret-free second-factor view a read endpoint returns.

type UnfinishedMigration

type UnfinishedMigration struct {
	Scope MigrationScope
	ID    int
}

UnfinishedMigration names one migration an export worker still owes work on.

type User

type User struct {
	ID           int                  `json:"id"`
	NodeID       string               `json:"node_id"`
	Login        string               `json:"login"`
	Name         string               `json:"name"`
	Email        string               `json:"email"`
	AvatarURL    string               `json:"avatar_url"`
	Bio          string               `json:"bio"`
	Type         string               `json:"type"`
	SiteAdmin    bool                 `json:"site_admin"`
	Suspended    bool                 `json:"suspended,omitempty"`
	StarredRepos map[string]time.Time `json:"starred_repos,omitempty"`
	// PinnedRepos is the user's ordered pinned-repo full names (max 6); a web-only
	// feature served from /ui-data.
	PinnedRepos []string `json:"pinned_repos,omitempty"`
	// Status is the profile status the changeUserStatus mutation sets; one per account.
	Status    *UserStatus `json:"status,omitempty"`
	CreatedAt time.Time   `json:"created_at"`
	UpdatedAt time.Time   `json:"updated_at"`
	// Account security + notification preferences are web-only (no REST), served
	// from /ui-data. TwoFactor holds the TOTP secret and recovery-code digests;
	// it is store-only state reachable only through account_security.go.
	TwoFactor               *TwoFactorConfig         `json:"two_factor,omitempty"`
	NotificationPreferences *NotificationPreferences `json:"notification_preferences,omitempty"`
	Blog                    string                   `json:"blog,omitempty"`
	Company                 string                   `json:"company,omitempty"`
	Location                string                   `json:"location,omitempty"`
	TwitterUsername         string                   `json:"twitter_username,omitempty"`
	Hireable                *bool                    `json:"hireable,omitempty"`
	Emails                  []UserEmail              `json:"emails,omitempty"`
	InteractionLimit        string                   `json:"interaction_limit,omitempty"`
	InteractionLimitExpiry  *time.Time               `json:"interaction_limit_expiry,omitempty"`
	PasswordHash            string                   `json:"password_hash,omitempty"`
	// ExternalIdentities binds the account to the stable (issuer, subject) pairs
	// its providers guarantee, so a mutable username cannot re-key the account and
	// one provider cannot overwrite another's grant.
	ExternalIdentities []ExternalIdentity `json:"external_identities,omitempty"`
	// SCIMManagedByOrg names the org whose SCIM owns this account, if any. Only
	// that org's SCIM may mutate the account's global login/name/email; an account
	// provisioned outside SCIM (empty) is never adopted, or any org owner could
	// rename or re-home an arbitrary global account.
	SCIMManagedByOrg string `json:"scim_managed_by_org,omitempty"`
}

User represents a GitHub user account.

func ActionsBotUser

func ActionsBotUser() *User

ActionsBotUser is the principal a workflow's GITHUB_TOKEN acts as, matching GitHub's `github-actions[bot]`. Its negative-app-id scheme lets a resource it authors attribute back through ActorUserLocked (ACT-014).

func ActorUserLocked

func ActorUserLocked(st *Store, id int) *User

ActorUserLocked resolves persisted users and derived App-bot IDs. Caller holds st.Mu.

func AppBotUser

func AppBotUser(app *App) *User

AppBotUser derives the Bot actor for installation-token writes from the app. The negative ID cannot collide with a real user.

func FindUserByNodeID

func FindUserByNodeID(st *Store, nodeID string) *User

func GhostUser

func GhostUser() *User

type UserEmail

type UserEmail struct {
	Email      string `json:"email"`
	Primary    bool   `json:"primary"`
	Verified   bool   `json:"verified"`
	Visibility string `json:"visibility,omitempty"` // "public", "private", or "" (null)
}

UserEmail is one email address on a user account (GitHub's `email` schema).

type UserKey

type UserKey struct {
	ID        int       `json:"id"`
	Key       string    `json:"key"`
	Title     string    `json:"title"`
	Verified  bool      `json:"verified"`
	UserID    int       `json:"user_id"`
	CreatedAt time.Time `json:"created_at"`
	// contains filtered or unexported fields
}

UserKey json tags shape the persisted row (responses go through userKeyToJSON); UserID must round-trip to rebuild KeysByUser.

type UserList

type UserList struct {
	ID          int    `json:"id"`
	NodeID      string `json:"node_id"`
	UserID      int    `json:"user_id"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	Description string `json:"description,omitempty"`
	IsPrivate   bool   `json:"is_private"`
	// RepoIDs are the repositories on the list, in the order they were added.
	RepoIDs     []int      `json:"repo_ids,omitempty"`
	LastAddedAt *time.Time `json:"last_added_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

UserList is one named list a user sorts starred repositories into, public or private, with a slug derived from its name.

func FindUserListByNodeID

func FindUserListByNodeID(st *Store, nodeID string) *UserList

FindUserListByNodeID resolves a UserList global node id.

type UserMigration

type UserMigration struct {
	MigrationCommon
	UserID int `json:"-"`
}

UserMigration is a user-scoped GitHub migration export.

type UserNamespaceAccessGrant

type UserNamespaceAccessGrant struct {
	ID           int       `json:"id"`
	EnterpriseID int       `json:"enterprise_id"`
	RepoID       int       `json:"repo_id"`
	GranteeID    int       `json:"grantee_id"`
	ExpiresAt    time.Time `json:"expires_at"`
}

UserNamespaceAccessGrant is an enterprise owner's temporary access to a user-namespace repository of a managed account. It admits its holder wherever a collaborator grant would, and nowhere else.

type UserNotificationsState

type UserNotificationsState struct {
	LastReadAt         time.Time            `json:"last_read_at,omitempty"`
	RepoLastReadAt     map[string]time.Time `json:"repo_last_read_at,omitempty"`
	ReadThreadIDs      map[string]time.Time `json:"read_thread_ids,omitempty"`
	DismissedThreadIDs map[string]bool      `json:"dismissed_thread_ids,omitempty"`
	// SavedThreadIDs backs the web inbox's Saved view (not part of REST).
	SavedThreadIDs map[string]bool                `json:"saved_thread_ids,omitempty"`
	Subscriptions  map[string]*ThreadSubscription `json:"subscriptions,omitempty"`
}

UserNotificationsState persists per-user notification read/subscription state.

type UserStatus

type UserStatus struct {
	UserID int    `json:"user_id"`
	Emoji  string `json:"emoji,omitempty"`
	// Message is the status text. An empty message with an emoji is still a
	// status, not its absence.
	Message string `json:"message,omitempty"`
	// OrganizationID scopes the status to one organization's members when set.
	OrganizationID int `json:"organization_id,omitempty"`
	// LimitedAvailability is GitHub's "busy" flag.
	LimitedAvailability bool       `json:"limited_availability,omitempty"`
	ExpiresAt           *time.Time `json:"expires_at,omitempty"`
	CreatedAt           time.Time  `json:"created_at"`
	UpdatedAt           time.Time  `json:"updated_at"`
}

UserStatus is the message, emoji and availability a user sets on their profile. GitHub keeps one per account, so it lives on the account and its node id derives from the account's.

type UserToServerToken

type UserToServerToken struct {
	Token             string            `json:"token"`
	UserID            int               `json:"user_id"`
	AppID             int               `json:"app_id"`              // set for ghu_ (GitHub App user-to-server)
	OAuthAppClientID  string            `json:"oauth_app_client_id"` // set for gho_ (OAuth App user token)
	Scopes            string            `json:"scopes"`              // classic OAuth scopes when gho_
	InstallationIDs   []int             `json:"installation_ids,omitempty"`
	Permissions       map[string]string `json:"permissions,omitempty"`    // nil means not permission-scoped
	RepositoryIDs     []int             `json:"repository_ids,omitempty"` // nil means not repository-scoped
	ExpiresAt         time.Time         `json:"expires_at"`
	RefreshTokenValue string            `json:"refresh_token_value,omitempty"`
	CreatedAt         time.Time         `json:"created_at"`
	Note              string            `json:"note,omitempty"`
	NoteURL           string            `json:"note_url,omitempty"`
	Fingerprint       string            `json:"fingerprint,omitempty"`
}

UserToServerToken is an OAuth-derived token bearing a user identity. Two prefix variants: gho_ (classic OAuth-App user token) sets OAuthAppClientID and classic Scopes; ghu_ (GitHub-App user-to-server) sets AppID and is scoped to installation permissions.

func CloneUserToServerToken

func CloneUserToServerToken(token *UserToServerToken) *UserToServerToken

type VerifiableDomain

type VerifiableDomain struct {
	ID        int    `json:"id"`
	NodeID    string `json:"node_id"`
	OwnerType string `json:"owner_type"`
	OwnerID   int    `json:"owner_id"`
	// Domain is stored normalized (NormalizeVerifiedDomain).
	Domain            string    `json:"domain"`
	VerificationToken string    `json:"verification_token"`
	TokenExpiresAt    time.Time `json:"token_expires_at"`
	IsVerified        bool      `json:"is_verified"`
	IsApproved        bool      `json:"is_approved"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
}

VerifiableDomain is one domain on an owner's verification ledger. OwnerType ("Enterprise" or "Organization") disambiguates OwnerID, which is drawn from separate id sequences.

func FindVerifiableDomainByNodeID

func FindVerifiableDomainByNodeID(st *Store, nodeID string) *VerifiableDomain

FindVerifiableDomainByNodeID resolves a domain global id to the LIVE row.

type VisualStudioSubscription

type VisualStudioSubscription struct {
	SubscriptionID string `json:"subscription_id"`
	Email          string `json:"email"`
	Username       string `json:"username,omitempty"`
	ManualMatch    bool   `json:"manual_match"`
}

type Webhook

type Webhook struct {
	ID          int      `json:"id"`
	URL         string   `json:"config_url"`
	Secret      string   `json:"secret"`
	ContentType string   `json:"content_type"`
	InsecureSSL string   `json:"insecure_ssl"`
	Events      []string `json:"events"`
	Active      bool     `json:"active"`
	RepoKey     string   `json:"-"`
	// OrgLogin marks an org-level hook; like RepoKey it equals the bucket key and the loader backfills it.
	// Exactly one of RepoKey/OrgLogin is set (both empty = app-level pseudo-hook).
	OrgLogin string `json:"-"`
	// MarketplaceSlug marks a Marketplace webhook; listing persistence owns its configuration.
	MarketplaceSlug string `json:"-"`
	// Global marks an appliance-wide GHES webhook owned by EnterpriseSettings.
	Global bool `json:"-"`
	// LastResponse is the outcome of the most recent delivery; nil until one occurs (rendered "unused").
	LastResponse *HookLastResponse `json:"last_response,omitempty"`
	CreatedAt    time.Time         `json:"created_at"`
	UpdatedAt    time.Time         `json:"updated_at"`
}

Webhook represents a GitHub repository webhook.

Secret is persisted (deliveries must keep signing X-Hub-Signature-256 after a restart) but never marshaled to clients (hookToJSON omits it). RepoKey stays json:"-": it equals the persistence bucket key ("owner/name"), which the loader backfills on reload.

func CloneWebhook

func CloneWebhook(h *Webhook) *Webhook

CloneWebhook detaches every mutable child from the store-owned hook. Callers must hold st.Mu when cloning a Store-owned hook.

type WebhookDelivery

type WebhookDelivery struct {
	ID             int               `json:"id"`
	HookID         int               `json:"hook_id"`
	AppID          int               `json:"app_id,omitempty"`
	InstallationID int               `json:"installation_id,omitempty"`
	RepositoryID   int               `json:"repository_id,omitempty"`
	TargetURL      string            `json:"url"`
	GUID           string            `json:"guid"`
	Event          string            `json:"event"`
	Action         string            `json:"action"`
	StatusCode     int               `json:"status_code"`
	Duration       float64           `json:"duration"`
	Request        *DeliveryRequest  `json:"request"`
	Response       *DeliveryResponse `json:"response"`
	Redelivery     bool              `json:"redelivery"`
	DeliveredAt    time.Time         `json:"delivered_at"`
	ThrottledAt    *time.Time        `json:"throttled_at"`
}

WebhookDelivery records a single delivery attempt for a webhook.

type WikiPage

type WikiPage struct {
	Slug      string    `json:"slug"`
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	Path      string    `json:"-"`
	RepoKey   string    `json:"-"`
	Author    string    `json:"author,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

WikiPage projects a page from the `<repo>.wiki.git` repository, which is the wiki. It is not stored; every field is derived. See store_wiki_git.go.

type WikiPageChange

type WikiPageChange struct {
	Slug     string
	Title    string
	PageName string
	Action   string
	SHA      string
}

WikiPageChange is one page a wiki commit range changed, as the gollum webhook reports.

type WikiPageRevision

type WikiPageRevision struct {
	ID        int       `json:"id"`
	Slug      string    `json:"slug"`
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	Editor    string    `json:"editor,omitempty"`
	Message   string    `json:"message,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

WikiPageRevision is one commit that changed a wiki page, with the full body at that commit. Reverting is a client-side PUT of an old body — no server revert.

type WikiProjection

type WikiProjection struct {
	Tip       plumbing.Hash
	Branch    string
	Pages     map[string]*WikiPage
	Revisions map[string][]*WikiPageRevision
}

WikiProjection is the wiki's tip commit read as pages, stamped with the tip it was derived from. A projection whose Tip is not the current tip is stale and discarded, not patched.

type Workflow

type Workflow struct {
	ID           string                  `json:"id"`
	Name         string                  `json:"name"`
	DisplayTitle string                  `json:"displayTitle,omitempty"`
	RunID        int                     `json:"runId"`
	RunNumber    int                     `json:"runNumber"`
	Jobs         map[string]*WorkflowJob `json:"jobs"`
	Env          map[string]string       `json:"env,omitempty"`
	Permissions  PermissionDef           `json:"permissions,omitempty"`
	Status       WorkflowStatus          `json:"status"`
	// PendingDeployments holds one record per reviewer-protected environment
	// the run waits on; EnvApprovals records every review submitted.
	PendingDeployments []*PendingDeployment `json:"pendingDeployments,omitempty"`
	EnvApprovals       []*EnvApproval       `json:"envApprovals,omitempty"`
	Result             Result               `json:"result"`
	CreatedAt          time.Time            `json:"createdAt"`
	MaxParallel        int                  `json:"-"` // fallback for directly-constructed runs
	MatrixMaxParallel  map[string]int       `json:"-"`
	CancelTimeout      func()               `json:"-"` // stops the timeout watcher goroutine
	EventName          string               `json:"eventName,omitempty"`
	Ref                string               `json:"ref,omitempty"`
	Sha                string               `json:"sha,omitempty"`
	RepoFullName       string               `json:"repoFullName,omitempty"`
	Inputs             map[string]string    `json:"inputs,omitempty"`
	ConcurrencyGroup   string               `json:"concurrencyGroup,omitempty"`
	CancelInProgress   bool                 `json:"-"`
	// ConcurrencyAcquiredAt is when this run took its concurrency group's
	// lease; zero without a group or while still queued behind it.
	ConcurrencyAcquiredAt time.Time `json:"-"`
	// Attempt is the 1-based run_attempt (zero means first); reruns bump it
	// and archive the prior attempt in Store.WorkflowAttempts.
	Attempt int `json:"attempt,omitempty"`
	// CancelRequested marks a run winding down; always()/cancelled() jobs may
	// still dispatch, and it finalizes with conclusion cancelled.
	CancelRequested bool `json:"-"`
	// EventPayload is the triggering webhook payload (github.event); not
	// persisted (in-flight runs aren't).
	EventPayload map[string]interface{} `json:"-"`
	// TypedInputs is the typed `inputs` context; Inputs keeps the string forms.
	TypedInputs map[string]interface{} `json:"-"`

	// WorkflowFileID / WorkflowFilePath identify the originating workflow FILE,
	// which GitHub's WorkflowRun.workflow_id/.path reference (not the run), so
	// they are carried separately from RunID. Zero/"" until resolved lazily in
	// workflowRunJSON.
	WorkflowFileID   int64  `json:"workflowFileId,omitempty"`
	WorkflowFilePath string `json:"workflowFilePath,omitempty"`
	CheckSuiteID     int64  `json:"checkSuiteId,omitempty"`
}

Workflow represents a running multi-job workflow.

func (*Workflow) AttemptNumber

func (wf *Workflow) AttemptNumber() int

AttemptNumber returns the 1-based run_attempt (the zero value is the first attempt).

func (*Workflow) RunDisplayTitle

func (wf *Workflow) RunDisplayTitle() string

type WorkflowCallBinding

type WorkflowCallBinding struct {
	CalledPath string
	CalledRepo string
	// With holds the caller's raw input templates; InputDefs the called
	// workflow's declarations (typing + defaults).
	With      map[string]string
	InputDefs map[string]*WorkflowInputDef
	// SecretsInherit / SecretsMap mirror the caller job's `secrets:`.
	SecretsMap     map[string]string
	SecretsInherit bool
	// Parent is the enclosing call's binding, or nil at the top. `secrets:
	// inherit` inherits the CALLING workflow's already-narrowed set, so secret
	// resolution walks this chain outermost-first.
	Parent     *WorkflowCallBinding `json:"-"`
	OutputDefs map[string]string
	// CalledJobKeys are the expanded keys of the called workflow's jobs;
	// CallerKey is the public caller job key (the needs-context prefix).
	CalledJobKeys []string
	CallerKey     string

	Mu sync.Mutex `json:"-"`
	// contains filtered or unexported fields
}

WorkflowCallBinding links the jobs produced by one reusable-workflow call: the gate resolves the caller's `with:` templates, called jobs read the resolved inputs, and the collector maps outputs onto the caller job key.

func (*WorkflowCallBinding) ResolvedInputs

func (b *WorkflowCallBinding) ResolvedInputs() map[string]interface{}

ResolvedInputs returns the typed inputs, nil until the gate ran.

func (*WorkflowCallBinding) SetResolvedInputs

func (b *WorkflowCallBinding) SetResolvedInputs(in map[string]interface{})

type WorkflowDef

type WorkflowDef struct {
	Name        string            `yaml:"name"`
	RunName     string            `yaml:"run-name"`
	Env         map[string]string `yaml:"env"`
	Permissions PermissionDef     `yaml:"permissions"`
	Defaults    RunDefaults       `yaml:"defaults"`
	Concurrency *ConcurrencyDef
	Jobs        map[string]*JobDef
}

WorkflowDef represents a parsed GitHub Actions workflow YAML.

func ParseWorkflow

func ParseWorkflow(yamlBytes []byte) (*WorkflowDef, error)

ParseWorkflow parses a GitHub Actions workflow YAML definition.

type WorkflowFile

type WorkflowFile struct {
	ID           int64     `json:"id"`
	Name         string    `json:"name"`
	Path         string    `json:"path"`
	State        string    `json:"state"`
	RepoFullName string    `json:"repo_full_name"`
	NodeID       string    `json:"node_id"`
	BadgeURL     string    `json:"badge_url"`
	YAML         string    `json:"yaml"`
	Source       string    `json:"source"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

WorkflowFile is the file-level workflow entity (the YAML on disk), distinct from the run-level Workflow. Source is "submitted" (registered when YAML lands at /api/v3/bleephub/workflow) or "discovered" (walked from git). The latest registration of a (repo, path) pair wins, so a fresh push refreshes the cached YAML. Every field must round-trip: a restored row with empty RepoFullName or YAML is undispatchable (422).

type WorkflowInputDef

type WorkflowInputDef struct {
	Description string        `yaml:"description"`
	Required    bool          `yaml:"required"`
	Default     interface{}   `yaml:"default"`
	Type        string        `yaml:"type"` // string | choice | boolean | number | environment
	Options     []interface{} `yaml:"options"`
}

WorkflowInputDef is a declared workflow_dispatch / workflow_call input.

type WorkflowJob

type WorkflowJob struct {
	Key             string                 `json:"key"`   // YAML key
	JobID           string                 `json:"jobId"` // UUID, used as Job.ID
	PlanID          string                 `json:"planId,omitempty"`
	DisplayName     string                 `json:"displayName"`
	Needs           []string               `json:"needs,omitempty"`
	Status          JobStatus              `json:"status"`
	Result          Result                 `json:"result"`
	Outputs         map[string]string      `json:"outputs,omitempty"`
	MatrixValues    map[string]interface{} `json:"matrix,omitempty"`
	ContinueOnError bool                   `json:"continueOnError,omitempty"`
	QueuedAt        time.Time              `json:"queuedAt,omitempty"`
	StartedAt       time.Time              `json:"startedAt,omitempty"`
	CompletedAt     time.Time              `json:"completedAt,omitempty"`
	MatrixGroup     string                 `json:"matrixGroup,omitempty"`
	Summary         string                 `json:"summary,omitempty"`
	Def             *JobDef                `json:"-"`
	// Hidden marks synthetic reusable-workflow gate/collector nodes the jobs
	// API never lists.
	Hidden bool `json:"hidden,omitempty"`
	// CheckRunID links the job to the check run mirroring it.
	CheckRunID int64 `json:"checkRunId,omitempty"`
	// ConcurrencyGroup is the evaluated jobs.<id>.concurrency.group, persisted
	// separately from Def so a waiting job survives a restart without
	// re-evaluating against changed dependency outputs.
	ConcurrencyGroup string `json:"concurrencyGroup,omitempty"`
	CancelInProgress bool   `json:"cancelInProgress,omitempty"`
}

WorkflowJob represents a single job within a workflow.

type WorkflowPermissions

type WorkflowPermissions struct {
	DefaultWorkflowPermissions   string `json:"default_workflow_permissions"`
	CanApprovePullRequestReviews bool   `json:"can_approve_pull_request_reviews"`
}

type WorkflowStatus

type WorkflowStatus string

WorkflowStatus is the lifecycle state of a Workflow.

const (
	WorkflowStatusRunning            WorkflowStatus = "running"
	WorkflowStatusCompleted          WorkflowStatus = "completed"
	WorkflowStatusPendingConcurrency WorkflowStatus = "pending_concurrency"
	// WorkflowStatusWaiting holds runs awaiting a deployment review on a
	// reviewer-protected environment.
	WorkflowStatusWaiting WorkflowStatus = "waiting"
	// WorkflowStatusActionRequired holds fork-PR runs awaiting maintainer
	// approval before any job dispatches (.../runs/{run_id}/approve releases it).
	WorkflowStatusActionRequired WorkflowStatus = "action_required"
)

Source Files

Jump to

Keyboard shortcuts

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