repos

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Overview

Package repos provides reusable per-repo installation logic for fullsend. It decouples the core install flow (scaffold commit, variable/secret writes) from CLI concerns (prompts, spinners, flag parsing) so that both the interactive CLI and future bulk-install commands can share the same logic.

Package repos implements parsing, validation, and resolution of the repos.yaml declarative manifest that drives multi-repo management (ADR 0057).

Index

Constants

View Source
const (
	ForgeGitHub = "github"
	ForgeGitLab = "gitlab"
)

Forge type constants used in the manifest's platform sections.

View Source
const (
	MintModePublic  = "public"
	MintModePrivate = "private"

	DefaultPublicMintURL = "https://mint.fullsend.sh"
)

Mint mode constants control the default mint URL for GitHub repos.

View Source
const (
	InferenceAuthVertexWIF    = "vertex-wif"
	InferenceAuthOpenAIAPIKey = "openai-api-key"
	// InferenceAuthOpenAIWIF selects OpenAI Workload Identity Federation
	// (ADR 0092). It needs no Fullsend-managed secret: the runtime
	// exchanges the GitHub Actions OIDC token using three non-secret
	// identifiers delivered as repository variables or through
	// .fullsend/config.yaml. GitHub only.
	InferenceAuthOpenAIWIF = "openai-wif"
)

Inference authentication methods accepted by inference.auth in repos.yaml and by repos install --inference-auth. There is no built-in default: every repository must resolve an explicit selection from its entry, its forge section, or defaults.

View Source
const (

	// DefaultScaffoldBranch is the branch name for fresh installations. It
	// is also reused for uninstall PR delivery (see UninstallPRMetadata)
	// since already-deployed per-repo shims only exclude this branch name
	// from triggering the fullsend dispatch job.
	DefaultScaffoldBranch = "fullsend/scaffold-install"

	// ScaffoldBumpBranchPrefix is the branch prefix for version upgrades.
	ScaffoldBumpBranchPrefix = "fullsend/bump-"
)
View Source
const ActionAdoptionRequired = "adoption-required"

ActionAdoptionRequired marks a ComponentAction reporting that an existing managed .fullsend/config.yaml predates ADR-0122 adoption (missing the ownership marker) and was therefore left untouched. It is deliberately distinct from "none" so convergeRepo's hasAction check below still counts a pending adoption as outstanding work instead of classifying the repo AlreadyCurrent.

View Source
const ActionSafetyRejected = "safety-rejected"

ActionSafetyRejected marks a ComponentAction reporting that the candidate managed configuration is less restrictive than the current effective configuration and the manifest did not declare that relaxation (ADR 0122). Distinct from "error" so status/adoption output can identify the affected keys without treating a parse failure as the same class of problem.

View Source
const DefaultGitHubURL = "https://github.com"

DefaultGitHubURL is the default forge URL for GitHub.com.

View Source
const GitLabPipelineVarRestrictionEnv = "FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION"

GitLabPipelineVarRestrictionEnv controls automatic project-setting changes. Typed dispatch activation always requires no_one_allowed, even when this flag is unset or disabled. Enforcement is blocked while managed schedules use pipeline variables; existing schedules are migrated before activation. ADR 0125 live validation remains a rollout prerequisite. An invalid flag value is an error.

View Source
const GitLabProjectLeaseVar = "FULLSEND_GITLAB_INSTALL_LEASE"

GitLabProjectLeaseVar names the project CI/CD variable that serves as the cross-process lease for GitLab role-credential and webhook transactions. It exists only while an installer holds it and carries no secret.

View Source
const GitLabWebhookName = "fullsend webhook dispatcher"

GitLabWebhookName is the name of the Fullsend-managed project webhook. GitLab instances older than 17.1 ignore webhook names, so an unnamed hook is Fullsend-managed only when its trigger URL embeds the stored FULLSEND_TRIGGER_TOKEN (see isFullsendWebhook).

View Source
const GitLabWebhookTriggerDescription = "fullsend webhook dispatcher"

GitLabWebhookTriggerDescription is the description of the Fullsend-managed pipeline trigger token. It identifies the token on probe and rotation.

View Source
const NoneSentinel = "none"

NoneSentinel is the YAML value that explicitly clears an inherited field in the override cascade. Use "fullsend_ref: none" in YAML to stop the per-repo → platform-default → built-in-default chain.

Variables

View Source
var ErrPollerContainmentIncomplete = errors.New("containment is incomplete")

ErrPollerContainmentIncomplete marks a ContainPoller failure that leaves a credential usable on the Poller account. Its text is authored by fullsend and is kept when failClosedPoller sanitizes API failures.

View Source
var ErrPollerSuppliedUnresolved = ErrSuppliedCredentialUnresolved

ErrPollerSuppliedUnresolved is an alias of ErrSuppliedCredentialUnresolved, kept for the later stacked PRs that use the Poller-specific name; errors.Is matches either.

View Source
var ErrSuppliedCredentialUnresolved = errors.New("supplied role credential ownership is unresolved")

ErrSuppliedCredentialUnresolved reports that an installed role credential (the Poller's or any other role's) is recorded as administrator-supplied but its owning account could not be attributed, so no same-named account can be treated as fullsend-managed.

View Source
var ValidDefaultKeys = []string{
	"defaults.allowed_remote_resources",
	"defaults.runtime",
	"defaults.inference.auth",
	"defaults.vendor",
	"defaults.config_base.source",
	"defaults.config_base.sha256",
	"github.url",
	"github.mint_url",
	"github.mint_mode",
	"github.fullsend_ref",
	"github.inference.auth",
	"gitlab.url",
	"gitlab.fullsend_ref",
	"gitlab.inference.auth",
	"gitlab.agent_runner_tags",
	"gitlab.control_runner_tags",
	"gitlab.runner_tags",
}

ValidDefaultKeys lists the manifest keys that can be set via `repos set-default`. Order matches the help text.

View Source
var WIFProviderPattern = regexp.MustCompile(
	`^projects/\d+/locations/global/workloadIdentityPools/[a-z][a-z0-9-]{2,30}[a-z0-9]/providers/[a-z][a-z0-9-]{2,30}[a-z0-9]$`,
)

WIFProviderPattern validates the full WIF provider resource name format required by google-github-actions/auth@v3. GCP pool/provider IDs: 4-32 chars, [a-z0-9-], start with letter, no trailing hyphen.

Functions

func AddToManifest added in v0.32.0

func AddToManifest(ctx context.Context, cfg ManifestEditConfig, forgeName string, entries []RepoEntry, clients ForgeClientFactory, progress ProgressFunc) (*ManifestAddResult, *Manifest, error)

AddToManifest appends repo entries to the appropriate platform section, skipping duplicates. The forgeName parameter determines which platform section receives the entries. When client is non-nil, each non-glob repo is probed for existing installation state and per-repo overrides are populated where the discovered values differ from platform defaults. Returns the result and the modified manifest. The manifest is written to disk only when ManifestPath is set and DryRun is false.

func AllMatch added in v0.37.0

func AllMatch(components []ComponentStatus) bool

AllMatch returns true when every ComponentStatus has Match == true.

func AppendGitLabPipelineRefStatus added in v0.44.0

func AppendGitLabPipelineRefStatus(ctx context.Context, client forge.Client, owner, repo string, userIDs []int, status *RepoStatus) bool

AppendGitLabPipelineRefStatus reports drift when the poller cannot create pipelines on the protected default branch. Returns true when a new drift entry was added. Missing repo metadata or unsupported forges are skipped rather than failing the whole status check.

func BuildScaffoldFiles

func BuildScaffoldFiles(cfg InstallConfig) ([]forge.TreeFile, error)

BuildScaffoldFiles generates the scaffold tree files for a per-repo install. Exported so the CLI dry-run path can display the file list without running the full install.

func CarveOutGlobCovered added in v0.46.0

func CarveOutGlobCovered(ctx context.Context, cfg ManifestEditConfig, names []string, clients ForgeClientFactory, apply func(forgeName string, platform *PlatformConfig, entry *RepoEntry) error) ([]string, error)

CarveOutGlobCovered gives each concrete repository in names that is covered only by a glob entry its own explicit entry, copied from the glob that resolution would use, and passes the new entry to apply together with its forge name and platform section so per-entry overrides can be recorded while the glob's other settings are preserved. When globs on more than one forge cover a name, the forge whose expansion discovers the repository is used (when clients is non-nil); undiscovered names use the first covering glob, GitHub before GitLab. Sibling repositories covered by the glob are left untouched. Names that already have an explicit entry, or that no glob covers, are skipped. An error from apply aborts before the manifest is written. Returns the names that received a new entry; the manifest is written when any did and DryRun is not set.

func ContainGitLabPoller added in v0.46.0

func ContainGitLabPoller(ctx context.Context, userID int64, inventory GitLabPollerContainmentOperations) error

ContainGitLabPoller invalidates managed authentication paths and reports every remaining path without deleting administrator-owned resources.

func DriftFieldName added in v0.37.0

func DriftFieldName(componentName string) string

DriftFieldName returns the component name without its category prefix, suitable for use as a Drift.Field value. "var:FULLSEND_MINT_URL" becomes "FULLSEND_MINT_URL"; "workflow" stays "workflow".

func EnrichGitLabRoleStatus added in v0.44.0

func EnrichGitLabRoleStatus(ctx context.Context, client forge.Client, owner, repo string, tokens []ProjectAccessToken, now time.Time, status *RepoStatus) bool

EnrichGitLabRoleStatus re-runs DiagnoseLifecycle with a token inventory so repos status can report expiry, revocation, and overlapping replacements. tokens may be nil. It reports whether any lifecycle drift entries were newly added to status.Drifts; callers must not assume a false return means the repo is otherwise free of drift, only that this call did not add to it.

func ExpectedScaffoldContent added in v0.38.0

func ExpectedScaffoldContent(ctx context.Context, resolved ResolvedConfig, dcfg DriftConfig, refResolver *RefResolver) ([]forge.TreeFile, error)

ExpectedScaffoldContent renders the scaffold files that a fresh install would produce for the given resolved config. The status path uses this to compare against installed files for content drift detection — when the rendered template differs from the installed file, the repo's scaffold is stale even if the ref string matches.

When fullsend_ref pins a version that differs from the running binary, the refResolver fetches remote scaffold templates from the pinned ref so the baseline matches the pinned version, not the embedded templates. This mirrors the converge path's FetchRemoteScaffold logic. Both paths share driftInstallConfig as the underlying input builder and BuildScaffoldFiles as the renderer.

Returns (nil, nil) when FullsendRef is empty — there is no expected ref to compare against.

func FetchRemoteScaffold added in v0.37.0

func FetchRemoteScaffold(ctx context.Context, ghClient forge.Client,
	manifestRef, resolvedSHA, forgeName string,
	agentRunnerTags, controlRunnerTags []string,
	vendored bool,
) (scaffold.InstallFiles, error)

FetchRemoteScaffold fetches scaffold templates from fullsend-ai/fullsend at the given ref and renders them for the specified forge. This is used when fullsend_ref pins to a version that differs from the running binary, so embedded templates would be incorrect.

Callers should skip this function when vendored is true: the running binary's embedded templates already match the binary being committed to the repo, so there is no version-skew concern and the remote fetch would add unnecessary API latency.

Template paths (scaffoldGitHubShimPath, scaffoldGitLabPaths) are pinned to the current binary's layout. If the remote ref reorganises these paths, the fetch returns an error. GitLab mutation paths must not fall back to embedded templates: their pipeline-input contract may be incompatible with the pinned version. Other callers may use best-effort fallback.

func GitLabBaseURL added in v0.46.0

func GitLabBaseURL(client forge.Client) string

GitLabBaseURL returns client's GitLab instance base URL, or "" when the client does not expose one.

func GitLabCleanupContext added in v0.46.0

func GitLabCleanupContext(ctx context.Context) (context.Context, context.CancelFunc)

GitLabCleanupContext is gitlabCleanupContext for GitLabTriggerOwner implementations, which budget each compensating request independently. Compensating requests after the Poller was raised to Maintainer must still reach GitLab when the operation context is canceled, or the Poller could keep standing Maintainer access.

func GitLabPATExpiresAt added in v0.44.0

func GitLabPATExpiresAt(now time.Time) string

GitLabPATExpiresAt returns the YYYY-MM-DD expiry GitLab expects for a project access token. GitLab evaluates expires_at in UTC.

func GitLabPipelineVarRestrictionEnforced added in v0.44.0

func GitLabPipelineVarRestrictionEnforced() bool

GitLabPipelineVarRestrictionEnforced reports whether setting changes are enabled.

func GitLabUsesTypedDispatch added in v0.46.0

func GitLabUsesTypedDispatch(ctx context.Context, client forge.Client, owner, repo string) (bool, error)

GitLabUsesTypedDispatch reports the installed wrapper's transport contract. A pending fresh install is gated separately against its queued scaffold. An installed wrapper that declares an incomplete spec:inputs contract is rejected rather than silently treated as legacy — see requireCompleteGitLabDispatchContract.

func GitLabWebhookNeedsProvisioning added in v0.46.0

func GitLabWebhookNeedsProvisioning(ctx context.Context, client forge.Client, baseURL, owner, repo string) (bool, error)

GitLabWebhookNeedsProvisioning reports whether the webhook fast-path is missing or misconfigured on owner/repo. It is read-only and is the convergence signal behind ConvergeResult.NeedsGitLabWebhook.

func GitLabWebhookTriggerURL added in v0.46.0

func GitLabWebhookTriggerURL(baseURL string, projectID int64, ref, token string) string

GitLabWebhookTriggerURL returns the native pipeline-trigger URL a project webhook posts to: :ref is pinned to ref so the triggered pipeline runs on that (protected) branch regardless of the payload. The result embeds token and must never be logged.

func HasFullsendEntries added in v0.38.0

func HasFullsendEntries(existing []byte) bool

HasFullsendEntries reports whether existing .gitlab-ci.yml content already contains all fullsend CI entries. It performs semantic drift detection by checking:

  1. include: contains the fullsend-pipeline.yml entry
  2. If stages: exists, it contains dispatch, poll, agent (if no stages: key, the included pipeline provides them).
  3. If workflow: exists, it must have a rules: sequence containing fullsend's if: conditions. If workflow: exists without rules:, that is drift — MergeGitLabCI would add them. (if no workflow: block at all, fullsend's jobs self-filter)

Used by the installer to skip unnecessary .gitlab-ci.yml writes when all entries are already present, avoiding YAML formatting churn.

func IsGitLabRoleManagedVar added in v0.44.0

func IsGitLabRoleManagedVar(name string) bool

IsGitLabRoleManagedVar reports whether a FULLSEND_* CI/CD variable is a GitLab role-credential artifact (registry, built-in or custom role secret), or the legacy shared token. This is an orphan-detection classification only: it tells drift/orphan scans that the name is recognized role-identity state, not an unmanaged leftover. It does not mean the variable is removed on uninstall — the legacy FULLSEND_FORGE_TOKEN shared token is deliberately excluded from automatic uninstall cleanup (see gitLabRoleUninstallVars and extraGitLabRoleUninstallVars) and requires manual cleanup.

func IsNumeric added in v0.34.0

func IsNumeric(s string) bool

IsNumeric reports whether s contains only ASCII digits.

func IsValidForge added in v0.33.0

func IsValidForge(name string) bool

IsValidForge reports whether the given forge name is supported.

func IsValidGCPProjectID added in v0.34.0

func IsValidGCPProjectID(s string) bool

IsValidGCPProjectID checks that s matches the GCP project ID format: 6-30 characters, lowercase letters, digits, and hyphens, starting with a letter.

