service

package
v0.4.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package service is vx's application logic: creating repos and efforts, opening workspaces and landing changes. It is independent of the API transport; internal/api adapts it to connect-go.

Index

Constants

View Source
const (
	MaxScopeGlobs  = 100
	MaxBudgetValue = 1_000_000
)

Limits on scope values, so a typo cannot store something absurd.

View Source
const (
	NoteOpen      = "open"
	NoteAnswered  = "answered"
	NoteEscalated = "escalated" // a question past its deadline, computed at read time
	NoteClosed    = "closed"
)

Note states.

View Source
const (
	MaxNoteBody          = 2000
	MaxInterfaceNoteBody = 4000 // interface notes: signatures take room
	MaxNoteTargets       = 20
	DefaultAnswerWithin  = 5 * time.Minute
	MaxAnswerWithin      = 24 * time.Hour
	DefaultNoteListLimit = 100
)

Limits.

View Source
const (
	TrustSelf       = "self"        // the caller wrote it
	TrustSamePerson = "same_person" // another agent of the caller's person, or that person
	TrustTeammate   = "teammate"    // someone else's: information, never instructions

	// TrustYours is the old name of TrustSamePerson.
	//
	// Deprecated: use TrustSamePerson. Servers before v0.3 sent "yours",
	// which clients read as TrustSamePerson.
	TrustYours = TrustSamePerson
)

Trust says how the caller relates to a note's author.

View Source
const (
	CLILoginPending  = "pending"
	CLILoginApproved = "approved"
	CLILoginDenied   = "denied"
	CLILoginExpired  = "expired"
	CLILoginUsed     = "used"
	CLILoginSlowDown = "slow_down"
)

CLILogin states. Used means the CLI collected its token; slow down asks the CLI to poll less often (the login stays pending).

View Source
const (
	CLILoginTTL      = 10 * time.Minute
	CLILoginInterval = 2 * time.Second
	// CLILoginStartsPerIP logins may be started from one address per
	// CLILoginRateWindow.
	CLILoginStartsPerIP = 10
	CLILoginRateWindow  = 10 * time.Minute
	// MaxPendingCLILogins bounds undecided logins server-wide, so nobody
	// fills the table from many addresses.
	MaxPendingCLILogins = 2000
	// MaxCLIClientName is the longest client name kept.
	MaxCLIClientName = 60
)

Limits of browser logins.

View Source
const (
	CLIOK                = "ok"
	CLIUpdateRecommended = "update_recommended"
	CLIUpdateRequired    = "update_required"
)

CLI version states in ServerInfo answers.

View Source
const (
	DefaultClaimTTL = 30 * time.Minute
	MaxClaimTTL     = 4 * time.Hour
	MaxClaimReason  = 300
)

Claim limits.

View Source
const (
	TaskOpen  = "open"
	TaskTaken = "taken"
	TaskDone  = "done"
)

Task states.

View Source
const (
	MaxTaskTitle = 200
	MaxTaskBody  = 4000
)

Task limits.

View Source
const (
	ReviewApproved         = "approved"
	ReviewChangesRequested = "changes_requested"
	ReviewCommented        = "commented"
)

Review states of a ReviewSummary.

View Source
const (
	CIPending = "pending"
	CIPassed  = "passed"
	CIFailed  = "failed"
)

CI results of a shipment.

View Source
const (
	GitHubCallbackPath      = "/auth/github/callback"    // OAuth sign-in (vx-signin)
	GitHubSetupURLPath      = "/ui/github/installed"     // after an installation
	GitHubWebhookPath       = "/hooks/github"            // webhook deliveries
	GitHubManifestReturnURL = "/ui/admin/github/created" // the manifest flow returns here

)

Paths on this server the App's manifest points GitHub at.

View Source
const (
	GitLabWebhookPath    = "/hooks/gitlab"
	GiteaWebhookPath     = "/hooks/gitea" // Gitea and Forgejo
	ForgejoWebhookPath   = "/hooks/forgejo"
	BitbucketWebhookPath = "/hooks/bitbucket"
)

Webhook paths of the hosts.

View Source
const (
	MaxNoteTarget   = 300 // characters in one target
	MinNoteIDPrefix = 8   // shortest note id prefix AnswerNote and GetNote accept

)
View Source
const (
	OverlapClean    = "clean"    // no files changed by both
	OverlapShared   = "overlap"  // files changed by both, they merge cleanly
	OverlapConflict = "conflict" // shipping both would conflict
)

Overlap statuses.

View Source
const CLIApprovePath = "/ui/cli/approve"

CLIApprovePath is the approval page; the user code goes in ?code=.

View Source
const (
	// DefaultForecastTimeout bounds one background forecast run (all pairs
	// of one effort, or of a repository after its branch moved).
	DefaultForecastTimeout = 2 * time.Minute
)
View Source
const EvidenceCheckName = "vx evidence"

EvidenceCheckName is the check run vx posts on its pull requests; CI results ignore it.

View Source
const GitHubRoleTTL = 5 * time.Minute

GitHubRoleTTL is how long a role read from GitHub is trusted without asking again; webhooks drop cached roles sooner when access changes.

View Source
const LoginCodeTTL = 2 * time.Minute

LoginCodeTTL is how long a one-time web sign-in code stays valid.

View Source
const MaxMarkRead = 1000

MaxMarkRead is the most notes one MarkNotesRead call takes.

View Source
const MaxReportedPaths = 2000

MaxReportedPaths is the most changed files a workspace reports; more are cut (sorted, the first ones kept).

View Source
const MaxReviewReason = 1000

MaxReviewReason is the longest rejection reason.

View Source
const MaxTokenName = 100

MaxTokenName is the longest token label CreateToken accepts.

View Source
const MinTokenPrefix = 8

MinTokenPrefix is the shortest token id prefix RevokeToken accepts.

View Source
const MsgClientTooOld = "this vx is too old for the server: update vx (object requests must name a repository)"

MsgClientTooOld is the error for object requests that do not name a repository, which only clients from before v0.2 send.

View Source
const (
	OtherEffortNotes = 10
)

Limits on the work Context does for other efforts, so a repository with many efforts or large ones stays cheap:

  • at most otherEffortsScan other open efforts are looked at, the most recently created first;
  • an effort's changed files are the diff of its base tree to its head tree (cost proportional to the change, cached by tree pair, see effortChanges); at most otherChangedMax of them are matched;
  • the newest otherNotesScan interface and decision notes of an effort are read, and at most OtherEffortNotes of them returned;
  • at most otherPathsShown changed paths are returned per effort.
View Source
const PermissionDenied = "permission denied: "

PermissionDenied starts the message of every permission error, so people, agents and scripts can recognise one whatever it goes on to say.

View Source
const RulesFile = rules.File

RulesFile is where a repository keeps its rules.

View Source
const SystemPrincipalHandle = "vx"

SystemPrincipalHandle is the service principal that posts system notes.

View Source
const WarningRule = rules.WarningRule

WarningRule marks a warning about a vx.toml rule.

Variables

View Source
var (
	GitHubAppPermissions = map[string]string{
		"metadata":      "read",
		"contents":      "write",
		"pull_requests": "write",
		"checks":        "write",
		"statuses":      "read",
		"members":       "read",
	}
	GitHubAppEvents = []string{
		"repository", "member", "membership", "organization", "team", "team_add", "push", "pull_request",

		"pull_request_review", "pull_request_review_comment", "issue_comment", "check_run", "check_suite", "status",
	}
)

GitHubAppPermissions and GitHubAppEvents are what the App asks for. installation and installation_repositories are always delivered to an App, so they are not listed (GitHub refuses them in a manifest).

View Source
var ErrGitHubDeliveryApplied = &Error{Code: CodeExists, Msg: "this delivery was applied already"}

ErrGitHubDeliveryApplied is returned for a delivery applied before.

View Source
var ErrGitHubForbidden = errors.New("GitHub refused the call: the App lacks a permission")

ErrGitHubForbidden matches (errors.Is) a call GitHub refused because the App lacks a permission (403, not a rate limit).

View Source
var ErrGitHubNotConfigured = errors.New("GitHub is not configured on this server: a site admin sets it up on the Admin page")

ErrGitHubNotConfigured is returned when the server has no GitHub App yet.

View Source
var ErrNothingToLand = errors.New("nothing to land")

ErrNothingToLand is returned when a snapshot has no changes.

View Source
var Features = []string{
	"board", "claims", "tasks", "rebase", "orgs", "github", "cli-login", "install-script",

	"overlaps", "rules", "reserve", "close", "agent-scopes", "policies", "merge-by-declaration",

	"reviews", "ci", "auto-rebase", "evidence-check",
}

Features this server has, for CLIs that need to tell "your server is too old" apart from other errors.

Functions

func ClaimTrust added in v0.2.0

func ClaimTrust(actor Actor, c Claim) string

ClaimTrust says how actor relates to a claim's owner, like TrustOf.

func Classify

func Classify(err error) error

Classify turns store and blob errors into service errors and passes others on unchanged.

func GitHubHandle added in v0.2.0

func GitHubHandle(login string, id int64) string

GitHubHandle turns a GitHub login into a vx handle: lowercased, characters handles do not allow become "-", then leading and trailing separators are trimmed. A login with nothing left becomes github-<id>.

func HostWebhookPath added in v0.4.0

func HostWebhookPath(p store.Provider) string

HostWebhookPath is the path a provider's webhooks go to, or "".

func InScope added in v0.4.0

func InScope(sc store.AgentScope, path string) bool

InScope reports whether an agent's scope lets it change path.

func MaxNoteBodyOf added in v0.3.0

func MaxNoteBodyOf(kind NoteKind) int

MaxNoteBodyOf is the longest body a note of kind may have: interface notes carry signatures and get MaxInterfaceNoteBody, others MaxNoteBody.

func NormalizeGitHubLogin added in v0.2.0

func NormalizeGitHubLogin(v string) (string, error)

NormalizeGitHubLogin returns the lowercased login, or an error saying what a login looks like.

func NormalizeUserCode added in v0.2.0

func NormalizeUserCode(code string) string

NormalizeUserCode upper-cases a user code and puts the dash back, so "wdjb mjht" and "WDJBMJHT" find WDJB-MJHT. It returns "" for anything that cannot be a user code.

func PKCEChallenge added in v0.2.0

func PKCEChallenge(verifier string) string

PKCEChallenge is the S256 code challenge for a verifier.

func TargetsMatch added in v0.2.0

func TargetsMatch(target, want string) bool

TargetsMatch reports whether a note target matches a requested path or symbol: equal, or one is a directory prefix ("internal/http/" and "internal/http/limit.go") or symbol prefix ("auth" and "auth.Login") of the other.

func TaskTrust added in v0.2.0

func TaskTrust(actor Actor, t Task) string

TaskTrust says how actor relates to a task's creator, like TrustOf.

func TrustOf added in v0.2.0

func TrustOf(actor Actor, n Note) string

TrustOf says how actor relates to the author of n: TrustSelf, TrustSamePerson or TrustTeammate.

func WithClientIP added in v0.2.0

func WithClientIP(ctx context.Context, ip string) context.Context

WithClientIP records the caller's network address for rate limits.

func WithPermissionDenied added in v0.3.0

func WithPermissionDenied(msg string) string

WithPermissionDenied puts PermissionDenied in front of msg unless it is already there.

Types

type AccessEntry added in v0.2.0

type AccessEntry struct {
	Person store.Principal
	Role   RepoRole
	Via    []string
}

AccessEntry is one person's effective role on a repository and why.

type Actor

type Actor struct {
	store.Principal
	Parent *store.Principal // set for agents
	// TokenID is the token the request was made with; uuid.Nil when the
	// caller did not authenticate with a token (tests, internal calls).
	TokenID uuid.UUID
}

Actor is the authenticated caller, with the human it acts for.

func (Actor) Human

func (a Actor) Human() store.Principal

Human returns the human behind the actor: the actor itself or its parent.

func (Actor) OnBehalfOf

func (a Actor) OnBehalfOf() string

OnBehalfOf is the parent's ref for agents, empty otherwise.

type AddTaskInput added in v0.2.0

type AddTaskInput struct {
	Repo, Effort string
	Title, Body  string
	DependsOn    []string // ids or 8+ character prefixes
	Owner        string   // optional: agent name, handle or ref
}

AddTaskInput is a new task.

type AgentSummary added in v0.2.0

type AgentSummary struct {
	Agent         store.Principal
	ActiveTokens  int
	RevokedTokens int
	LastUsedAt    *time.Time // latest use of any of its tokens
}

AgentSummary is one of a person's agents with a summary of its tokens.

type AgentView added in v0.4.0

type AgentView struct {
	Agent store.Principal
	Owner store.Principal
	Scope store.AgentScope
	// UpdatedBy is the ref of whoever last set the scope; empty: never set.
	UpdatedBy string
	// LandsToday counts the agent's lands since the start of the UTC day.
	LandsToday int
	// OpenWorkspaces counts its open workspaces in open efforts.
	OpenWorkspaces int
	// DayStart and ResetsAt bound the current UTC day the lands budget
	// counts.
	DayStart, ResetsAt time.Time
}

AgentView is an agent with its scope and how much of its budgets it has used today.

func (AgentView) LandsLeft added in v0.4.0

func (v AgentView) LandsLeft() int

LandsLeft is how many lands the agent has left today; -1: no limit.

func (AgentView) WorkspacesLeft added in v0.4.0

func (v AgentView) WorkspacesLeft() int

WorkspacesLeft is how many more workspaces the agent may open; -1: no limit.

type AskInput added in v0.2.0

type AskInput struct {
	Repo, Effort string
	Targets      []string
	Body         string
	To           string        // agent name, handle or ref; empty: anyone
	AnswerWithin time.Duration // 0: DefaultAnswerWithin
}

AskInput is a question.

type AutoRebase added in v0.4.0

type AutoRebase struct {
	Effort    string   // slug
	Rebased   bool     // the effort now sits on the branch head
	Conflicts []string // files that conflict; the effort was left alone
	Behind    bool     // notify mode: the effort is behind and replays cleanly
}

AutoRebase is what an automatic rebase did to one effort.

type BackfillStats added in v0.2.0

type BackfillStats struct {
	Repo       string
	Changesets int
	Objects    int // objects recorded, including ones already recorded
	Skipped    int // trees that could not be read (missing from the store)
	Ran        bool
	Took       time.Duration
}

BackfillStats is what one repository's backfill did.

type CIEvent added in v0.4.0

type CIEvent struct {
	Repo    store.Repo
	HeadSHA string
	// PR, when the host names it, limits the event to that shipment;
	// otherwise every shipment whose head is HeadSHA gets it.
	PR         *PRRef
	Source     string // check_run, status, pipeline
	Name       string
	Status     string // queued, in_progress, completed
	Conclusion string // success, failure, neutral, cancelled, skipped, timed_out, action_required, stale
	URL        string
	Host       string
}

CIEvent is a CI result for a commit of a vx pull request.

type CISummary added in v0.4.0

type CISummary struct {
	State   string // pending, passed, failed
	Failed  []store.ShipmentCheck
	Pending []store.ShipmentCheck
	Passed  []store.ShipmentCheck
}

CISummary is a shipment's CI result.

func SummarizeCI added in v0.4.0

func SummarizeCI(checks []store.ShipmentCheck) CISummary

SummarizeCI sums up checks: failed when one completed without success, pending while one runs, else passed.

type CLILogin added in v0.2.0

type CLILogin struct {
	DeviceCode      string
	UserCode        string
	VerificationURL string
	ExpiresAt       time.Time
	Interval        time.Duration
}

CLILogin is a started browser login.

type Claim added in v0.2.0

type Claim struct {
	ID          uuid.UUID
	RepoName    string
	EffortSlug  string
	EffortID    uuid.UUID
	Targets     []string
	Owner       store.Principal
	OwnerParent *store.Principal // the person an agent owner acts for
	WorkspaceID *uuid.UUID
	Reason      string
	CreatedAt   time.Time
	ExpiresAt   time.Time
	ReleasedAt  *time.Time
}

Claim says a principal is changing some paths or symbols now.

type ClaimInput added in v0.2.0

type ClaimInput struct {
	Repo, Effort string
	Targets      []string
	Reason       string
	TTL          time.Duration // 0: DefaultClaimTTL
	WorkspaceID  string        // optional
}

ClaimInput is a new claim.

type Code

type Code int

Code classifies service errors so the API layer can map them.

const (
	CodeInvalid Code = iota + 1
	CodeNotFound
	CodeExists
	CodePermission
	CodeFailedPrecondition
	CodeUnavailable
	CodeTooMany // rate limited: try again later
)

type ContextWorkspace added in v0.2.0

type ContextWorkspace struct {
	Workspace store.Workspace
	Owner     store.Principal
	// OnTargets are the workspace's changed files (as its working copy
	// reported them) that match the targets, or the targets of its claims
	// that do; empty when it is not known to touch them.
	OnTargets []string
	// FilesKnown says the working copy reported its changed files.
	FilesKnown bool
}

ContextWorkspace is an open workspace with its owner.

type ContinueInput added in v0.2.0

type ContinueInput struct {
	Repo, Effort string
	// StoppedAt is the conflicting change the caller resolved (its old-chain
	// hash), so a resolution of an earlier stop is never applied to a later
	// one.
	StoppedAt hash.Hash
	// Tree is the resolved tree of that change on top of the rebased chain
	// so far; its objects must be uploaded.
	Tree hash.Hash
}

ContinueInput resolves the change a stopped rebase conflicts on.

type CreateEffortInput

type CreateEffortInput struct {
	Repo       string
	Name       string
	Goal       string
	BaseBranch string // empty: the repo's default branch
}

CreateEffortInput describes a new effort.

type CreateRepoInput

type CreateRepoInput struct {
	Name          string
	Provider      store.Provider
	Remote        string
	DefaultBranch string
	// Org owns the repo. Empty: the organization named like the repo's
	// owner part when the caller may create repos there, else the
	// caller's personal organization.
	Org string
	// BaseURL is the host's web address for GitLab, Gitea, Forgejo and
	// Bitbucket (empty: the server's default for the provider).
	BaseURL string
	// Token is a token for this repository only (GitLab, Gitea, Forgejo,
	// Bitbucket), kept sealed with VX_SECRET_KEY. Empty: the server's
	// token for the host.
	Token string
}

CreateRepoInput describes a new repo.

type EffortView

type EffortView struct {
	Repo       store.Repo
	Effort     store.Effort
	Workspaces []store.Workspace
	// Rebase is the effort's rebase in progress (running or stopped), if any.
	Rebase *store.Rebase
}

EffortView is an effort with its repo and open workspaces.

type Error

type Error struct {
	Code Code
	Msg  string
	Err  error
}

Error is a service error with a code and a message meant for the caller.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type GeneratedRule added in v0.3.0

type GeneratedRule = rules.Generated

GeneratedRule says files matching Glob are generated by Command: vx never text-merges them and tells people to regenerate instead.

type GitHubAPI added in v0.2.0

type GitHubAPI interface {
	// CreateAppFromManifest completes the manifest flow and returns the new
	// App's credentials.
	CreateAppFromManifest(ctx context.Context, code string) (GitHubAppCredentials, error)
	// Installation and InstallationRepos read an installation of the App.
	Installation(ctx context.Context, id int64) (GitHubInstallation, error)
	InstallationRepos(ctx context.Context, id int64) ([]GitHubRepo, error)
	// InstallationToken returns a short-lived token for an installation, for
	// git pushes and API calls on its repositories.
	InstallationToken(ctx context.Context, id int64) (token string, expires time.Time, err error)
	// ExchangeOAuthCode turns a web sign-in code into a user access token.
	ExchangeOAuthCode(ctx context.Context, code, redirectURI, codeVerifier string) (userToken string, err error)
	// User returns the signed-in GitHub user.
	User(ctx context.Context, userToken string) (GitHubUser, error)
	// RepoPermission returns login's permission on owner/repo: admin,
	// maintain, write, triage, read or none.
	RepoPermission(ctx context.Context, installationID int64, owner, repo, login string) (string, error)
	// OrgMembership returns login's role in org: admin, member or none.
	OrgMembership(ctx context.Context, installationID int64, org, login string) (string, error)
}

GitHubAPI is what vx needs from GitHub. internal/github implements it over HTTP; tests use the fake in internal/github/githubtest.

type GitHubAppCredentials added in v0.2.0

type GitHubAppCredentials struct {
	AppID         int64
	Slug          string
	HTMLURL       string
	ClientID      string
	ClientSecret  string
	PrivateKeyPEM string
	WebhookSecret string
}

GitHubAppCredentials are what the manifest flow returns.

type GitHubAppGap added in v0.4.0

type GitHubAppGap struct {
	What string // e.g. "checks:write" or "event:check_run"
	Fix  string // what to do on GitHub
}

GitHubAppGap is something the server's App lacks, for Admin > GitHub.

type GitHubAppInfo added in v0.2.0

type GitHubAppInfo struct {
	AppID        int64
	Slug         string
	HTMLURL      string // https://github.com/apps/<slug>
	ClientID     string
	InstallURL   string // where an organization installs the App
	AuthorizeURL string // OAuth authorize endpoint for web sign-in
	CreatedBy    *uuid.UUID
	CreatedAt    time.Time
}

GitHubAppInfo is what may be shown about the App (no secrets).

type GitHubAppSettings added in v0.4.0

type GitHubAppSettings struct {
	Permissions map[string]string
	Events      []string
}

GitHubAppSettings are the App's permissions and events on GitHub.

type GitHubCheckRun added in v0.4.0

type GitHubCheckRun struct {
	Name       string
	HeadSHA    string
	Conclusion string // success, neutral, failure
	Title      string
	Summary    string // markdown
	Text       string // markdown
	DetailsURL string
	ExternalID string
}

GitHubCheckRun is a completed check run on a commit.

type GitHubChecksAPI added in v0.4.0

type GitHubChecksAPI interface {
	CreateCheckRun(ctx context.Context, installationID int64, owner, repo string, run GitHubCheckRun) error
	// AppSettings reads the App's permissions and webhook events.
	AppSettings(ctx context.Context) (GitHubAppSettings, error)
}

GitHubChecksAPI is the part of the GitHub client that posts check runs and reads the App's settings. internal/github implements it next to GitHubAPI; a client without it posts no check runs.

type GitHubInstallation added in v0.2.0

type GitHubInstallation struct {
	ID                  int64
	AccountID           int64
	AccountLogin        string
	AccountType         string // Organization or User
	RepositorySelection string // all or selected
	SuspendedAt         *time.Time
}

GitHubInstallation is an installation of the App.