func IsValidGCPRegion added in v0.34.0

func IsValidGCPRegion(s string) bool

IsValidGCPRegion checks that s looks like a GCP region: lowercase letters, digits, and hyphens (e.g. "us-central1", "europe-west4").

func IsValidRef added in v0.32.0

func IsValidRef(ref string) bool

IsValidRef reports whether ref contains only characters safe for use in GitHub Actions workflow uses: lines.

func LoadGitLabRoleState added in v0.44.0

func LoadGitLabRoleState(ctx context.Context, client forge.Client, owner, repo string) (gitlabroles.Registry, map[string]bool, error)

LoadGitLabRoleState reads the registered role policy and per-secret presence from a repository. Migration state is deliberately not read.

func LockGitLabProject added in v0.46.0

func LockGitLabProject(ctx context.Context, client forge.Client, owner, repo string, dryRun bool) (func(errp *error), error)

LockGitLabProject serializes every GitLab role-credential and webhook write transaction on one project: within this process by a mutex, and across installer processes (any host) by a lease taken atomically on the project itself (see forge.ProjectLeaser). The returned release function must be deferred with the caller's error pointer; it frees the lease and joins a failed release into *errp so a stuck lease is reported rather than silent. A dry run takes only the process-local mutex, since it must not write to the project. A nil error pointer still releases both locks but discards release errors.

It fails closed: a client that cannot take a lease, or a lease that stays held past the wait budget, is an error, and the caller must not proceed with credential or webhook changes. The lease is never taken over: a held lease is reported, not removed. The lease is not reentrant.

func ManagedGitLabLegacyTokenIDs added in v0.46.0

func ManagedGitLabLegacyTokenIDs(ctx context.Context, client forge.Client, owner, repo string) ([]int, error)

ManagedGitLabLegacyTokenIDs returns explicit creation records, never inferred IncomingID/outgoing/name-based distribution proof. Callers fail closed.

func ManagedGitLabRoleAccountID added in v0.46.0

func ManagedGitLabRoleAccountID(ctx context.Context, client forge.Client, owner, repo string, role gitlabroles.Role) (int, error)

ManagedGitLabRoleAccountID returns only durable account-creation provenance. A role name or minted-token ID does not authorize changing a same-named account. Missing provenance returns zero; unreadable state fails closed.

func ManagedGitLabRoleAccountIDs added in v0.46.0

func ManagedGitLabRoleAccountIDs(ctx context.Context, client forge.Client, owner, repo string) ([]int, error)

ManagedGitLabRoleAccountIDs lists positively recorded account IDs for the destructive token-client boundaries. Supplied exclusions are applied by the caller independently and always take precedence.

func ManagedGitLabRoleAccountNames added in v0.46.0

func ManagedGitLabRoleAccountNames(ctx context.Context, client forge.Client, owner, repo string) (map[int]string, error)

ManagedGitLabRoleAccountNames maps durable account-creation IDs to their expected role display names. Like ManagedGitLabRoleAccountIDs, it leaves supplied-account exclusions to the caller, where they override ownership. Removed custom registrations retain their derived name for uninstall, which retires the registry before account cleanup. Unreadable state fails closed.

func MarshalWithHeader added in v0.31.0

func MarshalWithHeader(m *Manifest) ([]byte, error)

MarshalWithHeader serializes the manifest with a descriptive header comment. Like Manifest.Marshal, it does not mutate the receiver — the deprecated runner_tags migration runs against a shallow copy.

func MatchManifestRepos added in v0.32.0

func MatchManifestRepos(manifest *Manifest, patterns []string) ([]string, error)

MatchManifestRepos returns the list of repo names from the manifest that match any of the given patterns. Used by CLI commands to resolve positional args (which may contain globs) against manifest entries.

func MergeGitLabCI added in v0.38.0

func MergeGitLabCI(existing []byte) ([]byte, error)

MergeGitLabCI merges fullsend's CI configuration into an existing .gitlab-ci.yml. It uses yaml.v3's Node API to preserve comments and formatting in the existing file.

The merge performs up to three operations:

  1. Appends an include entry for .gitlab/ci/fullsend-pipeline.yml (skipped if already present)
  2. Appends fullsend's current stages (dispatch, poll, agent) to the existing stages: array, deduplicating if already present. Skipped when no stages: key exists.
  3. When a workflow: block already exists, merges workflow:rules entries (deduplicates by if: condition) and sets auto_cancel.on_new_commit: none if not present. When no workflow: block exists, it is left absent so the repo's push-triggered pipelines are not disrupted.

When existing is nil or empty, returns a minimal .gitlab-ci.yml with just the fullsend include and workflow block.

func MergeMissingGitLabDebugTraceRule added in v0.44.0

func MergeMissingGitLabDebugTraceRule(existing []byte) (result []byte, changed bool, err error)

MergeMissingGitLabDebugTraceRule adds fullsend's CI_DEBUG_TRACE deny-before-admit workflow rule (ADR 0125) to an existing .gitlab-ci.yml when it is missing, leaving everything else — including any already-present fullsend rules, the workflow name, auto_cancel settings, and any user configuration — untouched.

This backfills already-enrolled repos: MergeGitLabCI (and the debug-trace rule it adds via fullsendWorkflowRules) only runs on fresh installs — the install call site skips it once HasFullsendEntries is true — and the periodic converge/upgrade path does not otherwise touch workflow:rules. Without this, a repo enrolled before this rule existed would never pick it up, leaving a debug-trace pipeline able to reach an admit rule and dump secrets at job init.

The rule is only merged when gitlabCIWorkflowIsFullsendOwned finds positive evidence that fullsend, not the repo owner, installed the workflow block — the same ownership gate StripObsoleteGitLabWorkflowRules uses — so a user's own hand-written workflow: block is never modified.