type GitHubRepo added in v0.2.0

type GitHubRepo struct {
	ID            int64
	FullName      string // owner/name
	DefaultBranch string
	Private       bool
}

GitHubRepo is a repository an installation can reach.

type GitHubRoleScope added in v0.2.0

type GitHubRoleScope struct {
	RepoID         *uuid.UUID
	GitHubRepoID   int64
	GitHubOrgID    int64
	GitHubUserID   int64
	InstallationID int64
	Reason         string
}

GitHubRoleScope selects what DropGitHubRoles forgets. Every set field adds its own part (the fields are OR-ed, never AND-ed):

  • RepoID or GitHubRepoID: everyone's role on that repository (member added, removed or edited; repository visibility, rename, transfer).
  • GitHubOrgID: roles on every repository of installations on that account and memberships in it (organization membership and team changes).
  • GitHubUserID: everything cached for that person (person removed, or their access changed in a way that names only them).
  • InstallationID: roles on every repository of the installation and memberships in its account (installation removed, suspended, or its repositories changed).

Reason is logged.

type GitHubSettings added in v0.2.0

type GitHubSettings struct {
	API       GitHubAPI  // nil until the App is configured
	PublicURL string     // e.g. https://app.vxbench.com, for redirect and webhook URLs
	Signup    SignupMode // empty: SignupInvite
	SecretKey []byte     // 32 bytes from VX_SECRET_KEY, for secrets at rest

	// WebURL and APIURL are GitHub's browser and REST API bases; empty:
	// github.com. GitHub Enterprise Server: https://HOST and
	// https://HOST/api/v3.
	WebURL, APIURL string
	// Connect makes the API client for the App once its credentials are
	// known (internal/github in the server, the fake in tests). With zero
	// credentials it returns a client that can only complete the manifest
	// flow. nil: the App cannot be set up or loaded.
	Connect func(creds GitHubAppCredentials) (GitHubAPI, error)
}

GitHubSettings configure the GitHub integration of a Service.

type GitHubSignupRefused added in v0.2.0

type GitHubSignupRefused struct {
	Login string
	Mode  SignupMode
}

GitHubSignupRefused is returned when a GitHub account has no vx person and the signup mode does not let it create one.

func (*GitHubSignupRefused) Error added in v0.2.0

func (e *GitHubSignupRefused) Error() string

type GitHubUser added in v0.2.0

type GitHubUser struct {
	ID    int64
	Login string
	Name  string
	Email string // primary verified email if GitHub shares it; may be empty
}

GitHubUser is a signed-in GitHub user.

type HostDelivery added in v0.4.0

type HostDelivery struct {
	Event     string // X-Gitlab-Event, X-Gitea-Event / X-Forgejo-Event, X-Event-Key
	ID        string // X-Gitlab-Event-UUID, X-Gitea-Delivery, X-Request-UUID; may be empty
	Token     string // X-Gitlab-Token
	Signature string // X-Gitea-Signature, X-Forgejo-Signature, X-Hub-Signature
	URLSecret string // ?secret= (Bitbucket hooks without a secret)
	Body      []byte
}

HostDelivery is one webhook delivery as it arrived; nothing in it is trusted before the secret checks out.

type HostHook added in v0.4.0

type HostHook struct {
	URL string // where the host delivers, e.g. https://vx.example.com/hooks/gitlab
	// Secret is the repository's webhook secret, only right after it was
	// made (vx keeps it sealed and never shows it again).
	Secret string
	// SecretSource says which secret verifies deliveries: "repository",
	// "server" (VX_<HOST>_WEBHOOK_SECRET) or "" (none yet: deliveries are
	// refused).
	SecretSource string
}

HostHook is how to register a repository's webhook on its host.

type HostSettings added in v0.4.0

type HostSettings struct {
	// WebhookSecrets are server-wide webhook secrets per provider
	// (VX_GITLAB_WEBHOOK_SECRET, VX_GITEA_WEBHOOK_SECRET,
	// VX_FORGEJO_WEBHOOK_SECRET, VX_BITBUCKET_WEBHOOK_SECRET). A delivery
	// signed with one is accepted for every repository of that provider
	// that has no secret of its own.
	WebhookSecrets map[store.Provider]string
}

HostSettings configure GitLab, Gitea, Forgejo and Bitbucket on a server.

type Inbox added in v0.2.0

type Inbox struct {
	Questions []Note // open questions to the caller (people: also to their agents)
	Answers   []Note // answers to the caller's questions, newest first
	Escalated []Note // people only: overdue questions in their efforts or to their agents
	// Notes are system notes addressed to the caller (people: also to their
	// agents) that no newer note replaced, newest first: review comments
	// and CI results from the git host (v0.4).
	Notes []Note
}

Inbox is what needs a principal's attention.

type LandInput

type LandInput struct {
	WorkspaceID uuid.UUID
	Base        hash.Hash // changeset the snapshot was made on
	Tree        hash.Hash // snapshot root tree; objects must be uploaded
	Intent      string    // empty: the workspace intent
	Evidence    *object.Evidence
	DependsOn   []string
	Model       string
	Session     string
	// RequireUpToDate refuses to merge onto newer work.
	RequireUpToDate bool
}

LandInput is a snapshot to land into a workspace's effort.

type LandResult

type LandResult struct {
	Landed     bool
	Changeset  store.ChangesetRow
	Files      []store.FileChange
	Rebased    bool              // the effort moved, the snapshot was merged onto it
	AutoMerged []string          // paths changed on both sides that merged cleanly
	Conflicts  []engine.Conflict // set when Landed is false
	EffortHead hash.Hash
	// EffortMoved is set when RequireUpToDate refused the land.
	EffortMoved bool
	// Warnings are problems found in the landed tree, such as a Go function
	// declared twice in one package after a clean text merge, a vx.toml
	// [[unique]] key used twice (kind "rule"), or a generated file both
	// sides changed, kept from the workspace (kind "generated"). They never
	// stop a land.
	Warnings []engine.Warning
	// OverlappingClaims are active claims of other principals on files this
	// land changed. They never stop a land.
	OverlappingClaims []Claim
	// KeptBoth lists paths where both sides inserted different lines at the
	// same place and the merge kept both; worth a look.
	KeptBoth []string
	// MergedByDecl lists .go paths whose lines conflicted but whose
	// top-level declarations did not, merged declaration by declaration;
	// worth a look, like KeptBoth.
	MergedByDecl []string
	// Overlaps are the effort's stored forecasts with other open efforts.
	// The forecast for this land runs after it, in the background, so they
	// may still describe the effort before this land.
	Overlaps []Overlap
	// Review is set when a "human" landing policy of vx.toml applies: the
	// change waits for a person as this pending review, Landed is false and
	// the effort head did not move.
	Review *Review
}

LandResult is the outcome of Land.

type ListNotesInput added in v0.2.0

type ListNotesInput struct {
	Repo, Effort string
	Targets      []string
	Kinds        []NoteKind
	Since        time.Time
	ThreadID     uuid.UUID
	Limit        int // 0: DefaultNoteListLimit
	// IncludeSuperseded keeps notes a newer note replaced (vx board --all);
	// by default they are left out.
	IncludeSuperseded bool
}

ListNotesInput filters a board listing.

type ListTasksInput added in v0.2.0

type ListTasksInput struct {
	Repo, Effort string
	States       []string
	Mine         bool
}

ListTasksInput filters an effort's tasks.

type LogEntry

type LogEntry struct {
	store.ChangesetRow
	Files []store.FileChange
}

LogEntry is a landed changeset with its file list.

type Membership added in v0.2.0

type Membership struct {
	Person store.Principal
	Role   OrgRole
	Teams  []string
}

Membership is a person in an organization.

type NewPerson added in v0.2.0

type NewPerson struct {
	Handle      string
	DisplayName string
	Email       string
	SiteAdmin   bool
	// Org, when set, adds the person to this organization as a member.
	Org string
	// CreateOrg creates Org with the person as its owner when it does not
	// exist yet (vx-server user-add on a new server).
	CreateOrg bool
}

NewPerson describes a person for AddPerson.

type Note added in v0.2.0

type Note struct {
	ID          uuid.UUID
	RepoName    string
	EffortSlug  string
	EffortID    uuid.UUID
	ThreadID    uuid.UUID // the root note of the thread; equals ID for a root
	Kind        NoteKind
	Targets     []string
	Author      store.Principal
	AuthorOwner *store.Principal // the person an agent author acts for
	To          *store.Principal // a question's addressee; nil: anyone
	Body        string
	State       string
	AnswerBy    *time.Time
	CreatedAt   time.Time
	// Supersedes is the author's earlier note this one replaces;
	// SupersededBy is set on a note a newer one replaced.
	Supersedes   *uuid.UUID
	SupersededBy *uuid.UUID
	System       bool // posted by vx itself
	Read         bool // the caller has seen it (filled per caller)
}

Note is one note on an effort's board.

type NoteContext added in v0.2.0

type NoteContext struct {
	Notes         []Note
	Working       []ContextWorkspace
	RecentChanges []LogEntry            // landed changes touching the targets, newest first, with files
	Claims        []Claim               // active claims on the targets (all when no targets)
	OtherEfforts  []OtherEffortActivity // the targets in other open efforts the caller can read
	Overlaps      []Overlap             // forecast collisions of this effort with others
}

NoteContext is what an agent should know before touching some targets.

type NoteKind added in v0.2.0

type NoteKind string

NoteKind is the type of a board note.

const (
	NotePlan      NoteKind = "plan"      // what I am about to change
	NoteDecision  NoteKind = "decision"  // a choice others should follow
	NoteInterface NoteKind = "interface" // a signature others can rely on
	NoteQuestion  NoteKind = "question"  // asked with Ask
	NoteAnswer    NoteKind = "answer"    // given with AnswerNote
	NoteBlocker   NoteKind = "blocker"   // what I am waiting on
	NoteHandoff   NoteKind = "handoff"   // work left for the next agent
	// Posted by vx itself (Note.System), never through PostNote:
	NoteOverlap NoteKind = "overlap" // a forecast collision with another effort
	NoteReview  NoteKind = "review"  // a review comment from the git host (v0.4)
	NoteCI      NoteKind = "ci"      // a CI result from the git host (v0.4)
)
const NoteApproval NoteKind = "approval"

NoteApproval is a system note about a review under a human landing policy: waiting, approved, rejected, or conflicting on approval. Notes to the author are addressed to them (Note.To).

const NoteRebase NoteKind = "rebase"

NoteRebase is a system note about the effort's base branch: rebased automatically, or in need of a rebase.

type Object added in v0.2.0

type Object struct {
	Kind hash.Kind
	Data []byte
	Hash hash.Hash // for uploads: what the client says it is; zero skips the check
}

Object is one object in transfer.

type Org added in v0.2.0

type Org struct {
	ID              uuid.UUID
	Handle          string
	DisplayName     string
	DefaultRepoRole RepoRole // RoleNone, RoleRead or RoleWrite
	Personal        bool
	CreatedAt       time.Time
}

Org is an organization.

type OrgDetail added in v0.2.0

type OrgDetail struct {
	Org     Org
	MyRole  OrgRole // empty when the caller is not a member
	Members []Membership
	Teams   []Team
	Repos   []store.Repo
}

OrgDetail is an organization with its members, teams and the repositories the caller can read.

type OrgRole added in v0.2.0

type OrgRole string

OrgRole is a person's role in an organization.