Returns the original content and changed=false when there is nothing to merge (no workflow: block, the rule is already present, or fullsend ownership of the block can't be established).

func PollerCanCreatePipeline added in v0.44.0

func PollerCanCreatePipeline(rule *forge.ProtectedBranchRule, userIDs []int) bool

PollerCanCreatePipeline reports whether a Developer-level poller can create pipelines on the given protected ref. A nil rule means the branch is not protected and CreatePipeline does not need merge/push access. GitLab allows pipeline creation when the caller may merge or push; Developer (30) is included by any role-based grant at 30 or below (except 0, "No one"), or when a poller user ID is listed.

func PollerPipelineUserIDs added in v0.44.0

func PollerPipelineUserIDs(tokens []ProjectAccessToken) []int

PollerPipelineUserIDs returns the GitLab user IDs of active poller identities: the shared fullsend-bot token and the fullsend-poller role token. Analyst/coder tokens are omitted because they do not call CreatePipeline. Inactive, revoked, or zero-user-id tokens are skipped.

func ReconcileManagedPollersForUninstall added in v0.46.0

func ReconcileManagedPollersForUninstall(ctx context.Context, client forge.Client, to GitLabTriggerOwner, owner, repo string, userIDs []int64) error

ReconcileManagedPollersForUninstall restores every listed managed Poller account (duplicates included) to at most Developer access, verifying the effective level, and revokes and verifies revocation of its bootstrap credentials. Every account is attempted and the failures are joined: a failure means the cleanup could not be confirmed, and uninstall must fail so the manifest entry is retained for retry. Server text is withheld from errors because it may echo credentials the redactor does not know.

func RecordManagedGitLabLegacyToken added in v0.46.0

func RecordManagedGitLabLegacyToken(ctx context.Context, client forge.Client, owner, repo string, token *ProjectAccessToken) error

RecordManagedGitLabLegacyToken records only the result of a token creation performed by this installer. It must never be called from inventory/backfill.

func RejectExtraneousURLParts added in v0.43.0

func RejectExtraneousURLParts(u *url.URL, field string) error

RejectExtraneousURLParts validates that a parsed URL contains only scheme and host — no path, userinfo, query, or fragment. The field parameter is used in error messages to identify the source.

func RemoveFromManifest added in v0.32.0

func RemoveFromManifest(cfg ManifestEditConfig, repos []string, progress ProgressFunc) (*ManifestRemoveResult, *Manifest, error)

RemoveFromManifest removes matching repo entries from all platform sections in the manifest. Patterns containing glob characters (*, ?, [) are matched against manifest entries using filepath.Match. Returns the result and the modified manifest.

func RuntimeSection added in v0.38.0

func RuntimeSection(runtime string) string

RuntimeSection renders the "Runtime" section appended to the scaffold PR body so the reviewer of a setup PR sees which agent runtime the repo will use and how to change it. An empty runtime means the default.

func SafeAPIError added in v0.46.0

func SafeAPIError(op string, err error) error

SafeAPIError reports an operation failure without the server's error text, for callers outside this package that handle credential-bearing calls. errors.Is and errors.As still see the original error.

func ScaffoldPathsForForge added in v0.34.0

func ScaffoldPathsForForge(forgeName string) []string

ScaffoldPathsForForge returns the scaffold file paths to delete for the given forge during uninstall.

func ScheduleVariablesFor added in v0.46.0

func ScheduleVariablesFor(spec ScheduleSpec, typed bool) map[string]string

ScheduleVariablesFor returns the pipeline variables to submit when creating the given schedule spec. When typed reports that the repo's effective GitLab wrapper is not yet on the typed pipeline-input contract, it returns the legacy FULLSEND_POLL_MODE override so slash and event polling keep working; otherwise it returns the spec's (variable-free) defaults. Exported so every schedule-creation call site — convergeSchedules and the CLI's post-install fresh-install path (setupGitLabPipelineSchedules) — selects variables from the same transport-aware logic instead of risking drift between two copies.

func SetDefault added in v0.34.0

func SetDefault(manifestPath, key, value string) error

SetDefault sets or removes a platform-level default in the manifest. An empty value removes the key. The file is created with version: 1 if it does not exist.

func StripObsoleteGitLabStages added in v0.44.0

func StripObsoleteGitLabStages(existing []byte) (result []byte, changed bool, err error)

StripObsoleteGitLabStages removes obsolete fullsend stages (see obsoleteGitLabStages) from an existing .gitlab-ci.yml, leaving everything else — including fullsend's current stages, user stages, includes, and workflow configuration — untouched. Unlike UnmergeGitLabCI (full teardown) this never removes fullsend's current stages; it only migrates away stages that are strictly obsolete.

An obsolete stage is only a stripping candidate when the file shows positive evidence that fullsend, not the repo owner, installed it: the fullsend pipeline include is present (this is an enrolled root CI file) AND at least one current fullsend stage is in the stages list (mergeStages ran and appended poll/agent alongside dispatch). A lone "dispatch" stage without poll or agent is treated as the repo's own and left in place. This gate differs from gitlabCIWorkflowIsFullsendOwned (workflow.name) because mergeStages never sets workflow.name — the merge-path repos that actually have stages: in the root file are exactly those that lack the name marker. Gating on the name would make this migration a no-op for the files that need it. "dispatch" is also not GitLab's standard MR-pipeline gate; the include-plus-current-stage fingerprint is the analogue of fullsend ownership for stages.

That fingerprint proves fullsend touched the stages: array, but not that a stage literally named "dispatch" is safe to delete — a repo enrolled via the merge path could independently have its own job on a "dispatch" stage, coexisting with fullsend's poll/agent. Deleting a stage that a job still references breaks the pipeline (GitLab rejects a job whose stage: isn't in stages:). So before removing an obsolete stage name, stageReferencedByJob scans top-level job definitions — including stages inherited via extends: or the YAML merge key (<<:) — for an effective stage: value matching it and, if found, leaves that stage in place — mirroring the conservative refusal gitlabCIWorkflowIsFullsendOwned already applies to the workflow: block. This scan only sees the root file's own top-level keys, so a second, non-fullsend include is also treated as absence of evidence: the root file might not be the whole picture, and a job living in that other include would be invisible to the scan.

Returns the original content and changed=false when there is nothing to strip (no stages: block, no obsolete stage present, fullsend ownership of the stages list can't be established, a non-fullsend include is also present, or every obsolete stage present is still referenced by a job).

func StripObsoleteGitLabWorkflowRules added in v0.44.0

func StripObsoleteGitLabWorkflowRules(existing []byte) (result []byte, changed bool, err error)

StripObsoleteGitLabWorkflowRules removes obsolete fullsend workflow:rules entries (see obsoleteGitLabWorkflowRules) from an existing .gitlab-ci.yml, leaving everything else — including fullsend's current rules, the workflow name, auto_cancel settings, and any user configuration — untouched. Unlike UnmergeGitLabCI (full teardown) this never removes fullsend's current entries; it only migrates away rules that are strictly obsolete.

An obsolete rule is only stripped when gitlabCIWorkflowIsFullsendOwned finds positive evidence that fullsend, not the repo owner, installed the workflow block — the obsolete condition ($CI_PIPELINE_SOURCE == "merge_request_event") is GitLab's standard MR-pipeline gate and repos commonly set it themselves.

Returns the original content and changed=false when there is nothing to strip (no workflow: block, no rules:, no obsolete rule present, or fullsend ownership of the block can't be established).

func UninstallSecretsForForge added in v0.34.0

func UninstallSecretsForForge(forgeName string) []string

UninstallSecretsForForge returns the CI/CD secret names to delete for the given forge during uninstall.

func UninstallVarsForForge added in v0.34.0

func UninstallVarsForForge(forgeName string) []string

UninstallVarsForForge returns the CI/CD variable names to delete for the given forge during uninstall.

func UnmergeGitLabCI added in v0.38.0

func UnmergeGitLabCI(existing []byte) ([]byte, error)

UnmergeGitLabCI removes fullsend's CI configuration from a .gitlab-ci.yml. It removes the fullsend pipeline include entry and the fullsend workflow:rules entries. Returns the cleaned YAML, or nil if the file has no remaining meaningful content.

func UpdateAppSet added in v0.44.0

func UpdateAppSet(cfg ManifestEditConfig, filters []string, appSet string) ([]string, error)

UpdateAppSet applies a GitHub app-set override to manifest entries selected by filters. A concrete filter matching a glob entry gets an explicit entry so the override is limited to that repository; glob filters update the matching glob entries. The manifest is written when it changed unless DryRun is set.

func UpdateInferenceAuth added in v0.46.0

func UpdateInferenceAuth(ctx context.Context, cfg ManifestEditConfig, filters []string, auth string, clients ForgeClientFactory) ([]string, error)

UpdateInferenceAuth persists an inference.auth selection on the manifest entries selected by filters, in both forge sections. With no filters every entry is updated. A concrete filter that matches no explicit entry but is covered by a glob gets a new explicit entry copied from the first matching glob (the same glob resolution would use), so the repository keeps that glob's other overrides while sibling repositories are left untouched. The selection is never written to defaults or to a forge section.

A glob filter that is narrower than (or merely overlaps) a glob manifest entry cannot select that entry without changing sibling repositories, so when clients is non-nil the glob entries are expanded the same way convergence expands them and each concrete repository matching a filter gets its own copied explicit entry. Glob entries selected directly by an identical filter pattern are updated in place and are not expanded further. With a nil clients factory no expansion happens.

Returns the names of entries whose value changed; the manifest is written only when something changed and DryRun is not set.

func UsableGitLabSSHKeyIDs added in v0.46.0

func UsableGitLabSSHKeyIDs(keys []GitLabAuthenticationKey, now time.Time) []int

UsableGitLabSSHKeyIDs returns authentication paths that prevent temporary elevation or verified containment. Unknown usage or malformed expiry is conservatively usable; signing-only and expired keys cannot authenticate.

func ValidInferenceAuths added in v0.46.0

func ValidInferenceAuths() []string

ValidInferenceAuths returns the accepted inference.auth values in documentation order.

func ValidateAllowedRemoteResourcesFormat added in v0.44.0

func ValidateAllowedRemoteResourcesFormat(field string, list []string) error

ValidateAllowedRemoteResourcesFormat checks that every entry in an allowed_remote_resources allowlist (repos.yaml defaults, a per-repo shorthand, or the shorthand once baked into a managed configuration file) is a well-formed prefix: a valid HTTPS URL, ending with "/", with no double-encoded sequences. These are the same format rules harness.ValidateAllowedRemoteResources applies at `fullsend run`/`lock` time; that check runs too late to guard this write path, since MatchingAllowedPrefixInList does a plain strings.HasPrefix match and a prefix missing its trailing slash can therefore match sibling hosts/paths it should not. It does not check coverage against an config-level allowlist — that requires the harness, which is not loaded here. Exported so repos.yaml write paths outside this package (the CLI's --allowed-remote-resources flag, `repos set-default`) can reject a malformed prefix before it is ever persisted, matching the check Manifest.Validate applies on load/converge.

func ValidateGitLabPipelineVarRestrictionEnv added in v0.46.0

func ValidateGitLabPipelineVarRestrictionEnv() error

ValidateGitLabPipelineVarRestrictionEnv rejects malformed automation modes.

func ValidateInferenceAuth added in v0.46.0

func ValidateInferenceAuth(key, value string) error

ValidateInferenceAuth accepts an empty value (inherit) or one of ValidInferenceAuths. The key names the offending field or flag in the error message.

func ValidateInferenceAuthForForge added in v0.46.0

func ValidateInferenceAuthForForge(forgeName, auth string) error

ValidateInferenceAuthForForge rejects an inference.auth selection the forge cannot satisfy. OpenAI Workload Identity Federation exchanges a GitHub Actions OIDC token, so it is GitHub only; a GitLab repository must use openai-api-key (or vertex-wif) instead.

func VerifyGitLabAccountDeletion added in v0.46.0

func VerifyGitLabAccountDeletion(ctx context.Context, userID int, inventory GitLabAccountDeletionInventory) error

VerifyGitLabAccountDeletion refuses deletion if credentials or owned resources remain, or any inventory cannot be verified. PATs are checked separately by managed-account cleanup before this resource check.

func VerifyGitLabPollerCredentials added in v0.46.0

func VerifyGitLabPollerCredentials(ctx context.Context, userID int64, revoked bool, inventory GitLabPollerCredentialInventory) error

VerifyGitLabPollerCredentials refuses elevation when credentials or owned resources could inherit temporary Maintainer access.

Types

type ComponentAction added in v0.38.0

type ComponentAction struct {
	Component string // e.g., "workflow", "thin-caller:<path>", "var:MINT_URL", "schedule:<name>", "ref"
	Action    string // "none", "add", "update", "upgrade", "delete", "orphan", "error", ActionAdoptionRequired, ActionSafetyRejected
	Detail    string // human-readable detail
}

ComponentAction describes an action taken (or planned) on a single installation component during convergence.

type ComponentStatus added in v0.37.0

type ComponentStatus struct {
	// Name identifies the component, prefixed by category:
	//   "workflow", "thin-caller:<path>", "scaffold:<path>", "var:<name>",
	//   "secret:<name>", "schedule:<name>", "openai-wif:<name>"
	Name string

	// Present is true when the component exists on the forge.
	Present bool

	// Expected is the manifest's desired value. Empty when value
	// checking does not apply (e.g., secrets whose values cannot be
	// read back, or when no expected value was provided).
	Expected string

	// Actual is the component's current value on the forge. Empty
	// when the component is not present or its value is opaque.
	Actual string

	// Match is true when the component meets its requirement. When no
	// inference.auth is selected, both GCP secrets absent is also a match
	// because Vertex is optional (see ProbeComponentsForAuth).
	Match bool
}

ComponentStatus describes the state of a single installation component as probed from the forge. Both install and status use this to answer "what's wrong with this repo?" — install acts on the answer, status reports it.

func ProbeComponents added in v0.37.0

func ProbeComponents(ctx context.Context, client forge.Client, owner, repo, forgeName string, fc ForgeConfig, expectedVarValues map[string]string) ([]ComponentStatus, error)

ProbeComponents checks all per-repo installation components and returns their status.

Components checked:

  • Shim workflow file (presence)
  • GitLab trust script (presence)
  • Per-repo thin callers (presence, GitHub only)
  • Required variables (presence; values compared when expectedVarValues contains a non-empty entry for the variable name)
  • Required secrets (presence only — values cannot be read back)

expectedVarValues maps variable names to their expected values for value-level drift detection. Pass nil for presence-only checking.

func ProbeComponentsForAuth added in v0.46.0

func ProbeComponentsForAuth(ctx context.Context, client forge.Client, owner, repo, forgeName, auth string, fc ForgeConfig, expectedVarValues map[string]string) ([]ComponentStatus, error)

ProbeComponentsForAuth is ProbeComponents for a repository whose effective inference.auth is known. The secrets probed are the ones that carry the selected method's credentials (inferenceSecretsForAuth), and each must be present to match. An empty auth keeps the legacy behavior: the GCP pair is probed and both absent counts as a match. openai-wif probes the GCP pair the same optional way and adds an openai-wif:identifiers component that matches only when a complete set of OpenAI WIF identifiers is live on the default branch. Installed repos also report openai-wif:workflows for their live workflow contract.

type ConfigBase added in v0.44.0

type ConfigBase struct {
	Source string `yaml:"source,omitempty"`
	SHA256 string `yaml:"sha256,omitempty"`
	// contains filtered or unexported fields
}

ConfigBase is the nested config_base object in repos.yaml. Source is a local path or HTTPS URL written as .fullsend/config.base.yaml; SHA256 is an optional digest matching github setup --config-hash. Empty Source inherits the parent value; "none" disables inheritance. Empty SHA256 inherits the parent digest; "none" skips validation.

type ContentDriftFile added in v0.38.0

type ContentDriftFile struct {
	// Path is the expected path from the template. Use InstalledPath
	// when reporting drift to show the actual location on the forge.
	Path string

	// InstalledPath is the actual path of the file on the forge. For
	// workflow files this may differ from Path due to extension
	// differences (.yml vs .yaml).
	InstalledPath string

	// Expected is the rendered template content for this file.
	Expected []byte
}

ContentDriftFile describes a scaffold file whose installed content differs from the expected template output after ref normalization.

func CheckFileContentDrift added in v0.38.0

func CheckFileContentDrift(ctx context.Context, client forge.Client,
	owner, repo string, fc ForgeConfig, forgeName string,
	expectedFiles []forge.TreeFile) ([]ContentDriftFile, error)

CheckFileContentDrift compares expected scaffold files against installed files on the forge, returning files whose content has drifted. Refs are normalized with replaceShimRef before comparison so that ref-format differences (tag vs SHA, annotation presence) do not produce false positives — ref drift is detected separately.

Both the status and converge paths use this function so they share the same comparison logic and cannot diverge.

Missing workflow and thin-caller files are handled by ProbeComponents; auxiliary scaffold files with forge-specific health semantics are also checked there.

type ConvergeBatchResult added in v0.38.0

type ConvergeBatchResult struct {
	Results []ConvergeResult
}

ConvergeBatchResult holds the aggregate outcome of a batch convergence.

func Converge added in v0.38.0

func Converge(ctx context.Context, cfg ConvergeConfig,
	clients ForgeClientFactory,
	commitScaffold ScaffoldCommitFunc,
	progress ProgressFunc) (*ConvergeBatchResult, error)

Converge processes every repo in the manifest through a single convergence pipeline: probe → diff → apply. For each repo it determines what components exist and what actions are needed, then applies only the necessary changes.

This replaces the former two-phase architecture where BatchInstall handled new repos and a separate Upgrade + Sync pass handled already-installed repos.

func (*ConvergeBatchResult) AlreadyCurrent added in v0.38.0

func (r *ConvergeBatchResult) AlreadyCurrent() []ConvergeResult

AlreadyCurrent returns results where no action was needed.

func (*ConvergeBatchResult) Converged added in v0.38.0

func (r *ConvergeBatchResult) Converged() []ConvergeResult

Converged returns results where repos had drifted components repaired.

func (*ConvergeBatchResult) Failed added in v0.38.0

func (r *ConvergeBatchResult) Failed() []ConvergeResult

Failed returns results that errored.

func (*ConvergeBatchResult) Installed added in v0.38.0

func (r *ConvergeBatchResult) Installed() []ConvergeResult

Installed returns results where repos were newly installed.

type ConvergeConfig added in v0.38.0

type ConvergeConfig struct {
	Manifest       *Manifest
	DryRun         bool
	RepoFilter     []string
	MaxConcurrency int

	// Roles is the list of agent roles to install (e.g., "triage", "coder").
	Roles []string

	// RolesExplicit is true when the caller explicitly passed --roles,
	// as opposed to Roles carrying the flag's own default value. Fresh
	// installs of a repo with a declared configuration preset use this
	// to decide whether to write roles into the overlay (explicit
	// override) or leave them unset so the preset's roles (or the
	// code-default fallback) take effect through the layered accessor
	// chain — see BuildScaffoldFiles.
	RolesExplicit bool

	// UpstreamRef is the git ref (SHA) used to pin scaffold workflow refs.
	UpstreamRef string
	// UpstreamTag is the version tag corresponding to UpstreamRef.
	UpstreamTag string

	// Direct controls scaffold delivery: true pushes directly to the
	// default branch; false creates a PR.
	Direct bool

	// Force allows downgrades when upgrading refs.
	Force bool

	// ReactivateSchedules opts in to reactivating a required GitLab
	// pipeline schedule (fullsend slash poll / fullsend event poll) that
	// exists but is disabled. Defaults to false: operators running
	// off-system polling (see "Off-system polling" in
	// configuring-gitlab.md) intentionally disable these schedules, so a
	// disabled-but-present schedule is reported as drift but left alone
	// unless this is set.
	ReactivateSchedules bool

	// InferenceProject is the GCP project ID for inference.
	InferenceProject string
	// InferenceProjectNumber is the numeric GCP project number,
	// auto-derived from InferenceProject when WIFProvider is not set.
	InferenceProjectNumber string
	// InferenceRegion is the GCP region for inference.
	InferenceRegion string

	// WIFProvider, when set, is used as the WIF provider resource name
	// for all repos instead of constructing per-repo provider IDs via
	// BuildRepoProviderID. This supports org-scoped WIF providers
	// (e.g., assertion.repository_owner == 'acme').
	WIFProvider string

	// ResolveProjectNumber, when set, derives the numeric project number
	// for InferenceProject when InferenceProjectNumber and WIFProvider are
	// both unset. It is called at most once, and only when a vertex-wif
	// repository needs a derived WIF provider, so OpenAI-only runs never
	// perform GCP lookups.
	ResolveProjectNumber func(ctx context.Context, projectID string) (string, error)

	// OpenAIAPIKey is the static OpenAI API key written as
	// FULLSEND_OPENAI_API_KEY to repositories whose inference.auth is
	// openai-api-key. Command-line input only: never persisted to the
	// manifest and never logged or reported.
	OpenAIAPIKey string

	// ReviewAppClientID is the OAuth client ID of the review agent's
	// GitHub App, pre-resolved by the caller for ReviewAppClientIDAppSet.
	// It seeds the per-repo resolution cache so repos on that app set
	// reuse it without a second lookup.
	ReviewAppClientID string

	// ReviewAppClientIDAppSet is the app set that ReviewAppClientID was
	// resolved for. Repos whose effective app set differs (via a per-repo
	// or platform app_set override) get their review client ID resolved
	// independently so FULLSEND_REVIEW_CLIENT_ID tracks the same app set
	// persisted as FULLSEND_APP_SET. Empty means ReviewAppClientID was
	// resolved for the built-in default app set.
	ReviewAppClientIDAppSet string

	// VendorOverride, when non-nil, overrides the manifest's resolved
	// vendor setting for all repos in this convergence run. This lets
	// `repos install --vendor` take effect without modifying the
	// manifest. When nil, the per-repo resolved Vendor field is used.
	VendorOverride *bool

	// ReadVendoredWorkflow, when non-nil, returns the content of a reusable
	// workflow (for example .github/workflows/reusable-prioritize.yml) that
	// a vendored install copies from the resolved vendor source, or an error
	// matching forge.ErrNotFound when the source lacks it. It lets the
	// openai-wif readiness check validate the workflows actually installed
	// rather than those at a remote ref. When nil, vendored installs are
	// checked against the remote ref like any other.
	ReadVendoredWorkflow func(path string) ([]byte, error)
}

ConvergeConfig holds all inputs for a convergence operation that processes every repo through a single pipeline: probe → diff → apply. It replaces the former two-phase architecture where BatchInstall handled new repos and Upgrade + Sync handled already-installed repos.

type ConvergeResult added in v0.38.0

type ConvergeResult struct {
	Owner   string
	Repo    string
	Actions []ComponentAction

	// Installed is true when the repo was not previously installed and
	// received a full install.
	Installed bool

	// NeedsGitLabPostInstall is true when GitLab pipeline schedules did
	// not already exist on the repo before this run. GitLab post-install
	// schedule setup is destructive — it deletes and recreates pipeline
	// schedules — so it must run only when those artifacts are genuinely
	// missing. Re-running install while the initialization MR is still
	// open (#7417) keeps Installed true (workflow file still absent) but
	// must not re-trigger this destructive setup once the schedules
	// already exist from a prior run. This is deliberately narrower than
	// "any fullsend-managed component exists" — the GCP inference secrets
	// every Install() writes are unrelated to GitLab post-install and
	// must not mask it having failed or never run. Shared-token bot-PAT
	// setup is gone: role credentials are the only GitLab runtime path.
	NeedsGitLabPostInstall bool

	// NeedsGitLabPipelineSchedules is true when at least one pipeline
	// schedule component (see PipelineScheduleSpecs) was not already
	// present before this run. Callers must gate pipeline-schedule setup
	// on this field, so a retry where the schedules already exist does
	// not delete and recreate them.
	NeedsGitLabPipelineSchedules bool

	// NeedsGitLabWebhook is true when the GitLab webhook fast-path (the
	// project webhook and its pipeline trigger token, ADR 0125) is
	// missing or misconfigured. It is a convergence signal, not an enable
	// gate: callers run the idempotent EnsureGitLabWebhookFastPath when it
	// is set, which provisions or repairs only the gap (and still defers
	// while its readiness gates are unmet). It is also true when the
	// probe could not complete, so the post-install step surfaces the
	// error instead of silently skipping the fast-path.
	NeedsGitLabWebhook bool

	// GitLabTypedDispatch reports whether the GitLab wrapper this run
	// installed (still possibly queued in an unmerged upgrade MR) uses the
	// pipeline-input dispatch contract rather than the legacy
	// pipeline-variable one. Set from InstallResult.GitLabTypedDispatch
	// for fresh installs (see Installed). Post-install schedule setup
	// must use this instead of re-reading the default branch, which can
	// still show the prior or absent wrapper while the install MR is
	// unmerged.
	GitLabTypedDispatch bool

	// Converged is true when the repo had drifted components that were
	// repaired (variables, refs, or missing scaffold files).
	Converged bool

	// AlreadyCurrent is true when all components matched and no action
	// was needed.
	AlreadyCurrent bool

	Error error

	// WIFProvider is the WIF provider resource name used during install.
	WIFProvider string
}

ConvergeResult holds the outcome of converging a single repo.

type DefaultsConfig

type DefaultsConfig struct {
	AllowedRemoteResources []string `yaml:"allowed_remote_resources,omitempty"`
	// Runtime is the default agent runtime for every repo (claude, pi, codex).
	Runtime string `yaml:"runtime,omitempty"`
	// Inference is the operator-provided default inference authentication
	// selection for every repository. It is not a built-in fallback: when
	// no level sets inference.auth, install/convergence/status report a
	// configuration error for the repository.
	Inference InferenceSettings `yaml:"inference,omitempty"`
	// Vendor, when true, vendors the fullsend binary and content into
	// each repo so CI does not need network access to fetch them.
	Vendor *bool `yaml:"vendor,omitempty"`
	// Signoff, when true, adds a Signed-off-by trailer for the
	// authenticated installing user to every scaffold commit created by
	// repos install. Forge sections and repository entries override it.
	Signoff *bool `yaml:"signoff,omitempty"`
	// ConfigBase is the default configuration preset, written as
	// .fullsend/config.base.yaml. Empty Source disables the default;
	// source "none" disables inheritance for entries that reference it.
	// SHA256 is an optional digest verified against the fetched preset.
	ConfigBase ConfigBase `yaml:"config_base,omitempty"`
	// Config is a fleet-wide sparse managed .fullsend/config.yaml
	// (ADR 0122). Presence opts every repository into managed configuration.
	Config config.ManagedConfig `yaml:"config,omitempty"`
}

DefaultsConfig holds default field values applied to every repo across all platforms.

type Drift added in v0.31.0

type Drift struct {
	Field    string `json:"field"`
	Expected string `json:"expected"`
	Actual   string `json:"actual"`
}

Drift describes a single field that differs between the manifest's desired state and the repo's actual state.

type DriftConfig added in v0.38.0

type DriftConfig struct {
	// UpstreamRef and UpstreamTag identify the running release. Matching
	// recorded refs use its embedded templates even without an upstream client.
	UpstreamRef string
	UpstreamTag string

	// InferenceRegion is the GCP region for inference. Only available
	// from CLI flags on repos install; empty on the status path.
	InferenceRegion string

	// ReviewAppClientID is the OAuth client ID of the review agent's
	// GitHub App. Only available from CLI flags on repos install.
	ReviewAppClientID string

	// AgentRunnerTags is a list of GitLab CI runner tags from the
	// manifest's GitLab platform section for agent (data-plane) jobs.
	AgentRunnerTags []string

	// ControlRunnerTags is a list of GitLab CI runner tags from the
	// manifest's GitLab platform section for control-plane jobs. Already
	// resolved through gitlabControlRunnerTags; independent of
	// AgentRunnerTags, so an unset control_runner_tags stays empty here.
	ControlRunnerTags []string
}

DriftConfig holds additional fields beyond ResolvedConfig that are needed to build a complete InstallConfig for drift detection. These fields come from the manifest or CLI flags and are not part of the per-repo resolved config.

type ForgeClientFactory added in v0.33.0

type ForgeClientFactory interface {
	// ConfigFor returns a ForgeConfig with a live Client for the named forge.
	// The factory lazily creates and caches clients, so a GitLab token is
	// only required if the manifest actually contains GitLab entries.
	ConfigFor(forgeName string) (ForgeConfig, error)
}

ForgeClientFactory creates ForgeConfig instances with a live Client. The CLI layer implements this with lazy client creation and caching.

type ForgeConfig added in v0.33.0

type ForgeConfig struct {
	// Client is the API client for this forge. Set by ForgeClientFactory;
	// nil when ForgeConfig is constructed by ForgeConfigFor (pattern-only).
	Client forge.Client

	// WorkflowPaths lists the shim workflow file paths to try, in order.
	WorkflowPaths []string

	// WorkflowRefPattern extracts the @ref from a fullsend shim workflow.
	WorkflowRefPattern *regexp.Regexp

	// ShimRefPattern matches all @ref occurrences in fullsend uses: lines
	// within a workflow file, used by upgrade to rewrite refs.
	ShimRefPattern *regexp.Regexp
}

ForgeConfig holds forge-specific CI paths and regex patterns used by status and upgrade operations. Each forge has different workflow file conventions and ref syntax. When populated by a ForgeClientFactory, the Client field carries a live API client for the forge.

func ForgeConfigFor added in v0.33.0

func ForgeConfigFor(forgeName string) ForgeConfig

ForgeConfigFor returns the ForgeConfig for the given forge name. Unknown values (including empty string) default to GitHub. This is intentional: callers in legacy code paths may pass an empty forge, and Validate() catches invalid forge names before they reach here.

func GitHubForgeConfig added in v0.33.0

func GitHubForgeConfig() ForgeConfig

GitHubForgeConfig returns the ForgeConfig for GitHub repositories. GitHub Actions workflow files live under .github/workflows/ and use the "uses: owner/repo/.github/workflows/file@ref" syntax.

func GitLabForgeConfig added in v0.33.0

func GitLabForgeConfig() ForgeConfig

GitLabForgeConfig returns the ForgeConfig for GitLab repositories. GitLab CI files live under .gitlab/ci/ and use include: directives with ref: fields. The pipeline wrapper carries the version marker (#7707). Native dispatch itself was removed in #7322 (see ADR 0067). ShimRefPattern matches the injected ref: marker line for upgrade drift detection. Leftover fullsend-dispatch.yml from installs before #7707 is still read for the installed ref by readWorkflowMarker.

type GitLabAccountDeletionInventory added in v0.46.0

type GitLabAccountDeletionInventory struct {
	SSHKeys   func(context.Context) ([]int, error)
	Jobs      func(context.Context) ([]int, error)
	Schedules func(context.Context) ([]int, error)
	Triggers  func(context.Context) ([]int, error)
}

GitLabAccountDeletionInventory supplies resource IDs that could remain usable or owned by an account. Adapters include resources with unknown owners conservatively. Every callback is required and must exhaust its inventory.

type GitLabAuthenticationKey added in v0.46.0

type GitLabAuthenticationKey struct {
	ID        int
	UsageType string
	ExpiresAt string
}

GitLabAuthenticationKey is the non-secret key metadata used to decide whether an account can still authenticate after its PATs are revoked.

type GitLabPipelineAccessResult added in v0.44.0

type GitLabPipelineAccessResult struct {
	Branch  string
	Action  string
	UserIDs []int
	Detail  string
}

GitLabPipelineAccessResult describes what EnsureGitLabPollerPipelineAccess did or would do for a repo's protected default branch.

func EnsureGitLabPollerPipelineAccess added in v0.44.0

func EnsureGitLabPollerPipelineAccess(ctx context.Context, client forge.Client, owner, repo string, userIDs []int, dryRun bool) (GitLabPipelineAccessResult, error)

EnsureGitLabPollerPipelineAccess makes a Developer-level poller able to CreatePipeline on the repo's default branch. When the branch is unprotected, or Developers already have merge or push, this is a no-op. Otherwise it grants each poller user merge access (not push) on that protected ref. GitHub clients that return ErrNotSupported are skipped.

type GitLabPipelineVarRestrictionResult added in v0.44.0

type GitLabPipelineVarRestrictionResult struct {
	// Role is the value observed before any change ("" if GitLab never
	// returned one, e.g. an older instance/edition).
	Role string
	// Action is none, blocked, update, would-update, or unsupported.
	Action string
	Detail string
}

GitLabPipelineVarRestrictionResult describes what EnsureGitLabPipelineVariableOverrideRole did or would do for a repo.

func ActivateGitLabTypedDispatch added in v0.46.0

func ActivateGitLabTypedDispatch(ctx context.Context, client forge.Client, owner, repo string, dryRun bool) (GitLabPipelineVarRestrictionResult, error)

ActivateGitLabTypedDispatch is the shared repository and CLI activation gate. It leaves schedules and settings untouched until all compatible templates have landed, and never enables delivery against a weaker setting. Dry runs perform the same checks without changing project state.

func EnsureGitLabPipelineVariableOverrideRole added in v0.44.0

func EnsureGitLabPipelineVariableOverrideRole(ctx context.Context, client forge.Client, owner, repo string, dryRun bool) (GitLabPipelineVarRestrictionResult, error)

EnsureGitLabPipelineVariableOverrideRole requires no_one_allowed. Drift is an error when automation is disabled, and setting changes are gated on schedule migration. Generic callers may receive unsupported without an error; GitLab activation must use requireGitLabPipelineVariableRestriction.

type GitLabPollerContainmentOperations added in v0.46.0

type GitLabPollerContainmentOperations struct {
	GitLabPollerCredentialInventory
	RevokeToken                  func(context.Context, int) error
	InstalledCredentialBelongsTo func(context.Context) (bool, error)
	DeleteInstalledCredential    func(context.Context) error
}

GitLabPollerContainmentOperations adds mutations to the read-only inventory for containment. Verification accepts only GitLabPollerCredentialInventory.

type GitLabPollerCredentialInventory added in v0.46.0

type GitLabPollerCredentialInventory struct {
	Tokens            func(context.Context) ([]ProjectAccessToken, error)
	UnmanagedTriggers func(context.Context) ([]int64, error)
	SSHKeys           func(context.Context) ([]int, error)
	Jobs              func(context.Context) ([]int, error)
	Schedules         func(context.Context) ([]int, error)
}

GitLabPollerCredentialInventory supplies read-only account-scoped queries. Every inventory must be complete or return an error.

type GitLabPollerQuiescenceVerifier added in v0.46.0

type GitLabPollerQuiescenceVerifier interface {
	VerifyPollerQuiescence(ctx context.Context, owner, repo string, userID int64) error
}

GitLabPollerQuiescenceVerifier is required before temporary elevation. Success must establish a server-side guarantee that all requests accepted with revoked credentials have finished, including asynchronous credential and job creation. Empty inventories or a fixed delay are insufficient. Adapters without this guarantee defer elevation and retain polling. Verification runs after revocation and the final safety inventory. The guarded orchestration is retained intentionally as the shared contract for adapters that can establish this guarantee. It remains tested but disabled in the live GitLab adapter; successful inventories never enable it by themselves.

type GitLabPollerUninstallReconciler added in v0.46.0

type GitLabPollerUninstallReconciler interface {
	ReconcileGitLabPollersForUninstall(ctx context.Context, client forge.Client, owner, repo string) error
}

GitLabPollerUninstallReconciler is implemented by the GitLab role token client the CLI hands to uninstall. Uninstall calls it under the project lease, before role credential cleanup, so a Poller account left elevated or holding an installer-only bootstrap credential by an interrupted trigger-creation transaction is not left behind by a successful uninstall.

An error wrapping ErrPollerSuppliedUnresolved means the installed Poller credential is recorded as administrator-supplied but its owner could not be attributed. Uninstall then leaves the installation state (including that provenance) in place and revokes nothing, so a retry can still exclude the supplied account and its tokens.

type GitLabRoleCleanupConfig added in v0.44.0

type GitLabRoleCleanupConfig struct {
	Owner  string
	Repo   string
	Client forge.Client
	// Tokens, when set, revokes active role project access tokens. Nil
	// skips PAT revocation; CI/CD variables and secrets are still
	// deleted.
	Tokens ProjectAccessTokenClient
	DryRun bool
}

GitLabRoleCleanupConfig controls removal of GitLab role-identity installation state: the registry, rotation document, built-in and custom role secrets, and matching role project access tokens. It does not touch the legacy FULLSEND_FORGE_TOKEN shared secret or its fullsend-bot project access token — a repository installed before the role-only rollout may require manual cleanup of those.

type GitLabRoleCleanupResult added in v0.44.0

type GitLabRoleCleanupResult struct {
	VarsDeleted   int
	TokensRevoked int
	DryRun        bool
	Diagnostics   []string
}

GitLabRoleCleanupResult is the non-secret outcome of identity cleanup.

func CleanupGitLabRoleIdentity added in v0.44.0

func CleanupGitLabRoleIdentity(ctx context.Context, cfg GitLabRoleCleanupConfig) (_ GitLabRoleCleanupResult, err error)

CleanupGitLabRoleIdentity removes GitLab role-identity installation state without recreating any of it. Missing variables, secrets, or tokens are not errors, so retries and uninstall of partial installs stay idempotent. A token-inventory failure after variables are deleted is still returned so uninstall can fail closed and leave the manifest entry for retry.

This function never reads or returns secret values.

func CleanupGitLabRoleIdentityLocked added in v0.46.0

func CleanupGitLabRoleIdentityLocked(ctx context.Context, cfg GitLabRoleCleanupConfig) (GitLabRoleCleanupResult, error)

CleanupGitLabRoleIdentityLocked is CleanupGitLabRoleIdentity for a caller that already holds the project lease from LockGitLabProject, such as an uninstall that serializes webhook teardown and role cleanup in one transaction. The lease is not reentrant.

type GitLabServiceAccount added in v0.46.0

type GitLabServiceAccount struct {
	ID   int
	Name string
}

GitLabServiceAccount is a GitLab project service account. Fullsend names each role service account after its role token name (fullsend-poller, fullsend-analyst, fullsend-coder, fullsend-role-<name>).

type GitLabServiceAccountAPI added in v0.46.0

type GitLabServiceAccountAPI interface {
	CreateProjectServiceAccount(ctx context.Context, owner, repo, name string) (GitLabServiceAccount, error)
	// DeleteProjectServiceAccount removes a positively identified account whose
	// creation could not be recorded, before any credentials are minted.
	DeleteProjectServiceAccount(ctx context.Context, owner, repo string, userID int) error
	ListProjectServiceAccounts(ctx context.Context, owner, repo string) ([]GitLabServiceAccount, error)
	CreateServiceAccountPAT(ctx context.Context, owner, repo string, userID int, name string, scopes []string, expiresAt string) (*ProjectAccessToken, error)
	ListServiceAccountPATs(ctx context.Context, owner, repo string, userID int) ([]ProjectAccessToken, error)
	RevokeServiceAccountPAT(ctx context.Context, owner, repo string, userID, tokenID int) error
	AddProjectMember(ctx context.Context, owner, repo string, userID int64, accessLevel int) error
	UpdateProjectMemberAccessLevel(ctx context.Context, owner, repo string, userID int64, accessLevel int) error
	// GetProjectMemberAccessLevel returns the effective access level,
	// including access inherited from groups.
	GetProjectMemberAccessLevel(ctx context.Context, owner, repo string, userID int64) (int, error)
}

GitLabServiceAccountAPI is the subset of the GitLab API needed to manage role service accounts, their personal access tokens, and their project membership.

type GitLabTriggerOwner added in v0.46.0

type GitLabTriggerOwner interface {
	// PollerUserID identifies the fullsend-managed Poller service account
	// using the installer's own authority, so identification keeps working
	// after the distributed runtime credential has been revoked or removed.
	// An error wrapping forge.ErrNotFound means there is no managed Poller
	// service account, or the installed Poller credential is an
	// administrator-supplied one, so its membership must not be changed.
	PollerUserID(ctx context.Context, owner, repo string) (int64, error)
	// CreatePollerBootstrap creates the installer-only bootstrap personal
	// access token for the Poller account. Its value is held in memory by the
	// caller only: it is never stored in CI/CD variables, logs, or agent
	// environments.
	CreatePollerBootstrap(ctx context.Context, owner, repo string, userID int64) (*PollerBootstrap, error)
	// CreatePipelineTriggerTokenAsPoller creates a pipeline trigger token
	// authenticated as the Poller identity with the bootstrap credential.
	CreatePipelineTriggerTokenAsPoller(ctx context.Context, owner, repo, description string, bootstrap *PollerBootstrap) (*forge.PipelineTriggerToken, error)
	// RevokePollerBootstrap revokes every active bootstrap personal access
	// token of the Poller account (including orphans left by an interrupted
	// run) and verifies that none remains active.
	RevokePollerBootstrap(ctx context.Context, owner, repo string, userID int64) error
	// SetProjectMemberAccessLevel changes a direct project member's
	// access level using the install-time admin credential.
	SetProjectMemberAccessLevel(ctx context.Context, owner, repo string, userID int64, accessLevel int) error
	// VerifyPollerElevationSafe reports whether the identified Poller may be
	// raised to temporary Maintainer access. It returns an error when the
	// account's credentials cannot be fully accounted for: an active personal
	// access token that is neither the managed runtime credential nor the
	// installer's bootstrap credential, or a pipeline trigger token fullsend
	// does not manage. Failure containment cannot revoke what fullsend does not
	// manage, and the install must not elevate an account that holds such a
	// credential.
	VerifyPollerElevationSafe(ctx context.Context, owner, repo string, userID int64) error
	// VerifyPollerCredentialsRevoked repeats the safety inventory after
	// revocation and requires no active PATs. Managed
	// names are not evidence of revocation. It runs before bootstrap creation.
	VerifyPollerCredentialsRevoked(ctx context.Context, owner, repo string, userID int64) error
	// RevokePollerRuntimeCredentials invalidates the distributed Poller
	// runtime credential before elevation: it removes the installed Poller
	// CI/CD secret, then revokes the account's managed personal access tokens
	// and verifies none remains active. Credentials fullsend does not manage
	// are never touched.
	RevokePollerRuntimeCredentials(ctx context.Context, owner, repo string, userID int64) error
	// CreatePollerRuntimeToken creates a replacement runtime personal access
	// token for the Poller account. The caller stores it.
	CreatePollerRuntimeToken(ctx context.Context, owner, repo string, userID int64, expiresAt string) (*PollerRuntimeToken, error)
	// ContainPoller disables the positively identified managed Poller
	// credential for userID: it revokes the account's managed personal
	// access tokens (runtime and bootstrap) and removes the installed Poller
	// CI/CD secret only when its credential belongs to userID, so a Poller
	// that could not be returned to Developer access stops authenticating
	// while credentials of other identities are preserved. Every step is attempted; failures are joined. It
	// reports an error when an active token that fullsend does not manage
	// remains on the account, since containment is then incomplete.
	ContainPoller(ctx context.Context, owner, repo string, userID int64) error
}

GitLabTriggerOwner lets the webhook fast path mint its pipeline trigger token as the Poller identity rather than as the install-time admin (issue #8083). GitLab binds a trigger token to its creator and creating one needs Maintainer access, so the Poller service account is raised to Maintainer only for the duration of the create call and then restored to Developer before the webhook is enabled or updated. Creation and rotation additionally require GitLabPollerQuiescenceVerifier. This optional capability must guarantee server-side request draining; owners without it can reconcile existing triggers but defer new creation/rotation.

type GitLabWebhookResult added in v0.46.0

type GitLabWebhookResult struct {
	// Action is "none" (already provisioned), "deferred" (a readiness
	// gate is not met; nothing was changed), "update" (one or more
	// pieces were created or repaired), or "would-update" (dry run).
	Action string
	// Details lists one human-readable line per step taken or planned.
	// Lines never contain the trigger token, webhook secret, or webhook
	// URL.
	Details []string
}

GitLabWebhookResult describes the outcome of EnsureGitLabWebhookFastPath.

func EnsureGitLabWebhookFastPath added in v0.46.0

func EnsureGitLabWebhookFastPath(ctx context.Context, client forge.Client, baseURL, owner, repo string, rotate, dryRun bool) (res GitLabWebhookResult, err error)

EnsureGitLabWebhookFastPath converges the webhook fast-path on owner/repo. It is idempotent and probe-first: only missing or misconfigured pieces are created or repaired, and a fully provisioned repository is left untouched (Action "none").

  • Trigger token: minted on the project when the active managed trigger cannot be identified, FULLSEND_TRIGGER_TOKEN is missing or unsafe (the value cannot be read back from GitLab), or when rotate is true. The new value is stored as FULLSEND_TRIGGER_TOKEN before any webhook update, and superseded Fullsend-managed tokens are revoked only after the webhook points at the new one. The active token ID is recorded in the webhook description, so a revocation that failed earlier is retried by ordinary convergence.
  • Webhook secret: generated when missing and stored as FULLSEND_WEBHOOK_SECRET only after the webhook carries it, so a failed webhook update is retried by ordinary convergence.
  • Credential variables: a stored credential is reused only when its variable is a masked, protected, wildcard-scoped environment variable; otherwise it is regenerated and stored safely.
  • Webhook: created when absent; updated when its trigger URL, ref, or event filters drift, or when either credential changed; duplicate Fullsend-managed webhooks are deleted. Hooks Fullsend does not own (see isFullsendWebhook) are never touched.

Nothing is changed while a readiness gate is unmet (Action "deferred"); see gitlabWebhookReadiness. dryRun performs the same probes and gates and reports the planned changes without making them.

The whole transaction runs under the project lease (see LockGitLabProject), so installers in other processes cannot interleave inventory, minting, publication, or revocation on the same project. When the lease cannot be taken nothing is changed (Action "deferred") and the error is returned.

func EnsureGitLabWebhookFastPathWithTriggerOwner added in v0.46.0

func EnsureGitLabWebhookFastPathWithTriggerOwner(ctx context.Context, client forge.Client, triggerOwner GitLabTriggerOwner, baseURL, owner, repo string, rotate, dryRun bool) (res GitLabWebhookResult, err error)

EnsureGitLabWebhookFastPathWithTriggerOwner is EnsureGitLabWebhookFastPath with the trigger token minted as the Poller identity through triggerOwner. A nil triggerOwner, or a project without an installed Poller credential, mints as the client's own identity, which the runtime privilege ceiling then accepts only below Maintainer.

func ReconcileGitLabPollerElevation added in v0.46.0

func ReconcileGitLabPollerElevation(ctx context.Context, client forge.Client, triggerOwner GitLabTriggerOwner, owner, repo string, dryRun bool) (res GitLabWebhookResult, err error)

ReconcileGitLabPollerElevation returns a managed Poller left above Developer (for example by an interrupted rotation) to Developer access, or contains its credential when that cannot be verified. Install calls it for every GitLab repository, independently of whether any webhook work is pending. Dry runs, a nil triggerOwner, and a Poller that is absent or not the managed service account change nothing.

func ReconcileGitLabWebhookSafety added in v0.46.0

func ReconcileGitLabWebhookSafety(ctx context.Context, client forge.Client, owner, repo string, dryRun bool) (GitLabWebhookResult, error)

ReconcileGitLabWebhookSafety enforces only the trigger-token safety invariants: it revokes the managed webhook and trigger tokens when an invariant is violated or cannot be verified, and otherwise changes nothing — it never provisions. Callers use it for repositories whose installation or convergence failed, where an existing credential must not outlive a weakened restriction but provisioning must not proceed.

It runs under the project lease (see LockGitLabProject) and fails closed, changing nothing, when the lease cannot be taken.

func ReconcileGitLabWebhookSafetyWithTriggerOwner added in v0.46.0

func ReconcileGitLabWebhookSafetyWithTriggerOwner(ctx context.Context, client forge.Client, triggerOwner GitLabTriggerOwner, owner, repo string, dryRun bool) (res GitLabWebhookResult, err error)

ReconcileGitLabWebhookSafetyWithTriggerOwner is ReconcileGitLabWebhookSafety that also returns a positively identified managed Poller left above Developer (for example by an interrupted install) to Developer access before the safety checks run, and contains its credential when that cannot be verified. Without a triggerOwner the Poller is not touched.

type GitLabWebhookTeardownResult added in v0.46.0

type GitLabWebhookTeardownResult struct {
	// HooksDeleted counts Fullsend-owned project webhooks deleted.
	HooksDeleted int
	// TriggersRevoked counts Fullsend-managed pipeline trigger tokens revoked.
	TriggersRevoked int
}

GitLabWebhookTeardownResult describes what TeardownGitLabWebhookFastPath removed.

func TeardownGitLabWebhookFastPath added in v0.46.0

func TeardownGitLabWebhookFastPath(ctx context.Context, client forge.Client, owner, repo string) (_ GitLabWebhookTeardownResult, err error)

TeardownGitLabWebhookFastPath removes the webhook fast-path from owner/repo during uninstall: it deletes the webhooks Fullsend owns and revokes the Fullsend-managed pipeline trigger tokens, so no webhook is left requesting pipelines against a repository whose scaffold is being removed and no trigger bearer credential outlives it. Ownership follows isFullsendWebhook: a hook is deleted only when it carries the Fullsend name or is unnamed and embeds the stored FULLSEND_TRIGGER_TOKEN, so user-owned trigger hooks survive. The credential variables themselves are deleted with the other wildcard-scoped uninstall secrets after this returns; run this first, because legacy-hook ownership depends on the stored token. Deleting an already-absent hook or token is not an error, so a retry after a partial failure converges. Errors never include credential values.

The teardown runs under the project lease that serializes installers, so an installer cannot publish a replacement hook and trigger between the resource discovery and deletion below. Callers that already hold the lease (for example an uninstall that also cleans up role credentials) use TeardownGitLabWebhookFastPathLocked instead.

func TeardownGitLabWebhookFastPathLocked added in v0.46.0

func TeardownGitLabWebhookFastPathLocked(ctx context.Context, client forge.Client, owner, repo string) (GitLabWebhookTeardownResult, error)

TeardownGitLabWebhookFastPathLocked is TeardownGitLabWebhookFastPath for a caller that already holds the project lease from LockGitLabProject. The lease is not reentrant, so calling the unlocked variant while holding it would wait on itself.

type InferenceSettings added in v0.46.0

type InferenceSettings struct {
	// Auth selects which managed inference credentials the repository
	// needs: "vertex-wif", "openai-api-key" or "openai-wif". Empty
	// inherits from the next level (entry → forge section → defaults).
	Auth string `yaml:"auth,omitempty"`
}

InferenceSettings is the nested inference block in repos.yaml. It may appear under defaults, a forge section, or a repository entry. It holds only the non-secret authentication selection; credential and connection values are supplied on the command line and never stored here.

type InstallConfig

type InstallConfig struct {
	Owner string
	Repo  string
	Forge string

	// Roles is the list of agent roles to install (e.g., "triage", "code").
	Roles []string

	MintURL string

	InferenceProject string
	InferenceRegion  string

	// InferenceAuth is the repository's effective inference.auth
	// (InferenceAuthVertexWIF, InferenceAuthOpenAIAPIKey or
	// InferenceAuthOpenAIWIF). It selects
	// which inference credentials Install writes. Empty keeps the legacy
	// behavior: the Vertex secrets are written when InferenceProject is set.
	InferenceAuth string

	// OpenAIAPIKey is the static OpenAI API key written as
	// FULLSEND_OPENAI_API_KEY when InferenceAuth is
	// InferenceAuthOpenAIAPIKey. It comes from the command line only;
	// it is never persisted to the manifest and never logged.
	OpenAIAPIKey string

	// UpstreamRef is the git ref (SHA) used to pin scaffold workflow refs.
	// Empty for dev builds (falls back to config.DefaultUpstreamRef).
	UpstreamRef string
	// UpstreamTag is the version tag corresponding to UpstreamRef (e.g., "v0.42.0").
	UpstreamTag string

	// Pinned reports whether UpstreamRef came from an explicit manifest
	// fullsend_ref pin (resolveTargetRef's manifestRef) rather than the
	// running release's own default ref. A fresh install with no manifest
	// pin uses the running binary's release-default UpstreamRef together
	// with its embedded templates, which match that ref by construction —
	// PrebuiltScaffoldFiles is unnecessary there. An explicit pin can
	// target a different release, so GitLab requires PrebuiltScaffoldFiles
	// fetched for that ref. Leave false for GitHub and for unpinned
	// installs.
	Pinned bool

	// Skip flags control which install steps are executed. Set by callers
	// that handle specific steps externally (e.g., admin.go handles mint
	// setup before calling Install).
	SkipAppSetup bool

	// SkipScaffoldAndConfig skips scaffold file delivery and variable/secret
	// writes. The caller handles these steps externally (e.g., vendor mode
	// commits scaffold and vendor files together atomically).
	SkipScaffoldAndConfig bool

	// WIFProvider is the pre-computed WIF provider resource name. The caller
	// is responsible for computing or provisioning this value before calling
	// Install. Required unless SkipScaffoldAndConfig is true.
	WIFProvider string

	// PerRepoConfig, when set, overrides the default per-repo config
	// generated by NewPerRepoConfig. Used during migration to carry
	// over org config fields into the per-repo config.
	PerRepoConfig config.PerRepoConfigWriter

	// Runtime, when set, is written as the per-repo `runtime:` of the
	// generated config (`fullsend admin install <owner>/<repo> --runtime`).
	// Empty keeps the code default; ignored when PerRepoConfig is set.
	Runtime string

	// VendorBinary renders scaffold workflows to reference the vendored
	// binary path instead of fetching from upstream on each CI run.
	VendorBinary bool

	// ReviewAppClientID is the OAuth client ID of the review agent's
	// GitHub App. When set, it is written as the FULLSEND_REVIEW_CLIENT_ID
	// repo variable so that pre-fetch-prior-review.sh can validate
	// provenance of prior review comments.
	ReviewAppClientID string

	// AppSet is the GitHub App set prefix (apps named "{app_set}-{role}").
	// When set, it is written as the FULLSEND_APP_SET repo variable so the
	// scaffold workflows can derive bot identities. GitHub-only; empty for
	// GitLab, where no FULLSEND_APP_SET variable is written.
	AppSet string

	// AgentRunnerTags is a list of GitLab CI runner tags embedded in the
	// agent job so sandbox work is routed to the data-plane fleet.
	AgentRunnerTags []string

	// ControlRunnerTags is a list of GitLab CI runner tags embedded in
	// control-plane jobs (poll today). Independent of AgentRunnerTags:
	// unset renders an empty (untagged) tag list, not the agent tags.
	ControlRunnerTags []string

	// Direct controls scaffold delivery: true pushes directly to the default
	// branch; false creates a PR.
	Direct bool

	// ReuseSecrets indicates that the inference secrets for InferenceAuth
	// (see inferenceSecretsForAuth) already exist on the repo and should
	// not be overwritten. When true, InferenceProject, WIFProvider and
	// OpenAIAPIKey may be empty and secret writes are skipped.
	ReuseSecrets bool

	// PrebuiltScaffoldFiles, when non-nil, replaces the embedded scaffold
	// template collection. Used when fullsend_ref pins to a version that
	// differs from the running binary, so templates are fetched from the
	// fullsend-ai/fullsend repo at the pinned ref.
	PrebuiltScaffoldFiles scaffold.InstallFiles

	// Preset, when non-nil, is written byte-for-byte as
	// .fullsend/config.base.yaml. The overlay is generated independently
	// unless ManagedConfig is set.
	Preset []byte

	// ManagedConfig, when non-nil, is written as .fullsend/config.yaml
	// instead of generating an installer overlay. Used for config-managed
	// repositories (ADR 0122). Unmanaged repos leave this nil so existing
	// installer generation is preserved.
	ManagedConfig []byte

	// ExistingConfig, when non-nil and ManagedConfig is nil, is written
	// byte-for-byte as .fullsend/config.yaml instead of generating an
	// installer overlay. Used on a fresh install when a hand-authored
	// config.yaml already exists and must survive (it may carry settings,
	// such as OpenAI WIF identifiers, that the selected route depends on).
	ExistingConfig []byte

	// ManagedConfigAdoptionRequired, when true, skips writing
	// .fullsend/config.yaml entirely, even though ManagedConfig may be
	// set: the caller found an existing file that does not carry the
	// ADR-0122 ownership marker, or the pre-write safety gate rejected
	// the candidate, so the file must be left untouched — the same
	// contract convergeManagedConfigFiles enforces on the already-
	// installed path. Callers that do not check for adoption or the
	// safety gate (repos outside the managed-configuration install/
	// converge flow) leave this false so existing behavior is unchanged.
	ManagedConfigAdoptionRequired bool
}

InstallConfig is a pure data struct holding all inputs needed for a per-repo installation. CLI flags, environment variables, and interactive prompts are resolved by the caller before constructing this struct.

type InstallResult

type InstallResult struct {
	Owner string
	Repo  string

	Success bool
	Error   error

	// WIFProvider is the WIF provider resource name, either pre-existing
	// (from InstallConfig) or newly provisioned.
	WIFProvider string

	// GitLabTypedDispatch reports whether the GitLab wrapper queued for
	// commit (the pending scaffold files, not a live re-read) uses the
	// pipeline-input dispatch contract rather than the legacy
	// pipeline-variable one. Only meaningful for ForgeGitLab installs.
	// Callers that need to act on the install's dispatch transport (e.g.
	// post-install schedule creation) must use this instead of re-reading
	// the default branch: that commit may still be an unmerged upgrade MR,
	// in which case a live read would see the prior (or absent) wrapper
	// and misclassify a pending typed installation as legacy.
	GitLabTypedDispatch bool

	// ScaffoldFiles are the files delivered to the repository. Delivery can
	// open an unmerged pull/merge request instead of landing on the default
	// branch, so callers must not treat them as live (see
	// scaffoldFilesOnDefaultBranch).
	ScaffoldFiles []forge.TreeFile
}

InstallResult holds the outcome of a per-repo installation.

func Install

func Install(ctx context.Context, cfg InstallConfig,
	client forge.Client,
	commitScaffold ScaffoldCommitFunc,
	progress ProgressFunc) (*InstallResult, error)

Install performs a per-repo fullsend installation. It generates and commits scaffold files, and writes repository variables and secrets. The caller is responsible for computing the WIF provider resource name (via InstallConfig.WIFProvider) before calling this function — GCP provisioning is handled separately by `inference provision` and `mint enroll`.

type ManagedPollerLister added in v0.46.0

type ManagedPollerLister interface {
	ManagedPollerUserIDs(ctx context.Context, owner, repo string) ([]int64, error)
}

ManagedPollerLister is implemented by a GitLabTriggerOwner that can list every fullsend-managed Poller service account (duplicates included) with installer authority. An error wrapping forge.ErrNotFound means there is none.

type ManagedVar added in v0.38.0

type ManagedVar struct {
	Name    string
	Value   string
	Dynamic bool // true = presence-only (value mutated at runtime)
}

ManagedVar describes a repository variable with its expected value and whether it is dynamic (mutated at runtime). Static variables are value-checked during drift detection; dynamic variables are presence-checked only.

type Manifest

type Manifest struct {
	Version  int             `yaml:"version"`
	Defaults DefaultsConfig  `yaml:"defaults,omitempty"`
	GitHub   *PlatformConfig `yaml:"github,omitempty"`
	GitLab   *PlatformConfig `yaml:"gitlab,omitempty"`
	// contains filtered or unexported fields
}

Manifest is the top-level structure of a repos.yaml file. Platform sections (github, gitlab) replace the former nested forge section. Each platform section contains infrastructure config AND its repos list.

func LoadManifest

func LoadManifest(ctx context.Context, pathOrURL string) (*Manifest, error)

LoadManifest reads and parses a repos.yaml manifest from a local file path or an HTTPS URL. Remote fetches enforce a 30-second timeout and a 1 MB response size limit.

func (*Manifest) AllRepos added in v0.37.0

func (m *Manifest) AllRepos() []RepoEntry

AllRepos returns a flat list of all repo entries across all platform sections. The order is GitHub repos first, then GitLab repos, preserving the order within each section.

func (*Manifest) DistinctForges added in v0.33.0

func (m *Manifest) DistinctForges() []string

DistinctForges returns the deduplicated set of forge names actually used by entries in the manifest. Only forges with a non-nil platform section containing repos are included. The order is deterministic (github before gitlab).

func (*Manifest) DistinctForgesFor added in v0.44.0

func (m *Manifest) DistinctForgesFor(filter []string) ([]string, error)

DistinctForgesFor returns the deduplicated set of forge names used by repos matching filter. An empty filter returns DistinctForges(). The order is deterministic (github before gitlab). A glob manifest entry counts as selected when a concrete filter would be produced by expanding it (for example entry "acme/*" and filter "acme/api"). An error is returned if a filter or manifest entry is an invalid glob pattern.

func (*Manifest) EnsurePlatform added in v0.37.0

func (m *Manifest) EnsurePlatform(forgeName string) *PlatformConfig

EnsurePlatform returns the PlatformConfig for the given forge name, creating it if it does not exist.

func (*Manifest) ExpandGlobs

func (m *Manifest) ExpandGlobs(ctx context.Context, clients ForgeClientFactory) ([]ResolvedRepo, error)

ExpandGlobs resolves wildcard repo entries by listing org repos via the forge API (requires network access). Explicit entries always win over glob-matched entries. The returned list is deduplicated and sorted.

ListOrgRepos is called with includePrivate=true because repos.yaml manifests are used in per-repo mode, where agents run on the target repo itself. Archived and forked repos remain excluded.

The clients factory provides per-forge API clients so glob entries targeting different forges resolve against the correct API.

func (*Manifest) ExpandGlobsFor added in v0.44.0

func (m *Manifest) ExpandGlobsFor(ctx context.Context, clients ForgeClientFactory, filter []string) ([]ResolvedRepo, error)

ExpandGlobsFor is like ExpandGlobs, but skips expanding a platform's glob entries when filter is non-empty and does not select any repo on that platform. This keeps a filtered operation (e.g. "repos install gitlab-group/project") from requiring credentials for a forge that only appears via an unrelated glob entry (e.g. a GitHub "acme/*" entry) elsewhere in the manifest.

func (*Manifest) HasForge added in v0.33.0

func (m *Manifest) HasForge(name string) bool

HasForge reports whether any repo in the manifest resolves to the given forge name.

func (*Manifest) LayeredConfig added in v0.44.0

func (m *Manifest) LayeredConfig(entry RepoEntry, baseYAML []byte) (config.PerRepoConfigReader, error)

LayeredConfig returns the effective per-repo configuration for entry: managed configuration → config.base.yaml (baseYAML) → code defaults. Unmanaged repositories skip the managed layer. baseYAML may be empty.

func (*Manifest) Marshal

func (m *Manifest) Marshal() ([]byte, error)

Marshal serializes the manifest back to YAML. Deprecated runner_tags is dropped so rewrites emit agent_runner_tags. Marshal does not mutate the receiver: the deprecated-key migration runs against a shallow copy, so the caller's Manifest (and its platform configs) are unchanged after a call to Marshal.

func (*Manifest) PlatformFor added in v0.37.0

func (m *Manifest) PlatformFor(forgeName string) *PlatformConfig

PlatformFor returns the PlatformConfig for the given forge name, or nil if that platform section is not present in the manifest.

func (*Manifest) RenderManagedConfig added in v0.44.0

func (m *Manifest) RenderManagedConfig(entry RepoEntry) (data []byte, ok bool, err error)

RenderManagedConfig returns the canonical sparse configuration YAML body for a config-managed repository — the explicitly supplied manifest values, with no code defaults or config.base.yaml baked in. ok is false when the repository is not config-managed; data is then nil.

The returned bytes deliberately carry no file header. perRepoConfig's Marshal() prepends perRepoConfigHeader, the unmanaged per-repo-install header — not the ADR 0122 ownership marker ("# This file is managed by 'fullsend repos': ...") that every managed .fullsend/config.yaml written by the install path begins with. This function has no adoption-detection state (no forge read of the existing file), so it cannot decide whether the marker belongs on the result or whether an existing file requires adoption first; it renders the config body only. desiredManagedConfig is the install-path renderer (#7632) that prefixes the marker and is compared against the installed file by convergeManagedConfigFiles / checkManagedConfigDrift in managed_config_lifecycle.go, which also implement the adoption gate for an existing markerless file.

func (*Manifest) ResolveConfig

func (m *Manifest) ResolveConfig(owner, repo string) (ResolvedConfig, bool)

ResolveConfig computes the fully merged configuration for the given owner/repo by looking up the entry in the manifest's platform sections. The resolution order is:

  1. Per-repo override (from RepoEntry)
  2. Platform-level default (from PlatformConfig)
  3. Built-in defaults (empty strings)

The sentinel value "none" at any level stops the fallback chain, returning "". The second return value indicates whether the repo was found in the manifest's repo list. When false, the returned config is empty.

For repos matched via glob expansion, use ResolveConfigForEntry instead — this method only finds exact matches in the manifest's repo list and will not match glob patterns.

func (*Manifest) ResolveConfigForEntry

func (m *Manifest) ResolveConfigForEntry(owner, repo, forgeName string, entry RepoEntry) ResolvedConfig

ResolveConfigForEntry computes the fully merged configuration for the given owner/repo using the provided RepoEntry and forge name. Use this with entries returned by ExpandGlobs, which carry per-glob overrides that ResolveConfig cannot find by exact match.

func (*Manifest) ResolveConfigWithGlobs added in v0.33.0

func (m *Manifest) ResolveConfigWithGlobs(owner, repo string) (ResolvedConfig, bool)

ResolveConfigWithGlobs resolves config for a repo, falling back to glob-pattern matching when the exact entry lookup fails.

func (*Manifest) SignoffForgesFor added in v0.46.0

func (m *Manifest) SignoffForgesFor(filter []string) ([]string, error)

SignoffForgesFor returns the forges (in DistinctForgesFor order) that have at least one manifest entry selected by filter whose resolved signoff setting is true. Callers use it to resolve the installing user's identity once per forge before any scaffold commit is made.

A concrete (non-glob) filter pattern is resolved exactly as the real per-repo resolution does (ResolveConfigWithGlobs: an explicit entry first, then the first matching glob), so an explicit unsigned entry or an earlier unsigned glob is not overridden by a signed glob that also matches. Glob filter patterns and unfiltered runs stay conservative, so a forge may be reported when no concrete repository it expands to ends up needing a trailer. Even so, a glob entry that an earlier glob entry fully covers can never win resolution, so it is ignored (see globShadowedByEarlier).

func (*Manifest) TotalRepoCount added in v0.37.0

func (m *Manifest) TotalRepoCount() int

TotalRepoCount returns the total number of repo entries across all platform sections.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate checks the manifest for structural correctness:

  • version must be 1
  • github.url defaults to https://github.com when unset; mint_url defaults to DefaultPublicMintURL in public mode, and is required in private mode
  • gitlab.url is required when a gitlab section is present with repos
  • platform-specific fields are rejected on the wrong platform
  • each repo entry must have a valid owner/repo or owner/glob format
  • glob characters are only allowed in the repo name, not the owner
  • no duplicate repo entries (before glob expansion)
  • glob patterns must be valid filepath.Match patterns
  • forge URLs must be valid HTTPS URLs with no path component
  • inference.auth values must be one of ValidInferenceAuths

func (*Manifest) ValidateForUninstall added in v0.46.0

func (m *Manifest) ValidateForUninstall() error

ValidateForUninstall is Validate without the inference.auth value checks. Uninstall removes every Fullsend-managed inference credential regardless of the selected method, so a missing or invalid inference.auth must not block cleanup of an installation.

func (*Manifest) ValidateStructure added in v0.46.0

func (m *Manifest) ValidateStructure() error

ValidateStructure is Validate without the inference.auth value checks. Callers that evaluate repositories independently (status, uninstall) use it so one invalid inference.auth does not abort the whole command; the effective selection is checked per repository via ResolvedConfig.RequireInferenceAuth where it matters.

type ManifestAddResult added in v0.32.0

type ManifestAddResult struct {
	Added   []string
	Skipped []string
}

ManifestAddResult holds the outcome of adding repos to a manifest.

type ManifestEditConfig added in v0.32.0

type ManifestEditConfig struct {
	Manifest     *Manifest
	ManifestPath string
	DryRun       bool
}

ManifestEditConfig holds inputs for manifest add/remove operations.

type ManifestRemoveResult added in v0.32.0

type ManifestRemoveResult struct {
	Removed []string
	Skipped []string
}

ManifestRemoveResult holds the outcome of removing repos from a manifest.

type OrphanFile added in v0.38.0

type OrphanFile struct {
	Path string
}

OrphanFile describes a file that exists on the forge at a managed scaffold path but is no longer produced by the current template.

func CheckOrphanFiles added in v0.38.0

func CheckOrphanFiles(ctx context.Context, client forge.Client,
	owner, repo string, fc ForgeConfig, forgeName string,
	expectedFiles []forge.TreeFile) ([]OrphanFile, error)

CheckOrphanFiles compares the set of managed scaffold paths against the expected template output, checking which managed paths exist on the forge but are absent from the expected files. These are orphan files — leftover from a previous template version.

type OrphanVar added in v0.38.0

type OrphanVar struct {
	Name string
}

OrphanVar describes a repository variable with the FULLSEND_ prefix that exists on the forge but is not in the current managed variable set.

func CheckOrphanVars added in v0.38.0

func CheckOrphanVars(ctx context.Context, client forge.Client,
	owner, repo string, cfg InstallConfig, mintURL string) ([]OrphanVar, error)

CheckOrphanVars lists all repository variables on the forge and returns those with the FULLSEND_ prefix that are not in the managed variable set for the given forge. These are orphan variables — leftover from a previous installation or a removed feature. GitLab retired poll-state variables (gitlabRetiredLegacyVars) are known-retired: they are not reported as orphans so already-installed repos do not warn during the migrate-then-delete transition.

The managed set is computed using the FULL superset of possible managed variables — conditional fields (InferenceRegion, ReviewAppClientID) are populated with placeholders so that variables like FULLSEND_GCP_REGION are never flagged as orphans just because the caller doesn't know their expected value.

type PlatformConfig added in v0.37.0

type PlatformConfig struct {
	URL         string `yaml:"url,omitempty"`
	MintURL     string `yaml:"mint_url,omitempty"`
	MintMode    string `yaml:"mint_mode,omitempty"`
	FullsendRef string `yaml:"fullsend_ref,omitempty"`
	// AppSet is the GitHub App set prefix (apps named "{app_set}-{role}")
	// persisted as the FULLSEND_APP_SET repo variable. GitHub-only; the
	// sentinel "none" resets a per-repo override back to the built-in
	// default. Rejected under the gitlab platform.
	AppSet string `yaml:"app_set,omitempty"`
	// AgentRunnerTags routes GitLab agent (data-plane) jobs. GitLab-only.
	AgentRunnerTags []string `yaml:"agent_runner_tags,omitempty"`
	// ControlRunnerTags routes GitLab control-plane jobs (poll today;
	// webhook dispatcher next). GitLab-only. Fully independent of
	// AgentRunnerTags: there is no cross-fallback. Unset renders an
	// empty tag list (untagged), not the agent tags.
	ControlRunnerTags []string `yaml:"control_runner_tags,omitempty"`
	// DeprecatedRunnerTags is the deprecated gitlab.runner_tags alias.
	// Parse populates AgentRunnerTags from it when agent_runner_tags is
	// unset; MarshalWithHeader / Manifest.Marshal drop it so rewrites
	// emit agent_runner_tags.
	DeprecatedRunnerTags []string `yaml:"runner_tags,omitempty"`
	// Inference holds the forge-wide inference authentication selection,
	// overriding defaults.inference and overridden by repository entries.
	Inference InferenceSettings `yaml:"inference,omitempty"`
	// Signoff, when non-nil, enables or disables a Signed-off-by trailer
	// on scaffold commits for every repository in this forge section,
	// overriding defaults.signoff and overridden by repository entries.
	Signoff *bool       `yaml:"signoff,omitempty"`
	Repos   []RepoEntry `yaml:"repos"`
}

PlatformConfig holds per-platform infrastructure settings and the list of repos managed under that platform. A single struct serves both GitHub and GitLab; validation rejects platform-specific fields on the wrong platform (e.g. mint_url under gitlab).

type PollerBootstrap added in v0.46.0

type PollerBootstrap struct {
	ID    int
	Token string
}

PollerBootstrap is the installer-only bootstrap credential. Token is the secret value; it exists only in memory for one trigger-creation transaction.

type PollerElevationUnsafeError added in v0.46.0

type PollerElevationUnsafeError struct {
	Reason string
}

PollerElevationUnsafeError is returned by GitLabTriggerOwner.VerifyPollerElevationSafe when elevating the Poller would be unsafe. Reason is authored by fullsend and carries no credential material, so it may be shown to the operator verbatim.

func (*PollerElevationUnsafeError) Error added in v0.46.0

type PollerRuntimeToken added in v0.46.0

type PollerRuntimeToken struct {
	ID    int
	Token string
}

PollerRuntimeToken is a newly created runtime credential for the Poller.

type ProgressFunc

type ProgressFunc func(repo, phase, message string)

ProgressFunc is a callback for reporting installation progress. The caller maps this to spinner output, structured logs, or whatever UI is appropriate.

Parameters:

  • repo: the "owner/repo" being installed
  • phase: a machine-readable phase name (e.g., "scaffold", "vars", "secrets")
  • message: a human-readable status message

type ProjectAccessToken added in v0.44.0

type ProjectAccessToken struct {
	ID        int
	Name      string
	Token     string
	Active    bool
	ExpiresAt string
	Revoked   bool
	UserID    int
}

ProjectAccessToken is the subset of a GitLab project access token needed to store a role credential. Token is the secret value and is present only at creation time; it must never appear in logs, status, or Error strings.

type ProjectAccessTokenClient added in v0.44.0

type ProjectAccessTokenClient interface {
	CreateProjectAccessToken(ctx context.Context, owner, repo, name string, scopes []string, accessLevel int, expiresAt string) (*ProjectAccessToken, error)
	ListProjectAccessTokens(ctx context.Context, owner, repo string) ([]ProjectAccessToken, error)
	RevokeProjectAccessToken(ctx context.Context, owner, repo string, tokenID int) error
}

ProjectAccessTokenClient creates, lists, and revokes GitLab project access tokens. Implementations must not log token values. List results typically omit Token (GitLab returns the secret only at creation).

type RefResolver added in v0.37.0

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

RefResolver resolves symbolic fullsend_ref values (tags, branches) to commit SHAs on the fullsend-ai/fullsend repository. Results are cached so repeated calls for the same ref avoid redundant API calls.

func NewRefResolver added in v0.37.0

func NewRefResolver(client forge.Client) *RefResolver

NewRefResolver creates a resolver that uses the given GitHub client. The client must target GitHub's API since fullsend-ai/fullsend is always a GitHub repository.

func (*RefResolver) IsAncestor added in v0.37.0

func (r *RefResolver) IsAncestor(ctx context.Context, potentialAncestor, descendant string) (bool, error)

IsAncestor reports whether potentialAncestor is an ancestor of (or identical to) descendant in the fullsend-ai/fullsend repository. Both arguments must be commit SHAs. Returns false with a nil error when the relationship cannot be determined (e.g., diverged commits).

func (*RefResolver) Resolve added in v0.37.0

func (r *RefResolver) Resolve(ctx context.Context, ref string) string

Resolve resolves ref to a commit SHA on fullsend-ai/fullsend. If ref is already a SHA it is returned unchanged. Tags are tried first, then branches. If resolution fails, ref is returned as-is (graceful degradation to string comparison).

type RepoEntry

type RepoEntry struct {
	Name                   string   `yaml:"name"`
	FullsendRef            string   `yaml:"fullsend_ref,omitempty"`
	MintURL                string   `yaml:"mint_url,omitempty"`
	MintMode               string   `yaml:"mint_mode,omitempty"`
	AllowedRemoteResources []string `yaml:"allowed_remote_resources,omitempty"`
	// AppSet overrides the GitHub App set prefix for this repository,
	// persisted as the FULLSEND_APP_SET repo variable. GitHub-only; the
	// sentinel "none" resets back to the built-in default.
	AppSet string `yaml:"app_set,omitempty"`
	// Runtime is the agent runtime written as the repo's `runtime:` at
	// install time (claude, pi, codex); empty inherits defaults.runtime,
	// and an empty resolved value keeps the code default (claude).
	Runtime string `yaml:"runtime,omitempty"`
	// Inference overrides the inference authentication selection for this
	// repository (or every repository matched by this glob entry).
	Inference InferenceSettings `yaml:"inference,omitempty"`
	// Vendor overrides the default vendor setting for this repo.
	// nil inherits defaults.vendor; non-nil overrides it.
	Vendor *bool `yaml:"vendor,omitempty"`
	// Signoff overrides the forge-section and defaults signoff setting
	// for this repository. nil inherits; an explicit false disables an
	// inherited true.
	Signoff *bool `yaml:"signoff,omitempty"`
	// ConfigBase configures the configuration preset written as
	// .fullsend/config.base.yaml. Empty Source inherits
	// defaults.config_base; source "none" disables inheritance. SHA256
	// is an optional digest verified against the fetched preset.
	ConfigBase ConfigBase `yaml:"config_base,omitempty"`
	// Config is a sparse managed .fullsend/config.yaml for this
	// repository (ADR 0122). Presence opts this repository into managed
	// configuration even when the mapping is empty. runtime and
	// allowed_remote_resources are rejected here; use the sibling fields.
	Config config.ManagedConfig `yaml:"config,omitempty"`
}

RepoEntry represents a single repo or glob pattern in a platform's repos list. Always uses object form with name as the required field. Override fields use plain strings (config_base is a nested object); the sentinel value "none" stops the inheritance chain.

type RepoState added in v0.32.0

type RepoState struct {
	Installed       bool
	MintURL         string
	InferenceRegion string
	FullsendRef     string
}

RepoState holds the installation state of a single repo as read from forge variables and workflow files.

func ProbeRepoState added in v0.32.0

func ProbeRepoState(ctx context.Context, client forge.Client, owner, repo, forgeName string, fc ForgeConfig) (RepoState, error)

ProbeRepoState reads a repo's current per-repo installation state by probing all installation components (workflow files, variables, secrets). A repo is considered per-repo installed when at least one required variable is present — a workflow file alone may be a leftover from the removed per-org enrollment. Returns a zero RepoState when no required variables are found.

type RepoStatus added in v0.31.0

type RepoStatus struct {
	Owner           string  `json:"owner"`
	Repo            string  `json:"repo"`
	Forge           string  `json:"forge,omitempty"`
	Installed       bool    `json:"installed"`
	CurrentRef      string  `json:"current_ref,omitempty"`
	ExpectedRef     string  `json:"expected_ref,omitempty"`
	MintURL         string  `json:"mint_url,omitempty"`
	ExpectedMintURL string  `json:"expected_mint_url,omitempty"`
	Region          string  `json:"region,omitempty"`
	Drifts          []Drift `json:"drifts,omitempty"`
	Error           string  `json:"error,omitempty"`

	// ConfigRejected marks a repo whose manifest configuration was rejected
	// before any forge state was inspected (for example a missing
	// inference.auth selection). Callers that enrich status with further
	// forge lookups must skip these rows. Not serialized.
	ConfigRejected bool `json:"-"`

	// GitLab role-credential status. Names only; never token values.
	GitLabRolesReady      bool     `json:"gitlab_roles_ready,omitempty"`
	GitLabRolesPartial    bool     `json:"gitlab_roles_partial,omitempty"`
	GitLabRoleDiagnostics []string `json:"gitlab_role_diagnostics,omitempty"`
}

RepoStatus holds the status of a single repo as compared against the manifest's desired state.

type ResolvedConfig

type ResolvedConfig struct {
	Owner                  string
	Repo                   string
	Forge                  string
	ForgeConfig            ForgeConfig
	MintURL                string
	MintMode               string
	FullsendRef            string
	AllowedRemoteResources []string
	// AppSet is the resolved GitHub App set prefix persisted as the
	// FULLSEND_APP_SET repo variable. GitHub-only; empty for GitLab.
	AppSet string
	// AppSetExplicit reports whether app_set was explicitly configured
	// (per-repo override or manifest default, including the "none"
	// sentinel). When false, convergence preserves any existing
	// FULLSEND_APP_SET value on the repo rather than forcing the default.
	AppSetExplicit bool
	// Runtime is the resolved agent runtime (entry, then defaults); empty
	// means the code default.
	Runtime string
	// InferenceAuth is the resolved inference authentication method
	// (entry, then forge section, then defaults). Empty means no level
	// declared one; RequireInferenceAuth turns that into an actionable
	// error for install, convergence, and status.
	InferenceAuth string
	// Vendor is true when the fullsend binary and content should be
	// vendored into the repo for offline CI.
	Vendor bool
	// Signoff is true when scaffold commits for this repository carry a
	// Signed-off-by trailer for the authenticated installing user
	// (entry, then forge section, then defaults; default false).
	Signoff bool
	// Config is the resolved preset source; empty means no preset is
	// declared and an existing base file is preserved without comparison.
	Config string
	// ConfigHash is the resolved SHA-256 hex digest; empty skips
	// digest validation.
	ConfigHash string
	// ConfigManaged reports whether this repository is opted into a
	// managed .fullsend/config.yaml (ADR 0122). defaults.config opts every
	// repository in; a repository config block opts in only that repository.
	ConfigManaged bool
	// Managed is the sparse managed configuration: defaults.config merged with
	// the repository config, plus authoritative runtime and
	// allowed_remote_resources shorthands. Nil when ConfigManaged is
	// false. It does not bake in code defaults or config.base.yaml.
	Managed config.PerRepoConfigWriter
}

ResolvedConfig is the fully resolved configuration for a single repository after merging manifest defaults and platform-level settings. The ForgeConfig field carries per-forge patterns and (when populated by ForgeClientFactory.ConfigFor) a live API client.

func (ResolvedConfig) RequireInferenceAuth added in v0.46.0

func (c ResolvedConfig) RequireInferenceAuth() error

RequireInferenceAuth returns an actionable configuration error when no manifest level (entry, forge section, defaults) selects an inference authentication method for this repository, or when the effective selection is not a valid method. Install, convergence, and status call it before any dependent forge reads or writes; uninstall deliberately does not, so incomplete or older installations can still be cleaned up.

type ResolvedRepo

type ResolvedRepo struct {
	Owner string
	Repo  string
	Forge string
	Entry RepoEntry
}

ResolvedRepo pairs an owner/repo with the manifest entry that matched it (either an explicit entry or a glob-generated one).

type RoleProvisionConfig added in v0.44.0

type RoleProvisionConfig struct {
	Owner    string
	Repo     string
	Client   forge.Client
	Tokens   ProjectAccessTokenClient
	Registry gitlabroles.Registry
	// RegistryProvided is true when the operator explicitly supplied
	// --gitlab-role-registry this run, as opposed to Registry being
	// populated from a previously stored registry variable. Used only
	// to decide whether to surface a diagnostic when the supplied
	// registry is not persisted.
	RegistryProvided bool
	// ProvidedTokens maps a role name to an administrator-supplied
	// PAT (free-tier enrollment or a custom own credential). Values
	// must never be logged.
	ProvidedTokens map[gitlabroles.Role]string
	Now            time.Time
	DryRun         bool
}

RoleProvisionConfig is the input to ProvisionGitLabRoleCredentials.

type RoleProvisionFailure added in v0.44.0

type RoleProvisionFailure struct {
	Role   gitlabroles.Role
	Secret string
	Reason string
}

RoleProvisionFailure is a per-role error. Reason and Secret are names and messages only — never token values.

type RoleProvisionResult added in v0.44.0

type RoleProvisionResult struct {
	Report          gitlabroles.Report
	Created         []gitlabroles.Role
	Enrolled        []gitlabroles.Role
	Skipped         []gitlabroles.Role
	Reused          []gitlabroles.Role
	Failed          []RoleProvisionFailure
	RegistryWritten bool
	DryRun          bool
	Diagnostics     []string
}

RoleProvisionResult is the observable outcome of a provision run. Token values are not included.

func ProvisionGitLabRoleCredentials added in v0.44.0

func ProvisionGitLabRoleCredentials(ctx context.Context, cfg RoleProvisionConfig) (_ RoleProvisionResult, err error)

ProvisionGitLabRoleCredentials creates or enrolls credentials for every registered role (built-in and custom), stores them as protected masked CI/CD variables, writes the registry, and reports which roles are ready.

It never revokes or overwrites FULLSEND_FORGE_TOKEN. Existing role secrets are left in place (reinstall / retry). A failed role does not roll back roles that already succeeded. A repository installed before the role-only rollout may still carry FULLSEND_FORGE_TOKEN; provisioning does not retire it, and no automated path does — that leftover secret and its matching fullsend-bot project access token require manual cleanup.

type RoleRotateConfig added in v0.44.0

type RoleRotateConfig struct {
	Owner    string
	Repo     string
	Client   forge.Client
	Tokens   ProjectAccessTokenClient
	Registry gitlabroles.Registry
	// Roles limits rotation to these names. Empty means every
	// own-credential registered role.
	Roles []gitlabroles.Role
	// Force rotates even when the current PAT is not yet due.
	Force bool
	// LeadTime is how far ahead of expiry a credential is due.
	// Zero uses gitlabroles.DefaultRotationLead.
	LeadTime time.Duration
	// GracePeriod is how long the previous PAT stays active after a
	// successful distribution so in-flight jobs can finish. Zero uses
	// gitlabroles.DefaultRotationGrace.
	GracePeriod time.Duration
	Now         time.Time
	DryRun      bool
	Holder      string
	LockTTL     time.Duration
	// ProvidedTokens maps a role name to an administrator-supplied
	// replacement PAT. Values must never be logged.
	ProvidedTokens map[gitlabroles.Role]string
}

RoleRotateConfig is the input to RotateGitLabRoleCredentials.

type RoleRotateResult added in v0.44.0

type RoleRotateResult struct {
	Report      gitlabroles.Report
	Rotated     []gitlabroles.Role
	Skipped     []gitlabroles.Role
	Reused      []gitlabroles.Role
	Failed      []RoleProvisionFailure
	Overlapping []gitlabroles.Role
	RolledBack  []gitlabroles.Role
	Cleaned     []gitlabroles.Role
	InProgress  []gitlabroles.Role
	DryRun      bool
	Diagnostics []string
}

RoleRotateResult is the observable outcome of a rotation run. Token values are not included.

func RotateGitLabRoleCredentials added in v0.44.0

func RotateGitLabRoleCredentials(ctx context.Context, cfg RoleRotateConfig) (_ RoleRotateResult, err error)

RotateGitLabRoleCredentials replaces due (or Force) own-credential GitLab role PATs without touching FULLSEND_FORGE_TOKEN.

Create-then-distribute is used instead of GitLab's rotate-in-place API so the previous credential stays valid until grace cleanup: in-flight jobs that already hold the old token keep working. A failed create or distribution rolls the attempt back (revokes only the unused replacement) and leaves the last known-good secret in place. Concurrent callers for the same role are serialized and idempotent within gitlabroles.IdempotentRotationWindow.

type ScaffoldCommitFunc

type ScaffoldCommitFunc func(ctx context.Context, owner, repo string,
	files []forge.TreeFile, direct bool, installed bool) error

ScaffoldCommitFunc delivers scaffold files to a repository and returns any error encountered.

The installed parameter indicates whether the shim workflow is already on the default branch (true = upgrade, false = fresh install). CLI implementations use this to select the appropriate commit message, PR title, and branch. Fresh-install metadata (DefaultScaffoldBranch) must be used until that workflow lands, even if variables or secrets already exist from a previous incomplete run.

The CLI layer provides an implementation wrapping layers.CommitScaffoldFiles, which adds retry on non-fast-forward errors, branch-protection fallback to PR delivery, and fork-based PR support for non-owner users.

type ScaffoldMetadataOpts added in v0.36.0

type ScaffoldMetadataOpts struct {
	// GuardInstalled indicates whether the repo already has fullsend
	// installed (true = upgrade path, false = fresh install). When nil,
	// the function defaults to fresh-install metadata.
	GuardInstalled *bool

	// OldVersion, when non-empty, overrides the existing-version detection
	// from the workflow file. Only meaningful on the upgrade path.
	OldVersion string
}

ScaffoldMetadataOpts holds pre-fetched values for BuildScaffoldPRMetadata.

type ScaffoldPRMetadata added in v0.36.0

type ScaffoldPRMetadata struct {
	CommitMsg string
	PRTitle   string
	PRBody    string
	Branch    string
}

ScaffoldPRMetadata holds commit/PR metadata for scaffold file delivery. Values differ based on whether this is a fresh install or a version upgrade.

func BuildScaffoldPRMetadata added in v0.36.0

func BuildScaffoldPRMetadata(ctx context.Context, client forge.Client,
	owner, repo, upstreamTag string, opts ...ScaffoldMetadataOpts) ScaffoldPRMetadata

BuildScaffoldPRMetadata returns PR metadata appropriate for the operation type: fresh install vs. version upgrade. Callers must indicate whether the repo is already installed via opts.GuardInstalled; when nil the function defaults to fresh-install metadata.

func UninstallPRMetadata added in v0.44.0

func UninstallPRMetadata() ScaffoldPRMetadata

UninstallPRMetadata returns commit/PR metadata for scaffold file removal.

Branch intentionally reuses DefaultScaffoldBranch rather than a distinct uninstall branch name: already-deployed per-repo shims (see internal/scaffold/fullsend-repo/templates/shim-per-repo.yaml) only skip dispatch for head.ref == "fullsend/scaffold-install". A separate uninstall branch name would fail open and let the teardown PR trigger the fullsend dispatch job (with live WIF/mint credentials) against itself.

Known limitation: because install and uninstall share a branch, an in-flight PR from one operation is not closed or relabeled when the other operation runs against the same repo (closeStaleScaffoldPRs in internal/layers/commit.go skips the current branch, and commitBranchAndPR treats an "already exists" PR as success without updating its title or body). If `repos install`/`converge` and `repos uninstall` race on the same repo, the surviving PR's title and body can describe the opposite of what its diff now does (e.g., an "initialize fullsend" PR whose diff deletes the workflow files, or vice versa). This is accepted for now — see docs/cli/repos.md's `repos uninstall` section — rather than adding branch-content detection or a forge "update PR title/body" call.

type ScheduleSpec added in v0.39.0

type ScheduleSpec struct {
	// ComponentName is the probe component name (e.g., "schedule:slash-poll").
	ComponentName string
	// Description is the human-readable schedule description stored in GitLab.
	Description string
	// Cron is the cron expression for the schedule.
	Cron string
	// Variables are the CI/CD variables set on the schedule trigger.
	Variables map[string]string
}

ScheduleSpec defines a fullsend pipeline schedule for GitLab repos. All sites that create, detect, or match pipeline schedules must use PipelineScheduleSpecs() to stay in sync.

func PipelineScheduleSpecs added in v0.39.0

func PipelineScheduleSpecs() []ScheduleSpec

PipelineScheduleSpecs returns the canonical list of fullsend pipeline schedules for GitLab repos.

type ServiceAccountTokenClient added in v0.46.0

type ServiceAccountTokenClient struct {
	// ManagedLegacyTokenIDs supplies positive creation records for destructive
	// legacy operations. A nil callback supplies no ownership evidence.
	ManagedLegacyTokenIDs func(ctx context.Context, owner, repo string) ([]int, error)
	// LegacyTokenCreated durably records a token returned by this creation call.
	LegacyTokenCreated func(ctx context.Context, owner, repo string, token *ProjectAccessToken) error
	SA                 GitLabServiceAccountAPI
	Legacy             ProjectAccessTokenClient

	// AccountCreated durably records accounts created by this installer. Minting
	// a PAT on an existing same-named account is not ownership of that account.
	AccountCreated func(ctx context.Context, owner, repo string, account GitLabServiceAccount) error
	// ManagedAccountIDs supplies durable creation provenance for existing
	// account reuse and lifecycle inventories. Live adapters must set it.
	// Provisioning and destructive operations treat nil as an empty allowlist
	// and refuse accounts without provenance; only the read-only operational
	// inventory accepts every role-named account when it is nil.
	ManagedAccountIDs func(ctx context.Context, owner, repo string) ([]int, error)
	// ManagedAccountNames supplies the expected display name for each durably
	// owned account. Live adapters set it alongside ManagedAccountIDs to reject
	// cross-role renames. Nil retains generic role-name validation of owned
	// accounts. Supplied exclusions take precedence.
	ManagedAccountNames func(ctx context.Context, owner, repo string) (map[int]string, error)
	// VerifyToken authenticates a newly minted credential before publication.
	VerifyToken func(ctx context.Context, owner, repo string, token *ProjectAccessToken) error
	// VerifyAccountDeletion checks unrelated credentials and owned resources.
	VerifyAccountDeletion func(ctx context.Context, owner, repo string, userID int) error
	// SuppliedAccountIDs, when set, returns the service accounts that own
	// administrator-supplied credentials for any role, including owners of
	// credentials since replaced. They are never selected, re-leveled,
	// inventoried for destructive cleanup, or scheduled for revocation: a
	// same-named account is not fullsend's to manage. Their token metadata
	// stays in the operational inventory so rotation can judge lifecycle. It
	// is consulted only when the project has a role service account, and an
	// error fails the operation closed.
	SuppliedAccountIDs func(ctx context.Context, owner, repo string) ([]int, error)
	// SuppliedTokenIDs, when set, returns for each supplied owner whose
	// enrolled credential's token ID was recorded, the IDs of those tokens. The
	// operational inventory then reports only those tokens of such an account as
	// the supplied credential; the account's other tokens are not fullsend's and
	// stay out of lifecycle analysis. An account absent from the result has no
	// recorded token ID, so all of its tokens stand in for the credential. An
	// error fails the operation closed. Each token is reported under the token
	// name of the role it was enrolled for, not the account's display name.
	SuppliedTokenIDs func(ctx context.Context, owner, repo string) (map[int][]SuppliedTokenRef, error)
	// CurrentSuppliedAccountIDs, when set, returns the subset of
	// SuppliedAccountIDs that own a currently installed supplied credential.
	// The operational inventory reports only those accounts' tokens; an
	// excluded account whose supplied credential was since replaced is a
	// historical exclusion for destructive operations only, and its tokens are
	// not the runtime credential so they must not stand in for the role. When
	// nil, every supplied owner is treated as current. An error fails the
	// operation closed.
	CurrentSuppliedAccountIDs func(ctx context.Context, owner, repo string) ([]int, error)
	// contains filtered or unexported fields
}

ServiceAccountTokenClient provisions GitLab role credentials as personal access tokens of per-role project service accounts, so each role identity is an ordinary project member whose access level can be changed (issue #8083). Project access token bots cannot be re-leveled, which is why the Poller must be a service account to own the webhook trigger token.

It implements ProjectAccessTokenClient so provisioning, rotation, status, pipeline access, and uninstall see service-account tokens and any remaining legacy project access tokens through one inventory. When the instance does not offer project service accounts (404, 403, or not supported), Create falls back to Legacy project access tokens.

func (ServiceAccountTokenClient) ConfirmOutgoingTokenInactive added in v0.46.0

func (c ServiceAccountTokenClient) ConfirmOutgoingTokenInactive(ctx context.Context, owner, repo string, tokenID int) (bool, error)

ConfirmOutgoingTokenInactive verifies an outgoing rotation obligation can be retired without revocation. A token located in an authoritative source can be classified immediately. Every configured inventory must succeed to prove absence; neither a DELETE 404 nor an unavailable inventory establishes it.

func (ServiceAccountTokenClient) CreateProjectAccessToken added in v0.46.0

func (c ServiceAccountTokenClient) CreateProjectAccessToken(ctx context.Context, owner, repo, name string, scopes []string, accessLevel int, expiresAt string) (*ProjectAccessToken, error)

CreateProjectAccessToken ensures the role service account named name exists and is a Developer project member, then mints a personal access token for it. The returned token's UserID is the service account's user ID. Access above Developer is refused: role identities never hold standing Maintainer access.

func (ServiceAccountTokenClient) ListProjectAccessTokens added in v0.46.0

func (c ServiceAccountTokenClient) ListProjectAccessTokens(ctx context.Context, owner, repo string) ([]ProjectAccessToken, error)

ListProjectAccessTokens returns legacy project access tokens together with the personal access tokens of every role service account. Uninstall revokes from this inventory, so an inventory source is skipped only when its absence is positively established: the service-account listing is absent (404/not supported) before any account was discovered, or the legacy listing is not supported or not found. Failures after accounts were discovered, and legacy authorization failures, make the inventory incomplete and are returned as errors. When both sources fail, both failures are preserved; the result matches forge.ErrNotFound only when each source reported not found.

Operational consumers (rotation, status, protected-ref reconciliation) use ListProjectAccessTokens, which also accepts a forbidden listing of one source when the other succeeded: GitLab returns 403 for plan gating, so requiring both sources would stall the lifecycle on plan-gated instances. Destructive cleanup uses ListProjectAccessTokensStrict instead.

func (ServiceAccountTokenClient) ListProjectAccessTokensStrict added in v0.46.0

func (c ServiceAccountTokenClient) ListProjectAccessTokensStrict(ctx context.Context, owner, repo string) ([]ProjectAccessToken, error)

ListProjectAccessTokensStrict is ListProjectAccessTokens for destructive cleanup: a forbidden listing of either source is an incomplete inventory, because credentials may exist that the installer cannot see. It also lists the installer-only Poller bootstrap tokens an interrupted trigger-creation transaction can leave active, which operational consumers (rotation selection, status) must not see as runtime credentials.

func (ServiceAccountTokenClient) RevokeProjectAccessToken added in v0.46.0

func (c ServiceAccountTokenClient) RevokeProjectAccessToken(ctx context.Context, owner, repo string, tokenID int) error

RevokeProjectAccessToken revokes tokenID on whichever role service account owns it, or as a legacy project access token otherwise. GitLab project access tokens and service-account personal access tokens share one token ID space, so the ID is unambiguous.

func (ServiceAccountTokenClient) SuppliedOwnerIDs added in v0.46.0

func (c ServiceAccountTokenClient) SuppliedOwnerIDs(ctx context.Context, owner, repo string) ([]int, error)

SuppliedOwnerIDs returns the project-wide set of accounts that own administrator-supplied role credentials, the same exclusion set every destructive boundary of this client applies. A nil lookup yields none.

type StatusResult added in v0.31.0

type StatusResult struct {
	Repos    []RepoStatus  `json:"repos"`
	Summary  StatusSummary `json:"summary"`
	Warnings []string      `json:"warnings,omitempty"`
}

StatusResult holds the full output of a status check.

func Status added in v0.31.0

func Status(ctx context.Context, manifest *Manifest, clients ForgeClientFactory, maxConcurrency int, repoFilter []string, release ...DriftConfig) (*StatusResult, error)

Status compares the manifest's desired state against the actual forge state for each repo. It returns a StatusResult with per-repo status and aggregate counts. API calls are parallelised up to maxConcurrency. The optional release supplies the running binary's ref/tag for matching embedded scaffold templates after release-default manifest writeback.

type StatusSummary added in v0.31.0

type StatusSummary struct {
	Total        int `json:"total"`
	Installed    int `json:"installed"`
	NotInstalled int `json:"not_installed"`
	Drifted      int `json:"drifted"`
	Errored      int `json:"errored"`
}

StatusSummary provides aggregate counts across all repos. Counts are not mutually exclusive: a repo can be both Installed and Errored (e.g. variables present but workflow read fails), so Installed + NotInstalled + Errored may exceed Total.

type StrictTokenInventory added in v0.46.0

type StrictTokenInventory interface {
	ListProjectAccessTokensStrict(ctx context.Context, owner, repo string) ([]ProjectAccessToken, error)
}

StrictTokenInventory is implemented by token clients whose inventory has a stricter variant for destructive cleanup.

type SuppliedTokenRef added in v0.46.0

type SuppliedTokenRef struct {
	ID   int
	Name string
}

SuppliedTokenRef is an enrolled administrator-supplied credential's GitLab token ID together with the token name of the role it was enrolled for.

type UninstallConfig added in v0.32.0

type UninstallConfig struct {
	Manifest *Manifest
	Repos    []string
	DryRun   bool
	// Direct controls scaffold file removal: true pushes deletions
	// directly to the default branch; false creates a PR. Variable
	// and secret deletions are API-only and always happen immediately.
	Direct         bool
	MaxConcurrency int
	// GitLabTokens, when set, revokes GitLab role and shared-bot project
	// access tokens during uninstall. Nil skips PAT revocation; CI/CD
	// variables and secrets are still deleted. A revocation failure
	// fails the uninstall so the manifest entry remains for retry.
	GitLabTokens ProjectAccessTokenClient
}

UninstallConfig holds all inputs for a multi-repo uninstall operation.

type UninstallResult added in v0.32.0

type UninstallResult struct {
	Owner           string
	Repo            string
	Success         bool
	Error           error
	WorkflowDeleted bool
	VarsDeleted     int
	SecretsDeleted  int
	TokensRevoked   int
}

UninstallResult holds the outcome of uninstalling fullsend from a single repo.

func Uninstall added in v0.32.0

func Uninstall(ctx context.Context, cfg UninstallConfig,
	clients ForgeClientFactory,
	commitScaffold ScaffoldCommitFunc,
	progress ProgressFunc) ([]UninstallResult, error)

Uninstall tears down fullsend from the specified repos.

It runs in a single phase: parallel per-repo cleanup (bounded by MaxConcurrency) removes scaffold files via commitScaffold (PR by default, or a direct push when cfg.Direct is true), then deletes variables and secrets via the forge API.

GCP WIF cleanup is handled separately via `inference deprovision`.

Does NOT modify repos.yaml — use RemoveFromManifest for that.

Jump to

Keyboard shortcuts

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