const (
	OrgOwner  OrgRole = "owner"
	OrgAdmin  OrgRole = "admin"
	OrgMember OrgRole = "member"
)

type OtherEffortActivity added in v0.3.0

type OtherEffortActivity struct {
	Effort       store.Effort
	Owner        store.Principal
	Claims       []Claim
	Notes        []Note // interface and decision notes, newest first
	Working      []ContextWorkspace
	ChangedPaths []string // among the targets: changed in that effort, not shipped
}

OtherEffortActivity is another open effort's activity on some targets.

type Overlap added in v0.3.0

type Overlap struct {
	RepoName    string
	Effort      store.Effort // the caller's side
	Other       store.Effort
	OtherOwner  store.Principal
	Status      string
	SharedFiles []string
	Conflicts   []string
	Warnings    []engine.Warning // kind "rule" for vx.toml violations, "duplicate" for Go
	CheckedAt   time.Time
}

Overlap is a forecast collision between two open efforts of a repository.

type PRRef added in v0.4.0

type PRRef struct {
	Repo       store.Repo
	Number     string // the host's number (shipments.provider_ref); may be empty
	HeadBranch string // vx/...; used when Number matches no shipment
	HeadSHA    string
	URL        string
}

PRRef names a pull (or merge) request of a vx shipment on the git host.

type PostNoteInput added in v0.2.0

type PostNoteInput struct {
	Repo, Effort string
	Kind         NoteKind // plan, decision, interface, blocker, handoff
	Targets      []string
	Body         string
	Supersedes   string // optional: id or 8+ character prefix of the author's own earlier note
}

PostNoteInput is a non-question note.

type RebaseView added in v0.2.0

type RebaseView struct {
	Repo   store.Repo
	Effort store.Effort
	Rebase store.Rebase
	// UpToDate is set when there was nothing to rebase: the effort already
	// sits on the head of the branch. No rebase is recorded then.
	UpToDate bool
	// StoppedAt is the old-chain change whose replay conflicts, when the
	// rebase is stopped. Writing the merge of BaseTree (its parent's tree),
	// ChangeTree (its tree) and OntoTree (the rebased chain so far) with
	// conflict markers reproduces the conflicts.
	StoppedAt                      *store.ChangesetRow
	BaseTree, ChangeTree, OntoTree hash.Hash
	StartedBy, UpdatedBy           string // principal refs
}

RebaseView is a rebase with what a caller needs to show or resume it.

type RepoGrant added in v0.2.0

type RepoGrant struct {
	Repo    string
	Subject string // "user:alice" or "team:acme/backend"
	Role    RepoRole
}

RepoGrant is a direct grant of a role on a repository.

type RepoRole added in v0.2.0

type RepoRole string

RepoRole is what a principal may do in a repository. Roles are ordered: admin includes write, write includes read.

const (
	RoleNone  RepoRole = ""
	RoleRead  RepoRole = "read"
	RoleWrite RepoRole = "write"
	RoleAdmin RepoRole = "admin"
)

func RoleFromGitHub added in v0.2.0

func RoleFromGitHub(perm string) RepoRole

RoleFromGitHub maps a GitHub repository permission to a vx role.

func (RepoRole) Includes added in v0.2.0

func (r RepoRole) Includes(need RepoRole) bool

Includes reports whether r is at least need.

type RepoView added in v0.2.0

type RepoView struct {
	store.Repo
	Role RepoRole
}

RepoView is a repository with the caller's role on it.

type Reservation added in v0.3.0

type Reservation = store.Reservation

Reservation is a value vx reserve handed out.

type Review added in v0.4.0

type Review struct {
	store.Review
	RepoName    string
	EffortSlug  string
	Author      store.Principal
	AuthorOwner *store.Principal // the person an agent author acts for
	DecidedBy   *store.Principal
	// Files are the changes of the snapshot against its base (GetReview
	// only).
	Files []store.FileChange
	// CanDecide says whether the caller may approve or reject it; when not,
	// CannotDecide says why.
	CanDecide    bool
	CannotDecide string
}

Review is a land waiting for a person, with who it is by and, for the caller, whether they may decide it.

func (Review) WaitingText added in v0.4.0

func (r Review) WaitingText() string

WaitingText is what the author's vx land prints:

Waiting for a person to review: internal/store/migrations/021_x.sql (policy in vx.toml)

type ReviewDecision added in v0.4.0

type ReviewDecision struct {
	Review Review
	// Landed is set when an approval landed the change; Conflicts when it
	// could not because the change now conflicts with the effort (the
	// review stays pending and goes back to the author).
	Landed    *LandResult
	Conflicts []engine.Conflict
}

ReviewDecision is the outcome of ApproveReview or RejectReview.

type ReviewEvent added in v0.4.0

type ReviewEvent struct {
	PR   PRRef
	Kind ReviewKind
	// State is the review's state for ReviewSummary.
	State string
	// ID is the host's id of the review or comment. A later event with the
	// same id (an edit) supersedes the earlier note.
	ID string
	// Edited is set for an edit of an earlier review or comment: its note
	// is replaced, and no new task is added.
	Edited   bool
	Reviewer string // the reviewer's login on the host
	Body     string
	URL      string
	// Path and Line are where a ReviewLine comment is (Line in the file
	// as of CommitSHA; 0: the file as a whole).
	Path      string
	Line      int
	CommitSHA string
	Host      string // "GitHub", "GitLab", ...: shown in the note
}

ReviewEvent is a review, or a comment, on a vx pull request.

type ReviewKind added in v0.4.0

type ReviewKind string

ReviewKind says what a ReviewEvent is.

const (
	ReviewSummary ReviewKind = "review"  // a submitted review: approved, changes requested or commented
	ReviewLine    ReviewKind = "line"    // a comment on a line of the diff
	ReviewComment ReviewKind = "comment" // a comment in the pull request's conversation
)

type ReviewQuery added in v0.4.0

type ReviewQuery struct {
	Repo   string // empty: every repository the caller can read
	Effort string // needs Repo
	// States: empty means pending only.
	States []store.ReviewState
	Limit  int
}

ReviewQuery filters ListReviews.

type RevokeInput added in v0.2.0

type RevokeInput struct {
	// ID is a token id or a unique prefix of one (at least 8 characters)
	// among the tokens the caller may manage.
	ID string
	// AllowCurrent allows revoking the token the request is made with, which
	// signs the caller out.
	AllowCurrent bool
}

RevokeInput says which token to revoke.

type Rules added in v0.3.0

type Rules = rules.Rules

Rules are a repository's vx.toml (see internal/rules).

func ParseRules added in v0.3.0

func ParseRules(data []byte) (Rules, error)

ParseRules parses vx.toml. Unknown keys, invalid globs and regular expressions are errors that say the line and what is wrong.

type ScopeInput added in v0.4.0

type ScopeInput struct {
	Clear          bool
	SetAllow       bool
	Allow          []string
	SetDeny        bool
	Deny           []string
	MaxLandsPerDay *int
	MaxLines       *int
	MaxFiles       *int
	MaxWorkspaces  *int
}

ScopeInput changes an agent's scope. Fields left nil (or Set* false) keep their value; Clear removes every limit first.

type ServerInfo added in v0.2.0

type ServerInfo struct {
	Version       string
	MinCLIVersion string
	Features      []string
	GitHubSignIn  bool
}

ServerInfo is the server's version and the oldest CLI it accepts.

type Service

type Service struct {
	Store    *store.Store
	Blobs    blob.Store
	Upstream UpstreamSyncer // nil: repos without an upstream only
	Shipper  Shipper        // nil: shipping disabled
	// Hosts configures GitLab, Gitea, Forgejo and Bitbucket webhooks.
	Hosts HostSettings
	Now   func() time.Time
	// MaxLandAttempts bounds compare-and-swap retries when several agents
	// land into the same effort at once.
	MaxLandAttempts int

	// GitHub configures sign-in with GitHub and GitHub-backed repositories;
	// its API is nil until a GitHub App is set up.
	GitHub GitHubSettings

	// ForecastTimeout bounds one background overlap forecast run; zero:
	// DefaultForecastTimeout.
	ForecastTimeout time.Duration
	// contains filtered or unexported fields
}

Service holds the dependencies of the application logic.

func New

func New(st *store.Store, blobs blob.Store, upstream UpstreamSyncer) *Service

New returns a Service with defaults filled in. When upstream can also ship (the git bridge can), it is used for that too.

func (*Service) Abandon

func (s *Service) Abandon(ctx context.Context, actor Actor, id uuid.UUID) (WorkspaceView, error)

Abandon closes a workspace without landing it (write).

func (*Service) AbortRebase added in v0.2.0

func (s *Service) AbortRebase(ctx context.Context, actor Actor, repoName, slug string) (RebaseView, error)

AbortRebase drops the effort's rebase in progress. The effort is left as it was; the changesets the rebase stored stay unreferenced.

func (*Service) AddPerson added in v0.2.0

func (s *Service) AddPerson(ctx context.Context, by *store.Principal, n NewPerson) (store.Principal, string, bool, error)

AddPerson creates a person, their personal organization and a first token, without checking who asks: CreatePerson checks, and vx-server user-add runs it with by nil. It reports whether it created n.Org.

func (*Service) AddTask added in v0.2.0

func (s *Service) AddTask(ctx context.Context, actor Actor, in AddTaskInput) (Task, error)

AddTask adds a task to an effort's plan.

func (*Service) AnswerNote added in v0.2.0

func (s *Service) AnswerNote(ctx context.Context, actor Actor, questionID string, body string) (Note, Note, error)

AnswerNote answers a question (by id or an 8+ character id prefix) and returns the answer and the updated question.

func (*Service) ApplyCI added in v0.4.0

func (s *Service) ApplyCI(ctx context.Context, ev CIEvent) error

ApplyCI records a CI result on the shipments whose head is the event's commit and, when the shipment's result changes, tells the authors of its changes: on failure which checks failed, on success one short note. Each new note replaces the author's previous CI note on that pull request; a rerun with the same outcome posts nothing.

func (*Service) ApplyGitHubOrgMembership added in v0.2.0

func (s *Service) ApplyGitHubOrgMembership(ctx context.Context, githubOrgID, githubUserID int64, role string) error

ApplyGitHubOrgMembership records a membership change GitHub reported in a webhook (organization member_added, member_removed, member_invited does not count): role is admin, member or "" (not a member). It drops the person's cached answers for that organization and updates the linked vx organization. People vx does not know are ignored.

func (*Service) ApplyReview added in v0.4.0

func (s *Service) ApplyReview(ctx context.Context, ev ReviewEvent) error

ApplyReview posts a review or comment on a vx pull request as review notes: a line comment to the author of the change that wrote the line, anything else to every agent whose changes are in the pull request. A review that requests changes also adds a task for each of them. Events for pull requests vx did not open are ignored.

func (*Service) ApproveCLILogin added in v0.2.0

func (s *Service) ApproveCLILogin(ctx context.Context, actor Actor, userCode string, approve bool) error

ApproveCLILogin approves or denies a pending login by user code; approval lets the CLI collect a token for the person named after the client.

func (*Service) ApproveReview added in v0.4.0

func (s *Service) ApproveReview(ctx context.Context, actor Actor, id string) (ReviewDecision, error)

ApproveReview approves a pending review and lands it onto the current effort head with the normal merge (write; a person, see cannotDecide). The approval is recorded in the change's evidence. When the merge conflicts the review stays pending and a note asks the author to resolve and land again.

func (*Service) Ask added in v0.2.0

func (s *Service) Ask(ctx context.Context, actor Actor, in AskInput) (Note, error)

Ask posts a question, optionally to one principal, that escalates after its deadline.

func (*Service) Authorize added in v0.2.0

func (s *Service) Authorize(ctx context.Context, actor Actor, repo string, need RepoRole) (store.Repo, RepoRole, error)

Authorize returns the repository named repo if actor has at least need on it. A repository the actor cannot read is reported as not found, so its existence does not leak; one it can read but needs more on is a permission error (the repository and the actor's role come back with it). Agents are checked as the person they act for.

Every service function that takes a repository name calls this first. It runs one query, plus a cache lookup (and when that is stale, a call to GitHub) for GitHub-backed repositories.

func (*Service) AuthorizeID added in v0.2.0

func (s *Service) AuthorizeID(ctx context.Context, actor Actor, repoID uuid.UUID, need RepoRole) (RepoRole, error)

AuthorizeID is Authorize for a repository id (for objects, workspaces and other records that carry a repo id).

func (*Service) BackfillObjects added in v0.2.0

func (s *Service) BackfillObjects(ctx context.Context, log *slog.Logger) ([]BackfillStats, error)

BackfillObjects queues every repository that has changesets but no recorded objects and backfills each queued repository, one at a time. Requests for a repository that is still queued backfill it on demand, so a long backfill of one repository does not hold up the others.

func (*Service) BackfillRepoObjects added in v0.2.0

func (s *Service) BackfillRepoObjects(ctx context.Context, repoID uuid.UUID, force bool, log *slog.Logger) (BackfillStats, error)

BackfillRepoObjects records the objects of every changeset tree in the repository. Unless force is set it does nothing for a repository that is not queued. Concurrent calls for one repository wait for each other.

func (*Service) BlobReader added in v0.2.0

func (s *Service) BlobReader(ctx context.Context, actor Actor, repoID uuid.UUID) (func(context.Context, hash.Hash) ([]byte, error), error)

BlobReader returns a function that reads file contents of the repository with id repoID, after checking once that actor can read it. The web UI and the MCP tools read blobs through it. Zero hashes read as empty.

func (*Service) Branch

func (s *Service) Branch(ctx context.Context, actor Actor, repo store.Repo, name string) (store.Branch, error)

Branch returns a tracked branch, importing it first if vx does not follow it yet. This is how efforts can start from any branch on the fly. The caller has authorized actor on repo already.

func (*Service) BranchMoved added in v0.4.0

func (s *Service) BranchMoved(ctx context.Context, repo store.Repo, branch, by string) []AutoRebase

BranchMoved runs after vx imported branch of repo: it marks the efforts whose changes reached the branch merged, then rebases the open efforts on it, or tells them they need a rebase (vx.toml [automation] rebase). by names what moved the branch, for the op log ("github push"). Errors are logged: the import itself succeeded.

func (*Service) CanSealSecrets added in v0.4.0

func (s *Service) CanSealSecrets() bool

CanSealSecrets reports whether the server has a key to keep secrets.

func (*Service) CheckCLIVersion added in v0.2.0

func (s *Service) CheckCLIVersion(cliVersion, baseURL string) (status, message string)

CheckCLIVersion says whether a CLI of cliVersion works with this server, and what to tell its user. Dev builds and CLIs that send no version are always ok.

func (*Service) CheckRules added in v0.3.0

func (s *Service) CheckRules(ctx context.Context, r Rules, base, tree hash.Hash) ([]engine.Warning, error)

CheckRules reports violations of rules in tree, limited to the paths changed between base and tree, as warnings of kind WarningRule.

func (*Service) CloseEffort added in v0.3.0

func (s *Service) CloseEffort(ctx context.Context, actor Actor, repoName, slug string, state store.EffortState) (store.Effort, error)

CloseEffort marks an effort merged or abandoned (write). Its changes and board stay readable; it can no longer be landed into, and lists, context and overlap forecasts leave it out. Closing a closed effort again with the same state changes nothing.

func (*Service) CompleteGitHubSetup added in v0.2.0

func (s *Service) CompleteGitHubSetup(ctx context.Context, actor Actor, code, state string) error

CompleteGitHubSetup exchanges the manifest code for the App's credentials and stores them encrypted (site admins).

func (*Service) Context added in v0.2.0

func (s *Service) Context(ctx context.Context, actor Actor, repo, effort string, targets []string) (NoteContext, error)

Context returns notes on the targets, open workspaces, active claims and recent changes touching them. Without targets it returns the effort's latest notes and changes. OtherEfforts is what other open efforts of the repository do on the targets (without targets: on the files this effort changed); see otherEfforts for the rules and limits.

func (*Service) ContinueRebase added in v0.2.0

func (s *Service) ContinueRebase(ctx context.Context, actor Actor, in ContinueInput) (RebaseView, error)

ContinueRebase records the resolved tree as the stopped change's rebased version, marked as resolved by the actor, and replays the rest. It may stop again on a later change.

func (*Service) CreateAgent

func (s *Service) CreateAgent(ctx context.Context, actor Actor, name, displayName string) (store.Principal, string, error)

CreateAgent creates an agent that acts for the calling human and returns it with a fresh token. Agents cannot create agents.

func (*Service) CreateEffort

func (s *Service) CreateEffort(ctx context.Context, actor Actor, in CreateEffortInput) (store.Effort, error)

CreateEffort starts an effort on the current head of its base branch (write).

func (*Service) CreateLoginCode added in v0.2.0

func (s *Service) CreateLoginCode(ctx context.Context, actor Actor) (string, time.Time, error)

CreateLoginCode returns a one-time code that signs the actor in to the web UI. It expires after LoginCodeTTL and works once.

func (*Service) CreateOrg added in v0.2.0

func (s *Service) CreateOrg(ctx context.Context, actor Actor, handle, displayName string) (Org, error)

CreateOrg creates an organization owned by the calling person.

func (*Service) CreatePerson added in v0.2.0

func (s *Service) CreatePerson(ctx context.Context, actor Actor, handle, displayName, email string, siteAdmin bool, org string) (store.Principal, string, error)

CreatePerson creates a person with a first token (site admins), optionally as a member of an organization.

func (*Service) CreateRepo

func (s *Service) CreateRepo(ctx context.Context, actor Actor, in CreateRepoInput) (store.Repo, error)

CreateRepo registers a repo. A repo with an upstream imports its default branch right away; a repo without one starts from an empty snapshot.

func (*Service) CreateTeam added in v0.2.0

func (s *Service) CreateTeam(ctx context.Context, actor Actor, org, name string) (Team, error)

CreateTeam, DeleteTeam, SetTeamMember and RemoveTeamMember manage teams (org owners and admins).

func (*Service) CreateToken added in v0.2.0

func (s *Service) CreateToken(ctx context.Context, actor Actor, agent, name string) (store.Token, store.Principal, string, error)

CreateToken issues a new token to the caller (agent empty) or to one of the caller's agents and returns it with its secret, which is shown once.

Only people can create tokens, also for themselves. Agents can list and revoke their own tokens, but if an agent could mint tokens, a leaked agent token could create replacements that survive its revocation, so revoking it would no longer contain the leak. An agent that needs a new token asks the person it acts for.

func (*Service) DeleteTeam added in v0.2.0

func (s *Service) DeleteTeam(ctx context.Context, actor Actor, org, name string) error

func (*Service) DismissWelcome added in v0.2.0

func (s *Service) DismissWelcome(ctx context.Context, actor Actor, dismissed bool) error

DismissWelcome hides the welcome page from the navigation (or shows it again).

func (*Service) DropGitHubRoles added in v0.2.0

func (s *Service) DropGitHubRoles(ctx context.Context, scope GitHubRoleScope) error

DropGitHubRoles forgets cached GitHub answers in scope, so the next check asks GitHub. Webhooks call it; it never calls GitHub. An empty scope is an error, so a caller bug cannot silently keep stale roles.

func (*Service) EffortOverlaps added in v0.3.0

func (s *Service) EffortOverlaps(ctx context.Context, actor Actor, repoName, slug string) ([]Overlap, error)

EffortOverlaps returns an effort's stored forecasts that are not clean, without recomputing them (read). The web UI shows them.

func (*Service) ForecastOverlaps added in v0.3.0

func (s *Service) ForecastOverlaps(ctx context.Context, repo store.Repo, effortID uuid.UUID) error

ForecastOverlaps recomputes the forecast between effort and every other open effort of its repository with the same base branch, and posts or updates overlap notes on both boards when something changed. Called after every land and when the base branch moves; it never fails a land (errors are logged). It is internal: no actor, no access check.

func (*Service) GetAgent added in v0.4.0

func (s *Service) GetAgent(ctx context.Context, actor Actor, agent string) (AgentView, error)

GetAgent returns an agent with its scope and today's usage. An agent may read its own (agent empty); a person their agents'; a site admin anyone's, by handle.

func (*Service) GetChangeset

func (s *Service) GetChangeset(ctx context.Context, actor Actor, repoName, ref string) (store.Repo, LogEntry, error)

GetChangeset resolves a changeset by hash, prefix or change ID (read).

func (*Service) GetEffort

func (s *Service) GetEffort(ctx context.Context, actor Actor, repoName, slug string) (EffortView, error)

GetEffort loads an effort by repo name and slug (read), with its rebase in progress if there is one.

func (*Service) GetInbox added in v0.2.0

func (s *Service) GetInbox(ctx context.Context, actor Actor) (Inbox, error)

GetInbox returns what needs the caller's attention across efforts, in the repositories the caller can read.

func (*Service) GetNote added in v0.2.0

func (s *Service) GetNote(ctx context.Context, actor Actor, id string) (Note, error)

GetNote returns one note by id or an 8+ character id prefix.

func (*Service) GetObjects added in v0.2.0

func (s *Service) GetObjects(ctx context.Context, actor Actor, repo string, hashes []hash.Hash, maxBytes int) ([]Object, error)

GetObjects returns objects that are part of repo, in the order asked, stopping before maxBytes (but always returning at least one); the client asks again for the rest. An object that is not part of repo is not found, whether or not another repository has it.

func (*Service) GetOrg added in v0.2.0

func (s *Service) GetOrg(ctx context.Context, actor Actor, handle string) (OrgDetail, error)

GetOrg returns an organization the caller is a member of (or any, for site admins).

func (*Service) GetRebase added in v0.2.0

func (s *Service) GetRebase(ctx context.Context, actor Actor, repoName, slug string) (RebaseView, bool, error)

GetRebase returns the effort's rebase in progress, or else its latest one. Found is false when the effort was never rebased.

func (*Service) GetRepo added in v0.2.0

func (s *Service) GetRepo(ctx context.Context, actor Actor, name string) (RepoView, []store.Branch, error)

GetRepo returns a repository the caller can read, with its branches.

func (*Service) GetReview added in v0.4.0

func (s *Service) GetReview(ctx context.Context, actor Actor, id string) (Review, error)

GetReview returns one review with the files its snapshot changes (read).

func (*Service) GetRules added in v0.3.0

func (s *Service) GetRules(ctx context.Context, actor Actor, repoName, effort string) (Rules, error)

GetRules returns the vx.toml rules of a repository (read): at the head of effort when one is given, else at the head of the default branch. No vx.toml: empty Rules. A vx.toml that does not parse is an error that says where.

func (*Service) GetWorkspace

func (s *Service) GetWorkspace(ctx context.Context, actor Actor, id uuid.UUID) (WorkspaceView, error)

GetWorkspace loads a workspace with its effort and repo (read).

func (*Service) GitHubApp added in v0.2.0

func (s *Service) GitHubApp(ctx context.Context) (GitHubAppInfo, error)

GitHubApp returns the server's App: ErrGitHubNotConfigured when there is none.

func (*Service) GitHubAppGaps added in v0.4.0

func (s *Service) GitHubAppGaps(ctx context.Context, actor Actor) ([]GitHubAppGap, error)

GitHubAppGaps lists the permissions and events this vx needs that the App lacks (site admins): those GitHub refused, and those the App's settings on GitHub do not have.

func (*Service) GitHubAppInstallURL added in v0.2.0

func (s *Service) GitHubAppInstallURL(ctx context.Context) (string, error)

GitHubAppInstallURL is where an organization installs the App; empty without an App.

func (*Service) GitHubAppManifest added in v0.2.0

func (s *Service) GitHubAppManifest() ([]byte, error)

GitHubAppManifest builds the manifest of this server's App.

func (*Service) GitHubClient added in v0.2.0

func (s *Service) GitHubClient(ctx context.Context) (GitHubAPI, error)

GitHubClient returns the API client for the server's App: ErrGitHubNotConfigured when there is none. s.GitHub.API, when set, wins (tests).

func (*Service) GitHubLinkFinish added in v0.2.0

func (s *Service) GitHubLinkFinish(ctx context.Context, actor Actor, code, verifier string) (GitHubUser, error)

GitHubLinkFinish links the GitHub account a sign-in code is for to the signed-in person, for people created with a token before GitHub sign-in.

func (*Service) GitHubLinkOf added in v0.2.0

func (s *Service) GitHubLinkOf(ctx context.Context, actor Actor) (store.GitHubLink, bool, error)

GitHubLinkOf returns the GitHub account linked to a person; ok is false when there is none.

func (*Service) GitHubManifestFormURL added in v0.2.0

func (s *Service) GitHubManifestFormURL(org, state string) string

GitHubManifestFormURL is where the manifest form posts: the person's account, or org when set. state goes along and comes back.

func (*Service) GitHubRepoToken added in v0.2.0

func (s *Service) GitHubRepoToken(ctx context.Context, repo store.Repo) (string, error)

GitHubRepoToken returns an installation token for a repository linked to an installation of the App, for git over HTTPS (user x-access-token) and API calls; "" for other repositories, which use VX_GITHUB_TOKEN or SSH. The git bridge asks for it on every fetch, push and pull request; the client caches tokens until shortly before they expire.

func (*Service) GitHubRole added in v0.2.0

func (s *Service) GitHubRole(ctx context.Context, repo store.Repo, person store.Principal) (role RepoRole, ok bool, err error)

GitHubRole returns a person's role on a GitHub-backed repository, from the cache or GitHub. ok is false when the repository is not GitHub-backed (then vx's own roles apply). Authorize calls it. An agent is checked as its person; a service principal has no GitHub role. When GitHub cannot be reached and no answer younger than an hour is cached, err is a retryable CodeUnavailable error and role is RoleNone.

func (*Service) GitHubSettingsURL added in v0.2.0

func (s *Service) GitHubSettingsURL(r store.Repo) string

GitHubSettingsURL is where access to a GitHub-backed repository is managed on GitHub.

func (*Service) GitHubSetupManifest added in v0.2.0

func (s *Service) GitHubSetupManifest(ctx context.Context, actor Actor) (manifest []byte, state string, err error)

GitHubSetupManifest returns the App manifest (JSON) and a state value for the manifest flow (site admins). The web page posts it to GitHub.

func (*Service) GitHubSignInEnabled added in v0.2.0

func (s *Service) GitHubSignInEnabled(ctx context.Context) bool

GitHubSignInEnabled reports whether people can sign in with GitHub here: the server has a GitHub App.

func (*Service) GitHubSignInFinish added in v0.2.0

func (s *Service) GitHubSignInFinish(ctx context.Context, code, verifier string) (p store.Principal, token string, isNew bool, err error)

GitHubSignInFinish completes a web sign-in: it links or creates the person (per the signup mode), syncs their organizations, and returns the person and a new web-session token. isNew is true on first sign-in.

func (*Service) GitHubSignInStart added in v0.2.0

func (s *Service) GitHubSignInStart(ctx context.Context, next string) (authorizeURL, state, verifier string, err error)

GitHubSignInStart returns the GitHub authorize URL for a web sign-in and the state and PKCE verifier the web layer keeps in a short-lived cookie. next is kept by the web layer too; it is not sent to GitHub.

func (*Service) GitHubWebURL added in v0.2.0

func (s *Service) GitHubWebURL() string

GitHubWebURL is GitHub's browser base URL (github.com or GHE).

func (*Service) GrantRepo added in v0.2.0

func (s *Service) GrantRepo(ctx context.Context, actor Actor, repo, subject string, role RepoRole) (RepoGrant, error)

GrantRepo gives a person or team a role on a repository (repo admins). On a GitHub-backed repository only service principals can be granted: people's roles come from GitHub.

func (*Service) HandleGitHubWebhook added in v0.2.0

func (s *Service) HandleGitHubWebhook(ctx context.Context, event, deliveryID, signature string, body []byte) error

HandleGitHubWebhook verifies and applies a webhook delivery: installations, repositories, membership and permission changes.

func (*Service) HandleHostWebhook added in v0.4.0

func (s *Service) HandleHostWebhook(ctx context.Context, kind store.Provider, d HostDelivery) error

HandleHostWebhook verifies and applies a delivery from GitLab (kind gitlab), Gitea or Forgejo (gitea, forgejo: both accept either) or Bitbucket (bitbucket). A delivery is applied to every vx repository that follows its upstream and whose secret (its own, else the server's for the host) verifies it.

func (*Service) HostRepoToken added in v0.4.0

func (s *Service) HostRepoToken(ctx context.Context, repo store.Repo) (string, error)

HostRepoToken returns the token vx keeps for a GitLab, Gitea, Forgejo or Bitbucket repository, or "" when it has none (the server's token for its host applies). The git bridge calls it; nothing logs the result.

func (*Service) Info added in v0.2.0

func (s *Service) Info(ctx context.Context) ServerInfo

Info describes this server.

func (*Service) InstallCommand added in v0.2.0

func (s *Service) InstallCommand(baseURL string) string

InstallCommand is the one-liner that installs vx from the server at baseURL (PublicURL wins when set).

func (*Service) InviteGitHubLogin added in v0.2.0

func (s *Service) InviteGitHubLogin(ctx context.Context, by *store.Principal, login, note string, siteAdmin bool) (store.SignupInvite, error)

InviteGitHubLogin invites a GitHub login on behalf of by (nil: the server console, vx-server invite). siteAdmin makes the person a site admin when they sign up; only the console can ask for that.

func (*Service) InviteGitHubUser added in v0.2.0

func (s *Service) InviteGitHubUser(ctx context.Context, actor Actor, login, note string) error

InviteGitHubUser allows a GitHub login to sign up while sign-up is invite-only (site admins).

func (*Service) IsSiteAdmin added in v0.2.0

func (s *Service) IsSiteAdmin(ctx context.Context, actor Actor) bool

IsSiteAdmin reports whether actor (or, for agents, its person) is a site admin. It reads the database, so a change applies at once.

func (*Service) Land

func (s *Service) Land(ctx context.Context, actor Actor, in LandInput) (LandResult, error)

Land merges a workspace snapshot into its effort (write).

When the effort has not moved since the snapshot's base, the snapshot becomes the new head. When it has, the snapshot is merged onto the current head with a three-way merge, and only real conflicts are sent back. The head moves with a compare-and-swap, so concurrent lands never lose work: the loser merges again on the new head and retries.

func (*Service) ListAgents added in v0.2.0

func (s *Service) ListAgents(ctx context.Context, actor Actor) ([]AgentSummary, error)

ListAgents returns the agents acting for the calling person.

func (*Service) ListClaims added in v0.2.0

func (s *Service) ListClaims(ctx context.Context, actor Actor, repo, effort string, targets []string) ([]Claim, error)

ListClaims returns the active claims of an effort, optionally only those matching targets (TargetsMatch).

func (*Service) ListEfforts

func (s *Service) ListEfforts(ctx context.Context, actor Actor, repoName string, state store.EffortState) (store.Repo, []store.Effort, error)

ListEfforts lists a repo's efforts (read).

func (*Service) ListGitHubInvites added in v0.2.0

func (s *Service) ListGitHubInvites(ctx context.Context, actor Actor, all bool) ([]store.SignupInvite, error)

ListGitHubInvites lists invites (site admins): open ones, or all.

func (*Service) ListNotes added in v0.2.0

func (s *Service) ListNotes(ctx context.Context, actor Actor, in ListNotesInput) ([]Note, error)

ListNotes lists an effort's notes, newest first.

func (*Service) ListOrgs added in v0.2.0

func (s *Service) ListOrgs(ctx context.Context, actor Actor, all bool) ([]Org, []OrgRole, error)

ListOrgs lists the caller's organizations, or all of them for site admins with all set.

func (*Service) ListOverlaps added in v0.3.0

func (s *Service) ListOverlaps(ctx context.Context, actor Actor, repoName, effort string) ([]Overlap, error)

ListOverlaps returns the stored forecasts of an effort (read), or of every pair in the repository when effort is empty. A forecast older than the efforts' heads or the branch head is recomputed first, within a short time limit; past it the stored one is returned.

func (*Service) ListPeople added in v0.2.0

func (s *Service) ListPeople(ctx context.Context, actor Actor) ([]store.Principal, error)

ListPeople lists every person on the server (site admins).

func (*Service) ListRepos added in v0.2.0

func (s *Service) ListRepos(ctx context.Context, actor Actor) ([]RepoView, error)

ListRepos lists the repositories the caller can read, with the caller's role on each.

func (*Service) ListReservations added in v0.3.0

func (s *Service) ListReservations(ctx context.Context, actor Actor, repoName, rule string) ([]Reservation, error)

ListReservations lists the values vx reserve handed out in a repository (read), newest first; rule narrows it to one [unique] rule.

func (*Service) ListReviews added in v0.4.0

func (s *Service) ListReviews(ctx context.Context, actor Actor, q ReviewQuery) ([]Review, error)

ListReviews returns reviews in the repositories the caller can read (read), newest first: pending ones unless States says otherwise.

func (*Service) ListShipments

func (s *Service) ListShipments(ctx context.Context, actor Actor, repoName, slug string) ([]store.Shipment, error)

ListShipments returns an effort's shipments (read).

func (*Service) ListTasks added in v0.2.0

func (s *Service) ListTasks(ctx context.Context, actor Actor, in ListTasksInput) ([]Task, error)

ListTasks lists an effort's tasks: not done first, then by creation.

func (*Service) ListTokens added in v0.2.0

func (s *Service) ListTokens(ctx context.Context, actor Actor, agent string) (store.Principal, []store.Token, error)

ListTokens returns the tokens of the caller (agent empty) or of one of the caller's agents, given by name ("backend") or handle ("alice/backend").

func (*Service) LoadGitHubApp added in v0.2.0

func (s *Service) LoadGitHubApp(ctx context.Context) error

LoadGitHubApp loads the App at server start. No App is not an error; an App the server cannot open (no or another VX_SECRET_KEY) is.

func (*Service) Log

func (s *Service) Log(ctx context.Context, actor Actor, repoName, slug string, limit int, withFiles bool) ([]LogEntry, error)

Log lists changes landed in an effort since its base, newest first (read).

func (*Service) MakeClaim added in v0.2.0

func (s *Service) MakeClaim(ctx context.Context, actor Actor, in ClaimInput) (Claim, []Claim, error)

MakeClaim records a claim and returns it with the active claims of others on the same targets. It never fails because of them.

func (*Service) MarkNotesRead added in v0.3.0

func (s *Service) MarkNotesRead(ctx context.Context, actor Actor, ids []uuid.UUID) error

MarkNotesRead records that actor was shown notes. Notes in repositories the caller cannot read, and ids of no note, are skipped silently, so the call never tells whether a note exists.

func (*Service) MissingObjects added in v0.2.0

func (s *Service) MissingObjects(ctx context.Context, actor Actor, repo string, hashes []hash.Hash) ([]hash.Hash, error)

MissingObjects returns the hashes that are not part of repo yet, which the client then uploads. An object stored only for another repository is missing here: uploading it again costs little, because storage dedupes, and proves the uploader has the bytes.

func (*Service) MyGitHubInstallations added in v0.2.0

func (s *Service) MyGitHubInstallations(ctx context.Context, actor Actor) ([]GitHubInstallation, error)

MyGitHubInstallations lists the installations of the App on the actor's own GitHub account and on GitHub organizations GitHub says they are a member of. It is empty for people without a GitHub link.

func (*Service) OpenShipment

func (s *Service) OpenShipment(ctx context.Context, actor Actor, in ShipInput) (ShipResult, error)

OpenShipment pushes the planned commits to vx/<effort> and opens or updates the pull request. Shipping again replaces the branch and updates the same PR. vx never merges: that stays a decision on the git host. PlanShipment checks admin on the repository.

func (*Service) OpenWorkspace

func (s *Service) OpenWorkspace(ctx context.Context, actor Actor, repoName, slug, intent string) (WorkspaceView, error)

OpenWorkspace starts a task in an effort, based on the effort's head (write).

func (*Service) OverlapCounts added in v0.3.0

func (s *Service) OverlapCounts(ctx context.Context, actor Actor, repoName string) (map[uuid.UUID][2]int, error)

OverlapCounts returns, for each open effort of a repository the actor can read, how many other efforts it overlaps with and how many of those conflict (read). The web UI shows them as badges.

func (*Service) PeekLoginCode added in v0.2.0

func (s *Service) PeekLoginCode(ctx context.Context, code string) (store.Principal, error)

PeekLoginCode tells who a code would sign in, without using it up.

func (*Service) PendingCLILogin added in v0.2.0

func (s *Service) PendingCLILogin(ctx context.Context, actor Actor, userCode string) (clientName string, expires time.Time, err error)

PendingCLILogin returns the client name of a pending login by user code, for the approval page (signed-in people only).

func (*Service) PlanShipment

func (s *Service) PlanShipment(ctx context.Context, actor Actor, repoName, slug, target string) (ShipPlan, error)

PlanShipment replays the effort's changes, oldest first, onto the latest head of the target branch. Each change becomes one commit. A change whose parent is not the current tree is merged onto it, so an effort started on an older commit, or on another branch, still ships cleanly. Shipping needs admin on the repository.

func (*Service) PlanSplit added in v0.4.0

func (s *Service) PlanSplit(ctx context.Context, actor Actor, in SplitInput) (ShipPlan, error)

PlanSplit plans shipping an effort as several pull requests (admin). The plan's Groups hold the parts; Problems say why the split cannot ship as grouped (OpenShipment refuses it then). The whole-effort fields of the plan (Steps, Conflicts, Warnings) are those of PlanShipment.

func (*Service) PollCLILogin added in v0.2.0

func (s *Service) PollCLILogin(ctx context.Context, deviceCode string) (status, token string, p store.Principal, err error)

PollCLILogin returns the state of a login; on approval it returns the new token exactly once. Later polls return CLILoginUsed. Polling faster than the interval returns CLILoginSlowDown while the login is pending.

func (*Service) PostNote added in v0.2.0

func (s *Service) PostNote(ctx context.Context, actor Actor, in PostNoteInput) (Note, error)

PostNote adds a plan, decision, interface, blocker or handoff note.

func (*Service) PutObjects added in v0.2.0

func (s *Service) PutObjects(ctx context.Context, actor Actor, repo string, objs []Object) ([]hash.Hash, error)

PutObjects stores objects and records them as part of repo. The caller needs write access. The server hashes the bytes it receives, so an object only becomes part of a repository when its content was sent.

func (*Service) ReadBlob added in v0.2.0

func (s *Service) ReadBlob(ctx context.Context, actor Actor, repoID uuid.UUID, h hash.Hash) ([]byte, error)

ReadBlob reads one file's contents from a repository actor can read.

func (*Service) ReadableRepoIDs added in v0.2.0

func (s *Service) ReadableRepoIDs(ctx context.Context, actor Actor) (ids []uuid.UUID, all bool, err error)

ReadableRepoIDs returns the ids of every repository actor can read, for filtering lists. all is true when the actor can read every repository (a site admin), in which case ids is nil.

func (*Service) ReadableRepos added in v0.2.0

func (s *Service) ReadableRepos(ctx context.Context, actor Actor, org *uuid.UUID) ([]store.Repo, []RepoRole, error)

ReadableRepos lists the repositories actor can read, by name, with its role on each, in one query. org limits it to one organization's repositories; nil lists them all.

func (*Service) RebaseEffort added in v0.2.0

func (s *Service) RebaseEffort(ctx context.Context, actor Actor, repoName, slug, onto string) (RebaseView, error)

RebaseEffort replays the effort's changes, oldest first, onto the latest head of onto (default: the effort's base branch), after importing that branch's new commits. Each change is three-way merged onto the rebased chain so far with the same rules as a land, and keeps its change id, intent, author and evidence; it is marked as rebased. The effort head moves only when every change replayed, with a compare-and-swap; changes landed meanwhile are replayed too. When a change conflicts the rebase stops and waits for ContinueRebase or AbortRebase.

func (*Service) RedeemLoginCode added in v0.2.0

func (s *Service) RedeemLoginCode(ctx context.Context, code string) (store.Principal, string, error)

RedeemLoginCode uses up a code and issues a new token for its principal, to be kept in the browser's session cookie.

func (*Service) RejectReview added in v0.4.0

func (s *Service) RejectReview(ctx context.Context, actor Actor, id, reason string) (ReviewDecision, error)

RejectReview rejects a pending review with a reason (write; a person, see cannotDecide). The author's workspace stays open: they change the files and land again, which opens a new review, or abandon it.

func (*Service) ReleaseClaims added in v0.2.0

func (s *Service) ReleaseClaims(ctx context.Context, actor Actor, id, workspaceID string) ([]Claim, error)

ReleaseClaims ends one claim (id or prefix) or all of the caller's claims for a workspace, and returns what it released.

func (*Service) RemoveMember added in v0.2.0

func (s *Service) RemoveMember(ctx context.Context, actor Actor, org, person string) error

RemoveMember removes a person from an organization and its teams.

func (*Service) RemoveTeamMember added in v0.2.0

func (s *Service) RemoveTeamMember(ctx context.Context, actor Actor, org, team, person string) (Team, error)

func (*Service) RepoAccess added in v0.2.0

func (s *Service) RepoAccess(ctx context.Context, actor Actor, repo string) ([]RepoGrant, []AccessEntry, error)

RepoAccess lists a repository's direct grants and everyone's effective role (repo admins).

func (*Service) RepoRoleOf added in v0.2.0

func (s *Service) RepoRoleOf(ctx context.Context, actor Actor, r store.Repo) RepoRole

RepoRoleOf returns actor's role on r without checking anything, for filling my_role in responses. It is RoleNone when the actor cannot read r.

func (*Service) ReportChanges added in v0.3.0

func (s *Service) ReportChanges(ctx context.Context, actor Actor, workspaceID uuid.UUID, paths []string) error

ReportChanges records the files the caller's open workspace has changed locally (write). vx status, vx sync, vx claim and vx wait send them.

func (*Service) Reserve added in v0.3.0

func (s *Service) Reserve(ctx context.Context, actor Actor, repoName, effort, rule string) (value, example string, err error)

Reserve hands out the next free value of a unique rule (write): one more than the largest key used in the head of the effort's target branch, in the head of any open effort of the repository, or reserved before, formatted like the existing keys (same zero padding). The value is recorded in rule_reservations, whose primary key makes concurrent calls get different values: the loser computes again. example is a file name to use, like "internal/store/migrations/017_<name>.sql".

func (*Service) ResolveActor

func (s *Service) ResolveActor(ctx context.Context, p store.Principal) (Actor, error)

ResolveActor loads the parent of an agent principal.

func (*Service) RevokeRepo added in v0.2.0

func (s *Service) RevokeRepo(ctx context.Context, actor Actor, repo, subject string) error

RevokeRepo removes a direct grant (repo admins). It also works on GitHub-backed repositories, to clean up grants made before the repository was linked (they have no effect there).

func (*Service) RevokeToken added in v0.2.0

func (s *Service) RevokeToken(ctx context.Context, actor Actor, in RevokeInput) (store.Token, store.Principal, bool, error)

RevokeToken revokes one of the caller's tokens or one of their agents'. It returns the token and whether it was already revoked.

func (*Service) RulesAt added in v0.3.0

func (s *Service) RulesAt(ctx context.Context, tree hash.Hash) (Rules, error)

RulesAt returns the rules in vx.toml at the root of tree (none: empty Rules, no error).

func (*Service) SaveGitHubApp added in v0.2.0

func (s *Service) SaveGitHubApp(ctx context.Context, creds GitHubAppCredentials, createdBy *uuid.UUID) error

SaveGitHubApp stores the App's credentials sealed with the server key and starts using them. CompleteGitHubSetup calls it; tests too.

func (*Service) SetAgentScope added in v0.4.0

func (s *Service) SetAgentScope(ctx context.Context, actor Actor, agent string, in ScopeInput) (AgentView, error)

SetAgentScope changes an agent's path scope and budgets. Only the agent's person and site admins may; an agent cannot change any scope, not even its own, or a scope would limit nothing.

func (*Service) SetBase

func (s *Service) SetBase(ctx context.Context, actor Actor, id uuid.UUID, base hash.Hash) (WorkspaceView, error)

SetBase records that the workspace's files now sit on base, which must be on the effort's chain (write).

func (*Service) SetMember added in v0.2.0

func (s *Service) SetMember(ctx context.Context, actor Actor, org, person string, role OrgRole) (Membership, error)

SetMember adds a person to an organization or changes their role. Owners and admins may; only owners make owners; the last owner stays.

func (*Service) SetRepoHost added in v0.4.0

func (s *Service) SetRepoHost(ctx context.Context, actor Actor, in SetRepoHostInput) (HostHook, error)

SetRepoHost sets the token of a GitLab, Gitea, Forgejo or Bitbucket repository or makes a new webhook secret for it (admin), and says how to register the webhook.

func (*Service) SetTeamMember added in v0.2.0

func (s *Service) SetTeamMember(ctx context.Context, actor Actor, org, team, person string) (Team, error)

func (*Service) ShipmentsCI added in v0.4.0

func (s *Service) ShipmentsCI(ctx context.Context, actor Actor, repoName, slug string) (map[uuid.UUID]ShipmentCIView, error)

ShipmentsCI returns the CI results of an effort's shipments (read), by shipment id; shipments without a CI result are missing.

func (*Service) ShowWelcome added in v0.2.0

func (s *Service) ShowWelcome(ctx context.Context, actor Actor) bool

ShowWelcome reports whether the welcome page is still linked from the navigation for actor's person.

func (*Service) SignupModeOrDefault added in v0.2.0

func (s *Service) SignupModeOrDefault() SignupMode

SignupModeOrDefault is the signup mode in effect: invite unless set.

func (*Service) StartCLILogin added in v0.2.0

func (s *Service) StartCLILogin(ctx context.Context, clientName string) (CLILogin, error)

StartCLILogin begins a browser login for a CLI (no token needed).

func (*Service) SyncBranch

func (s *Service) SyncBranch(ctx context.Context, actor Actor, repoName, branch string) (store.Branch, int, error)

SyncBranch imports the latest commits of an upstream branch (write). For repos without an upstream it returns the branch as it is.

func (*Service) SyncGitHubAccount added in v0.2.0

func (s *Service) SyncGitHubAccount(ctx context.Context, githubAccountID int64) error

SyncGitHubAccount syncs the installations on a GitHub account that have no vx organization yet: call it when the person of a GitHub user account signs in for the first time, so their personal installation comes in.

func (*Service) SyncGitHubOrgs added in v0.2.0

func (s *Service) SyncGitHubOrgs(ctx context.Context, person store.Principal) error

SyncGitHubOrgs refreshes a person's memberships in every GitHub organization with an installation of the App, and so in the linked vx organizations, and drops their cached roles. Web sign-in calls it. It asks GitHub once per organization installation.

func (*Service) SyncInstallation added in v0.2.0

func (s *Service) SyncInstallation(ctx context.Context, installationID int64) error

SyncInstallation reads an installation's account and repositories from GitHub and creates or updates the matching vx organization and repos.

func (*Service) Token added in v0.2.0

func (s *Service) Token(ctx context.Context, actor Actor, id string) (store.Token, store.Principal, error)

Token returns a token the caller may manage, by id or unique prefix, with its owner. It changes nothing; use it to show what RevokeToken would do.

func (*Service) TokenCreateTarget added in v0.2.0

func (s *Service) TokenCreateTarget(ctx context.Context, actor Actor, agent string) (store.Principal, error)

TokenCreateTarget returns who CreateToken would create a token for, or why the caller may not. It changes nothing.

func (*Service) UpdateOrg added in v0.2.0

func (s *Service) UpdateOrg(ctx context.Context, actor Actor, handle, displayName string, defaultRole *RepoRole) (Org, error)

UpdateOrg changes an organization's display name or default repository role (owners and admins). Empty values are unchanged.

func (*Service) UpdateTask added in v0.2.0

func (s *Service) UpdateTask(ctx context.Context, actor Actor, in UpdateTaskInput) (Task, []Task, error)

UpdateTask applies an action to a task and returns it, plus the tasks a done unblocked.

func (*Service) WaitForecasts added in v0.3.0

func (s *Service) WaitForecasts()

WaitForecasts blocks until the background forecasts queued so far have finished. Servers call it on shutdown; tests call it before looking.

func (*Service) WithdrawGitHubInvite added in v0.2.0

func (s *Service) WithdrawGitHubInvite(ctx context.Context, actor Actor, login string) error

WithdrawGitHubInvite deletes an open invite (site admins).

type SetRepoHostInput added in v0.4.0

type SetRepoHostInput struct {
	Repo string
	// Token replaces the repository's token; "" removes it (the server's
	// token for the host applies again). nil: unchanged.
	Token *string
	// RotateWebhookSecret makes a new webhook secret and returns it once.
	RotateWebhookSecret bool
}

SetRepoHostInput changes how vx reaches a repository's host.

type ShipGroup added in v0.4.0

type ShipGroup struct {
	Part   int    // 1-based
	Name   string // from the intents, e.g. "add-limiter-middleware"
	Title  string // pull request title
	Branch string // vx/<effort>/<n>-<name>
	Base   string // the target branch, or the previous part's branch (stacked)
	Steps  []ShipStep
	Files  []string // paths the part changes on its base
	// Why says why changes share this part: a common file, depends_on.
	Why          []string
	Tree         hash.Hash // tree after the part, on top of its base
	Conflicts    []engine.Conflict
	ConflictedAt *store.ChangesetRow
	// Problem says why the part cannot ship as grouped; empty: it can.
	Problem  string
	Warnings []engine.Warning
	Body     string
	// Previous is the shipment this part updates, when shipped before.
	Previous *store.Shipment
}

ShipGroup is one part of a split: one branch and one pull request.

func (ShipGroup) Commits added in v0.4.0

func (g ShipGroup) Commits() []ShipStep

Commits returns the steps of the part that produce a commit.

func (ShipGroup) PRRef added in v0.4.0

func (g ShipGroup) PRRef() string

PRRef names the part's pull request for the other parts' bodies: "#41" once it has a number, else its branch.

type ShipInput

type ShipInput struct {
	Repo, Effort, Target string
	Title, Body          string // empty: generated
	Draft                bool
	// Split ships one pull request per part (PlanSplit); Groups is a
	// person's grouping, empty for vx's.
	Split  SplitMode
	Groups [][]string
}

ShipInput controls OpenShipment.

type ShipPart added in v0.4.0

type ShipPart struct {
	Group    ShipGroup
	Shipment store.Shipment
	PR       provider.OpenedPR
}

ShipPart is one pushed part of a split.

type ShipPlan

type ShipPlan struct {
	Repo         store.Repo
	Effort       store.Effort
	Target       string
	TargetHead   store.ChangesetRow
	Branch       string
	Title        string
	Body         string
	Steps        []ShipStep
	Conflicts    []engine.Conflict
	ConflictedAt *store.ChangesetRow
	// Warnings are problems found in the tree that would ship, checked over
	// every path the effort changes on the target. They do not stop a ship.
	Warnings []engine.Warning

	// A split (PlanSplit) ships Groups, one pull request each.
	Split  SplitMode
	Groups []ShipGroup
	// Suggested: vx chose the grouping (not a person).
	Suggested bool
	// Problems say why the split cannot ship as grouped.
	Problems []string
	// Notes are things to know that do not stop the split.
	Notes []string
	// Stale are open parts of an earlier split that this one no longer
	// has: shipping stops updating them.
	Stale []store.Shipment
}

ShipPlan is what shipping an effort would produce.

func (ShipPlan) Commits

func (p ShipPlan) Commits() []ShipStep

Commits returns the steps that produce a commit.

type ShipResult

type ShipResult struct {
	Plan     ShipPlan
	Shipment store.Shipment // the first part of a split
	PR       provider.OpenedPR
	Parts    []ShipPart // a split's parts, in order
}

ShipResult is a pushed branch and, where the provider has them, its PR.

type ShipStep

type ShipStep struct {
	Changeset store.ChangesetRow
	Tree      hash.Hash // tree after this step, on top of the target
	Files     int       // files this step changes on the target
	Skipped   bool      // the target already has this change
}

ShipStep is one landed change replayed onto the target.

type ShipmentCIView added in v0.4.0

type ShipmentCIView struct {
	State   string // "", pending, passed, failed
	HeadSHA string
	Checks  []store.ShipmentCheck
	Failed  []store.ShipmentCheck
}

ShipmentCIView is what vx ship list, vx status and the web ship page show about a shipment's CI.

func (ShipmentCIView) Line added in v0.4.0

func (v ShipmentCIView) Line() string

Line is "CI: passed", "CI: failed (go test, https://...)" or "".

type Shipper

type Shipper interface {
	ExportBranch(ctx context.Context, repo store.Repo, baseSHA, branch string, commits []provider.Commit) ([]string, error)
	OpenPullRequest(ctx context.Context, repo store.Repo, pr provider.PullRequest) (provider.OpenedPR, error)
}

Shipper pushes branches and opens pull requests on the git host.

type SignupMode added in v0.2.0

type SignupMode string

SignupMode says who may create an account by signing in with GitHub.

const (
	SignupInvite SignupMode = "invite" // only invited GitHub logins (the default)
	SignupOpen   SignupMode = "open"   // anyone with a GitHub account
	SignupClosed SignupMode = "closed" // nobody new; existing people still sign in
)

func ParseSignupMode added in v0.2.0

func ParseSignupMode(v string) (SignupMode, error)

ParseSignupMode reads a signup mode from configuration (VX_SIGNUP).

type SplitInput added in v0.4.0

type SplitInput struct {
	Repo, Effort, Target string
	Mode                 SplitMode
	// Groups is a person's grouping: change ids (or unique prefixes) per
	// part, in order. Empty: vx suggests the grouping, keeping the parts
	// shipped before.
	Groups [][]string
}

SplitInput controls PlanSplit.

type SplitMode added in v0.4.0

type SplitMode string

SplitMode says how an effort ships as several pull requests.

const (
	// SplitNone ships the effort as one pull request.
	SplitNone SplitMode = ""
	// SplitIndependent ships parts that merge in any order: changes that
	// touch a common file, or where one depends on another, stay in one
	// part, and every part replays onto the target on its own.
	SplitIndependent SplitMode = "independent"
	// SplitStacked ships an ordered list of parts, each based on the
	// previous part's branch.
	SplitStacked SplitMode = "stacked"
)

func ParseSplitMode added in v0.4.0

func ParseSplitMode(s string) (SplitMode, error)

ParseSplitMode reads "independent", "stacked" or "" (one pull request).

type Task added in v0.2.0

type Task struct {
	ID            uuid.UUID
	RepoName      string
	EffortSlug    string
	EffortID      uuid.UUID
	Title, Body   string
	State         string
	Owner         *store.Principal
	DependsOn     []uuid.UUID
	Blocked       bool // computed: some DependsOn task is not done
	CreatedBy     store.Principal
	CreatedParent *store.Principal // the person an agent creator acts for
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

Task is one item of an effort's shared plan.

type Team added in v0.2.0

type Team struct {
	ID      uuid.UUID
	OrgID   uuid.UUID
	Org     string
	Name    string
	Members []store.Principal
}

Team is a named group of an organization's members.

type UniqueRule added in v0.3.0

type UniqueRule = rules.Unique

UniqueRule says that files matching Glob may not share the first group of Key (for example two migrations with the same number).

type UpdateTaskInput added in v0.2.0

type UpdateTaskInput struct {
	ID     string
	Action string
	Owner  string
	Force  bool
}

UpdateTaskInput changes a task: Action is take, release, done, reopen or assign (with Owner).

type UpstreamSyncer

type UpstreamSyncer interface {
	// DefaultBranch asks the provider for the repo's default branch.
	DefaultBranch(ctx context.Context, repo store.Repo) (string, error)
	// SyncBranch imports new commits on branch and records its head.
	SyncBranch(ctx context.Context, repo store.Repo, branch string) (store.Branch, int, error)
}

UpstreamSyncer imports branches from a repo's git provider.

type WorkspaceView

type WorkspaceView struct {
	Repo      store.Repo
	Effort    store.Effort
	Workspace store.Workspace
}

WorkspaceView is a workspace with its effort and repo.

Jump to

Keyboard shortcuts

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