models

package
v1.0.0-rc1 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	AgentSessionStatusIdle       = "idle"
	AgentSessionStatusStreaming  = "streaming"
	AgentSessionStatusFailed     = "failed"
	AgentSessionStatusTerminated = "terminated"
)
View Source
const (
	AgentMessageRoleUser      = "user"
	AgentMessageRoleAssistant = "assistant"
	AgentMessageRoleTool      = "tool"
	AgentMessageRoleSystem    = "system"

	AgentToolStatusStarted  = "started"
	AgentToolStatusFinished = "finished"
	AgentToolStatusFailed   = "failed"
)
View Source
const (
	CanvasColumnKeyBacklog = "backlog"
	CanvasColumnKeyVerify  = "verify"
	CanvasColumnKeyDone    = "done"
)
View Source
const (
	CanvasEventStatePending = "pending"
	CanvasEventStateRouted  = "routed"
)
View Source
const (
	CanvasMemorySourceNode   = "node"
	CanvasMemorySourceManual = "manual"
)
View Source
const (
	CanvasNodeStateReady = "ready"
	CanvasNodeStateError = "error"

	NodeTypeTrigger   = "trigger"
	NodeTypeComponent = "component"
	NodeTypeWidget    = "widget"
)

Node states. The state column no longer acts as a dispatch mutex: scheduling is derived from execution counts per queue. The error state keeps its meaning (broken configuration blocks dispatch).

View Source
const (
	CanvasNodeExecutionStatePending    = "pending"
	CanvasNodeExecutionStateStarted    = "started"
	CanvasNodeExecutionStateCancelling = "cancelling"
	CanvasNodeExecutionStateFinished   = "finished"

	CanvasNodeExecutionResultPassed    = "passed"
	CanvasNodeExecutionResultFailed    = "failed"
	CanvasNodeExecutionResultCancelled = "cancelled"

	CanvasNodeExecutionResultReasonOk            = "ok"
	CanvasNodeExecutionResultReasonError         = "error"
	CanvasNodeExecutionResultReasonErrorResolved = "error_resolved"

	// CanvasNodeExecutionFrozenComponentKey stores the component an execution
	// started with when a later model-source switch replaces the runtime node.
	CanvasNodeExecutionFrozenComponentKey = "frozenComponent"
)
View Source
const (
	NodeRequestTypePullRequestChecksStart = "pull-request-checks-start"
	NodeRequestTypeInvokeAction           = "invoke-action"
	NodeRequestTypeVisualEvidenceCapture  = "visual-evidence-capture"

	NodeExecutionRequestStatePending   = "pending"
	NodeExecutionRequestStateCompleted = "completed"
)
View Source
const (
	CanvasRunStatePending    = "pending"
	CanvasRunStateStarted    = "started"
	CanvasRunStateCancelling = "cancelling"
	CanvasRunStateFinished   = "finished"

	CanvasRunResultPassed    = core.RunResultPassed
	CanvasRunResultFailed    = core.RunResultFailed
	CanvasRunResultCancelled = core.RunResultCancelled
)
View Source
const (
	ProviderGitHub    = "github"
	ProviderBitbucket = "bitbucket"
	ProviderGoogle    = "google"
	ProviderPassword  = "password"

	DomainTypeOrganization = "org"

	DisplayNameOwner      = "Owner"
	DisplayNameAdmin      = "Admin"
	DisplayNameMaintainer = "Maintainer"
	DisplayNameOperator   = "Operator"

	RoleOrgAdmin      = "org_admin"
	RoleOrgMaintainer = "org_maintainer"
	RoleOrgOperator   = "org_operator"

	// Role descriptions
	DescOrgAdmin      = "Manage members, billing, and organization settings"
	DescOrgMaintainer = "Create and edit automations, integrations, and models"
	DescOrgOperator   = "Create tasks and interact with them"

	// Metadata descriptions
	MetaDescOrgAdmin      = "Can manage members, billing, and organization settings."
	MetaDescOrgMaintainer = "Can create and edit automations, set integrations, and change models."
	MetaDescOrgOperator   = "Can create tasks and interact with them."

	// User types
	UserTypeHuman  = "human"
	UserTypeAPIKey = "api_key"
)
View Source
const (
	DatadogWebhookOutcomeAccepted       = "accepted"
	DatadogWebhookOutcomeNoSubscription = "no_subscription"
	DatadogWebhookOutcomeIgnored        = "ignored"
	DatadogWebhookOutcomeRejected       = "rejected"
	DatadogWebhookOutcomeFailed         = "failed"
	DatadogWebhookOutcomePending        = "pending"

	// DatadogWebhookReceiptRetention is how long Installation Admin keeps a receipt.
	DatadogWebhookReceiptRetention = 14 * 24 * time.Hour
)
View Source
const (
	FactoryKeyMinLength = 2
	FactoryKeyMaxLength = 5
	FactoryURLIDLength  = 8

	DefaultFactoryWorkOrderListLimit = 100
)
View Source
const (
	FactoryAgentResourceKindMCPServer   = "mcp_server"
	FactoryAgentResourceKindSkill       = "skill"
	FactoryAgentResourceKindSetup       = "setup_command"
	FactoryAgentResourceKindContextRepo = "context_repo"

	FactoryAgentResourceSetupName = "setup"

	FactoryAgentResourceAuthHeaders = "headers"
	FactoryAgentResourceAuthOAuth   = "oauth"

	FactoryAgentResourceSourceInline = "inline"

	FactoryAgentResourceOAuthNotConnected   = "not_connected"
	FactoryAgentResourceOAuthConnected      = "connected"
	FactoryAgentResourceOAuthNeedsReconnect = "needs_reconnect"
	FactoryAgentResourceOAuthVendorRejected = "vendor_rejected"

	FactoryAgentResourceSecretRefreshToken = "refresh_token"
	FactoryAgentResourceSecretAccessToken  = "access_token"
	FactoryAgentResourceSecretClientSecret = "client_secret"
	FactoryAgentResourceSecretCodeVerifier = "code_verifier"

	ReservedFactoryAgentResourceName = "superplane"

	MaxEnabledFactoryMCPServers = 20

	MaxFactoryAgentSkillMarkdownBytes = 64 * 1024

	MaxFactorySetupCommands         = 100
	MaxFactorySetupCommandBytes     = 32 * 1024
	MaxFactorySetupCommandLineBytes = 2000
	MaxEnabledFactoryContextRepos   = 20
)
View Source
const (
	FactoryAppTemplateMetadataKey      = "factoryTemplate"
	FactoryAppTemplateBacklogID        = "backlog"
	FactoryAppTemplateVisualEvidenceID = "visual-evidence"
	FactoryAppBacklogTriggerID         = "trigger"
)
View Source
const (
	FactoryIntakeSourceGitHubIssues       = "github-issues"
	FactoryIntakeSourceSentryExceptions   = "sentry-exceptions"
	FactoryIntakeSourcePagerDutyIncidents = "pagerduty-incidents"
	FactoryIntakeSourceProductiveTasks    = "productive-tasks"
	FactoryIntakeSourceJiraIssues         = "jira-issues"
	FactoryIntakeSourceDependabotAlerts   = "dependabot-alerts"
	FactoryIntakeSourceDatadog            = "datadog"
	FactoryIntakeSourceLinearIssues       = "linear-issues"

	FactoryIntakeInitialImportStatusUnspecified = "unspecified"
	FactoryIntakeInitialImportStatusPending     = "pending"
	FactoryIntakeInitialImportStatusCompleted   = "completed"
	FactoryIntakeInitialImportStatusFailed      = "failed"
	FactoryIntakeInitialImportStatusSkipped     = "skipped"
)
View Source
const (
	FactoryLineStepTypeRunApp = "runApp"

	// DefaultFactoryLineStepMaxParallelism is the number of in-flight runs
	// a step allows when maxParallelism is not set.
	DefaultFactoryLineStepMaxParallelism = 10
)
View Source
const (
	FactoryOnboardingIssuesSourceVCS    = "vcs"
	FactoryOnboardingIssuesSourceLinear = "linear"
	FactoryOnboardingIssuesSourceJira   = "jira"
	FactoryOnboardingIssuesSourceSkip   = "skip"

	FactoryOnboardingAgentHarnessClaudeCode = "claude-code"
	FactoryOnboardingAgentHarnessCursor     = "cursor"
	FactoryOnboardingAgentHarnessCodex      = "codex"
	FactoryOnboardingAgentHarnessSuperPlane = "superplane"
)
View Source
const (
	PlanningSessionStateRunning = "running"
	PlanningSessionStateEnded   = "ended"

	PlanningSessionKindTaskCreation      = "task_creation"
	PlanningSessionKindWorkOrderAnalysis = "work_order_analysis"

	PlanningSessionMessageRoleUser  = "user"
	PlanningSessionMessageRoleAgent = "agent"
	PlanningSessionMessageRolePlan  = "plan"

	PlanningWaitIdle     = ""
	PlanningWaitPending  = "pending"
	PlanningWaitResolved = "resolved"

	PlanningWaitKindMessage = "message"
	PlanningWaitKindCreated = "created"
	PlanningWaitKindSkipped = "skipped"
	PlanningWaitKindEnded   = "ended"

	PlanningSessionHeartbeatStale = 5 * time.Minute
)
View Source
const (
	PlanningSessionActivityStatusRunning     = "running"
	PlanningSessionActivityStatusPassed      = "passed"
	PlanningSessionActivityStatusFailed      = "failed"
	PlanningSessionActivityStatusCancelled   = "cancelled"
	PlanningSessionActivityStatusTimedOut    = "timed_out"
	PlanningSessionActivityStatusInterrupted = "interrupted"
)
View Source
const (
	PlanningSpecArtifactKey         = "spec"
	PlanningSpecArtifactTitle       = "plan.md"
	PlanningSpecArtifactCanvasRunID = "canvasRunId"

	// Clarity is how well the task is defined. Confidence is how likely a
	// coding agent completes the task in one run without steering.
	PlanningClarityCheckKey     = "clarity"
	PlanningClarityCheckName    = "Clarity score"
	PlanningConfidenceCheckKey  = "confidence"
	PlanningConfidenceCheckName = "Confidence score"
	PlanningScoreMax            = 5
)
View Source
const (
	PlanningComplexityCheckKey     = "complexity"
	PlanningComplexityCheckName    = "Complexity"
	PlanningVerifiabilityCheckKey  = "verifiability"
	PlanningVerifiabilityCheckName = "Verifiability"

	// Review sub-parameters use a 1 through 3 scale: 3 is good, 2 is
	// partial, 1 is bad. The legacy scores keep PlanningScoreMax.
	PlanningReviewScoreMax = 3
)
View Source
const (
	FactoryPRFeedbackHandlerSubjectGitHubPullRequest    = "github-pull-request"
	FactoryPRFeedbackHandlerSourcePullRequestDiscussion = "pull-request-discussion"
	FactoryPRFeedbackHandlerSourcePullRequestChecks     = "pull-request-checks"
)
View Source
const (
	FactoryPullRequestProviderGitHub    = "github"
	FactoryPullRequestProviderBitbucket = "bitbucket"

	FactoryPullRequestStateOpen   = "open"
	FactoryPullRequestStateDraft  = "draft"
	FactoryPullRequestStateClosed = "closed"
	FactoryPullRequestStateMerged = "merged"
)
View Source
const (
	FactoryPullRequestAccessConcurrent = "concurrent"
	FactoryPullRequestAccessWaiting    = "waiting"
	FactoryPullRequestAccessExclusive  = "exclusive"
	FactoryPullRequestAccessReleased   = "released"

	FactoryPullRequestActivityStateActive       = "active"
	FactoryPullRequestActivityStateFinished     = "finished"
	FactoryPullRequestActivityStateLimitReached = "limit_reached"
)
View Source
const (
	// FactoryVelocityMergeSourcePeople is work a person wrote by hand.
	FactoryVelocityMergeSourcePeople = "people"

	// FactoryVelocityMergeSourceAgent is work the SuperPlane agent wrote. The
	// sync recognizes it by the agent co-author trailer on the merge commit,
	// which names the agent whichever instance opened the pull request.
	FactoryVelocityMergeSourceAgent = "agent"
)

Who wrote the merge. The velocity report draws one series per source.

View Source
const (
	FactoryVelocitySyncStateIdle = 0
	// Backfilling continues older history before BackfilledFrom.
	FactoryVelocitySyncStateBackfilling = -1
	// CatchUp reads newer merges after the older history is saved.
	FactoryVelocitySyncStateCatchUp = -2
	// CatchingUp continues a newer-window read before BackfilledFrom.
	FactoryVelocitySyncStateCatchingUp = -3
)
View Source
const (
	FactoryWorkOrderStateDraft  = "draft"
	FactoryWorkOrderStateOpen   = "open"
	FactoryWorkOrderStateClosed = "closed"

	FactoryWorkOrderResultCompleted      = "completed"
	FactoryWorkOrderResultRejected       = "rejected"
	FactoryWorkOrderResultFailed         = "failed"
	FactoryWorkOrderResultArchived       = "archived"
	FactoryWorkOrderResultPRClosed       = "pr_closed"
	FactoryWorkOrderResultManualRejected = "manual_rejected"

	DefaultMCPClientName = "MCP client"
)
View Source
const (
	FactoryWorkOrderArtifactTypeMarkdown = factory.ArtifactTypeMarkdown
	FactoryWorkOrderArtifactTypeBranch   = factory.ArtifactTypeBranch
	FactoryWorkOrderArtifactTypeLink     = factory.ArtifactTypeLink
	FactoryWorkOrderArtifactTypeFile     = factory.ArtifactTypeFile

	// MaxFactoryWorkOrderArtifactDataBytes caps JSON-encoded artifact data.
	MaxFactoryWorkOrderArtifactDataBytes = 64 * 1024

	// MaxFactoryWorkOrderArtifactKeyBytes matches the `key` column width.
	MaxFactoryWorkOrderArtifactKeyBytes = 512
)
View Source
const (
	FactoryWorkOrderCheckLevelPositive = factory.CheckLevelPositive
	FactoryWorkOrderCheckLevelNeutral  = factory.CheckLevelNeutral
	FactoryWorkOrderCheckLevelCaution  = factory.CheckLevelCaution
	FactoryWorkOrderCheckLevelCritical = factory.CheckLevelCritical

	FactoryWorkOrderCheckFormatFraction = factory.CheckFormatFraction
	FactoryWorkOrderCheckFormatPercent  = factory.CheckFormatPercent
	FactoryWorkOrderCheckFormatBoolean  = factory.CheckFormatBoolean

	// MaxFactoryWorkOrderCheckKeyBytes and name match the column widths.
	MaxFactoryWorkOrderCheckKeyBytes  = 255
	MaxFactoryWorkOrderCheckNameBytes = 255

	// MaxFactoryWorkOrderCheckAnalysisBytes caps the markdown analysis,
	// mirroring the artifact data cap.
	MaxFactoryWorkOrderCheckAnalysisBytes = 64 * 1024

	// MaxFactoryWorkOrderCheckRecentScores caps the per-check score
	// history kept on the row; older entries fall off the front. Full
	// history stays in `order.check.reported` timeline events.
	MaxFactoryWorkOrderCheckRecentScores = 10
)
View Source
const (
	FactoryWorkOrderExecutionStatusPending  = "pending"
	FactoryWorkOrderExecutionStatusRunning  = "running"
	FactoryWorkOrderExecutionStatusFinished = "finished"
)
View Source
const (
	WorkOrderExecutionFailureReasonNoHostedCredit             = "no_hosted_credit"
	WorkOrderExecutionFailureReasonHostedSubscriptionRequired = "hosted_subscription_required"
	WorkOrderExecutionFailureReasonWorkspaceBudgetEmpty       = "workspace_budget_empty"
)

Failure reasons stored on a factory step. The UI maps each code to copy and a billing action.

View Source
const (
	FactoryWorkOrderLineDispatchStateActive   = "active"
	FactoryWorkOrderLineDispatchStateFinished = "finished"
)
View Source
const (
	FactoryWorkOrderStatusNoteKindInfo = factory.StatusNoteKindInfo

	MaxFactoryWorkOrderStatusNoteKeyBytes      = 255
	MaxFactoryWorkOrderStatusNoteHeadlineBytes = 255

	// MaxFactoryWorkOrderStatusNoteBodyBytes caps the markdown body; a
	// note is a one-paragraph announcement, not a report.
	MaxFactoryWorkOrderStatusNoteBodyBytes = 16 * 1024

	MaxFactoryWorkOrderStatusNoteCtaLabelBytes = 255
	MaxFactoryWorkOrderStatusNoteCtaURLBytes   = 2048

	// MaxFactoryWorkOrderStatusNotes caps how many notes one order can
	// carry. Notes are latest-only per key; this is a payload-size bound.
	MaxFactoryWorkOrderStatusNotes = 20
)
View Source
const (
	FileStatePending      = "pending"
	FileStateReady        = "ready"
	FileStateFailed       = "failed"
	FilePurposeAttachment = "attachment"
	FilePurposeArtifact   = "artifact"

	MaxFileBytes             = 70 << 20
	MaxArtifactFileBytes     = 100 << 20
	MaxFilesPerWorkOrder     = 20
	MaxOrganizationFileBytes = 10 << 30
	MaxFileNameBytes         = 255
	StalePendingFileAge      = time.Hour
)
View Source
const (
	DefaultWelcomeGrantCents   int64 = 5000
	DefaultWelcomeGrantTTL           = 14 * 24 * time.Hour
	DefaultMarkupBPS                 = 1000
	DefaultWarningThresholdBPS       = 2000
	MarkupBaseBPS                    = 10000
	MicrosPerCent              int64 = 10_000
)
View Source
const (
	IntegrationStatePending = "pending"
	IntegrationStateReady   = "ready"
	IntegrationStateError   = "error"
)
View Source
const (
	IntegrationRequestTypeSync         = "sync"
	IntegrationRequestTypeInvokeAction = "invoke-action"

	IntegrationRequestStatePending   = "pending"
	IntegrationRequestStateCompleted = "completed"
)
View Source
const (
	LinearWebhookOutcomeAccepted       = "accepted"
	LinearWebhookOutcomeIgnored        = "ignored"
	LinearWebhookOutcomeNoSubscription = "no_subscription"
	LinearWebhookOutcomeRejected       = "rejected"
	LinearWebhookOutcomeFailed         = "failed"
	LinearWebhookOutcomePending        = "pending"

	// LinearWebhookReceiptRetention is how long Installation Admin keeps a receipt.
	LinearWebhookReceiptRetention = 14 * 24 * time.Hour
)
View Source
const (
	BillingPlanTrial    = "trial"
	BillingPlanBusiness = "business"
	BillingPlanNone     = "none"

	BillingPlanSourceSystem = "system"
	BillingPlanSourcePolar  = "polar"
	BillingPlanSourceAdmin  = "admin"

	PolarSubscriptionStatusActive     = "active"
	PolarSubscriptionStatusTrialing   = "trialing"
	PolarSubscriptionStatusCanceled   = "canceled"
	PolarSubscriptionStatusUnpaid     = "unpaid"
	PolarSubscriptionStatusRevoked    = "revoked"
	PolarSubscriptionStatusPastDue    = "past_due"
	PolarSubscriptionStatusIncomplete = "incomplete"

	DefaultIncludedGrantCents  int64 = 5000
	DefaultIncludedGrantMonths       = 1
	DefaultTopupGrantMonths          = 12
)
View Source
const (
	LLMCreditGrantKindWelcome     = "welcome"
	LLMCreditGrantKindAdmin       = "admin"
	LLMCreditGrantKindIncluded    = "included"
	LLMCreditGrantKindTopup       = "topup"
	LLMCreditGrantKindTopupRefund = "topup_refund"

	LLMCreditGrantKindTrialAdjustment = "trial_adjustment"
	LLMCreditGrantKindTopupAdjustment = "topup_adjustment"
	LLMCreditGrantKindAdminAdjustment = "admin_adjustment"

	CreditBalanceBucketTrial = "trial"
	CreditBalanceBucketTopup = "topup"
	CreditBalanceBucketGrant = "grant"
)
View Source
const (
	RunnerStatePending    = "pending"
	RunnerStateIdle       = "idle"
	RunnerStateBusy       = "busy"
	RunnerStateTerminated = "terminated"

	RunnerTerminationRequested           = "requested"
	RunnerTerminationInterrupted         = "interrupted"
	RunnerTerminationRegistrationExpired = "registration_timeout"
	RunnerTerminationProvisioningFailed  = "provisioning_failed"
	RunnerTerminationVersionMismatch     = "version_mismatch"
	RunnerTerminationTaskCompleted       = "task_completed"
	RunnerTerminationConnectionLost      = "connection_lost"
)
View Source
const (
	RunnerFleetScopeInstallation = "installation"
	RunnerFleetScopeOrganization = "organization"

	RunnerFleetE1LargeAMD64 = "e1-large-amd64"
	RunnerFleetE1LargeARM64 = "e1-large-arm64"
	RunnerFleetE1TinyAMD64  = "e1-tiny-amd64"
	RunnerFleetE1TinyARM64  = "e1-tiny-arm64"

	DefaultRunnerVersion = "dev"
)
View Source
const (
	RunnerTaskBackendLegacy     = "legacy"
	RunnerTaskBackendIntegrated = "integrated"

	RunnerTaskStateQueued    = "queued"
	RunnerTaskStateReserved  = "reserved"
	RunnerTaskStateRunning   = "running"
	RunnerTaskStateSucceeded = "succeeded"
	RunnerTaskStateFailed    = "failed"
	RunnerTaskStateCanceled  = "canceled"
	RunnerTaskStateLost      = "lost"

	RunnerTaskLogStateActive     = "active"
	RunnerTaskLogStateArchivable = "archivable"
	RunnerTaskLogStateArchiving  = "archiving"
	RunnerTaskLogStateArchived   = "archived"
)
View Source
const (
	SelectableLLMSourceHostedName = "SuperPlane"
	SelectableLLMSourceBYOKName   = "Your keys"
)
View Source
const (
	SentryWebhookOutcomeAccepted     = "accepted"
	SentryWebhookOutcomeNoConnection = "no_connection"
	SentryWebhookOutcomeRejected     = "rejected"
	SentryWebhookOutcomeFailed       = "failed"

	// SentryWebhookReceiptRetention is how long Installation Admin keeps a receipt.
	SentryWebhookReceiptRetention = 14 * 24 * time.Hour
)
View Source
const (
	SpendingGroupByWorkspace     = "workspace"
	SpendingGroupByUser          = "user"
	SpendingGroupByModel         = "model"
	SpendingGroupByMachine       = "machine"
	SpendingGroupByFundingSource = "funding_source"

	SpendingTimeGrainHour  = "hour"
	SpendingTimeGrainDay   = "day"
	SpendingTimeGrainMonth = "month"
)
View Source
const (
	SuperPlaneRunnerNoCreditMessage        = "This organization has no hosted credit."
	SuperPlaneRunnerSubscribeMessage       = "Subscribe to Business to keep SuperPlane-hosted runs."
	SuperPlaneRunnerNoFactoryBudgetMessage = "This workspace has no remaining hosted credit."
	SuperPlaneRunnerNoModelMessage         = "The instance has no SuperPlane agent model."
	SuperPlaneRunnerModelNotAllowedMessage = "This workspace does not allow the SuperPlane agent model."
)
View Source
const (
	UsagePriceBookMatchExact  = "exact"
	UsagePriceBookMatchPrefix = "prefix"
	UsagePriceBookMatchFamily = "family"
)
View Source
const (
	NotificationWorkspaceScopeAll      = "all"
	NotificationWorkspaceScopeFiltered = "filtered"
	NotificationWorkspaceScopeNone     = "none"

	NotificationChannelEmail   = "email"
	NotificationChannelBrowser = "browser"

	NotificationTypeWorkOrderStatusOwned     = "work_order_status_owned"
	NotificationTypeWorkOrderStatusNoteOwned = "work_order_status_note_owned"
	NotificationTypeWorkOrderAgentQuestion   = "work_order_agent_question"
	NotificationTypeWorkOrderPlanReady       = "work_order_plan_ready"

	// NotificationTypeNoneSelected is stored when an all-workspaces list has
	// no current types. Delivery ignores unknown names, so every current
	// type stays off. Serialize drops this name, so the API returns an
	// empty list rather than the empty-list default.
	NotificationTypeNoneSelected = "none"
)
View Source
const (
	WebhookStatePending      = "pending"
	WebhookStateProvisioning = "provisioning"
	WebhookStateReady        = "ready"
	WebhookStateFailed       = "failed"
)
View Source
const (
	UsageKindModel   = "model"
	UsageKindCompute = "compute"

	UsageFundingSourceBYOK   = "byok"
	UsageFundingSourceHosted = "hosted"

	UsageProviderAnthropic  = "anthropic"
	UsageProviderOpenAI     = "openai"
	UsageProviderOpenRouter = "openrouter"
	UsageProviderCustom     = "custom"
	UsageProviderPerplexity = "perplexity"
	UsageProviderRunner     = "runner"

	UsageIdempotencyKeyRunner = "runner"
)
View Source
const AccountBlockedMessage = "Your account has been blocked. Please contact support."
View Source
const CustomLLMAppName = "customLlm"

CustomLLMAppName is the integration app for an organization custom provider.

View Source
const DefaultConcurrencyMax = 1
View Source
const EmailProviderSMTP = "smtp"
View Source
const MaxRunErrorsCount = 50
View Source
const MaxUserLastLocationPathBytes = 2048

MaxUserLastLocationPathBytes bounds the stored path so a malformed or abusive client cannot grow the row without limit. Deep links in the app are short (organization slug, resource id, a few query params), so this leaves generous headroom.

View Source
const OrganizationSortRemainingCreditCents = "remaining_credit_cents"
View Source
const SuperPlaneRunnerComponent = "runnerSuperPlane"
View Source
const (
	WorkOrderCreatedRefinementEnabledDataKey = "taskRefinementEnabled"
)

Variables

View Source
var (
	ErrAccountDeleteLastInstallationAdmin = errors.New("promote another installation admin before you delete this account")
	ErrLastSignInMethod                   = errors.New("keep at least one sign-in method")
	ErrSignInMethodNotConnected           = errors.New("this sign-in method is not connected")
	ErrSignInIdentityInUse                = errors.New("this identity already belongs to another SuperPlane account")
	ErrAccountEmailNotFromSignInMethod    = errors.New("choose an email from a connected sign-in method")
	ErrAccountEmailInUse                  = errors.New("this email already belongs to another SuperPlane account")
)
View Source
var (
	// Returned when the same app entrypoint is invoked twice in one chain, e.g.
	// A/run1 -> A/run2 -> A/run1.
	ErrSubRunEntrypointCycle = errors.New("sub-run entrypoint cycle detected")

	// Returned when invoke chains cross back into an app they already visited, e.g.
	// A -> B -> C -> A.
	ErrSubRunWorkflowCycle = errors.New("sub-run workflow cycle detected")

	// Returned when the chain crosses too many app boundaries without cycling, e.g.
	// A -> B -> C -> D -> ... -> Z when Z exceeds the configured limit.
	ErrSubRunCrossWorkflowDepthExceeded = errors.New("sub-run cross-workflow depth exceeded")
)
View Source
var (
	ErrNameAlreadyUsed         = fmt.Errorf("name already used")
	ErrSlugAlreadyUsed         = fmt.Errorf("slug already used")
	ErrInvitationAlreadyExists = fmt.Errorf("invitation already exists")
)
View Source
var (
	ErrFactorySystemSkillProtected               = errors.New("system skills cannot be deleted, renamed, or disabled")
	ErrFactorySystemSkillMetadataInvalid         = errors.New("system skills require a template, a positive version, and an enabled skill")
	ErrFactoryAgentResourceNotFound              = errors.New("factory agent resource not found")
	ErrFactoryAgentResourceKindInvalid           = errors.New("factory agent resource kind is not valid")
	ErrFactoryAgentResourceNameInvalid           = errors.New("factory agent resource name is not valid")
	ErrFactoryAgentResourceNameReserved          = errors.New("factory agent resource name is reserved")
	ErrFactoryAgentResourceNameSetupReserved     = errors.New("factory agent resource name is reserved for setup commands")
	ErrFactoryAgentResourceNameTaken             = errors.New("factory agent resource name already exists")
	ErrFactoryAgentResourceAuthInvalid           = errors.New("factory agent resource auth is not valid")
	ErrFactoryAgentResourceURLRequired           = errors.New("MCP URL is required")
	ErrFactoryAgentResourceURLTaken              = errors.New("factory agent resource URL already connected")
	ErrFactoryAgentResourceHeaderInvalid         = errors.New("MCP header is not valid")
	ErrFactoryAgentResourceKindNotSupported      = errors.New("factory agent resource kind is not supported yet")
	ErrFactoryAgentResourceMCPCapReached         = errors.New("workspace already has the maximum number of enabled MCP connections")
	ErrFactoryAgentResourceSecretNotFound        = errors.New("factory agent resource secret not found")
	ErrFactoryAgentResourceMarkdownRequired      = errors.New("skill markdown is required")
	ErrFactoryAgentResourceMarkdownTooLarge      = errors.New("skill markdown is too large")
	ErrFactoryAgentResourceCommandsRequired      = errors.New("setup commands are required")
	ErrFactoryAgentResourceCommandTooLarge       = errors.New("setup commands are too large")
	ErrFactoryAgentResourceTooManyCommands       = errors.New("too many setup commands")
	ErrFactoryAgentResourceRepositoryRequired    = errors.New("repository is required")
	ErrFactoryAgentResourceRepositoryInvalid     = errors.New("repository must use the owner/name format")
	ErrFactoryAgentResourceRepositoryTaken       = errors.New("this repository is already added")
	ErrFactoryAgentResourceContextRepoCapReached = errors.New("workspace already has the maximum number of context repositories")
)
View Source
var (
	ErrFactoryIntakeNotFound       = errors.New("factory intake not found")
	ErrFactoryIntakeCanvasInUse    = errors.New("canvas already implements a factory intake")
	ErrFactoryIntakeSourceInvalid  = errors.New("factory intake source is not valid")
	ErrFactoryIntakeCanvasRequired = errors.New("factory intake canvas is required")
)
View Source
var (
	ErrFactoryLineNotFound          = errors.New("factory line not found")
	ErrFactoryLineNameAlreadyExists = errors.New("factory line name already exists")
	ErrFactoryLineHasNoSteps        = errors.New("factory line has no steps")
	ErrFactoryLineStepNotOnRun      = errors.New("factory line step entrypoint must use the onRun trigger")
	ErrFactoryLineStepOutOfRange    = errors.New("factory line step index is out of range")
)
View Source
var (
	ErrFactoryOnboardingInvalidIssuesSource      = errors.New("invalid issues source")
	ErrFactoryOnboardingInvalidAgentHarness      = errors.New("invalid agent harness")
	ErrFactoryOnboardingInvalidIntegrationID     = errors.New("invalid integration id")
	ErrFactoryOnboardingInvalidAppID             = errors.New("invalid provisioned app id")
	ErrFactoryOnboardingInvalidLineID            = errors.New("invalid provisioned line id")
	ErrFactoryOnboardingInvalidRepository        = errors.New("repository must use the owner/name format")
	ErrFactoryOnboardingInvalidVCSProvider       = errors.New("invalid version control provider")
	ErrFactoryOnboardingVCSIntegrationRequired   = errors.New("version control integration id is required")
	ErrFactoryOnboardingAgentIntegrationRequired = errors.New("agent integration id is required")
	ErrFactoryOnboardingHostedAgentUnavailable   = errors.New("hosted agent credentials are not available")
	ErrFactoryOnboardingAppRepositoryRequired    = errors.New("app repository is required")
	ErrFactoryOnboardingBacklogRepoRequired      = errors.New("backlog repository is required")
	ErrFactoryOnboardingIssuesSourceRequired     = errors.New("issues source is required")
	ErrFactoryOnboardingAgentHarnessRequired     = errors.New("agent harness is required")
	ErrFactoryOnboardingAppIDRequired            = errors.New("provisioned app id is required")
	ErrFactoryOnboardingLineIDRequired           = errors.New("provisioned line id is required")
)
View Source
var (
	ErrFactoryPlanningSessionInvalid  = errors.New("invalid planning session")
	ErrFactoryPlanningSessionNotFound = errors.New("planning session not found")
	ErrFactoryPlanningSessionEnded    = errors.New("planning session has ended")
	ErrFactoryPlanningSessionNoDraft  = errors.New("planning session has no draft")
	ErrFactoryPlanningWaitIdle        = errors.New("planning session is not waiting")
)
View Source
var (
	ErrFactoryPRFeedbackHandlerNotFound       = errors.New("factory PR feedback handler not found")
	ErrFactoryPRFeedbackHandlerCanvasInUse    = errors.New("canvas already implements a factory PR feedback handler")
	ErrFactoryPRFeedbackHandlerSubjectInvalid = errors.New("factory PR feedback handler subject is not valid")
	ErrFactoryPRFeedbackHandlerSourceInvalid  = errors.New("factory PR feedback handler source is not valid")
	ErrFactoryPRFeedbackHandlerCanvasRequired = errors.New("factory PR feedback handler canvas is required")
)
View Source
var (
	ErrFactoryPullRequestNotFound             = errors.New("factory pull request not found")
	ErrFactoryPullRequestInvalid              = errors.New("invalid factory pull request")
	ErrFactoryPullRequestAlreadyExists        = errors.New("factory pull request already exists")
	ErrFactoryPullRequestRunAlreadyLinked     = errors.New("run is already linked to a different pull request")
	ErrFactoryPullRequestLookupIncomplete     = errors.New("pull request lookup is incomplete")
	ErrFactoryPullRequestActivityNotFound     = errors.New("factory pull request activity not found")
	ErrFactoryPullRequestActivityDuplicate    = errors.New("factory pull request activity already exists for this handler and revision")
	ErrFactoryPullRequestActivityLimitReached = errors.New("factory pull request activity reached the attempt limit")
)
View Source
var (
	ErrFactoryWorkOrderNotFound     = errors.New("factory work order not found")
	ErrFactoryWorkOrderInvalidState = errors.New("invalid work order state transition")
)
View Source
var (
	ErrFactoryWorkOrderArtifactNotFound         = errors.New("factory work order artifact not found")
	ErrFactoryWorkOrderArtifactInvalid          = errors.New("invalid work order artifact")
	ErrFactoryWorkOrderArtifactKeyAlreadyExists = errors.New("factory work order artifact key already exists")
)
View Source
var (
	ErrFactoryWorkOrderExecutionNotFound = errors.New("factory work order execution not found")
	ErrFactoryWorkOrderNotDispatchable   = errors.New("work order cannot be dispatched in its current state")
)
View Source
var (
	ErrFactoryWorkOrderLineDispatchNotFound = errors.New("factory work order line dispatch not found")

	// ErrFactoryWorkOrderLineDispatchActive replaces
	// ErrFactoryWorkOrderExecutionActive as the sentinel returned by the
	// dispatch guard and the open -> draft revert guard.
	ErrFactoryWorkOrderLineDispatchActive = errors.New("work order already has an active line dispatch")
)
View Source
var (
	ErrFileNotFound         = errors.New("file not found")
	ErrFileInvalid          = errors.New("invalid file")
	ErrFileNotReady         = errors.New("file is not ready")
	ErrFileQuotaExceeded    = errors.New("file quota exceeded")
	ErrFileContentType      = errors.New("file content type is not allowed")
	ErrFileForeignReference = errors.New("file does not belong to this workspace")
)
View Source
var (
	ErrHostedLLMProviderNotFound        = errors.New("hosted llm provider is not configured")
	ErrHostedLLMProviderDisabled        = errors.New("hosted llm provider is disabled")
	ErrHostedLLMProviderNoKey           = errors.New("hosted llm provider has no API key")
	ErrHostedLLMProviderNoManagementKey = errors.New("hosted llm provider has no provisioning API key")
)
View Source
var (
	ErrMCPOAuthClientNotFound  = errors.New("mcp oauth client not found")
	ErrMCPOAuthCodeNotFound    = errors.New("mcp oauth code not found")
	ErrMCPOAuthRefreshNotFound = errors.New("mcp oauth refresh token not found")
)
View Source
var (
	ErrHostedSubscriptionRequired = errors.New("a Business subscription is required for SuperPlane-hosted runs")
	ErrInvalidBillingPlan         = errors.New("billing plan is invalid")
	ErrPolarManagedBillingPlan    = errors.New("this organization uses Polar for billing. Cancel or change the subscription in Polar")
)
View Source
var (
	ErrHostedCreditEmpty        = errors.New("hosted credit is empty")
	ErrCreditGrantNotPositive   = errors.New("credit grant must be greater than zero")
	ErrCreditBalanceBucket      = errors.New("credit type must be trial, topup, or grant")
	ErrCreditBalanceNegative    = errors.New("credit balance cannot be negative")
	ErrCreditBalanceChanged     = errors.New("the credit balance changed; reload and try again")
	ErrTrialCreditNotActive     = errors.New("this organization has no active trial credit")
	ErrFactoryHostedBudgetEmpty = errors.New("this workspace has no remaining hosted credit")
	ErrPolarOrderIDRequired     = errors.New("polar order id is required")
	ErrPolarRefundIDRequired    = errors.New("polar refund id is required")
)
View Source
var (
	ErrRunnerNotFound            = errors.New("runner not found")
	ErrRunnerBusy                = errors.New("busy runner cannot be terminated")
	ErrRunnerIdempotencyConflict = errors.New("idempotency key was used with a different request")
	ErrRunnerRegistrationInvalid = errors.New("runner registration is invalid")
	ErrRunnerVersionMismatch     = errors.New("runner version does not match")
	ErrRunnerCredentialNotFound  = errors.New("runner credential not found")
	ErrRunnerConnectionReplaced  = errors.New("runner connection was replaced")
)
View Source
var (
	ErrRunnerFleetNotFound   = errors.New("runner fleet not found")
	ErrRunnerFleetIDConflict = errors.New("runner fleet ID conflicts with an existing fleet")
)
View Source
var (
	ErrRunnerTaskNotFound           = errors.New("runner task not found")
	ErrRunnerTaskNotReservable      = errors.New("runner task is not available for reservation")
	ErrRunnerTaskFleetMismatch      = errors.New("runner task fleet does not match runner fleet")
	ErrRunnerTaskBackendMismatch    = errors.New("runner task does not use the integrated backend")
	ErrRunnerTaskAlreadyAssigned    = errors.New("runner task already has a runner")
	ErrRunnerTaskNotStartable       = errors.New("runner task is not available to start")
	ErrRunnerTaskNotCompletable     = errors.New("runner task is not available to complete")
	ErrRunnerTaskLogStoreRequired   = errors.New("runner task active log store is required")
	ErrRunnerTaskCompletionConflict = errors.New("runner task has a different terminal result")
	ErrTaskLogLifecycleNotFound     = errors.New("runner task log lifecycle not found")
	ErrTaskLogChunkSequenceConflict = errors.New("runner task log chunk sequence is not next")
	ErrTaskLogLifecycleClosed       = errors.New("runner task log lifecycle is closed")
)
View Source
var (
	ErrSelectableLLMModelIncomplete = errors.New("selectable model key is incomplete")
	ErrSelectableLLMModelNotAllowed = errors.New("this workspace does not allow the selected model")
)
View Source
var (
	ErrSuperPlaneRunnerNoCredit         = errors.New("this organization has no hosted credit")
	ErrSuperPlaneRunnerNoFactoryBudget  = errors.New("this workspace has no remaining hosted credit")
	ErrSuperPlaneRunnerNoModel          = errors.New("the instance has no SuperPlane agent model")
	ErrSuperPlaneRunnerModelNotAllowed  = errors.New("this workspace does not allow the SuperPlane agent model")
	ErrDefaultHostedModelIncomplete     = errors.New("SuperPlane agent model requires a provider and a model")
	ErrDefaultHostedModelNotOnAllowlist = errors.New("SuperPlane agent model is not on a hosted allowlist")
	ErrDefaultHostedModelMustBeReplaced = errors.New("Pick a SuperPlane agent model before you remove the current default from the allowlist")
)
View Source
var DefaultOrganizationRoles = []string{
	RoleOrgAdmin,
	RoleOrgMaintainer,
	RoleOrgOperator,
}
View Source
var ErrAPIKeyNameAlreadyExists = errors.New("API key name already exists")
View Source
var ErrAccountBlocked = errors.New(AccountBlockedMessage)
View Source
var ErrAgentSessionNotFound = errors.New("agent session not found")
View Source
var ErrCanvasNameAlreadyExists = errors.New("canvas name already exists")
View Source
var ErrFactoryHostedSpendBudgetNegative = errors.New("hosted spend limit cannot be negative")
View Source
var ErrFactoryKeyAlreadyExists = errors.New("factory key already exists in this organization")
View Source
var ErrFactoryKeyInvalid = errors.New("factory key must be 2 to 5 uppercase letters")
View Source
var ErrFactoryKeyRequired = errors.New("factory key is required")
View Source
var ErrFactoryNameAlreadyExists = errors.New("factory name already exists")
View Source
var ErrFactoryNameRequired = errors.New("factory name is required")
View Source
var ErrFactoryNotFound = errors.New("factory not found")
View Source
var ErrFactoryOnboardingNotComplete = errors.New("factory onboarding is not complete")
View Source
var ErrFactorySystemSkillRequired = errors.New("only system skills can be restored")
View Source
var ErrFactoryURLIDAlreadyExists = errors.New("factory url id already exists")
View Source
var ErrFactoryWorkOrderCheckInvalid = errors.New("invalid work order check")
View Source
var ErrFactoryWorkOrderStatusNoteInvalid = errors.New("invalid work order status note")
View Source
var ErrFactoryWorkOrderTitleRequired = errors.New("title is required")
View Source
var ErrInstallationGitHubAppExists = errors.New("installation GitHub App already exists")
View Source
var ErrLastOrganizationOwner = errors.New("cannot remove the last organization owner")
View Source
var ErrLinkedAccountInUse = errors.New("linked account belongs to another account")

ErrLinkedAccountInUse reports that the external identity is already linked to another member in a shared organization. Velocity credits one GitHub login to one member per organization.

View Source
var ErrModelNotInParentList = errors.New("model is not in the parent selected-model list")
View Source
var ErrNotificationWorkspaceScopeInvalid = errors.New("workspace scope must be all, filtered, or none")
View Source
var ErrRunErrorMessageRequired = errors.New("run error message is required")
View Source
var ErrRunErrorsTooLarge = errors.New("run errors exceed maximum size")
View Source
var ErrRunErrorsTooMany = errors.New("run errors exceed maximum count")
View Source
var ErrUsagePriceBookConflict = errors.New("current price book changed")

ErrUsagePriceBookConflict is returned when a publish uses a stale current version.

View Source
var ErrUsagePriceBookCurrent = errors.New("cannot delete the current price book")

ErrUsagePriceBookCurrent is returned when a delete targets the current version.

View Source
var ErrUsagePriceBookLast = errors.New("cannot delete the last price book")

ErrUsagePriceBookLast is returned when a delete would remove the last version.

View Source
var ErrUserLastLocationPathInvalid = errors.New("path must be a relative in-app path")
View Source
var LinkableProviders = []string{ProviderGitHub, ProviderBitbucket}

LinkableProviders lists the services a member can link and unlink. A linked account records who the member is on that service, so SuperPlane can attribute the activity it finds there. A provider that only proves identity does not belong here.

NotificationTypes lists every configurable notification type.

Functions

func AccountHasPassword

func AccountHasPassword(tx *gorm.DB, accountID uuid.UUID) (bool, error)

func AccountSignInMethodCount

func AccountSignInMethodCount(tx *gorm.DB, account *Account) (int, error)

func ActivateUsagePriceBook

func ActivateUsagePriceBook(tx *gorm.DB, version string) error

ActivateUsagePriceBook marks an existing version current. It does not touch the in-memory book, because the caller can still roll the transaction back. Call LoadCurrentPriceBook after the commit.

func AddCanvasMemory added in v0.10.0

func AddCanvasMemory(canvasID uuid.UUID, namespace string, values any) error

func AddCanvasMemoryInTransaction added in v0.10.0

func AddCanvasMemoryInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string, values any) error

func AnalysisContinuationText

func AnalysisContinuationText(tx *gorm.DB, session *FactoryPlanningSession) (string, error)

func AnnotateSuperPlaneRunnerNodes

func AnnotateSuperPlaneRunnerNodes(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID, nodes []Node) error

func AppendAgentSessionMessage added in v0.21.0

func AppendAgentSessionMessage(msg *AgentSessionMessage) error

func AppendAgentSessionMessageInTransaction added in v0.21.0

func AppendAgentSessionMessageInTransaction(tx *gorm.DB, msg *AgentSessionMessage) error

AppendAgentSessionMessageInTransaction upserts by (session_id, provider_event_id) when ProviderEventID is set, so a re-delivered provider event updates the existing row instead of duplicating it.

func AppendDatadogWebhookTask

func AppendDatadogWebhookTask(tx *gorm.DB, receiptID, taskID uuid.UUID) error

AppendDatadogWebhookTask records a SuperPlane task created from this webhook. A second append of the same task ID does not duplicate it.

func AppendLinearWebhookTask

func AppendLinearWebhookTask(tx *gorm.DB, receiptID, taskID uuid.UUID) error

AppendLinearWebhookTask records a SuperPlane task created from this webhook. A second append of the same task ID does not duplicate it.

func AppendSentryWebhookTask

func AppendSentryWebhookTask(tx *gorm.DB, receiptID, taskID uuid.UUID) error

AppendSentryWebhookTask records a SuperPlane task created from this webhook. A second append of the same task ID does not duplicate it.

func ApplyMarkupMicros

func ApplyMarkupMicros(providerMicros int64, markupBPS int) int64

ApplyMarkupMicros returns billed micros for SuperPlane-hosted credit.

func AssertDefaultHostedLLMModelAllowed

func AssertDefaultHostedLLMModelAllowed(tx *gorm.DB, defaultModel DefaultHostedLLMModel) error

func AssertFactoryHostedBudgetAvailable

func AssertFactoryHostedBudgetAvailable(tx *gorm.DB, factory *Factory) error

func AssertHostedCreditAvailable

func AssertHostedCreditAvailable(tx *gorm.DB, orgID uuid.UUID) error

func AssertHostedRunAllowed

func AssertHostedRunAllowed(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID) error

AssertHostedRunAllowed rejects a new hosted start when the organization has no open trial or active Business plan, remaining credit is empty, or the factory hosted budget is exhausted. Pass a committed connection so remaining credit includes billed spend from other runs.

func AvailableCanvasName

func AvailableCanvasName(tx *gorm.DB, organizationID uuid.UUID, factoryID *uuid.UUID, preferred string) (string, error)

AvailableCanvasName returns preferred, or preferred with the lowest " (n)" suffix that no other canvas in the same scope holds. A generated canvas has to pick a free name before insert. Pass the factory ID for a canvas the factory owns, or nil for an organization-level canvas.

func BYOKIntegrationAppName

func BYOKIntegrationAppName(provider string) (string, error)

func CanonicalContextRepo

func CanonicalContextRepo(repository string) string

func CanonicalMCPServerURL

func CanonicalMCPServerURL(raw string) string

func CanvasHasFactoryAppTemplate

func CanvasHasFactoryAppTemplate(tx *gorm.DB, canvasID uuid.UUID, templateID string) (bool, error)

func CanvasHasGitHubPullRequestEvent

func CanvasHasGitHubPullRequestEvent(
	tx *gorm.DB,
	canvasID uuid.UUID,
	nodeID, repository string,
	number int64,
) (bool, error)

func CanvasMemoryNamespaceSource added in v0.25.0

func CanvasMemoryNamespaceSource(canvasID uuid.UUID, namespace string) (string, error)

func CanvasMemoryNamespaceSourceInTransaction added in v0.25.0

func CanvasMemoryNamespaceSourceInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string) (string, error)

CanvasMemoryNamespaceSourceInTransaction returns the source associated with existing rows in a namespace, or empty string if the namespace has no rows.

func CentsToMicros

func CentsToMicros(cents int64) int64

func CheckCanvasExistence added in v0.26.0

func CheckCanvasExistence(tx *gorm.DB, orgID, id uuid.UUID) (bool, error)

func ClaudeAliasCandidateIDs

func ClaudeAliasCandidateIDs(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID) ([]string, error)

ClaudeAliasCandidateIDs lists selectable model ids that can replace an alias.

func ClearAPIKeyTokenHashesCreatedByAccount

func ClearAPIKeyTokenHashesCreatedByAccount(tx *gorm.DB, accountID uuid.UUID) error

ClearAPIKeyTokenHashesCreatedByAccount wipes token hashes on org API keys created by any human user belonging to the given account.

func ClearTokenHashesForAccountInTransaction added in v0.21.0

func ClearTokenHashesForAccountInTransaction(tx *gorm.DB, accountID uuid.UUID) error

ClearTokenHashesForAccountInTransaction wipes the API token hash on every user that belongs to the given account. Combined with bumping the account's password_changed_at, this ensures that no previously issued credential (cookie, scoped JWT, or API token) keeps working after a password change.

func CompactModelIDs

func CompactModelIDs(ids []string) []string

func CompletePendingActionRequestsInTransaction added in v0.26.0

func CompletePendingActionRequestsInTransaction(tx *gorm.DB, installationID uuid.UUID, actionName string, parameters any) error

CompletePendingActionRequestsInTransaction completes every pending invoke-action request for the installation that matches both the action name and the exact parameters. Matching on parameters keeps legitimately distinct calls (e.g. AWS provisionRule for different detail types) separate, while collapsing duplicate or self-rescheduling chains of the same action (#5386). Parameters are compared as jsonb, which is canonical and key-order-independent, against the same json.Marshal representation used when the request was created.

Matching rows are selected first (narrowed by the indexed app_installation_id/state/type columns) and then completed by primary key, so the write touches only the few matched rows rather than scanning on the jsonb predicate.

func CompletePendingExecutionActionRequests

func CompletePendingExecutionActionRequests(tx *gorm.DB, executionID uuid.UUID, actionName string, parameters map[string]any) error

func CompletePendingRequestsForExecution added in v0.29.0

func CompletePendingRequestsForExecution(tx *gorm.DB, executionID uuid.UUID) error

func CompleteVCSProviderInstallationReconciliation

func CompleteVCSProviderInstallationReconciliation(
	tx *gorm.DB,
	provider string,
	installationID int64,
	claimedAt time.Time,
) error

func CompleteVCSProviderReconciliation

func CompleteVCSProviderReconciliation(tx *gorm.DB, provider string, claimedAt time.Time) error

func CompleteVCSProviderRepositorySync

func CompleteVCSProviderRepositorySync(
	tx *gorm.DB,
	provider string,
	repositoryID int64,
	claimedAt time.Time,
) error

func ConcreteClaudeModelID

func ConcreteClaudeModelID(stored string, candidates []string) string

ConcreteClaudeModelID replaces a Claude family alias with a versioned id. A versioned id is returned unchanged. The newest candidate in that family wins. With no candidate, a fixed versioned id is used so the alias is not returned.

func CountActiveExecutionsForNode

func CountActiveExecutionsForNode(tx *gorm.DB, workflowID uuid.UUID, nodeID string) (int64, error)

CountActiveExecutionsForNode counts the node's executions occupying a concurrency slot: pending, started, or cancelling. Pending executions count because they will start, and cancelling ones because they hold resources until they terminate — the same slot semantics the queue worker uses when capacity-gating dispatch.

func CountActiveExecutionsInQueue

func CountActiveExecutionsInQueue(tx *gorm.DB, workflowID uuid.UUID, nodeID, queueName string) (int64, error)

CountActiveExecutionsInQueue counts the executions occupying slots in a node's queue. Queues are private to a node, so capacity is scoped by (workflow, node, resolved queue name).

func CountActiveHumanUsersByOrganization added in v0.13.0

func CountActiveHumanUsersByOrganization(orgID string) (int64, error)

func CountActiveHumanUsersByOrganizationInTransaction added in v0.13.0

func CountActiveHumanUsersByOrganizationInTransaction(tx *gorm.DB, orgID string) (int64, error)

func CountActiveInstallationAdmins

func CountActiveInstallationAdmins(tx *gorm.DB) (int64, error)

func CountActiveNodeExecutionsForRootEventInTransaction added in v0.13.0

func CountActiveNodeExecutionsForRootEventInTransaction(tx *gorm.DB, rootEventID uuid.UUID) (int64, error)

func CountActiveUsersByOrganizationIDs added in v0.0.18

func CountActiveUsersByOrganizationIDs(orgIDs []string) (map[string]int64, error)

func CountAgentSessionMessagesInTransaction added in v0.21.0

func CountAgentSessionMessagesInTransaction(tx *gorm.DB, sessionID uuid.UUID) (int64, error)

func CountCanvasEvents added in v0.6.0

func CountCanvasEvents(db *gorm.DB, canvasID uuid.UUID, nodeID string) (int64, error)

func CountCanvasRuns added in v0.21.0

func CountCanvasRuns(workflowID uuid.UUID, filters CanvasRunFilters) (int64, error)

func CountCanvasRunsInTransaction added in v0.26.0

func CountCanvasRunsInTransaction(tx *gorm.DB, workflowID uuid.UUID, filters CanvasRunFilters) (int64, error)

func CountCanvasVersionsInTransaction added in v0.28.0

func CountCanvasVersionsInTransaction(tx *gorm.DB, workflowID uuid.UUID) (int64, error)

func CountCanvasesByOrganization added in v0.13.0

func CountCanvasesByOrganization(orgID string) (int64, error)

func CountCanvasesByOrganizationIDs added in v0.6.0

func CountCanvasesByOrganizationIDs(orgIDs []string) (map[string]int64, error)

func CountCanvasesByOrganizationInTransaction added in v0.13.0

func CountCanvasesByOrganizationInTransaction(tx *gorm.DB, orgID string) (int64, error)

func CountFactoriesByIDs

func CountFactoriesByIDs(tx *gorm.DB, organizationID uuid.UUID, ids []uuid.UUID) (int64, error)

CountFactoriesByIDs counts the active factories in the organization matching the given IDs. Callers use it to verify a caller-provided workspace list before persisting references to it.

func CountFactoriesByOrganization

func CountFactoriesByOrganization(tx *gorm.DB, organizationID uuid.UUID) (int64, error)

func CountFactoriesUsingVCSIntegration

func CountFactoriesUsingVCSIntegration(tx *gorm.DB, organizationID, integrationID uuid.UUID) (int64, error)

CountFactoriesUsingVCSIntegration counts workspaces in the organization that still store this integration as their version-control connection.

func CountIntegrationsByOrganization added in v0.13.0

func CountIntegrationsByOrganization(orgID string) (int64, error)

func CountIntegrationsByOrganizationInTransaction added in v0.13.0

func CountIntegrationsByOrganizationInTransaction(tx *gorm.DB, orgID string) (int64, error)

func CountNodeExecutions

func CountNodeExecutions(db *gorm.DB, workflowID uuid.UUID, nodeID string, states []string, results []string) (int64, error)

func CountNodeQueueItems

func CountNodeQueueItems(db *gorm.DB, workflowID uuid.UUID, nodeID string) (int64, error)

func CountNodeQueueItemsForRootEventInTransaction added in v0.13.0

func CountNodeQueueItemsForRootEventInTransaction(tx *gorm.DB, rootEventID uuid.UUID) (int64, error)

func CountOpenTaskFiles

func CountOpenTaskFiles(tx *gorm.DB, workOrderID uuid.UUID) (int64, error)

func CountOrganizationsByBillingAccount added in v0.13.0

func CountOrganizationsByBillingAccount(tx *gorm.DB, accountID string) (int64, error)

func CountPendingRequestsForExecutionsInTransaction added in v0.13.0

func CountPendingRequestsForExecutionsInTransaction(tx *gorm.DB, executionIDs []uuid.UUID) (int64, error)

func CountReadyTaskFiles

func CountReadyTaskFiles(tx *gorm.DB, workOrderID uuid.UUID) (int64, error)

func CountRecentMagicCodes added in v0.14.0

func CountRecentMagicCodes(email string, since time.Time) (int64, error)

func CountRecentMagicCodesInTransaction added in v0.14.0

func CountRecentMagicCodesInTransaction(tx *gorm.DB, email string, since time.Time) (int64, error)

func CountUnhealthyBitbucketForgeInstallations

func CountUnhealthyBitbucketForgeInstallations(tx *gorm.DB, now, deliveryCutoff time.Time) (int64, error)

CountUnhealthyBitbucketForgeInstallations monitors delivery health without deleting installation records or invalidating otherwise usable tokens.

func CountUserAPITokens

func CountUserAPITokens(tx *gorm.DB, userID uuid.UUID) (int64, error)

func CreateAgentSessionInTransaction added in v0.21.0

func CreateAgentSessionInTransaction(tx *gorm.DB, session *AgentSession) error

func CreateAppMessage added in v0.29.0

func CreateAppMessage(tx *gorm.DB, canvasID uuid.UUID, nodeID string, payload any) error

func CreateDatadogWebhookReceipt

func CreateDatadogWebhookReceipt(tx *gorm.DB, receipt DatadogWebhookReceipt) (uuid.UUID, error)

func CreateLinearWebhookReceipt

func CreateLinearWebhookReceipt(tx *gorm.DB, receipt LinearWebhookReceipt) (uuid.UUID, error)

func CreateMCPOAuthCode

func CreateMCPOAuthCode(tx *gorm.DB, code *MCPOAuthCode) error

func CreateMCPOAuthRefreshToken

func CreateMCPOAuthRefreshToken(tx *gorm.DB, token *MCPOAuthRefreshToken) error

func CreateNodeExecutionKVInTransaction added in v0.6.0

func CreateNodeExecutionKVInTransaction(tx *gorm.DB, workflowID uuid.UUID, nodeID string, executionID uuid.UUID, key, value string) error

func CreateOrganizationBYOKModelAllowlistIfAbsent

func CreateOrganizationBYOKModelAllowlistIfAbsent(
	tx *gorm.DB,
	orgID uuid.UUID,
	provider string,
	models datatypes.JSONSlice[string],
) error

CreateOrganizationBYOKModelAllowlistIfAbsent inserts the allowlist only when the organization has not saved one yet. An existing row, including an empty list, stays unchanged.

func CreateRejectedDatadogWebhookReceiptIfAllowed

func CreateRejectedDatadogWebhookReceiptIfAllowed(
	tx *gorm.DB,
	receipt DatadogWebhookReceipt,
	since time.Time,
	limit int,
) (uuid.UUID, bool, time.Time, error)

CreateRejectedDatadogWebhookReceiptIfAllowed stores one rejected receipt when this integration is under the limit. A caller that is already at the limit stores nothing. oldest is the earliest rejected receipt in the window when the limit is already met, so the caller can skip later calls until it expires. The limit is counted before any lock. The lock is taken only when a receipt may still be stored.

func CreateSentryWebhookReceipt

func CreateSentryWebhookReceipt(tx *gorm.DB, receipt SentryWebhookReceipt) (uuid.UUID, error)

func CreateUserAPIToken

func CreateUserAPIToken(tx *gorm.DB, token *UserAPIToken) error

func CreditGrantActorNames

func CreditGrantActorNames(tx *gorm.DB, grants []OrganizationLLMCreditGrant) (map[uuid.UUID]string, error)

func DelayVCSProviderRepositorySync

func DelayVCSProviderRepositorySync(
	tx *gorm.DB,
	provider string,
	repositoryID int64,
	runAt time.Time,
	priority VCSProviderRepositorySyncPriority,
) error

func DeleteAccountLinkedAccount

func DeleteAccountLinkedAccount(tx *gorm.DB, accountID uuid.UUID, provider, providerID string) error

func DeleteAgentSessionForUserCanvas added in v0.28.0

func DeleteAgentSessionForUserCanvas(tx *gorm.DB, organizationID, userID, canvasID uuid.UUID) error

DeleteAgentSessionForUserCanvas takes an explicit *gorm.DB per the transaction guidelines (no InTransaction suffix / conn wrapper); pass a tx or database.DB(ctx).

func DeleteAgentSessionsForCanvasInTransaction added in v0.21.0

func DeleteAgentSessionsForCanvasInTransaction(tx *gorm.DB, organizationID, canvasID uuid.UUID) error

func DeleteAgentSessionsForOrganizationInTransaction added in v0.21.0

func DeleteAgentSessionsForOrganizationInTransaction(tx *gorm.DB, organizationID uuid.UUID) error

func DeleteCanvasMemory added in v0.10.0

func DeleteCanvasMemory(canvasID, memoryID uuid.UUID) error

func DeleteCanvasMemoryInTransaction added in v0.10.0

func DeleteCanvasMemoryInTransaction(tx *gorm.DB, canvasID, memoryID uuid.UUID) error

func DeleteCanvasNode added in v0.6.0

func DeleteCanvasNode(tx *gorm.DB, node CanvasNode) error

func DeleteCanvasSubscriptionsForNode added in v0.29.0

func DeleteCanvasSubscriptionsForNode(tx *gorm.DB, workflowID uuid.UUID, nodeID string) error

func DeleteEmailSettings added in v0.15.0

func DeleteEmailSettings(provider string) error

func DeleteEmailSettingsInTransaction added in v0.15.0

func DeleteEmailSettingsInTransaction(tx *gorm.DB, provider string) error

func DeleteExpiredCompletedNodeRequests added in v0.30.0

func DeleteExpiredCompletedNodeRequests(db *gorm.DB, olderThan time.Time, limit int) (int64, error)

DeleteExpiredCompletedNodeRequests deletes up to limit completed node requests whose updated_at is on or before olderThan. Pending requests are never touched.

func DeleteExpiredDatadogWebhookReceipts

func DeleteExpiredDatadogWebhookReceipts(tx *gorm.DB, olderThan time.Time, limit int) (int64, error)

DeleteExpiredDatadogWebhookReceipts removes receipts older than olderThan. It deletes at most limit rows so one pass cannot scan the whole table.

func DeleteExpiredLinearWebhookReceipts

func DeleteExpiredLinearWebhookReceipts(tx *gorm.DB, olderThan time.Time, limit int) (int64, error)

DeleteExpiredLinearWebhookReceipts removes receipts older than olderThan. It deletes at most limit rows so one pass cannot scan the whole table.

func DeleteExpiredSentryAppInstallGrants

func DeleteExpiredSentryAppInstallGrants(tx *gorm.DB, now time.Time) error

DeleteExpiredSentryAppInstallGrants drops grants that no callback claimed in time, so install codes and tokens do not stay in the database.

func DeleteExpiredSentryWebhookReceipts

func DeleteExpiredSentryWebhookReceipts(tx *gorm.DB, olderThan time.Time, limit int) (int64, error)

DeleteExpiredSentryWebhookReceipts removes receipts older than olderThan. It deletes at most limit rows so one pass cannot scan the whole table.

func DeleteFactoryIntakesByCanvas

func DeleteFactoryIntakesByCanvas(tx *gorm.DB, canvasID uuid.UUID) error

DeleteFactoryIntakesByCanvas removes the intakes a canvas implements. The canvas reference is a RESTRICT foreign key, so canvas deletion has to call this before the canvas row goes away.

func DeleteFactoryPRFeedbackHandlersByCanvas

func DeleteFactoryPRFeedbackHandlersByCanvas(tx *gorm.DB, canvasID uuid.UUID) error

DeleteFactoryPRFeedbackHandlersByCanvas removes the handlers a canvas implements. The canvas reference is a RESTRICT foreign key, so canvas deletion has to call this before the canvas row goes away.

func DeleteFactoryVelocityRepositoryMerges

func DeleteFactoryVelocityRepositoryMerges(tx *gorm.DB, factoryID uuid.UUID) error

DeleteFactoryVelocityRepositoryMerges drops every stored merge of a workspace. The sync calls it when the workspace changed its repository, so merges of the repository it no longer reports on do not linger.

func DeleteFinishedVCSProviderInstallationRequesters

func DeleteFinishedVCSProviderInstallationRequesters(tx *gorm.DB, provider string, createdBefore time.Time) error

DeleteFinishedVCSProviderInstallationRequesters deletes requester rows whose installation has no reconcile job and no interactive repository sync job left. Background syncs are routine and do not belong to the request. createdBefore keeps new rows while the reconcile job enqueues their syncs.

func DeleteGroupMetadata

func DeleteGroupMetadata(groupName, domainType, domainID string) error

func DeleteGroupMetadataInTransaction

func DeleteGroupMetadataInTransaction(tx *gorm.DB, groupName, domainType, domainID string) error

func DeleteInstallationLicense

func DeleteInstallationLicense(tx *gorm.DB) error

func DeleteIntegrationSubscriptionsForNodeInTransaction added in v0.6.0

func DeleteIntegrationSubscriptionsForNodeInTransaction(tx *gorm.DB, workflowID uuid.UUID, nodeID string) error

func DeleteMCPOAuthCode

func DeleteMCPOAuthCode(tx *gorm.DB, code *MCPOAuthCode) error

func DeleteMCPOAuthCodesForClient

func DeleteMCPOAuthCodesForClient(
	tx *gorm.DB,
	organizationID, factoryID, userID uuid.UUID,
	clientID string,
) error

func DeleteMCPOAuthRefreshToken

func DeleteMCPOAuthRefreshToken(tx *gorm.DB, token *MCPOAuthRefreshToken) error

func DeleteMCPOAuthRefreshTokensForClient

func DeleteMCPOAuthRefreshTokensForClient(
	tx *gorm.DB,
	organizationID, factoryID, userID uuid.UUID,
	clientID string,
) error

func DeleteMetadataForOrganization

func DeleteMetadataForOrganization(tx *gorm.DB, domainType, domainID string) error

func DeleteRoleMetadata

func DeleteRoleMetadata(roleName, domainType, domainID string) error

func DeleteRoleMetadataInTransaction

func DeleteRoleMetadataInTransaction(tx *gorm.DB, roleName, domainType, domainID string) error

func DeleteSentryAppInstallGrant

func DeleteSentryAppInstallGrant(tx *gorm.DB, installationUUID string) error

DeleteSentryAppInstallGrant drops the grant of an installation, for example after Sentry reports that the organization uninstalled the app.

func DeleteUsagePriceBook

func DeleteUsagePriceBook(tx *gorm.DB, version string) error

DeleteUsagePriceBook removes one non-current catalog version.

func DeleteUserAPITokensForAccount

func DeleteUserAPITokensForAccount(tx *gorm.DB, accountID uuid.UUID) error

DeleteUserAPITokensForAccount deletes every personal API token belonging to any user of the given account. It mirrors ClearAPIKeyTokenHashesCreatedByAccount so that a password change or an account block invalidates every personal token, not just the legacy users.token_hash column.

func DeleteVCSProviderInstallRequestsForAccount

func DeleteVCSProviderInstallRequestsForAccount(
	tx *gorm.DB,
	provider string,
	accountID *int64,
	accountLogin string,
) error

func DeleteVCSProviderInstallation

func DeleteVCSProviderInstallation(tx *gorm.DB, provider string, installationID int64) error

func DeleteVCSProviderInstallationsMissingFromSnapshot

func DeleteVCSProviderInstallationsMissingFromSnapshot(
	tx *gorm.DB,
	provider string,
	installationIDs []int64,
	observedBefore time.Time,
) error

func DeleteVCSProviderRepositories

func DeleteVCSProviderRepositories(tx *gorm.DB, provider string, installationID int64, repositoryIDs []int64) error

func DemoteFromInstallationAdmin added in v0.14.0

func DemoteFromInstallationAdmin(accountID string) error

func DisableExperimentalFeature added in v0.21.0

func DisableExperimentalFeature(orgID uuid.UUID, featureID string) error

DisableExperimentalFeature removes the given feature id from the organization's enabled set. Disabling an id that is not enabled is a no-op.

func DisableExperimentalFeatureInTransaction added in v0.21.0

func DisableExperimentalFeatureInTransaction(tx *gorm.DB, orgID uuid.UUID, featureID string) error

func DiscardStagedFilesForUser added in v0.28.0

func DiscardStagedFilesForUser(db *gorm.DB, workflowID, userID uuid.UUID, paths []string) error

func EnableExperimentalFeature added in v0.21.0

func EnableExperimentalFeature(orgID uuid.UUID, featureID string) error

EnableExperimentalFeature adds the given feature id to the organization's enabled set, deduping. The caller is responsible for validating that the feature id exists in the registry.

func EnableExperimentalFeatureInTransaction added in v0.21.0

func EnableExperimentalFeatureInTransaction(tx *gorm.DB, orgID uuid.UUID, featureID string) error

func EndPlanningSessionForFinishedRun

func EndPlanningSessionForFinishedRun(tx *gorm.DB, canvasRunID uuid.UUID, _ string) error

EndPlanningSessionForFinishedRun closes the planning session when the canvas run is finished. The follow-up loop keeps the run in progress while it waits up to five minutes for the next user message. A finished run means the agent process is gone: the idle wait ended, the agent failed, or a passed greet never entered wait. The next user message reopens the session and starts a new run with the analysis rewind.

func EnqueueVCSProviderInstallationReconciliation

func EnqueueVCSProviderInstallationReconciliation(
	tx *gorm.DB,
	provider string,
	installationID int64,
	organizationID uuid.UUID,
	runAt time.Time,
) error

func EnqueueVCSProviderReconciliation

func EnqueueVCSProviderReconciliation(tx *gorm.DB, provider string, runAt time.Time) error

func EnqueueVCSProviderRepositorySync

func EnqueueVCSProviderRepositorySync(
	tx *gorm.DB,
	provider string,
	repositoryID int64,
	runAt time.Time,
	priority VCSProviderRepositorySyncPriority,
) error

func ExpireOpenIncludedGrants

func ExpireOpenIncludedGrants(tx *gorm.DB, orgID uuid.UUID) error

ExpireOpenIncludedGrants stops leftover Business included dollars from remaining spendable after Polar cancels or refunds the subscription. It rewrites the Polar order key so a later subscribe can grant a new included allowance.

func FactoryAppTemplateID

func FactoryAppTemplateID(nodes []Node) string

func FactoryAppTemplateMetadata

func FactoryAppTemplateMetadata(templateID string, version int) map[string]any

FactoryAppTemplateMetadata returns the persisted marker for a generated factory app. The marker survives canvas renames and user-facing copy changes.

func FactoryAppTemplateMetadataFor

func FactoryAppTemplateMetadataFor(templateID string, version int, provider string) map[string]any

FactoryAppTemplateMetadataFor records the template id and, when set, the Git host. An empty provider leaves existing canvases readable as GitHub.

func FactoryURLIDFromRouteSegment

func FactoryURLIDFromRouteSegment(segment string) (string, bool)

func FindCanvasVersionsByIDs added in v0.26.0

func FindCanvasVersionsByIDs(workflowID uuid.UUID, versionIDs []uuid.UUID) (map[uuid.UUID]*CanvasVersion, error)

func FindCanvasVersionsByIDsInTransaction added in v0.26.0

func FindCanvasVersionsByIDsInTransaction(
	tx *gorm.DB,
	workflowID uuid.UUID,
	versionIDs []uuid.UUID,
) (map[uuid.UUID]*CanvasVersion, error)

func FindFactoryIDForCanvas

func FindFactoryIDForCanvas(tx *gorm.DB, orgID uuid.UUID, canvasID uuid.UUID) (*uuid.UUID, error)

func FindLatestNodeExecutionKVValueInTransaction added in v0.22.0

func FindLatestNodeExecutionKVValueInTransaction(tx *gorm.DB, executionID uuid.UUID, key string) (string, error)

FindLatestNodeExecutionKVValueInTransaction returns the value from the newest row for this execution and key (by created_at, then id).

func FindLiveCanvasSpecInTransaction added in v0.11.0

func FindLiveCanvasSpecInTransaction(tx *gorm.DB, workflowID uuid.UUID) ([]Node, []Edge, error)

func FindLiveCanvasSpecsByCanvasIDs added in v0.28.0

func FindLiveCanvasSpecsByCanvasIDs(tx *gorm.DB, canvasIDs []uuid.UUID) (map[uuid.UUID]LiveCanvasSpec, error)

func FindRoleMetadataByNames

func FindRoleMetadataByNames(roleNames []string, domainType, domainID string) (map[string]*RoleMetadata, error)

func FindUserAvatarURLsInOrganization

func FindUserAvatarURLsInOrganization(tx *gorm.DB, orgID uuid.UUID, userIDs []uuid.UUID) (map[uuid.UUID]string, error)

FindUserAvatarURLsInOrganization returns profile image URLs for organization members, using linked GitHub accounts when present and sign-in providers as fallback. Keys are omitted when no avatar URL is known.

func FindUserCanvasPreferencesForCanvases added in v0.28.0

func FindUserCanvasPreferencesForCanvases(
	tx *gorm.DB,
	organizationID uuid.UUID,
	userID uuid.UUID,
	canvasIDs []uuid.UUID,
) (map[uuid.UUID]UserCanvasPreference, error)

func FindUserNotificationSettingsForUsers

func FindUserNotificationSettingsForUsers(
	tx *gorm.DB,
	organizationID uuid.UUID,
	userIDs []uuid.UUID,
) (map[uuid.UUID]UserNotificationSettings, error)

FindUserNotificationSettingsForUsers batch-loads settings for recipient resolution. Users without a row are absent from the result map.

func FindWorkOrderIDsByLinkedRunIDs

func FindWorkOrderIDsByLinkedRunIDs(tx *gorm.DB, runIDs []uuid.UUID) (map[uuid.UUID]uuid.UUID, error)

FindWorkOrderIDsByLinkedRunIDs returns the work order each canvas run is linked to through factory_pull_request_runs.

func FormatDomain

func FormatDomain(domainType, domainID string) string

func FormatHostedLLMModelKey

func FormatHostedLLMModelKey(provider, model string) string

func FormatSelectableLLMModelKey

func FormatSelectableLLMModelKey(source, provider, model string) string

func GenerateFactoryKeyFromName

func GenerateFactoryKeyFromName(name string) string

GenerateFactoryKeyFromName produces a stable candidate key from a factory name (letters only, uppercased, trimmed to the max length). Callers still need to check organization uniqueness before persisting.

func GenerateNodeID added in v0.0.43

func GenerateNodeID(blockName string, nodeName string) string

func GenerateUniqueFactoryKey

func GenerateUniqueFactoryKey(tx *gorm.DB, organizationID uuid.UUID, name string) (string, error)

GenerateUniqueFactoryKey picks a key that is unique among active factories in the given organization. It first tries the name-derived seed, then walks through letter-only variants. Used by tests and by the CLI, where callers may not care about picking a specific key.

Keys are letters-only by the schema check constraint, so we cannot fall back to numeric suffixes. Instead we pad with `X` and cycle through the last character.

func GenerateUniqueNodeID added in v0.0.43

func GenerateUniqueNodeID(node Node, reservedIDs map[string]bool) string

func GenerateUniqueOrganizationSlug

func GenerateUniqueOrganizationSlug(tx *gorm.DB, base string, excludeID uuid.UUID) (string, error)

GenerateUniqueOrganizationSlug slugifies base and returns a slug that is not currently used by another active (non-deleted) organization. It appends "-2", "-3", and so on until it finds one that is free. Pass uuid.Nil for excludeID when creating a new organization, or the organization's own ID when regenerating a slug on update so the organization does not collide with itself.

func GetActiveOrganizationIDs

func GetActiveOrganizationIDs() ([]string, error)

func GetInstallationID added in v0.1.0

func GetInstallationID(tx *gorm.DB) (string, error)

func GrantVCSProviderBindingRepository

func GrantVCSProviderBindingRepository(
	tx *gorm.DB,
	integrationID uuid.UUID,
	provider string,
	repositoryID int64,
) error

func GrantWelcomeCredit

func GrantWelcomeCredit(tx *gorm.DB, orgID, accountID uuid.UUID) error

func HardDeleteOrganization

func HardDeleteOrganization(id string) error

func HasExperimentalFeature added in v0.21.0

func HasExperimentalFeature(orgID uuid.UUID, featureID string) (bool, error)

HasExperimentalFeature reports whether the given feature id is active for the organization with the given id. Released features are reported true without loading the organization from the database.

func HasMCPOAuthRefreshTokenForClient

func HasMCPOAuthRefreshTokenForClient(
	tx *gorm.DB,
	organizationID, factoryID, userID uuid.UUID,
	clientID string,
	now time.Time,
) (bool, error)

func HasOfferedHostedLLMProvider

func HasOfferedHostedLLMProvider(tx *gorm.DB) (bool, error)

HasOfferedHostedLLMProvider is true when SuperPlane can resolve hosted credentials and at least one allowlisted model for a coding agent.

func HasStagedFilesForUser added in v0.28.0

func HasStagedFilesForUser(db *gorm.DB, workflowID, userID uuid.UUID) (bool, error)

func HasVCSProviderInstallRequestForAccount

func HasVCSProviderInstallRequestForAccount(
	tx *gorm.DB,
	provider string,
	accountID *int64,
	accountLogin string,
) (bool, error)

func HasVCSProviderInstallRequests

func HasVCSProviderInstallRequests(tx *gorm.DB, provider string) (bool, error)

func HostedLLMTechnicalName

func HostedLLMTechnicalName(provider, model string) string

func HostedPlanGatesEnabled

func HostedPlanGatesEnabled() bool

HostedPlanGatesEnabled is true when Polar billing is configured. pkg/models cannot import pkg/billing/polar, so this reads POLAR_ACCESS_TOKEN the same way polar.Configured does.

func IncludedGrantKey

func IncludedGrantKey(subscriptionID string, periodEnd time.Time) string

func IncrementAndMaybeInvalidateCodes added in v0.14.0

func IncrementAndMaybeInvalidateCodes(email string, maxVerifyAttempts int) (bool, error)

IncrementAndMaybeInvalidateCodes atomically increments verify_attempts on all active codes for the given email. If the threshold is reached, it invalidates all active codes in the same transaction. Returns true if codes were invalidated.

func IncrementAndMaybeInvalidateCodesInTransaction added in v0.14.0

func IncrementAndMaybeInvalidateCodesInTransaction(conn *gorm.DB, email string, maxVerifyAttempts int) (bool, error)

func IntersectModelIDs

func IntersectModelIDs(parent, subset []string) []string

func InvalidateActiveMagicCodesInTransaction added in v0.14.0

func InvalidateActiveMagicCodesInTransaction(tx *gorm.DB, email string) error

func IsAgentSessionStreaming added in v0.26.0

func IsAgentSessionStreaming(sessionID uuid.UUID) (bool, error)

func IsAllowedArtifactContentType

func IsAllowedArtifactContentType(contentType string) bool

func IsAllowedFileContentType

func IsAllowedFileContentType(contentType string) bool

func IsBacklogFactoryApp

func IsBacklogFactoryApp(nodes []Node, _ []Edge) bool

func IsClaudeFamilyAlias

func IsClaudeFamilyAlias(stored string) bool

IsClaudeFamilyAlias reports whether stored is haiku, opus, or sonnet, with an optional single provider prefix such as "anthropic/opus".

func IsDefaultOrganizationRole

func IsDefaultOrganizationRole(roleName string) bool

func IsInlineAudioContentType

func IsInlineAudioContentType(contentType string) bool

func IsInlineImageContentType

func IsInlineImageContentType(contentType string) bool

func IsInlineMediaContentType

func IsInlineMediaContentType(contentType string) bool

func IsInlineVideoContentType

func IsInlineVideoContentType(contentType string) bool

func IsLegacyAnalyzeBacklog

func IsLegacyAnalyzeBacklog(nodes []Node) bool

IsLegacyAnalyzeBacklog reports a generated version 1 or 2 Backlog graph. Those graphs still have the Analyze / intent.md nodes. SuperPlane upgrades them and no longer starts that path.

func IsLiveCanvasVersion added in v0.28.0

func IsLiveCanvasVersion(tx *gorm.DB, canvas *Canvas, version *CanvasVersion) bool

func IsOrganizationSlugAvailable

func IsOrganizationSlugAvailable(tx *gorm.DB, slug string, excludeID uuid.UUID) (bool, error)

IsOrganizationSlugAvailable reports whether slug is free to use, ignoring soft-deleted organizations and, when excludeID is not uuid.Nil, the organization with that ID. Callers that want to let the user control the exact slug (rather than auto-suffixing) use this before rejecting a requested slug as taken.

func IsReservedOrganizationSlug

func IsReservedOrganizationSlug(slug string) bool

IsReservedOrganizationSlug reports whether slug is a reserved top-level path segment that must never be used as an organization slug.

func IsRunnerCreationIdempotencyKeyConflict

func IsRunnerCreationIdempotencyKeyConflict(err error) bool

IsRunnerCreationIdempotencyKeyConflict identifies the unique-key race that occurs when concurrent retries create the same logical runner. The caller can then load and return the runner committed by the winning transaction.

func IsValidNotificationWorkspaceScope

func IsValidNotificationWorkspaceScope(scope string) bool

func IsValidUserLastLocationPath

func IsValidUserLastLocationPath(path string) bool

IsValidUserLastLocationPath reports whether path is safe to store and later redirect a user to. It must be a same-origin, relative path (so we never redirect off SuperPlane) and stay within the size limit.

func IsValidWorkOrderArtifactType

func IsValidWorkOrderArtifactType(t string) bool

IsValidWorkOrderArtifactType reports whether CreateArtifact accepts t.

func IsValidWorkOrderCheckFormat

func IsValidWorkOrderCheckFormat(format string) bool

IsValidWorkOrderCheckFormat reports whether ReportCheck accepts the format.

func IsValidWorkOrderCheckLevel

func IsValidWorkOrderCheckLevel(level string) bool

IsValidWorkOrderCheckLevel reports whether ReportCheck accepts the level.

func IsValidWorkOrderCommentAuthorKind

func IsValidWorkOrderCommentAuthorKind(kind string) bool

IsValidWorkOrderCommentAuthorKind reports whether the given author kind is accepted by RecordCommentAdded / API handlers.

func IsValidWorkOrderStatusNoteKind

func IsValidWorkOrderStatusNoteKind(kind string) bool

func KnownHostedLLMProviders

func KnownHostedLLMProviders() []string

func LinearWebhookDeliveryAccepted

func LinearWebhookDeliveryAccepted(tx *gorm.DB, webhookID uuid.UUID, deliveryKey string) (bool, error)

LinearWebhookDeliveryAccepted reports whether this subscription already accepted the same Linear payload.

func ListAnalysisPlanningSessionsForWorkOrders

func ListAnalysisPlanningSessionsForWorkOrders(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID]*FactoryPlanningSession, error)

ListAnalysisPlanningSessionsForWorkOrders loads the analysis session for each work order. Work orders without a session are absent from the map. Messages and activities stay unloaded.

func ListChecksForWorkOrders

func ListChecksForWorkOrders(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID][]FactoryWorkOrderCheck, error)

ListChecksForWorkOrders loads the latest check row per key for each work order. Order within an order matches ListChecks: first report first.

func ListExpiredPendingRunnerIDs

func ListExpiredPendingRunnerIDs(tx *gorm.DB, now time.Time, limit int) ([]uuid.UUID, error)

func ListFactoryPullRequestNumbers

func ListFactoryPullRequestNumbers(tx *gorm.DB, factoryID uuid.UUID, repository string) ([]int64, error)

ListFactoryPullRequestNumbers returns the numbers of every pull request SuperPlane opened in a repository, whatever state it reached.

The velocity sync uses it to exclude SuperPlane work from the people merges it stores. State is deliberately not filtered: a pull request whose merge webhook has not arrived yet is still SuperPlane's, and must not be counted as people output in the meantime.

func ListFactoryWorkOrderExecutionsByLineDispatchIDs

func ListFactoryWorkOrderExecutionsByLineDispatchIDs(
	tx *gorm.DB,
	lineDispatchIDs []uuid.UUID,
) (map[uuid.UUID][]FactoryWorkOrderExecutionRecord, error)

ListFactoryWorkOrderExecutionsByLineDispatchIDs bulk-loads step executions for the given line dispatches, keyed by line_dispatch_id.

func ListFactoryWorkOrderQueueItemsByLineDispatchIDs

func ListFactoryWorkOrderQueueItemsByLineDispatchIDs(
	tx *gorm.DB,
	lineDispatchIDs []uuid.UUID,
) (map[uuid.UUID]FactoryWorkOrderQueueItemRecord, error)

ListFactoryWorkOrderQueueItemsByLineDispatchIDs bulk-loads queue items for the given line dispatches, keyed by line_dispatch_id. Position is the item's 1-based place in its step's FIFO queue across all work orders of the line, so the UI can render "3rd in queue".

func ListModelsForRunTrees

func ListModelsForRunTrees(tx *gorm.DB, rootIDs []uuid.UUID) (map[uuid.UUID][]string, error)

ListModelsForRunTrees returns distinct ledger models for each root run, including spend recorded on descendant runs.

func ListModelsForWorkOrderExecutions

func ListModelsForWorkOrderExecutions(tx *gorm.DB, executionIDs []uuid.UUID) (map[uuid.UUID][]string, error)

ListModelsForWorkOrderExecutions returns distinct ledger models keyed by step execution. Missing IDs are absent from the map.

func ListOrganizationOwnerIDs

func ListOrganizationOwnerIDs(tx *gorm.DB, orgID uuid.UUID) ([]string, error)

func ListPullRequestRuns

func ListPullRequestRuns(tx *gorm.DB, pullRequestIDs []uuid.UUID) (map[uuid.UUID][]FactoryPullRequestLinkedRun, error)

func ListPullRequestsByWorkOrderIDs

func ListPullRequestsByWorkOrderIDs(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID][]FactoryPullRequest, error)

func ListRootEventsForRuns

func ListRootEventsForRuns(tx *gorm.DB, canvasID uuid.UUID, runIDs []uuid.UUID) (map[uuid.UUID]CanvasEvent, error)

ListRootEventsForRuns returns the event that started each run, keyed by run id. A root event is the one with no execution behind it.

func ListUsageByMachineTypeForWorkOrders

func ListUsageByMachineTypeForWorkOrders(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID][]UsageByMachineType, error)

ListUsageByMachineTypeForWorkOrders returns compute spend rows keyed by work order. Missing IDs are absent from the map.

func ListUsageByModelForWorkOrders

func ListUsageByModelForWorkOrders(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID][]UsageByModel, error)

ListUsageByModelForWorkOrders returns model spend rows keyed by work order. Missing IDs are absent from the map.

func ListWorkOrderLineDispatchesByWorkOrderIDs

func ListWorkOrderLineDispatchesByWorkOrderIDs(
	tx *gorm.DB,
	workOrderIDs []uuid.UUID,
) (map[uuid.UUID][]FactoryWorkOrderLineDispatchRecord, error)

ListWorkOrderLineDispatchesByWorkOrderIDs bulk-loads line dispatches (with their step executions) for the given work orders, keyed by work order id. Dispatches for a given order are ordered oldest-first, matching how re-dispatches of the same line should render as separate, ordered traversals.

func ListWorkOrdersBySourceRunIDs

func ListWorkOrdersBySourceRunIDs(tx *gorm.DB, factoryID uuid.UUID, runIDs []uuid.UUID) (map[uuid.UUID]FactoryWorkOrder, error)

ListWorkOrdersBySourceRunIDs returns the work order each run created, keyed by run id. A run creates at most one work order.

func LoadCurrentPriceBook

func LoadCurrentPriceBook(tx *gorm.DB) error

LoadCurrentPriceBook installs the current database catalog into the in-memory price book. Callers keep the compiled-in fallback when this returns an error (empty table or missing migration).

func LockAndCountOpenTaskFiles

func LockAndCountOpenTaskFiles(tx *gorm.DB, organizationID, workOrderID uuid.UUID) (int64, error)

func LockStagedFilesForUser

func LockStagedFilesForUser(tx *gorm.DB, workflowID, userID uuid.UUID) error

func LockVisualEvidenceCapture

func LockVisualEvidenceCapture(tx *gorm.DB, canvasID uuid.UUID, number int64) error

func MapAPIKeyNameUniqueConstraintError

func MapAPIKeyNameUniqueConstraintError(err error) error

func MapCanvasNameUniqueConstraintError added in v0.19.0

func MapCanvasNameUniqueConstraintError(err error) error

func MapFactoryConstraintError

func MapFactoryConstraintError(err error) error

MapFactoryConstraintError converts Postgres unique-constraint violations into the domain-specific errors that upper layers know how to translate into user-facing responses.

func MapFactoryIntakeCanvasUniqueConstraintError

func MapFactoryIntakeCanvasUniqueConstraintError(err error) error

func MapFactoryLineNameUniqueConstraintError

func MapFactoryLineNameUniqueConstraintError(err error) error

func MapFactoryNameUniqueConstraintError

func MapFactoryNameUniqueConstraintError(err error) error

MapFactoryNameUniqueConstraintError is a compatibility shim; call MapFactoryConstraintError instead in new code.

func MapFactoryPRFeedbackHandlerCanvasUniqueConstraintError

func MapFactoryPRFeedbackHandlerCanvasUniqueConstraintError(err error) error

func MapFactoryWorkOrderArtifactKeyUniqueConstraintError

func MapFactoryWorkOrderArtifactKeyUniqueConstraintError(err error) error

MapFactoryWorkOrderArtifactKeyUniqueConstraintError maps a violation of the per-factory unique `key` index to a sentinel error, mirroring MapFactoryNameUniqueConstraintError.

func MarkAgentSessionContextReplayed added in v0.26.0

func MarkAgentSessionContextReplayed(sessionID uuid.UUID) error

func MaybeAttachAnalysisSession

func MaybeAttachAnalysisSession(tx *gorm.DB, canvas *Canvas, event *CanvasEvent, run *CanvasRun) error

func MaybeLinkVisualEvidenceRun

func MaybeLinkVisualEvidenceRun(tx *gorm.DB, canvas *Canvas, event *CanvasEvent, run *CanvasRun) error

MaybeLinkVisualEvidenceRun attaches a Visual Evidence canvas run to the factory pull request in the root event. The task Verify list shows a column app only after that link exists.

func ModelIsSelectable

func ModelIsSelectable(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID, provider, fundingSource, model string) (bool, error)

func NextUsagePriceBookVersion

func NextUsagePriceBookVersion(tx *gorm.DB, now time.Time) (string, error)

NextUsagePriceBookVersion returns YYYY-MM-DD.N for now, incrementing N.

func NodeTypeName added in v0.0.43

func NodeTypeName(node Node) string

func NormalizeBYOKLLMProvider

func NormalizeBYOKLLMProvider(provider string) (string, error)

func NormalizeContextRepoName

func NormalizeContextRepoName(repository string) string

func NormalizeDisabledTools

func NormalizeDisabledTools(names []string) []string

func NormalizeFactoryAgentResourceName

func NormalizeFactoryAgentResourceName(name string) string

func NormalizeFactoryKey

func NormalizeFactoryKey(key string) string

NormalizeFactoryKey uppercases and trims whitespace so callers can accept user input in any case, then re-check it with ValidateFactoryKey.

func NormalizeHostedLLMProvider

func NormalizeHostedLLMProvider(provider string) (string, error)

func NormalizeSetupCommands

func NormalizeSetupCommands(commands []string) []string

func OrganizationBYOKModelAllowlistExists

func OrganizationBYOKModelAllowlistExists(tx *gorm.DB, orgID uuid.UUID, provider string) (bool, error)

OrganizationBYOKModelAllowlistExists is false until the organization saves a model list for the provider. An empty saved list still counts as saved.

func OrganizationBillingIsPolarManaged

func OrganizationBillingIsPolarManaged(plan *OrganizationBillingPlan) bool

func OrganizationHasExperimentalFeatures

func OrganizationHasExperimentalFeatures(tx *gorm.DB, orgID uuid.UUID, featureIDs ...string) (bool, error)

OrganizationHasExperimentalFeatures reports whether every feature is active for the organization. Released features count as active.

func OrganizationIDsPendingInitialOnboardingOnly

func OrganizationIDsPendingInitialOnboardingOnly(tx *gorm.DB, organizationIDs []uuid.UUID) (map[uuid.UUID]struct{}, error)

OrganizationIDsPendingInitialOnboardingOnly returns organizations whose only workspaces are unfinished first-run setup. Organizations that also have a completed workspace are omitted.

func OriginLabelFromURL

func OriginLabelFromURL(rawURL string) string

func ParseSetupCommandsText

func ParseSetupCommandsText(text string) []string

func ParseUsageFundingSource

func ParseUsageFundingSource(source string) (string, error)

ParseUsageFundingSource accepts hosted or byok. Empty input is an error.

func PathBelongsToOrganization

func PathBelongsToOrganization(path, slug string) bool

PathBelongsToOrganization reports whether path is an in-app URL for slug. Accepts "/{slug}", "/{slug}/...", "/{slug}?...", and "/{slug}#...".

func PlanningRefineNote

func PlanningRefineNote(key, title string) string

func PolarRefundMicrosForOrder

func PolarRefundMicrosForOrder(tx *gorm.DB, polarOrderID string) (int64, error)

func PolarSubscriptionIsPaid

func PolarSubscriptionIsPaid(status string) bool

func PrefixGroup

func PrefixGroup(groupName string) string

func PrefixRole

func PrefixRole(role string) string

func PrefixUser

func PrefixUser(userID string) string

func PreloadRemovedMember

func PreloadRemovedMember(db *gorm.DB) *gorm.DB

func PromoteToInstallationAdmin added in v0.14.0

func PromoteToInstallationAdmin(accountID string) error

func PromoteToLiveInTransaction added in v0.17.0

func PromoteToLiveInTransaction(tx *gorm.DB, version *CanvasVersion, nodes []Node, edges []Edge) error

func RecordComputeUsage

func RecordComputeUsage(tx *gorm.DB, in ComputeUsageEventInput) error

RecordComputeUsage inserts one factory-linked runner-fleet row. Cost comes from the compute price book (zero until rates are published) at the raw provider rate; hosted markup does not apply. The stored cost_micros still draws down org hosted credit and factory hosted budgets, same as model usage. Org canvases are skipped.

func RecordUsage

func RecordUsage(tx *gorm.DB, in WorkspaceUsageEventInput) error

RecordUsage inserts one factory-linked model-usage row and copies ledger totals into the line-step cache when the run belongs to a line execution. Factory canvases without a line step (Backlog analysis, PR feedback) still persist. Org canvases are skipped. Each billed call gets its own row, including retries of the same node execution.

func RecordWorkOrderExecutionFailureReason

func RecordWorkOrderExecutionFailureReason(tx *gorm.DB, runID uuid.UUID, reason string) error

RecordWorkOrderExecutionFailureReason stores the failure reason on the factory step for the run. Runs outside a factory line have no step, so they are ignored.

func RefreshAccountLinkedAccount

func RefreshAccountLinkedAccount(tx *gorm.DB, linked *AccountLinkedAccount) error

RefreshAccountLinkedAccount updates an identity observed during sign-in. It preserves the member's explicit provider selection and activates the identity only when the account does not have an active identity yet.

func RefuseIfLastOrganizationOwner

func RefuseIfLastOrganizationOwner(tx *gorm.DB, orgID, userID uuid.UUID) error

func RejectedDatadogWebhookReceiptLockKey

func RejectedDatadogWebhookReceiptLockKey(integrationID uuid.UUID) int64

RejectedDatadogWebhookReceiptLockKey identifies the advisory lock that guards rejected receipt storage for one integration.

func ReleaseTerminatedRunnerCreationIdempotencyKey

func ReleaseTerminatedRunnerCreationIdempotencyKey(tx *gorm.DB, key string) error

ReleaseTerminatedRunnerCreationIdempotencyKey lets a controller retry the same logical provisioning request after its previous runner terminated. Pending and active runners keep the key so concurrent retries continue to return one runner.

func RemainingHostedCreditMicros

func RemainingHostedCreditMicros(tx *gorm.DB, organizationIDs []uuid.UUID) (map[uuid.UUID]int64, error)

RemainingHostedCreditMicros returns remaining hosted credit for each organization. An organization with no grants is 0. Spend follows allocateHostedCreditSpend, including expired welcome credit and negative adjustments.

func RememberAbandonedFileObjects

func RememberAbandonedFileObjects(tx *gorm.DB, organizationID, factoryID uuid.UUID, keys []string) error

func ReplaceFactoryVelocityRepositoryMerges

func ReplaceFactoryVelocityRepositoryMerges(
	tx *gorm.DB,
	factoryID uuid.UUID,
	provider string,
	from, to time.Time,
	merges []FactoryVelocityRepositoryMerge,
) error

ReplaceFactoryVelocityRepositoryMerges swaps the stored merges of a window for a freshly computed set.

The sync recomputes a whole window rather than adding to it, so a pull request that SuperPlane recorded after the merge was first seen, or a merge that changed source, stops counting the old way on the next tick.

The delete scopes to the given provider so one host never wipes the other.

func ReplaceManualCanvasMemoryNamespace added in v0.25.0

func ReplaceManualCanvasMemoryNamespace(canvasID uuid.UUID, namespace string, entries []any) error

func ReplaceManualCanvasMemoryNamespaceInTransaction added in v0.25.0

func ReplaceManualCanvasMemoryNamespaceInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string, entries []any) error

ReplaceManualCanvasMemoryNamespaceInTransaction replaces all manual-source rows in a namespace with one row per entry. Used by both create (no existing rows) and update (existing manual rows). The caller is responsible for enforcing origin-lock before invoking this.

func ReplaceVCSProviderInstallRequests

func ReplaceVCSProviderInstallRequests(tx *gorm.DB, provider string, requests []VCSProviderInstallRequest) error

func ReplaceVCSProviderRepositories

func ReplaceVCSProviderRepositories(
	tx *gorm.DB,
	provider string,
	installationID int64,
	repositories []VCSProviderRepository,
) error

func ReplaceVCSProviderRepositoryCollaborators

func ReplaceVCSProviderRepositoryCollaborators(
	tx *gorm.DB,
	provider string,
	repositoryID int64,
	collaborators []VCSProviderRepositoryCollaborator,
) error

func RequestVCSProviderInstallRequestRefresh

func RequestVCSProviderInstallRequestRefresh(tx *gorm.DB, provider string, until time.Time) error

func ResetLocalAfterOnboarding

func ResetLocalAfterOnboarding(tx *gorm.DB) error

ResetLocalAfterOnboarding wipes factory runtime data and restores trial billing with a full welcome credit window. It keeps organizations, workspaces, apps, lines, intakes, and integrations.

func ResetOrganizationBillingTrial

func ResetOrganizationBillingTrial(tx *gorm.DB, orgID uuid.UUID) error

ResetOrganizationBillingTrial puts one organization on a 14-day system trial, drops extra credit grants, refreshes welcome credit expiry, and deletes that organization's spend ledger.

func ResetStuckProvisioningWebhooks added in v0.12.0

func ResetStuckProvisioningWebhooks() (int64, error)

ResetStuckProvisioningWebhooks resets webhooks that have been stuck in "provisioning" state back to "pending". This handles the edge case where the process crashes during the external API call (Phase 2).

func ResolveExecutionErrors added in v0.1.5

func ResolveExecutionErrors(workflowID uuid.UUID, executionIDs []uuid.UUID) error

func ResolveExecutionErrorsInTransaction added in v0.1.5

func ResolveExecutionErrorsInTransaction(tx *gorm.DB, workflowID uuid.UUID, executionIDs []uuid.UUID) error

func ResolveFactoryWorkOrderCreatorAutomations

func ResolveFactoryWorkOrderCreatorAutomations(
	tx *gorm.DB,
	orders []FactoryWorkOrder,
) (map[uuid.UUID]*factory.AutomationRef, error)

func ResolveOrganizationMarkupBPS

func ResolveOrganizationMarkupBPS(tx *gorm.DB, orgID uuid.UUID) (int, error)

func ResolveSelectableLLMModels

func ResolveSelectableLLMModels(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID, provider, fundingSource string) ([]string, error)

ResolveSelectableLLMModels returns the models a picker and run gate may use. Factory lists that are missing or empty inherit the parent list.

func RestoreFileRefs

func RestoreFileRefs(tx *gorm.DB, organizationID, factoryID, workOrderID uuid.UUID, markdown string) (string, error)

func RetryVCSProviderInstallationReconciliation

func RetryVCSProviderInstallationReconciliation(
	tx *gorm.DB,
	provider string,
	installationID int64,
	claimedAt, runAt time.Time,
	reconcileError error,
) error

func RetryVCSProviderReconciliation

func RetryVCSProviderReconciliation(
	tx *gorm.DB,
	provider string,
	claimedAt, runAt time.Time,
	reconcileError error,
) error

func RetryVCSProviderRepositorySync

func RetryVCSProviderRepositorySync(
	tx *gorm.DB,
	provider string,
	repositoryID int64,
	claimedAt, runAt time.Time,
	syncError error,
) error

func ReversePolarOrderCredit

func ReversePolarOrderCredit(tx *gorm.DB, orgID uuid.UUID, polarOrderID string, reverseMicros int64, polarRefundID string) error

ReversePolarOrderCredit inserts a Polar refund so the reversed total equals reverseMicros, and never more than the purchase grant. Concurrent callers serialize on the purchase grant row.

func RevokeTerminatedRunnerCredentials

func RevokeTerminatedRunnerCredentials(tx *gorm.DB, terminatedBefore, now time.Time) error

func RewriteHostedProviderRunnerNodes

func RewriteHostedProviderRunnerNodes(nodes []Node)

func RewriteHostedProviderRunnerToSuperPlane

func RewriteHostedProviderRunnerToSuperPlane(node *Node) bool

RewriteHostedProviderRunnerToSuperPlane converts leftover hosted Claude, Codex, or OpenRouter nodes to runnerSuperPlane. BYOK nodes stay unchanged.

func RootEventSourcePayload

func RootEventSourcePayload(eventData any) any

RootEventSourcePayload peels a root event envelope down to its `.data` payload — used as work-order `source` for both run input and order().

func RunnerFleetMetricScope

func RunnerFleetMetricScope(scopeType, organizationSlug string) string

RunnerFleetMetricScope identifies a fleet's installation or organization scope.

func SaveAccountLinkedAccount

func SaveAccountLinkedAccount(tx *gorm.DB, linked *AccountLinkedAccount) error

SaveAccountLinkedAccount links the identity to the account and makes it the active identity for its provider. Other identities for the provider remain linked so activity from all of them can be attributed to the account.

func SaveCanvasVersionInTransaction added in v0.28.0

func SaveCanvasVersionInTransaction(tx *gorm.DB, version *CanvasVersion) error

func SaveInstallationGitHubApp

func SaveInstallationGitHubApp(
	tx *gorm.DB,
	githubAppID int64,
	slug string,
	encryptedPrivateKey []byte,
	encryptedWebhookSecret []byte,
) error

func SaveInstallationLicense

func SaveInstallationLicense(tx *gorm.DB, encryptedLicense []byte, installedBy *uuid.UUID) error

func SaveInstallationLicenseKeys

func SaveInstallationLicenseKeys(tx *gorm.DB, document string, version int64) error

SaveInstallationLicenseKeys stores a key list only when its version is newer than the cached one.

func SaveInstallationLicenseRevocations

func SaveInstallationLicenseRevocations(tx *gorm.DB, document string, version int64) error

SaveInstallationLicenseRevocations stores a revocation list only when its version is newer than the cached one.

func SaveInviteLink(tx *gorm.DB, inviteLink *OrganizationInviteLink) error

func SelectAccountLinkedAccount

func SelectAccountLinkedAccount(tx *gorm.DB, accountID uuid.UUID, provider, providerID string) error

func SelectableLLMProviderName

func SelectableLLMProviderName(provider string) string

func SelectableLLMRunnerComponent

func SelectableLLMRunnerComponent(model SelectableLLMModel) (string, error)

func SelectableLLMRunnerCredentials

func SelectableLLMRunnerCredentials(tx *gorm.DB, orgID uuid.UUID, model SelectableLLMModel) (map[string]any, error)

func SelectableLLMRunnerModel

func SelectableLLMRunnerModel(model SelectableLLMModel) string

func SelectableLLMSourceName

func SelectableLLMSourceName(source string) string

func SetOrganizationCreatedByAccount

func SetOrganizationCreatedByAccount(tx *gorm.DB, organizationID, accountID uuid.UUID) error

func SetOrganizationPolarCustomerID

func SetOrganizationPolarCustomerID(tx *gorm.DB, orgID uuid.UUID, customerID string) error

func SetUserIsOwner

func SetUserIsOwner(tx *gorm.DB, userID uuid.UUID, isOwner bool) error

func SetWelcomeGrantExpiresAt

func SetWelcomeGrantExpiresAt(tx *gorm.DB, orgID uuid.UUID, endsAt time.Time) error

func SetupCommandsText

func SetupCommandsText(commands []string) string

func SignedMicrosToCents

func SignedMicrosToCents(micros int64) int64

SignedMicrosToCents converts millionths of a dollar to whole cents and keeps the sign. Refunds store negative amounts.

func Slugify

func Slugify(name string) string

Slugify converts name into a lowercase, URL-friendly slug: it strips accents to their closest ASCII letter, replaces runs of characters outside [a-z0-9] with a single dash, trims leading/trailing dashes, and caps the result at maxOrganizationSlugLength characters. It returns defaultOrganizationSlug when name has no sluggable characters at all.

func SoftDeleteOrganization

func SoftDeleteOrganization(id string) error

func SoftDeleteOrganizationFactories

func SoftDeleteOrganizationFactories(tx *gorm.DB, organizationID uuid.UUID) error

func SoftDeleteOrganizationInTransaction

func SoftDeleteOrganizationInTransaction(tx *gorm.DB, id string) error

func SoftDeleteWebhookIfUnreferenced

func SoftDeleteWebhookIfUnreferenced(tx *gorm.DB, webhookID uuid.UUID) error

SoftDeleteWebhookIfUnreferenced soft-deletes webhookID when no live canvas node still references it. Live means the node, canvas, and organization are not deleted.

func SpendingBreakdownLabel

func SpendingBreakdownLabel(id string, catalogs SpendingCatalogs, groupBy string) string

SpendingBreakdownLabel resolves one breakdown row label from catalogs.

func SpendingModelDisplayName

func SpendingModelDisplayName(storedModel string, versionedIDs []string) string

SpendingModelDisplayName returns a versioned model id for explorer labels. Filter ids stay on the stored ledger model so existing rows still match.

func SumFactoryHostedBilledMicros

func SumFactoryHostedBilledMicros(tx *gorm.DB, orgID, factoryID uuid.UUID) (int64, error)

func SumReadyOrganizationFileBytes

func SumReadyOrganizationFileBytes(tx *gorm.DB, organizationID uuid.UUID) (int64, error)

func SumUsageAndModelsForRunTrees

func SumUsageAndModelsForRunTrees(tx *gorm.DB, rootIDs []uuid.UUID) (map[uuid.UUID]UsageTotals, map[uuid.UUID][]string, error)

SumUsageAndModelsForRunTrees returns ledger totals and distinct models for each root run, including spend recorded on descendant runs. One tree walk serves both aggregations.

func SumUsageForRunTrees

func SumUsageForRunTrees(tx *gorm.DB, rootIDs []uuid.UUID) (map[uuid.UUID]UsageTotals, error)

SumUsageForRunTrees returns ledger totals for each root run, including spend recorded on descendant runs.

func SumUsageForWorkOrders

func SumUsageForWorkOrders(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID]UsageTotals, error)

SumUsageForWorkOrders returns ledger totals keyed by work order. Missing IDs are absent from the map (zero value).

func SumUsageForWorkOrdersByKind

func SumUsageForWorkOrdersByKind(tx *gorm.DB, workOrderIDs []uuid.UUID) (map[uuid.UUID]UsageSplit, error)

SumUsageForWorkOrdersByKind returns ledger totals keyed by work order, with model spend and compute spend reported apart. Missing IDs are absent from the map (zero value).

Anything that is not compute counts as model spend, so the two bands always add up to what the work order cost.

func SummarizeComputeUsage

func SummarizeComputeUsage(tx *gorm.DB, filter UsageReportFilter) (UsageTotals, []UsageByMachineType, error)

SummarizeComputeUsage returns org or workspace VM totals and a per-machine-type breakdown.

func SummarizeUsage

func SummarizeUsage(tx *gorm.DB, filter UsageReportFilter) (UsageTotals, []UsageByModel, error)

SummarizeUsage returns org or workspace model totals and a per-model breakdown.

func SuperPlaneRunnerReadinessError

func SuperPlaneRunnerReadinessError(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID) error

func SuperPlaneRunnerReadinessMessage

func SuperPlaneRunnerReadinessMessage(err error) string

func SyncDefaultHostedLLMModelAfterProviderChange

func SyncDefaultHostedLLMModelAfterProviderChange(tx *gorm.DB) error

SyncDefaultHostedLLMModelAfterProviderChange clears the default when no hosted models remain. It rejects the change when other models still exist.

func SyncIncludedLLMCreditGrant

func SyncIncludedLLMCreditGrant(tx *gorm.DB, sync IncludedUsageSync) error

SyncIncludedLLMCreditGrant grants or expires Business included usage the same way Polar subscription webhooks do.

func SyncVCSProviderBindingRepositories

func SyncVCSProviderBindingRepositories(tx *gorm.DB, integrationID uuid.UUID, provider string) error

SyncVCSProviderBindingRepositories limits a binding to repositories selected by its active Factory workspaces. The transaction lock prevents concurrent workspace updates from replacing each other's grants.

func TouchAgentSessionHeartbeat added in v0.26.0

func TouchAgentSessionHeartbeat(sessionID uuid.UUID) error

TouchAgentSessionHeartbeat uses UpdateColumn so updated_at stays put — it's the optimistic-concurrency key for the per-turn idle transition.

func TouchUserAPITokenLastUsed

func TouchUserAPITokenLastUsed(tx *gorm.DB, id uuid.UUID, when time.Time) error

func UnmarshalJSONValue added in v0.23.0

func UnmarshalJSONValue(data []byte, value any) error

UnmarshalJSONValue decodes JSON into value using json.Number for numeric tokens and rejects payloads with multiple top-level values.

func UpdateAgentSessionProviderSessionInTransaction added in v0.26.0

func UpdateAgentSessionProviderSessionInTransaction(tx *gorm.DB, sessionID uuid.UUID, providerSessionID, toolSchemaRevision, status string) error

func UpdateAgentSessionStatus added in v0.21.0

func UpdateAgentSessionStatus(sessionID uuid.UUID, status string) error

func UpdateAgentSessionStatusIfUnchanged added in v0.26.0

func UpdateAgentSessionStatusIfUnchanged(sessionID uuid.UUID, status string, unchangedSince *time.Time) (bool, error)

func UpdateAgentSessionStatusIfUnchangedInTransaction added in v0.26.0

func UpdateAgentSessionStatusIfUnchangedInTransaction(tx *gorm.DB, sessionID uuid.UUID, status string, unchangedSince *time.Time) (bool, error)

func UpdateAgentSessionStatusInTransaction added in v0.21.0

func UpdateAgentSessionStatusInTransaction(tx *gorm.DB, sessionID uuid.UUID, status string) error

func UpdateDatadogWebhookReceiptResult

func UpdateDatadogWebhookReceiptResult(tx *gorm.DB, id uuid.UUID, status int, outcome string, subscriptionCount int) error

func UpdateDatadogWebhookReceiptSummary

func UpdateDatadogWebhookReceiptSummary(tx *gorm.DB, id uuid.UUID, summary DatadogWebhookReceipt) error

func UpdateInstallationMetadata added in v0.15.0

func UpdateInstallationMetadata(tx *gorm.DB, metadata *InstallationMetadata) error

func UpdateLinearWebhookReceiptResult

func UpdateLinearWebhookReceiptResult(tx *gorm.DB, id uuid.UUID, status int, outcome string, subscriptionCount int) error

func UpdateSentryWebhookReceiptResult

func UpdateSentryWebhookReceiptResult(tx *gorm.DB, id uuid.UUID, status int, outcome string, integrationCount int) error

func UpsertEmailSettings added in v0.0.43

func UpsertEmailSettings(settings *EmailSettings) error

func UpsertEmailSettingsInTransaction added in v0.0.43

func UpsertEmailSettingsInTransaction(tx *gorm.DB, settings *EmailSettings) error

func UpsertGroupMetadata

func UpsertGroupMetadata(groupName, domainType, domainID, displayName, description string) error

func UpsertGroupMetadataInTransaction

func UpsertGroupMetadataInTransaction(tx *gorm.DB, groupName, domainType, domainID, displayName, description string) error

func UpsertOrganizationLLMMarkup

func UpsertOrganizationLLMMarkup(tx *gorm.DB, orgID uuid.UUID, markupBPS *int) error

func UpsertRoleMetadata

func UpsertRoleMetadata(roleName, domainType, domainID, displayName, description string) error

func UpsertRoleMetadataInTransaction

func UpsertRoleMetadataInTransaction(tx *gorm.DB, roleName, domainType, domainID, displayName, description string) error

func UpsertSentryAppInstallGrant

func UpsertSentryAppInstallGrant(tx *gorm.DB, grant SentryAppInstallGrant) error

UpsertSentryAppInstallGrant replaces the grant of an installation. Sentry sends installation.created again after a reinstall, and only the newest grant can complete a connection.

func UpsertVCSProviderInstallation

func UpsertVCSProviderInstallation(tx *gorm.DB, installation *VCSProviderInstallation) error

func UpsertVCSProviderRepositories

func UpsertVCSProviderRepositories(
	tx *gorm.DB,
	provider string,
	installationID int64,
	repositories []VCSProviderRepository,
) error

func UsagePriceBookRatesEqual

func UsagePriceBookRatesEqual(a, b []UsagePriceBookRate) bool

UsagePriceBookRatesEqual reports whether two rate slices carry the same match rules and cents values. It ignores ids and version stamps.

func VCSProviderCatalogHasWork

func VCSProviderCatalogHasWork(tx *gorm.DB, provider string) (bool, error)

func VCSProviderCatalogSynchronizing

func VCSProviderCatalogSynchronizing(
	tx *gorm.DB,
	provider string,
	providerUserID int64,
	organizationID uuid.UUID,
) (bool, error)

func VCSProviderForIntegrationApp

func VCSProviderForIntegrationApp(appName string) (string, bool)

VCSProviderForIntegrationApp maps an integration app name to a workspace Git host.

func VCSProviderInstallRequestRefreshRequested

func VCSProviderInstallRequestRefreshRequested(tx *gorm.DB, provider string, now time.Time) (bool, error)

func VCSProviderRepositoriesSynchronizing

func VCSProviderRepositoriesSynchronizing(tx *gorm.DB, provider string, repositoryIDs []int64) (bool, error)

func VCSRepositoryCloneURL

func VCSRepositoryCloneURL(provider, repository string) string

VCSRepositoryCloneURL returns the HTTPS clone URL for an owner/name repository on the provider. An empty provider means GitHub.

func ValidCanvasColumnKey

func ValidCanvasColumnKey(key string) bool

func ValidFactoryIntakeSource

func ValidFactoryIntakeSource(source string) bool

func ValidFactoryPRFeedbackHandlerSource

func ValidFactoryPRFeedbackHandlerSource(source string) bool

func ValidFactoryPRFeedbackHandlerSubject

func ValidFactoryPRFeedbackHandlerSubject(subject string) bool

func ValidateDomainType

func ValidateDomainType(domainType string) error

func ValidateFactoryAgentResourceKind

func ValidateFactoryAgentResourceKind(kind string) error

func ValidateFactoryAgentResourceName

func ValidateFactoryAgentResourceName(name string) error

func ValidateFactoryKey

func ValidateFactoryKey(key string) error

ValidateFactoryKey rejects empty or malformed keys with a stable error that API handlers translate into an `InvalidArgument` response. Callers should normalize input with NormalizeFactoryKey first.

func ValidateFactoryOnboardingAgentHarness

func ValidateFactoryOnboardingAgentHarness(harness string) error

func ValidateFactoryOnboardingIssuesSource

func ValidateFactoryOnboardingIssuesSource(source string) error

func ValidateFactoryOnboardingVCSProvider

func ValidateFactoryOnboardingVCSProvider(provider string) error

func ValidateSpendingReportWindow

func ValidateSpendingReportWindow(since, until time.Time) error

ValidateSpendingReportWindow rejects windows longer than one year.

func ValidateSubRunCreation added in v0.30.0

func ValidateSubRunCreation(
	tx *gorm.DB,
	parentRunID uuid.UUID,
	targetWorkflowID uuid.UUID,
	targetNodeID string,
	maxCrossWorkflowDepth int,
) error

ValidateSubRunCreationInTransaction guards sub-run creation before a pending run is inserted. All checks walk the parent_run_id chain from the caller's run upward.

Same-app fan-out (forEach, loop, self-invoke into the same workflow) is allowed: those create sibling sub-runs and do not deepen the cross-app chain.

Checks (in order):

  1. Entrypoint cycle — A/run1 -> A/run2 -> A/run1
  2. Workflow cycle — A -> B -> C -> A
  3. Cross-app depth — A -> B -> C -> D -> ... -> Z (too many app hops)

func ValidateUsagePriceBookRates

func ValidateUsagePriceBookRates(rows []UsagePriceBookRate) error

ValidateUsagePriceBookRates rejects empty keys, unknown modes, negatives, and duplicates.

func WorkOrderExecutionFailureReasonFor

func WorkOrderExecutionFailureReasonFor(err error) string

WorkOrderExecutionFailureReasonFor maps a SuperPlane hosted credit error to a stored failure reason. Other errors return an empty string.

func WorkOrderReadyForAutoStart

func WorkOrderReadyForAutoStart(
	tx *gorm.DB,
	factoryModel *Factory,
	order *FactoryWorkOrder,
	session *FactoryPlanningSession,
) (bool, error)

Types

type AccessibleVCSProviderRepository

type AccessibleVCSProviderRepository struct {
	VCSProviderRepository
	AccountLogin string
	AccountType  string
}

func FindAccessibleVCSProviderRepository

func FindAccessibleVCSProviderRepository(
	tx *gorm.DB,
	provider string,
	providerUserID, repositoryID int64,
) (*AccessibleVCSProviderRepository, error)

func FindAccessibleVCSProviderRepositoryByName

func FindAccessibleVCSProviderRepositoryByName(
	tx *gorm.DB,
	provider string,
	providerUserID int64,
	fullName string,
) (*AccessibleVCSProviderRepository, error)

func FindInstalledVCSProviderRepository

func FindInstalledVCSProviderRepository(
	tx *gorm.DB,
	provider string,
	repositoryID int64,
) (*AccessibleVCSProviderRepository, error)

func FindInstalledVCSProviderRepositoryByName

func FindInstalledVCSProviderRepositoryByName(
	tx *gorm.DB,
	provider string,
	fullName string,
) (*AccessibleVCSProviderRepository, error)

func ListAccessibleVCSProviderRepositories

func ListAccessibleVCSProviderRepositories(
	tx *gorm.DB,
	provider string,
	providerUserID int64,
) ([]AccessibleVCSProviderRepository, error)

func ListInstalledVCSProviderRepositories

func ListInstalledVCSProviderRepositories(
	tx *gorm.DB,
	provider string,
) ([]AccessibleVCSProviderRepository, error)

type Account

type Account struct {
	ID                     uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	Email                  string
	Name                   string
	InstallationAdmin      bool `gorm:"default:false"`
	PasswordChangedAt      *time.Time
	BlockedAt              *time.Time
	WelcomeCreditGrantedAt *time.Time
	CreatedAt              *time.Time
	UpdatedAt              *time.Time
	DeletedAt              gorm.DeletedAt `gorm:"index"`
}

func CreateAccount

func CreateAccount(name, email string) (*Account, error)

func CreateAccountInTransaction

func CreateAccountInTransaction(tx *gorm.DB, name, email string) (*Account, error)

func FindAccountByEmail

func FindAccountByEmail(email string) (*Account, error)

func FindAccountByID

func FindAccountByID(id string) (*Account, error)

func FindAccountByProvider

func FindAccountByProvider(tx *gorm.DB, provider, providerID string) (*Account, error)

func ListAccounts added in v0.14.0

func ListAccounts(search string, limit, offset int, sortBy, sortDirection string) ([]Account, int64, error)

func (*Account) Block

func (a *Account) Block(tx *gorm.DB, now time.Time) error

Block marks the account blocked, invalidates sessions, and clears personal tokens plus org API keys created by the account's users.

func (*Account) DisconnectProvider

func (a *Account) DisconnectProvider(tx *gorm.DB, provider string) error

func (*Account) FindAccountProviderByID

func (a *Account) FindAccountProviderByID(provider, providerID string) (*AccountProvider, error)

func (*Account) GetAccountProvider

func (a *Account) GetAccountProvider(provider string) (*AccountProvider, error)

func (*Account) GetAccountProviders

func (a *Account) GetAccountProviders(tx *gorm.DB) ([]AccountProvider, error)

func (*Account) HasReceivedWelcomeCredit

func (a *Account) HasReceivedWelcomeCredit() bool

func (*Account) IsBlocked

func (a *Account) IsBlocked() bool

func (*Account) IsInstallationAdmin added in v0.14.0

func (a *Account) IsInstallationAdmin() bool

func (*Account) IsSessionFresh added in v0.21.0

func (a *Account) IsSessionFresh(issuedAt int64) bool

IsSessionFresh reports whether a token issued at the given Unix timestamp is still valid relative to the most recent password change. Tokens issued strictly before PasswordChangedAt are considered stale.

func (*Account) MarkPasswordChangedInTransaction added in v0.21.0

func (a *Account) MarkPasswordChangedInTransaction(tx *gorm.DB, now time.Time) error

MarkPasswordChangedInTransaction stamps the password rotation time on the account. Used together with rotating the password hash and clearing API tokens to invalidate every existing session for the account.

func (*Account) SetEmail

func (a *Account) SetEmail(tx *gorm.DB, email string) error

func (*Account) SignInEmails

func (a *Account) SignInEmails(tx *gorm.DB) ([]string, error)

func (*Account) SoftDelete

func (a *Account) SoftDelete(tx *gorm.DB, now time.Time) error

func (*Account) Unblock

func (a *Account) Unblock(tx *gorm.DB) error

Unblock clears the blocked flag. Existing sessions remain invalid; the user must sign in again.

func (*Account) UpdateEmail

func (a *Account) UpdateEmail(newEmail string) error

func (*Account) UpdateEmailForProvider

func (a *Account) UpdateEmailForProvider(newEmail, provider, providerID string) error

func (*Account) UpdateName

func (a *Account) UpdateName(tx *gorm.DB, name string) error

type AccountLinkedAccount

type AccountLinkedAccount struct {
	ID         uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	AccountID  uuid.UUID
	Provider   string
	ProviderID string
	Username   string
	Name       string
	AvatarURL  string
	Active     bool
	LinkedAt   time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

AccountLinkedAccount is an identity a member owns on another service. It is not a sign-in method: it grants no session and stores no token. SuperPlane uses it to attribute activity, such as repository authorship in Velocity.

func FindAccountLinkedAccount

func FindAccountLinkedAccount(tx *gorm.DB, accountID uuid.UUID, provider string) (*AccountLinkedAccount, error)

func ListAccountLinkedAccounts

func ListAccountLinkedAccounts(tx *gorm.DB, accountID uuid.UUID) ([]AccountLinkedAccount, error)

func NewAccountLinkedAccount

func NewAccountLinkedAccount(accountID uuid.UUID, provider, providerID, username, name, avatarURL string) *AccountLinkedAccount

func (*AccountLinkedAccount) NormalizedUsername

func (a *AccountLinkedAccount) NormalizedUsername() string

NormalizedUsername matches how the Velocity report resolves a login.

func (*AccountLinkedAccount) TableName

func (a *AccountLinkedAccount) TableName() string

type AccountMagicCode added in v0.14.0

type AccountMagicCode struct {
	ID             uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	Email          string     `gorm:"type:varchar(255);not null"`
	CodeHash       string     `gorm:"type:varchar(64);not null"`
	ExpiresAt      time.Time  `gorm:"not null"`
	UsedAt         *time.Time `gorm:"default:null"`
	VerifyAttempts int        `gorm:"not null;default:0"`
	CreatedAt      time.Time
}

func CreateAccountMagicCode added in v0.14.0

func CreateAccountMagicCode(email, codeHash string, expiresAt time.Time) (*AccountMagicCode, error)

func CreateAccountMagicCodeInTransaction added in v0.14.0

func CreateAccountMagicCodeInTransaction(tx *gorm.DB, email, codeHash string, expiresAt time.Time) (*AccountMagicCode, error)

func FindValidAccountMagicCode added in v0.14.0

func FindValidAccountMagicCode(email, codeHash string, maxVerifyAttempts int) (*AccountMagicCode, error)

func FindValidAccountMagicCodeInTransaction added in v0.14.0

func FindValidAccountMagicCodeInTransaction(tx *gorm.DB, email, codeHash string, maxVerifyAttempts int) (*AccountMagicCode, error)

func (*AccountMagicCode) MarkUsed added in v0.14.0

func (c *AccountMagicCode) MarkUsed() (bool, error)

func (*AccountMagicCode) MarkUsedInTransaction added in v0.14.0

func (c *AccountMagicCode) MarkUsedInTransaction(tx *gorm.DB) (bool, error)

MarkUsedInTransaction atomically marks the code as used only if it hasn't been used yet. Returns true if the code was successfully marked, false if it was already used by a concurrent request.

func (AccountMagicCode) TableName added in v0.14.0

func (AccountMagicCode) TableName() string

type AccountPasswordAuth added in v0.0.18

type AccountPasswordAuth struct {
	ID           uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	AccountID    uuid.UUID
	PasswordHash string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func CreateAccountPasswordAuth added in v0.0.18

func CreateAccountPasswordAuth(accountID uuid.UUID, passwordHash string) (*AccountPasswordAuth, error)

func CreateAccountPasswordAuthInTransaction added in v0.0.18

func CreateAccountPasswordAuthInTransaction(tx *gorm.DB, accountID uuid.UUID, passwordHash string) (*AccountPasswordAuth, error)

func FindAccountPasswordAuthByAccountID added in v0.0.18

func FindAccountPasswordAuthByAccountID(accountID uuid.UUID) (*AccountPasswordAuth, error)

func FindAccountPasswordAuthByAccountIDInTransaction added in v0.0.18

func FindAccountPasswordAuthByAccountIDInTransaction(tx *gorm.DB, accountID uuid.UUID) (*AccountPasswordAuth, error)

func (AccountPasswordAuth) TableName added in v0.0.18

func (AccountPasswordAuth) TableName() string

func (*AccountPasswordAuth) UpdatePasswordHash added in v0.0.18

func (a *AccountPasswordAuth) UpdatePasswordHash(passwordHash string) error

func (*AccountPasswordAuth) UpdatePasswordHashInTransaction added in v0.0.18

func (a *AccountPasswordAuth) UpdatePasswordHashInTransaction(tx *gorm.DB, passwordHash string) error

type AccountProvider

type AccountProvider struct {
	ID         uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	AccountID  uuid.UUID
	Provider   string
	ProviderID string
	Username   string
	Email      string
	Name       string
	AvatarURL  string
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

type AgentSession added in v0.21.0

type AgentSession struct {
	ID                      uuid.UUID `gorm:"primaryKey;default:uuid_generate_v4()"`
	OrganizationID          uuid.UUID
	UserID                  uuid.UUID
	CanvasID                uuid.UUID
	Provider                string
	ProviderSessionID       string
	AgentToolSchemaRevision string
	Status                  string
	LastActiveAt            *time.Time
	HeartbeatAt             *time.Time
	ContextReplayedAt       *time.Time
	CreatedAt               *time.Time
	UpdatedAt               *time.Time
}

func FailStuckStreamingSessions added in v0.21.0

func FailStuckStreamingSessions(heartbeatCutoff, legacyCutoff time.Time) ([]AgentSession, error)

FailStuckStreamingSessions flags leaked streaming rows. Heartbeated rows use heartbeatCutoff (tight); rows with no heartbeat yet — pre-heartbeat binaries, or new turns before the worker's first tick — fall back to updated_at with legacyCutoff (loose, sized above agentStreamTimeout).

func FindAgentSession added in v0.21.0

func FindAgentSession(sessionID uuid.UUID) (*AgentSession, error)

func FindAgentSessionByCanvasInTransaction added in v0.21.0

func FindAgentSessionByCanvasInTransaction(tx *gorm.DB, organizationID, userID, canvasID uuid.UUID) (*AgentSession, error)

func FindAgentSessionForUser added in v0.21.0

func FindAgentSessionForUser(organizationID, userID, sessionID uuid.UUID) (*AgentSession, error)

func FindAgentSessionForUserInTransaction added in v0.21.0

func FindAgentSessionForUserInTransaction(tx *gorm.DB, organizationID, userID, sessionID uuid.UUID) (*AgentSession, error)

FindAgentSessionForUserInTransaction enforces ownership: sessions are private per user, so a session is invisible to anyone but its creator.

func FindAgentSessionInTransaction added in v0.21.0

func FindAgentSessionInTransaction(tx *gorm.DB, sessionID uuid.UUID) (*AgentSession, error)

func ListAgentSessionsForCanvasInTransaction added in v0.21.0

func ListAgentSessionsForCanvasInTransaction(tx *gorm.DB, organizationID, canvasID uuid.UUID) ([]AgentSession, error)

func ListAgentSessionsForOrganizationInTransaction added in v0.21.0

func ListAgentSessionsForOrganizationInTransaction(tx *gorm.DB, organizationID uuid.UUID) ([]AgentSession, error)

func LockAgentSessionInTransaction added in v0.26.0

func LockAgentSessionInTransaction(tx *gorm.DB, sessionID uuid.UUID) (*AgentSession, error)

func (AgentSession) TableName added in v0.21.0

func (AgentSession) TableName() string

type AgentSessionImage added in v0.26.0

type AgentSessionImage struct {
	MediaType string `json:"media_type"`
	Data      string `json:"data"`
}

AgentSessionImage is a base64-encoded image attached to a user message.

type AgentSessionMessage added in v0.21.0

type AgentSessionMessage struct {
	ID              uuid.UUID `gorm:"primaryKey;default:uuid_generate_v4()"`
	SessionID       uuid.UUID
	ProviderEventID string
	Role            string
	Content         string
	ToolCallID      string
	ToolName        string
	ToolStatus      string
	Images          datatypes.JSONSlice[AgentSessionImage]
	CreatedAt       *time.Time
}

func CloseOpenToolMessages added in v0.21.0

func CloseOpenToolMessages(sessionID uuid.UUID) ([]AgentSessionMessage, error)

CloseOpenToolMessages flips lingering "started" tool rows to "finished" and returns them, so callers can broadcast the closure.

func FindAgentSessionMessage added in v0.26.0

func FindAgentSessionMessage(tx *gorm.DB, id uuid.UUID) (*AgentSessionMessage, error)

func ListAgentSessionMessagesPage added in v0.21.0

func ListAgentSessionMessagesPage(sessionID uuid.UUID, before *AgentSessionMessage, limit int) ([]AgentSessionMessage, error)

ListAgentSessionMessagesPage returns up to `limit` messages strictly older than `before` (or the most recent `limit` when `before` is nil), in chronological order (oldest-first). Used for tail-paginated chat scroll.

func (AgentSessionMessage) TableName added in v0.21.0

func (AgentSessionMessage) TableName() string

type AppMessage added in v0.29.0

type AppMessage struct {
	ID        uuid.UUID
	CanvasID  uuid.UUID
	NodeID    string
	Payload   datatypes.JSON
	CreatedAt time.Time
}

func ListAppMessages added in v0.29.0

func ListAppMessages(tx *gorm.DB) ([]AppMessage, error)

func LockAppMessage added in v0.29.0

func LockAppMessage(tx *gorm.DB, id uuid.UUID) (*AppMessage, error)

func (*AppMessage) Delete added in v0.29.0

func (m *AppMessage) Delete(tx *gorm.DB) error

func (*AppMessage) TableName added in v0.29.0

func (m *AppMessage) TableName() string

type AttachAnalysisSessionParams

type AttachAnalysisSessionParams struct {
	Repository  string
	CanvasID    uuid.UUID
	CanvasRunID uuid.UUID
	WorkOrderID uuid.UUID
}

type BitbucketForgeDelivery

type BitbucketForgeDelivery struct {
	InstallationID     string
	WorkspaceUUID      string
	WorkspaceSlug      string
	InstallerAccountID string
	APIBaseURL         string
	SystemToken        []byte
	TokenExpiresAt     time.Time
	DeliveredAt        time.Time
	Uninstall          bool
}

BitbucketForgeDelivery is one Forge call that carries a system token.

type BitbucketForgeInstallation

type BitbucketForgeInstallation struct {
	InstallationID     string `gorm:"primaryKey"`
	WorkspaceUUID      string
	WorkspaceSlug      string
	InstallerAccountID string
	APIBaseURL         string
	SystemToken        []byte
	TokenExpiresAt     time.Time
	LastDeliveryAt     time.Time
	InstalledAt        time.Time
	UninstalledAt      *time.Time
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

BitbucketForgeInstallation is one install of the SuperPlane Forge app on a Bitbucket workspace. The system token is ciphertext. Callers encrypt and decrypt it outside this package.

func FindBitbucketForgeInstallation

func FindBitbucketForgeInstallation(tx *gorm.DB, installationID string) (*BitbucketForgeInstallation, error)

FindBitbucketForgeInstallation loads one Forge installation by id.

func ListActiveBitbucketForgeInstallations

func ListActiveBitbucketForgeInstallations(tx *gorm.DB) ([]BitbucketForgeInstallation, error)

ListActiveBitbucketForgeInstallations returns installations that still have a cached token and have not been uninstalled.

func SaveBitbucketForgeDelivery

func SaveBitbucketForgeDelivery(tx *gorm.DB, delivery BitbucketForgeDelivery) (*BitbucketForgeInstallation, error)

SaveBitbucketForgeDelivery stores a Forge delivery. A token is written only when it expires later than the cached token. LastDeliveryAt still moves forward so a short-lived token does not make a fresh installation look stale. Deliveries are serialized per installation, including the first delivery.

func (BitbucketForgeInstallation) Stale

func (row BitbucketForgeInstallation) Stale(now time.Time) bool

Stale reports that the cached token must not be used. A missing token, an uninstall, an expiry, or three hours without a Forge delivery all count.

func (BitbucketForgeInstallation) TableName

func (BitbucketForgeInstallation) TableName() string

type BrowserAction

type BrowserAction struct {
	URL         string
	Method      string
	FormFields  map[string]string
	Description string
}

type Canvas added in v0.6.0

type Canvas struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      *uuid.UUID
	LiveVersionID  *uuid.UUID
	Name           string
	Description    string
	// ColumnKey is the line-board column this factory event automation is
	// shown on. Empty when the canvas is not attached to Verify or Done.
	ColumnKey                   *string
	CreatedBy                   *uuid.UUID
	DismissedAgentSuggestionIDs datatypes.JSONSlice[string]
	CreatedAt                   *time.Time
	UpdatedAt                   *time.Time
	DeletedAt                   gorm.DeletedAt `gorm:"index"`
}

func FindCanvas added in v0.6.0

func FindCanvas(orgID, id uuid.UUID) (*Canvas, error)

func FindCanvasByName added in v0.6.0

func FindCanvasByName(tx *gorm.DB, organizationID uuid.UUID, factoryID *uuid.UUID, name string) (*Canvas, error)

FindCanvasByName looks a canvas up in the scope its name is unique in. Pass the factory ID to search inside a factory, or nil to search the canvases that no factory owns.

func FindCanvasInTransaction added in v0.6.0

func FindCanvasInTransaction(tx *gorm.DB, orgID, id uuid.UUID) (*Canvas, error)

func FindCanvasWithoutOrgScope added in v0.6.0

func FindCanvasWithoutOrgScope(id uuid.UUID) (*Canvas, error)

func FindCanvasWithoutOrgScopeInTransaction added in v0.6.0

func FindCanvasWithoutOrgScopeInTransaction(tx *gorm.DB, id uuid.UUID) (*Canvas, error)

func FindUnscopedCanvas added in v0.6.0

func FindUnscopedCanvas(id uuid.UUID) (*Canvas, error)

func FindUnscopedCanvasInTransaction added in v0.6.0

func FindUnscopedCanvasInTransaction(tx *gorm.DB, id uuid.UUID) (*Canvas, error)

func ListCanvases added in v0.6.0

func ListCanvases(orgID string) ([]Canvas, error)

func ListCanvasesPaginated added in v0.14.0

func ListCanvasesPaginated(orgID, search string, limit, offset int) ([]Canvas, int64, error)

func ListDeletedCanvases added in v0.6.0

func ListDeletedCanvases(db *gorm.DB) ([]Canvas, error)

func ListOrganizationCanvases

func ListOrganizationCanvases(tx *gorm.DB, organizationID uuid.UUID) ([]Canvas, error)

func LockCanvas added in v0.6.0

func LockCanvas(tx *gorm.DB, id uuid.UUID) (*Canvas, error)

func LockCanvasForUpdate added in v0.28.0

func LockCanvasForUpdate(tx *gorm.DB, organizationUUID, canvasID uuid.UUID) (*Canvas, error)

func LockUnscopedCanvas

func LockUnscopedCanvas(tx *gorm.DB, id uuid.UUID) (*Canvas, error)

LockUnscopedCanvas locks a canvas row whether or not it is soft-deleted. Callers that decide cleanup from deleted_at must lock first, because a restore can clear that timestamp after an unlocked read.

func (*Canvas) CountRuns added in v0.30.0

func (c *Canvas) CountRuns(db *gorm.DB) (int64, error)

func (*Canvas) DeleteRemainingResources added in v0.30.0

func (c *Canvas) DeleteRemainingResources(db *gorm.DB, maxRecords int) (*RunDeletionSummary, bool, error)

DeleteRemainingResources removes workflow execution rows still scoped to this canvas after all runs have been deleted via CanvasRun.DeleteChain.

Run cleanup covers the normal path: events, executions, queue items, KVs, and requests that belong to a run. This sweep is still required because some rows are workflow-scoped but not run-scoped — notably trigger node requests created without an execution_id (CanvasNode.CreateRequest). Orphan or inconsistent rows (e.g. nil run_id from partial routing) are also cleared here before nodes and the canvas row can be removed. Each call deletes at most maxRecords rows total, using SQL LIMIT per resource type so large orphan sets cannot time out.

func (*Canvas) DismissAgentSuggestion

func (c *Canvas) DismissAgentSuggestion(tx *gorm.DB, suggestionID string) error

DismissAgentSuggestion appends suggestionID to the canvas-scoped dismissal list.

func (*Canvas) FindNode added in v0.6.0

func (c *Canvas) FindNode(id string) (*CanvasNode, error)

func (*Canvas) ListRuns added in v0.30.0

func (c *Canvas) ListRuns(db *gorm.DB, limit int) ([]CanvasRun, error)

func (*Canvas) SetColumnKey

func (c *Canvas) SetColumnKey(tx *gorm.DB, key string) error

SetColumnKey attaches this factory canvas to a board column. An empty key clears the attachment.

func (*Canvas) SoftDelete added in v0.6.0

func (c *Canvas) SoftDelete() error

func (*Canvas) SoftDeleteInTransaction added in v0.6.0

func (c *Canvas) SoftDeleteInTransaction(tx *gorm.DB) error

func (*Canvas) StampFactoryAppTemplate

func (c *Canvas) StampFactoryAppTemplate(tx *gorm.DB, triggerNodeID, templateID string, version int) error

StampFactoryAppTemplate records template identity in the live version and its normalized trigger node. Canvas changesets keep component metadata private, so generated templates stamp this server-owned key after publish.

func (*Canvas) StampFactoryAppTemplateFor

func (c *Canvas) StampFactoryAppTemplateFor(tx *gorm.DB, triggerNodeID, templateID string, version int, provider string) error

StampFactoryAppTemplateFor records template identity and the Git host.

func (*Canvas) TableName added in v0.6.0

func (c *Canvas) TableName() string

type CanvasEvent added in v0.6.0

type CanvasEvent struct {
	ID          uuid.UUID `gorm:"primaryKey;default:uuid_generate_v4()"`
	WorkflowID  uuid.UUID
	NodeID      string
	Channel     string
	CustomName  *string
	DedupKey    *string
	Data        JSONValue
	ExecutionID *uuid.UUID
	RunID       uuid.UUID
	State       string
	CreatedAt   *time.Time
}

func FindCanvasEvent added in v0.6.0

func FindCanvasEvent(id uuid.UUID) (*CanvasEvent, error)

func FindCanvasEventForCanvas added in v0.6.0

func FindCanvasEventForCanvas(db *gorm.DB, canvasID uuid.UUID, id uuid.UUID) (*CanvasEvent, error)

func FindCanvasEventInTransaction added in v0.6.0

func FindCanvasEventInTransaction(tx *gorm.DB, id uuid.UUID) (*CanvasEvent, error)

func FindCanvasEvents added in v0.6.0

func FindCanvasEvents(tx *gorm.DB, ids []string) ([]CanvasEvent, error)

func FindCanvasEventsForExecutions added in v0.6.0

func FindCanvasEventsForExecutions(tx *gorm.DB, executionIDs []string) ([]CanvasEvent, error)

func FindLastEventPerNode

func FindLastEventPerNode(tx *gorm.DB, canvasID uuid.UUID) ([]CanvasEvent, error)

FindLastEventPerNode finds the most recent event for each node in a workflow. Only returns events for nodes that have not been deleted.

func FindRootEventForRun

func FindRootEventForRun(tx *gorm.DB, runID uuid.UUID) (*CanvasEvent, error)

func ListCanvasEvents added in v0.6.0

func ListCanvasEvents(db *gorm.DB, canvasID uuid.UUID, nodeID string, limit int, before *time.Time) ([]CanvasEvent, error)

func ListCanvasEventsByIDsInTransaction added in v0.25.1

func ListCanvasEventsByIDsInTransaction(tx *gorm.DB, ids []uuid.UUID) ([]CanvasEvent, error)

func ListCanvasEventsForExecutionsInTransaction added in v0.6.0

func ListCanvasEventsForExecutionsInTransaction(tx *gorm.DB, executionIDs []uuid.UUID) ([]CanvasEvent, error)

func ListPendingCanvasEvents added in v0.6.0

func ListPendingCanvasEvents() ([]CanvasEvent, error)

func LockCanvasEvent added in v0.6.0

func LockCanvasEvent(tx *gorm.DB, id uuid.UUID) (*CanvasEvent, error)

func (*CanvasEvent) BeforeCreate added in v0.21.0

func (e *CanvasEvent) BeforeCreate(tx *gorm.DB) error

func (*CanvasEvent) Routed added in v0.6.0

func (e *CanvasEvent) Routed() error

func (*CanvasEvent) RoutedInTransaction added in v0.6.0

func (e *CanvasEvent) RoutedInTransaction(tx *gorm.DB) error

func (*CanvasEvent) TableName added in v0.6.0

func (e *CanvasEvent) TableName() string

type CanvasMemory added in v0.10.0

type CanvasMemory struct {
	ID        uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	CreatedAt time.Time
	UpdatedAt time.Time
	CanvasID  uuid.UUID
	Namespace string
	Values    datatypes.JSONType[any]
	Source    string
}

func AddCanvasMemoryRecordInTransaction added in v0.23.0

func AddCanvasMemoryRecordInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string, values any) (CanvasMemory, error)

func AddCanvasMemoryRecordWithSourceInTransaction added in v0.25.0

func AddCanvasMemoryRecordWithSourceInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string, values any, source string) (CanvasMemory, error)

func DeleteCanvasMemoriesByNamespaceAndMatches added in v0.10.0

func DeleteCanvasMemoriesByNamespaceAndMatches(canvasID uuid.UUID, namespace string, matches map[string]any) ([]CanvasMemory, error)

func DeleteCanvasMemoriesByNamespaceAndMatchesInTransaction added in v0.10.0

func DeleteCanvasMemoriesByNamespaceAndMatchesInTransaction(
	tx *gorm.DB,
	canvasID uuid.UUID,
	namespace string,
	matches map[string]any,
) ([]CanvasMemory, error)

func FindFirstCanvasMemoryByNamespaceAndMatches added in v0.10.0

func FindFirstCanvasMemoryByNamespaceAndMatches(canvasID uuid.UUID, namespace string, matches map[string]any) (*CanvasMemory, error)

func FindFirstCanvasMemoryByNamespaceAndMatchesInTransaction added in v0.10.0

func FindFirstCanvasMemoryByNamespaceAndMatchesInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string, matches map[string]any) (*CanvasMemory, error)

func ListCanvasMemories added in v0.10.0

func ListCanvasMemories(canvasID uuid.UUID) ([]CanvasMemory, error)

func ListCanvasMemoriesByNamespace added in v0.10.0

func ListCanvasMemoriesByNamespace(canvasID uuid.UUID, namespace string) ([]CanvasMemory, error)

func ListCanvasMemoriesByNamespaceAndMatches added in v0.10.0

func ListCanvasMemoriesByNamespaceAndMatches(canvasID uuid.UUID, namespace string, matches map[string]any) ([]CanvasMemory, error)

func ListCanvasMemoriesByNamespaceAndMatchesInTransaction added in v0.10.0

func ListCanvasMemoriesByNamespaceAndMatchesInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string, matches map[string]any) ([]CanvasMemory, error)

func ListCanvasMemoriesByNamespaceInTransaction added in v0.10.0

func ListCanvasMemoriesByNamespaceInTransaction(tx *gorm.DB, canvasID uuid.UUID, namespace string) ([]CanvasMemory, error)

func ListCanvasMemoriesInTransaction added in v0.10.0

func ListCanvasMemoriesInTransaction(tx *gorm.DB, canvasID uuid.UUID) ([]CanvasMemory, error)

func UpdateCanvasMemoriesByNamespace added in v0.23.0

func UpdateCanvasMemoriesByNamespace(canvasID uuid.UUID, namespace string, values map[string]any) ([]CanvasMemory, error)

func UpdateCanvasMemoriesByNamespaceAndMatches added in v0.10.0

func UpdateCanvasMemoriesByNamespaceAndMatches(canvasID uuid.UUID, namespace string, matches map[string]any, values map[string]any) ([]CanvasMemory, error)

func UpdateCanvasMemoriesByNamespaceAndMatchesInTransaction added in v0.10.0

func UpdateCanvasMemoriesByNamespaceAndMatchesInTransaction(
	tx *gorm.DB,
	canvasID uuid.UUID,
	namespace string,
	matches map[string]any,
	values map[string]any,
) ([]CanvasMemory, error)

func UpdateCanvasMemoriesByNamespaceInTransaction added in v0.23.0

func UpdateCanvasMemoriesByNamespaceInTransaction(
	tx *gorm.DB,
	canvasID uuid.UUID,
	namespace string,
	values map[string]any,
) ([]CanvasMemory, error)

func (CanvasMemory) TableName added in v0.10.0

func (CanvasMemory) TableName() string

type CanvasNode added in v0.6.0

type CanvasNode struct {
	WorkflowID    uuid.UUID `gorm:"primaryKey"`
	NodeID        string    `gorm:"primaryKey"`
	Name          string
	State         string
	StateReason   *string
	Type          string
	Position      datatypes.JSONType[Position]
	Ref           datatypes.JSONType[NodeRef]
	Configuration datatypes.JSONType[map[string]any]
	Metadata      datatypes.JSONType[map[string]any]
	IsCollapsed   bool

	//
	// The node's inline concurrency configuration. Each field defaults
	// independently, so all-NULL means the default behavior: one
	// execution at a time in the node's implicit queue. The key may
	// contain {{ }} expressions resolved per queue item.
	//
	ConcurrencyKey *string
	ConcurrencyMax *int

	WebhookID         *uuid.UUID
	AppInstallationID *uuid.UUID
	CreatedAt         *time.Time
	UpdatedAt         *time.Time
	DeletedAt         gorm.DeletedAt `gorm:"index"`
}

func FindActiveWebhookNodes added in v0.20.0

func FindActiveWebhookNodes(webhookID uuid.UUID) ([]CanvasNode, error)

func FindActiveWebhookNodesInTransaction added in v0.20.0

func FindActiveWebhookNodesInTransaction(tx *gorm.DB, webhookID uuid.UUID) ([]CanvasNode, error)

func FindCanvasNode added in v0.6.0

func FindCanvasNode(tx *gorm.DB, canvasID uuid.UUID, nodeID string) (*CanvasNode, error)

func FindCanvasNodes added in v0.6.0

func FindCanvasNodes(canvasID uuid.UUID) ([]CanvasNode, error)

func FindCanvasNodesByIDs added in v0.6.0

func FindCanvasNodesByIDs(tx *gorm.DB, canvasID uuid.UUID, nodeIDs []string) ([]CanvasNode, error)

func FindCanvasNodesInTransaction added in v0.6.0

func FindCanvasNodesInTransaction(tx *gorm.DB, workflowID uuid.UUID) ([]CanvasNode, error)

func FindCanvasNodesUnscoped added in v0.6.0

func FindCanvasNodesUnscoped(workflowID uuid.UUID) ([]CanvasNode, error)

func FindCanvasNodesUnscopedInTransaction added in v0.6.0

func FindCanvasNodesUnscopedInTransaction(tx *gorm.DB, workflowID uuid.UUID) ([]CanvasNode, error)

func FindUnscopedCanvasNode added in v0.27.0

func FindUnscopedCanvasNode(tx *gorm.DB, canvasID uuid.UUID, nodeID string) (*CanvasNode, error)

func FindWebhookNodes

func FindWebhookNodes(webhookID uuid.UUID) ([]CanvasNode, error)

func FindWebhookNodesInTransaction

func FindWebhookNodesInTransaction(tx *gorm.DB, webhookID uuid.UUID) ([]CanvasNode, error)

func ListCanvasNodesReady added in v0.6.0

func ListCanvasNodesReady(tx *gorm.DB) ([]CanvasNode, error)

ListCanvasNodesReady returns the component nodes with at least one actionable pending queue item, i.e. the nodes a dispatch pass can make progress on. A pending item is actionable when any of these holds:

  • it has no queue name: either not resolved yet (capacity is unknown until then) or the node's component manages its own queue items (never capacity-gated, never resolved — merge, loop);
  • the item's queue has fewer active executions than the node's concurrency max.

Nodes whose entire backlog waits on full queues are excluded: they become actionable again when an execution leaves an active state, so the next poll returns them.

func ListFactoryAppTemplateNodes

func ListFactoryAppTemplateNodes(tx *gorm.DB, organizationID, factoryID uuid.UUID, templateID string) ([]CanvasNode, error)

func ListReadyTriggers

func ListReadyTriggers() ([]CanvasNode, error)

func ListRetiredTriggerNodes

func ListRetiredTriggerNodes(tx *gorm.DB, triggerName, metadataIDKey string) ([]CanvasNode, error)

ListRetiredTriggerNodes returns trigger nodes whose removal is committed. A node is retired when the node itself is soft-deleted or its canvas is soft-deleted. metadataIDKey selects nodes that still store an external id.

func LockCanvasNode added in v0.6.0

func LockCanvasNode(tx *gorm.DB, workflowID uuid.UUID, nodeId string) (*CanvasNode, error)

func LockCanvasNodeForUpdate added in v0.6.0

func LockCanvasNodeForUpdate(tx *gorm.DB, workflowID uuid.UUID, nodeId string) (*CanvasNode, error)

func LockUnscopedCanvasNode

func LockUnscopedCanvasNode(tx *gorm.DB, workflowID uuid.UUID, nodeID string) (*CanvasNode, error)

LockUnscopedCanvasNode locks a node even when the node or its canvas is already soft-deleted. SKIP LOCKED returns ErrRecordNotFound when another worker holds the row.

func (*CanvasNode) ComponentName added in v0.26.0

func (c *CanvasNode) ComponentName() string

func (*CanvasNode) ConcurrencySpec

func (c *CanvasNode) ConcurrencySpec() *ConcurrencySpec

ConcurrencySpec returns the node's inline concurrency configuration, or nil when the node uses the default (one execution at a time).

func (*CanvasNode) CreateGitHubChecksEvent

func (n *CanvasNode) CreateGitHubChecksEvent(tx *gorm.DB, event *CanvasEvent) (bool, error)

CreateGitHubChecksEvent serializes startup and webhook delivery for one handler revision. The same delivery stays a duplicate after the run finishes. A later reopen, ready-for-review, or new push starts again only when its pull request time is newer than the stored snapshot.

func (*CanvasNode) CreateRequest added in v0.6.0

func (c *CanvasNode) CreateRequest(tx *gorm.DB, reqType string, spec NodeExecutionRequestSpec, runAt *time.Time) error

func (*CanvasNode) CreateVisualEvidenceCaptureRequest

func (c *CanvasNode) CreateVisualEvidenceCaptureRequest(
	tx *gorm.DB,
	capture VisualEvidenceCaptureRequest,
	runAt time.Time,
) (*CanvasNodeRequest, error)

func (*CanvasNode) FirstQueueItem added in v0.6.0

func (c *CanvasNode) FirstQueueItem(tx *gorm.DB) (*CanvasNodeQueueItem, error)

func (*CanvasNode) ListPendingQueueItems

func (c *CanvasNode) ListPendingQueueItems(tx *gorm.DB, limit int) ([]CanvasNodeQueueItem, error)

ListPendingQueueItems returns the node's actionable backlog in FIFO order, up to limit items. Items whose resolved queue is already at capacity are excluded, so a deep backlog on one busy queue cannot fill the scan window and starve items of other queues. Items without a queue name always qualify: either the name is not resolved yet (capacity is unknown until then) or the node's component manages its own queue items and is never capacity-gated.

func (*CanvasNode) SetConcurrencySpec

func (c *CanvasNode) SetConcurrencySpec(spec *ConcurrencySpec)

SetConcurrencySpec stores a concurrency spec on the node's columns. Empty fields are stored as NULL, so an absent spec and a spec with all fields empty are the same (default) configuration.

func (*CanvasNode) TableName added in v0.6.0

func (c *CanvasNode) TableName() string

func (*CanvasNode) UpdateState added in v0.6.0

func (c *CanvasNode) UpdateState(tx *gorm.DB, state string) error

type CanvasNodeExecution added in v0.6.0

type CanvasNodeExecution struct {
	ID         uuid.UUID `gorm:"primaryKey;default:uuid_generate_v4()"`
	WorkflowID uuid.UUID
	NodeID     string
	CreatedAt  *time.Time
	UpdatedAt  *time.Time

	//
	// Reference to the root WorkflowEvent record that started
	// this whole execution chain.
	//
	// This gives us an easy way to find all the executions
	// for that event with a simple query.
	//
	RootEventID uuid.UUID
	RunID       uuid.UUID

	//
	// Reference to the previous execution.
	// This is what allows us to build execution chains,
	// from any execution.
	//
	PreviousExecutionID *uuid.UUID

	//
	// The reference to a WorkflowEvent record,
	// which holds the input for this execution.
	//
	EventID uuid.UUID

	//
	// The resolved queue name this execution occupies a slot in.
	// Node-queue capacity is a count of active executions per queue name.
	//
	QueueName *string

	//
	// State management fields.
	//
	State         string
	Result        string
	ResultReason  string
	ResultMessage string
	CancelledBy   *uuid.UUID
	CancelledAt   *time.Time

	//
	// Components can store metadata about each execution here.
	// This allows them to control the behavior of each execution.
	//
	Metadata datatypes.JSONType[map[string]any]

	//
	// The configuration is copied from the node.
	// This enables us to allow node configuration updates
	// while executions are running.
	// Only new executions will use the new node configuration.
	//
	Configuration datatypes.JSONType[map[string]any]
}

func FindLastExecutionPerNode

func FindLastExecutionPerNode(tx *gorm.DB, workflowID uuid.UUID) ([]CanvasNodeExecution, error)

FindLastExecutionPerNode finds the most recent execution for each node in a workflow. Only returns executions for nodes that have not been deleted.

func FindNodeExecution

func FindNodeExecution(workflowID, id uuid.UUID) (*CanvasNodeExecution, error)

func FindNodeExecutionInTransaction

func FindNodeExecutionInTransaction(tx *gorm.DB, workflowID, id uuid.UUID) (*CanvasNodeExecution, error)

func FindNodeExecutionWithNodeID

func FindNodeExecutionWithNodeID(workflowID, id uuid.UUID, nodeID string) (*CanvasNodeExecution, error)

func FindNodeExecutionWithNodeIDInTransaction

func FindNodeExecutionWithNodeIDInTransaction(tx *gorm.DB, workflowID, id uuid.UUID, nodeID string) (*CanvasNodeExecution, error)

func FindNodeExecutionsByIDs added in v0.1.5

func FindNodeExecutionsByIDs(workflowID uuid.UUID, executionIDs []uuid.UUID) ([]CanvasNodeExecution, error)

func FindNodeExecutionsByIDsInTransaction added in v0.1.5

func FindNodeExecutionsByIDsInTransaction(tx *gorm.DB, workflowID uuid.UUID, executionIDs []uuid.UUID) ([]CanvasNodeExecution, error)

func FirstActiveNodeExecutionByKV

func FirstActiveNodeExecutionByKV(tx *gorm.DB, workflowID uuid.UUID, nodeID, key, value string) (*CanvasNodeExecution, error)

FirstActiveNodeExecutionByKV resolves the oldest active execution a key/value pair points at. It exists for Bitbucket build waits, where repeated waits for the same repository and SHA can leave a completed wait sharing a KV with a later active wait; the oldest-wins lookup would route build events to the completed wait and hide the active one. Other components keep the oldest-wins behavior. When several waits are active, the event wakes one and polling remains the fallback for the rest.

func FirstNodeExecutionByKVInTransaction

func FirstNodeExecutionByKVInTransaction(tx *gorm.DB, workflowID uuid.UUID, nodeID, key, value string) (*CanvasNodeExecution, error)

FirstNodeExecutionByKVInTransaction resolves the execution a key/value pair points at, e.g. an external correlation ID stored by a component. Values are expected to identify exactly one execution within a node. When more than one execution matches, the oldest wins — preserved behavior — and an error is logged, because a collision means a component stored a value that is not unique per execution and webhooks or integration messages may be routed to the wrong execution.

func ListActiveNodeExecutions added in v0.29.0

func ListActiveNodeExecutions(tx *gorm.DB, workflowID uuid.UUID, nodeID string) ([]CanvasNodeExecution, error)

func ListAllExecutionsForRootEvent added in v0.15.0

func ListAllExecutionsForRootEvent(rootEventID uuid.UUID) ([]CanvasNodeExecution, error)

func ListAllExecutionsForRootEventInTransaction added in v0.15.0

func ListAllExecutionsForRootEventInTransaction(tx *gorm.DB, rootEventID uuid.UUID) ([]CanvasNodeExecution, error)

func ListCancellingNodeExecutions added in v0.30.0

func ListCancellingNodeExecutions(db *gorm.DB) ([]CanvasNodeExecution, error)

func ListExecutionsForRunsInTransaction added in v0.26.0

func ListExecutionsForRunsInTransaction(tx *gorm.DB, workflowID uuid.UUID, runIDs []uuid.UUID) ([]CanvasNodeExecution, error)

func ListNodeExecutions

func ListNodeExecutions(db *gorm.DB, workflowID uuid.UUID, nodeID string, states []string, results []string, limit int, beforeTime *time.Time) ([]CanvasNodeExecution, error)

func ListParentExecutionsForRootEvents added in v0.15.0

func ListParentExecutionsForRootEvents(canvasID uuid.UUID, rootEventIDs []uuid.UUID) ([]CanvasNodeExecution, error)

func ListParentExecutionsForRootEventsInTransaction added in v0.15.0

func ListParentExecutionsForRootEventsInTransaction(tx *gorm.DB, canvasID uuid.UUID, rootEventIDs []uuid.UUID) ([]CanvasNodeExecution, error)

func ListPendingNodeExecutions

func ListPendingNodeExecutions() ([]CanvasNodeExecution, error)

func LockCancellingNodeExecutionInActiveCanvas added in v0.30.0

func LockCancellingNodeExecutionInActiveCanvas(tx *gorm.DB, id uuid.UUID) (*CanvasNodeExecution, error)

func LockPendingNodeExecutionInActiveCanvas added in v0.20.0

func LockPendingNodeExecutionInActiveCanvas(tx *gorm.DB, id uuid.UUID) (*CanvasNodeExecution, error)

func (*CanvasNodeExecution) BeforeCreate added in v0.21.0

func (e *CanvasNodeExecution) BeforeCreate(tx *gorm.DB) error

func (*CanvasNodeExecution) Cancel added in v0.6.0

func (e *CanvasNodeExecution) Cancel(cancelledBy *uuid.UUID) error

func (*CanvasNodeExecution) CancelInTransaction added in v0.6.0

func (e *CanvasNodeExecution) CancelInTransaction(tx *gorm.DB, cancelledBy *uuid.UUID) error

func (*CanvasNodeExecution) CreateRequest added in v0.6.0

func (e *CanvasNodeExecution) CreateRequest(tx *gorm.DB, reqType string, spec NodeExecutionRequestSpec, runAt *time.Time) error

func (*CanvasNodeExecution) EmitOutputsInTransaction added in v0.26.0

func (e *CanvasNodeExecution) EmitOutputsInTransaction(tx *gorm.DB, channelOutputs map[string][]any) ([]CanvasEvent, error)

func (*CanvasNodeExecution) Fail added in v0.6.0

func (e *CanvasNodeExecution) Fail(reason, message string) error

func (*CanvasNodeExecution) FailInTransaction added in v0.6.0

func (e *CanvasNodeExecution) FailInTransaction(tx *gorm.DB, reason, message string) (bool, error)

func (*CanvasNodeExecution) FrozenComponentName

func (e *CanvasNodeExecution) FrozenComponentName() string

func (*CanvasNodeExecution) GetInput added in v0.6.0

func (e *CanvasNodeExecution) GetInput(tx *gorm.DB) (any, error)

func (*CanvasNodeExecution) GetOutputs added in v0.6.0

func (e *CanvasNodeExecution) GetOutputs() ([]CanvasEvent, error)

func (*CanvasNodeExecution) GetOutputsInTransaction added in v0.6.0

func (e *CanvasNodeExecution) GetOutputsInTransaction(tx *gorm.DB) ([]CanvasEvent, error)

func (*CanvasNodeExecution) GetPreviousExecutionID added in v0.6.0

func (e *CanvasNodeExecution) GetPreviousExecutionID() string

func (*CanvasNodeExecution) IsFinished added in v0.29.0

func (e *CanvasNodeExecution) IsFinished(tx *gorm.DB) (bool, error)

func (*CanvasNodeExecution) Pass added in v0.6.0

func (e *CanvasNodeExecution) Pass(outputs map[string][]any) ([]CanvasEvent, error)

func (*CanvasNodeExecution) PassInTransaction added in v0.6.0

func (e *CanvasNodeExecution) PassInTransaction(tx *gorm.DB, channelOutputs map[string][]any) ([]CanvasEvent, error)

func (*CanvasNodeExecution) RequestCancellation added in v0.30.0

func (e *CanvasNodeExecution) RequestCancellation(tx *gorm.DB, cancelledBy *uuid.UUID) error

func (*CanvasNodeExecution) Start added in v0.6.0

func (e *CanvasNodeExecution) Start() error

func (*CanvasNodeExecution) StartInTransaction added in v0.6.0

func (e *CanvasNodeExecution) StartInTransaction(tx *gorm.DB) error

func (*CanvasNodeExecution) TableName added in v0.6.0

func (e *CanvasNodeExecution) TableName() string

type CanvasNodeExecutionKV added in v0.6.0

type CanvasNodeExecutionKV struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey;default:gen_random_uuid()"`
	WorkflowID  uuid.UUID `gorm:"type:uuid;not null"`
	NodeID      string    `gorm:"type:varchar(128);not null"`
	ExecutionID uuid.UUID `gorm:"type:uuid;not null"`
	Key         string    `gorm:"type:text;not null"`
	Value       string    `gorm:"type:text;not null"`
	CreatedAt   *time.Time
}

func (*CanvasNodeExecutionKV) TableName added in v0.6.0

func (c *CanvasNodeExecutionKV) TableName() string

type CanvasNodeQueueItem added in v0.6.0

type CanvasNodeQueueItem struct {
	ID         uuid.UUID `gorm:"primaryKey;default:uuid_generate_v4()"`
	WorkflowID uuid.UUID
	NodeID     string
	CreatedAt  *time.Time

	//
	// Reference to the root WorkflowEvent record that started
	// this whole execution chain.
	//
	// This gives us an easy way to find all the queue items
	// for that event with a simple query.
	//
	RootEventID uuid.UUID
	RootEvent   *CanvasEvent `gorm:"foreignKey:RootEventID"`
	RunID       uuid.UUID

	//
	// The reference to a CanvasEvent record,
	// which holds the input for this queue item.
	//
	EventID uuid.UUID

	//
	// The resolved queue name for this item. Nil until the queue worker
	// touches the item for the first time; the resolution is persisted so
	// name expressions are evaluated exactly once per item.
	//
	QueueName *string
}

func FindNodeQueueItem

func FindNodeQueueItem(workflowID uuid.UUID, queueItemID uuid.UUID) (*CanvasNodeQueueItem, error)

func ListNodeQueueItems

func ListNodeQueueItems(db *gorm.DB, workflowID uuid.UUID, nodeID string, limit int, beforeTime *time.Time) ([]CanvasNodeQueueItem, error)

func ListNodeQueueItemsForRuns added in v0.29.0

func ListNodeQueueItemsForRuns(tx *gorm.DB, workflowID uuid.UUID, runIDs []uuid.UUID) ([]CanvasNodeQueueItem, error)

func (*CanvasNodeQueueItem) BeforeCreate added in v0.21.0

func (i *CanvasNodeQueueItem) BeforeCreate(tx *gorm.DB) error

func (*CanvasNodeQueueItem) Delete added in v0.6.0

func (i *CanvasNodeQueueItem) Delete(tx *gorm.DB) error

func (*CanvasNodeQueueItem) TableName added in v0.6.0

func (i *CanvasNodeQueueItem) TableName() string

type CanvasNodeReference added in v0.7.0

type CanvasNodeReference struct {
	CanvasID   uuid.UUID
	CanvasName string
	NodeID     string
	NodeName   string
	NodeType   string
	NodeRef    datatypes.JSONType[NodeRef]
}

func ListIntegrationNodeReferences added in v0.6.0

func ListIntegrationNodeReferences(integrationID uuid.UUID) ([]CanvasNodeReference, error)

func (*CanvasNodeReference) ComponentName added in v0.20.0

func (c *CanvasNodeReference) ComponentName() string

type CanvasNodeRequest added in v0.6.0

type CanvasNodeRequest struct {
	ID          uuid.UUID
	WorkflowID  uuid.UUID
	NodeID      string
	ExecutionID *uuid.UUID
	State       string
	Type        string
	Spec        datatypes.JSONType[NodeExecutionRequestSpec]
	RunAt       time.Time
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

func ClaimDuePullRequestChecksStartRequest

func ClaimDuePullRequestChecksStartRequest(tx *gorm.DB, id uuid.UUID, leaseUntil time.Time) (*CanvasNodeRequest, error)

func ClaimDueVisualEvidenceCaptureRequest

func ClaimDueVisualEvidenceCaptureRequest(tx *gorm.DB, id uuid.UUID, leaseUntil time.Time) (*CanvasNodeRequest, error)

func FindCanvasNodeRequest

func FindCanvasNodeRequest(tx *gorm.DB, id uuid.UUID) (*CanvasNodeRequest, error)

func FindPendingRequestForNode

func FindPendingRequestForNode(tx *gorm.DB, workflowID uuid.UUID, nodeID string) (*CanvasNodeRequest, error)

func FindPendingVisualEvidenceCaptureRequest

func FindPendingVisualEvidenceCaptureRequest(
	tx *gorm.DB,
	canvasID uuid.UUID,
	nodeID string,
	pullRequestID uuid.UUID,
) (*CanvasNodeRequest, error)

func ListDuePullRequestChecksStartRequests

func ListDuePullRequestChecksStartRequests(tx *gorm.DB) ([]CanvasNodeRequest, error)

Include requests whose canvas was deleted so the processor can retire them.

func ListNodeRequests

func ListNodeRequests() ([]CanvasNodeRequest, error)

func ListPullRequestChecksStartRequests

func ListPullRequestChecksStartRequests(tx *gorm.DB, pullRequestID uuid.UUID) ([]CanvasNodeRequest, error)

func LockNodeRequest

func LockNodeRequest(tx *gorm.DB, id uuid.UUID) (*CanvasNodeRequest, error)

func (*CanvasNodeRequest) Complete added in v0.6.0

func (r *CanvasNodeRequest) Complete(tx *gorm.DB) error

func (*CanvasNodeRequest) Reschedule

func (r *CanvasNodeRequest) Reschedule(tx *gorm.DB, runAt time.Time) error

func (*CanvasNodeRequest) TableName added in v0.6.0

func (r *CanvasNodeRequest) TableName() string

type CanvasRun added in v0.21.0

type CanvasRun struct {
	ID                uuid.UUID `gorm:"primaryKey;default:uuid_generate_v4()"`
	WorkflowID        uuid.UUID
	NodeID            string
	VersionID         uuid.UUID
	ParentRunID       *uuid.UUID
	ParentWorkflowID  *uuid.UUID
	ParentExecutionID *uuid.UUID
	Callbacks         datatypes.JSONSlice[core.RunCallback]
	Input             JSONValue
	State             string
	Result            string
	Errors            datatypes.JSONSlice[RunError]
	CreatedAt         *time.Time
	UpdatedAt         *time.Time
	CancelledAt       *time.Time
	CancelledBy       *uuid.UUID
	FinishedAt        *time.Time
}

func CreateCanvasRunInTransaction added in v0.21.0

func CreateCanvasRunInTransaction(tx *gorm.DB, workflowID uuid.UUID, nodeID, state, result string) (*CanvasRun, error)

func FindCanvasRunByRootEventInTransaction added in v0.21.0

func FindCanvasRunByRootEventInTransaction(db *gorm.DB, rootEventID uuid.UUID) (*CanvasRun, error)

func FindCanvasRunInTransaction added in v0.21.0

func FindCanvasRunInTransaction(db *gorm.DB, workflowID, runID uuid.UUID) (*CanvasRun, error)

func FindCanvasRunsByKeys added in v0.30.0

func FindCanvasRunsByKeys(tx *gorm.DB, keys []CanvasRunKey) ([]CanvasRun, error)

func FindOrCreateCanvasRunForRootEventInTransaction added in v0.21.0

func FindOrCreateCanvasRunForRootEventInTransaction(tx *gorm.DB, rootEvent *CanvasEvent) (*CanvasRun, error)

func FindUnscopedCanvasRun

func FindUnscopedCanvasRun(db *gorm.DB, runID uuid.UUID) (*CanvasRun, error)

func ListCancellingCanvasRuns added in v0.30.0

func ListCancellingCanvasRuns(db *gorm.DB, limit int) ([]CanvasRun, error)

func ListCanvasRuns added in v0.21.0

func ListCanvasRuns(workflowID uuid.UUID, limit int, beforeTime *time.Time, filters CanvasRunFilters) ([]CanvasRun, error)

func ListCanvasRunsInTransaction added in v0.26.0

func ListCanvasRunsInTransaction(tx *gorm.DB, workflowID uuid.UUID, limit int, beforeTime *time.Time, filters CanvasRunFilters) ([]CanvasRun, error)

func ListChildRunsByParentExecutions added in v0.30.0

func ListChildRunsByParentExecutions(tx *gorm.DB, parentWorkflowID uuid.UUID, parentExecutionIDs []uuid.UUID) ([]CanvasRun, error)

func ListExpiredFinishedRuns added in v0.30.0

func ListExpiredFinishedRuns(db *gorm.DB, referenceTime time.Time, limit int) ([]CanvasRun, error)

func ListPendingRuns added in v0.30.0

func ListPendingRuns(tx *gorm.DB) ([]CanvasRun, error)

func ListStartedCanvasRuns added in v0.26.0

func ListStartedCanvasRuns(db *gorm.DB, limit int) ([]CanvasRun, error)

func LockCanvasRun added in v0.30.0

func LockCanvasRun(db *gorm.DB, workflowID, runID uuid.UUID) (*CanvasRun, error)

func LockCanvasRunInTransaction added in v0.26.0

func LockCanvasRunInTransaction(tx *gorm.DB, runID uuid.UUID) (*CanvasRun, error)

func LockExpiredFinishedRun added in v0.30.0

func LockExpiredFinishedRun(db *gorm.DB, referenceTime time.Time, runID uuid.UUID) (*CanvasRun, error)

func (*CanvasRun) AddError

func (r *CanvasRun) AddError(tx *gorm.DB, message string, maxSize int) error

* Appends a new error into the run errors slice. * Locks the run with FOR NO KEY UPDATE so concurrent appends do not * overwrite each other, while child FK inserts on the run can proceed.

func (*CanvasRun) CalculateResult added in v0.30.0

func (r *CanvasRun) CalculateResult(tx *gorm.DB) (string, error)

func (*CanvasRun) DeleteChain added in v0.30.0

func (r *CanvasRun) DeleteChain(db *gorm.DB) (*RunDeletionSummary, error)

func (*CanvasRun) DeleteQueueItems added in v0.30.0

func (r *CanvasRun) DeleteQueueItems(tx *gorm.DB) ([]CanvasNodeQueueItem, error)

func (*CanvasRun) DrainForCancellation added in v0.30.0

func (r *CanvasRun) DrainForCancellation(tx *gorm.DB, cancelledBy *uuid.UUID) (*RunCancellationDrainResult, error)

func (*CanvasRun) ErrorMessages

func (r *CanvasRun) ErrorMessages() []string

func (*CanvasRun) FindOpenWork added in v0.30.0

func (r *CanvasRun) FindOpenWork(tx *gorm.DB) (*OpenCanvasRunWork, error)

func (*CanvasRun) FindTargetNode added in v0.30.0

func (r *CanvasRun) FindTargetNode(tx *gorm.DB) (*CanvasNode, error)

func (*CanvasRun) ListExecutionsInStates added in v0.30.0

func (r *CanvasRun) ListExecutionsInStates(tx *gorm.DB, states []string) ([]CanvasNodeExecution, error)

func (*CanvasRun) MarkAsCancelling added in v0.30.0

func (r *CanvasRun) MarkAsCancelling(tx *gorm.DB, cancelledBy *uuid.UUID) error

func (*CanvasRun) RequestCancellation

func (r *CanvasRun) RequestCancellation(tx *gorm.DB, cancelledBy *uuid.UUID) (*RunCancellationResult, error)

func (*CanvasRun) RequestCompletion

func (r *CanvasRun) RequestCompletion(tx *gorm.DB, completedBy *uuid.UUID) (*RunCancellationResult, error)

RequestCompletion stops unfinished work while preserving a successful run result.

func (*CanvasRun) Start added in v0.30.0

func (r *CanvasRun) Start(db *gorm.DB) error

func (*CanvasRun) SupersedePendingEvents added in v0.30.0

func (r *CanvasRun) SupersedePendingEvents(tx *gorm.DB) ([]CanvasEvent, error)

func (*CanvasRun) TableName added in v0.21.0

func (r *CanvasRun) TableName() string

type CanvasRunFilters added in v0.21.0

type CanvasRunFilters struct {
	States  []string
	Results []string
}

type CanvasRunKey added in v0.30.0

type CanvasRunKey struct {
	WorkflowID uuid.UUID
	RunID      uuid.UUID
}

func CollectParentRunKeys added in v0.30.0

func CollectParentRunKeys(runs []CanvasRun) []CanvasRunKey

type CanvasSubscription added in v0.29.0

type CanvasSubscription struct {
	SourceCanvasID uuid.UUID `gorm:"column:source_canvas_id;primaryKey"`
	TargetCanvasID uuid.UUID `gorm:"column:target_canvas_id;primaryKey"`
	TargetNodeID   string    `gorm:"column:target_node_id;primaryKey"`
}

func (*CanvasSubscription) TableName added in v0.29.0

func (c *CanvasSubscription) TableName() string

type CanvasVersion added in v0.11.0

type CanvasVersion struct {
	ID            uuid.UUID
	WorkflowID    uuid.UUID
	OwnerID       *uuid.UUID
	CommitMessage string
	Nodes         datatypes.JSONSlice[Node]
	Edges         datatypes.JSONSlice[Edge]
	ConsolePanels datatypes.JSONType[[]ConsolePanel]
	ConsoleLayout datatypes.JSONType[[]ConsoleLayoutItem]
	CommitSHA     string
	CreatedAt     *time.Time
	UpdatedAt     *time.Time
}

func CreateCommitVersionWithSpecInTransaction added in v0.28.0

func CreateCommitVersionWithSpecInTransaction(
	tx *gorm.DB,
	canvasID uuid.UUID,
	userID uuid.UUID,
	commitMessage string,
	nodes []Node,
	edges []Edge,
) (*CanvasVersion, error)

func FindCanvasVersion added in v0.11.0

func FindCanvasVersion(workflowID, versionID uuid.UUID) (*CanvasVersion, error)

func FindCanvasVersionForUpdateInTransaction added in v0.17.0

func FindCanvasVersionForUpdateInTransaction(tx *gorm.DB, workflowID, versionID uuid.UUID) (*CanvasVersion, error)

func FindCanvasVersionInTransaction added in v0.11.0

func FindCanvasVersionInTransaction(tx *gorm.DB, workflowID, versionID uuid.UUID) (*CanvasVersion, error)

func FindLatestCanvasVersion added in v0.28.0

func FindLatestCanvasVersion(workflowID uuid.UUID) (*CanvasVersion, error)

func FindLatestCanvasVersionInTransaction added in v0.28.0

func FindLatestCanvasVersionInTransaction(tx *gorm.DB, workflowID uuid.UUID) (*CanvasVersion, error)

func FindLiveCanvasVersion added in v0.26.0

func FindLiveCanvasVersion(workflowID uuid.UUID) (*CanvasVersion, error)

func FindLiveCanvasVersionByCanvasInTransaction added in v0.11.0

func FindLiveCanvasVersionByCanvasInTransaction(tx *gorm.DB, canvas *Canvas) (*CanvasVersion, error)

func FindLiveCanvasVersionInTransaction added in v0.11.0

func FindLiveCanvasVersionInTransaction(tx *gorm.DB, workflowID uuid.UUID) (*CanvasVersion, error)

func FindVersionByCommitSHA added in v0.26.0

func FindVersionByCommitSHA(workflowID uuid.UUID, commitSHA string) (*CanvasVersion, error)

func FindVersionByCommitSHAInTransaction added in v0.26.0

func FindVersionByCommitSHAInTransaction(tx *gorm.DB, workflowID uuid.UUID, commitSHA string) (*CanvasVersion, error)

func ListCanvasVersions added in v0.11.0

func ListCanvasVersions(workflowID uuid.UUID) ([]CanvasVersion, error)

func ListCanvasVersionsInTransaction added in v0.11.0

func ListCanvasVersionsInTransaction(tx *gorm.DB, workflowID uuid.UUID) ([]CanvasVersion, error)

func UpdateCanvasVersionConsoleInTransaction added in v0.25.0

func UpdateCanvasVersionConsoleInTransaction(
	tx *gorm.DB,
	version *CanvasVersion,
	panels []ConsolePanel,
	layout []ConsoleLayoutItem,
) (*CanvasVersion, error)

func UpsertCanvasVersionConsole added in v0.25.0

func UpsertCanvasVersionConsole(canvasID uuid.UUID, panels []ConsolePanel, layout []ConsoleLayoutItem) (*CanvasVersion, error)

func UpsertCanvasVersionConsoleInTransaction added in v0.25.0

func UpsertCanvasVersionConsoleInTransaction(
	tx *gorm.DB,
	canvasID uuid.UUID,
	panels []ConsolePanel,
	layout []ConsoleLayoutItem,
) (*CanvasVersion, error)

func (*CanvasVersion) TableName added in v0.11.0

func (c *CanvasVersion) TableName() string

type CanvasVersionMetadata added in v0.30.0

type CanvasVersionMetadata struct {
	ID            uuid.UUID
	WorkflowID    uuid.UUID
	OwnerID       *uuid.UUID
	CommitMessage string
	CreatedAt     *time.Time
	UpdatedAt     *time.Time
}

func ListCanvasVersionHistoryInTransaction added in v0.28.0

func ListCanvasVersionHistoryInTransaction(
	tx *gorm.DB,
	workflowID uuid.UUID,
	limit int,
	before *time.Time,
) ([]CanvasVersionMetadata, error)

type CapabilityState added in v0.19.0

type CapabilityState struct {
	Name   string                          `json:"name"`
	State  core.IntegrationCapabilityState `json:"state"`
	Reason *string                         `json:"reason,omitempty"`
}

type CatalogModelPrice

type CatalogModelPrice struct {
	Provider string
	ModelID  string
	Rate     pricebook.Rate
}

CatalogModelPrice is one provider model id with cents-per-million rates.

type ClosedWorkOrderMetricRow

type ClosedWorkOrderMetricRow struct {
	WorkOrderID      uuid.UUID
	LineID           uuid.UUID
	ClosedAt         time.Time
	Merged           bool
	MergedAt         *time.Time
	ExecutionMinutes float64
	CostCents        int64
}

ClosedWorkOrderMetricRow is one closed work order attributed to a line, with the timestamps and cost the line-metrics aggregator needs.

func ListClosedWorkOrderMetricRows

func ListClosedWorkOrderMetricRows(tx *gorm.DB, factoryID uuid.UUID, from, to time.Time) ([]ClosedWorkOrderMetricRow, error)

ListClosedWorkOrderMetricRows returns one row per closed work order in [from, to) for the factory. Line attribution is the latest execution. Work orders with no executions are excluded. Close time is the latest order.status.updated event with toState=closed, not updated_at.

A row is merged when the work order result is completed, or when a factory pull request is stamped merged (merged_at or state=merged). Merge time is the pull request merged_at, or the close event when that stamp is missing.

type ComponentRef

type ComponentRef struct {
	Name string `json:"name"`
}

type ComputeUsageEventInput

type ComputeUsageEventInput struct {
	OrganizationID  uuid.UUID
	CanvasRunID     uuid.UUID
	NodeExecutionID uuid.UUID
	NodeID          string
	MachineType     string
	FleetID         string
	DurationSeconds int64
	IdempotencyKey  string
}

ComputeUsageEventInput is the call-site payload for one runner-fleet task.

type ConcurrencySpec

type ConcurrencySpec struct {
	// Key is an optional template expression that partitions the node's
	// backlog: each resolved value is an independent queue.
	Key string `json:"key,omitempty"`

	// Max is presence-aware: nil means the default (1). Must be 1 or
	// greater when set.
	Max *int `json:"max,omitempty"`
}

ConcurrencySpec is a node's inline concurrency configuration. A node without a spec runs one execution at a time.

func (*ConcurrencySpec) EffectiveMax

func (s *ConcurrencySpec) EffectiveMax() int

EffectiveMax returns the configured limit, defaulting to 1 when the spec or the field is absent.

type ConsoleLayoutItem added in v0.25.0

type ConsoleLayoutItem struct {
	I    string `json:"i"`
	X    int    `json:"x"`
	Y    int    `json:"y"`
	W    int    `json:"w"`
	H    int    `json:"h"`
	MinW *int   `json:"minW,omitempty"`
	MinH *int   `json:"minH,omitempty"`
}

type ConsolePanel added in v0.25.0

type ConsolePanel struct {
	ID      string         `json:"id"`
	Type    string         `json:"type"`
	Content map[string]any `json:"content"`
}

type CreateFileParams

type CreateFileParams struct {
	Scope          string
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	Filename       string
	ContentType    string
	CreatedByID    uuid.UUID
	Purpose        string
}

type CreditBalanceAdjustment

type CreditBalanceAdjustment struct {
	OrganizationID uuid.UUID
	Bucket         string
	TargetMicros   int64
	ExpectedMicros int64
	Note           string
	ActorAccountID *uuid.UUID
}

CreditBalanceAdjustment sets one credit type to an exact remaining balance. ExpectedMicros is the remaining balance the admin saw before the change.

type DatadogWebhookReceipt

type DatadogWebhookReceipt struct {
	ID                uuid.UUID `gorm:"primaryKey"`
	ReceivedAt        time.Time
	IntegrationID     uuid.UUID
	OrganizationID    uuid.UUID
	EventType         string
	AlertTransition   string
	AlertID           string
	Service           string
	IssueID           string
	HTTPStatus        int
	Outcome           string
	SubscriptionCount int
	// TaskIDs lists SuperPlane tasks this webhook created. IDs are comma-separated.
	TaskIDs string
}

DatadogWebhookReceipt is one incoming Datadog webhook. It stores the event type and the result. It does not store the payload, signature, or tokens.

func ListDatadogWebhookReceipts

func ListDatadogWebhookReceipts(tx *gorm.DB, limit, offset int) ([]DatadogWebhookReceipt, int64, error)

func (DatadogWebhookReceipt) TableName

func (DatadogWebhookReceipt) TableName() string

func (DatadogWebhookReceipt) TaskIDList

func (r DatadogWebhookReceipt) TaskIDList() []string

type DefaultHostedLLMModel

type DefaultHostedLLMModel struct {
	Provider string
	Model    string
}

DefaultHostedLLMModel is the instance model the SuperPlane agent runs.

func GetInstallationDefaultHostedLLMModel

func GetInstallationDefaultHostedLLMModel(tx *gorm.DB) (DefaultHostedLLMModel, error)

func InstallationDefaultHostedLLMModel

func InstallationDefaultHostedLLMModel(settings *InstallationLLMSettings) DefaultHostedLLMModel

func NormalizeDefaultHostedLLMModel

func NormalizeDefaultHostedLLMModel(provider, model string) (DefaultHostedLLMModel, error)

func ParseHostedLLMModelKey

func ParseHostedLLMModelKey(value string) (DefaultHostedLLMModel, error)

func ResolveRunnableHostedLLMModel

func ResolveRunnableHostedLLMModel(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID) (DefaultHostedLLMModel, error)

ResolveRunnableHostedLLMModel returns the installation default when the organization and workspace allow it. Otherwise it returns another allowed hosted model so excluding the default does not block hosted runs.

func (DefaultHostedLLMModel) IsSet

func (d DefaultHostedLLMModel) IsSet() bool

type DeleteCanvasNodeResult added in v0.29.0

type DeleteCanvasNodeResult struct {
	CancelledExecutionIDs []uuid.UUID
	DeletedQueueItems     []CanvasNodeQueueItem
}

func DeleteCanvasNodeWithResult added in v0.29.0

func DeleteCanvasNodeWithResult(tx *gorm.DB, node CanvasNode) (DeleteCanvasNodeResult, error)

type Edge

type Edge struct {
	SourceID string `json:"source_id"`
	TargetID string `json:"target_id"`
	Channel  string `json:"channel"`
}

type EmailSettings added in v0.0.43

type EmailSettings struct {
	ID            uuid.UUID `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
	Provider      string    `gorm:"type:varchar(50);uniqueIndex"`
	SMTPHost      string
	SMTPPort      int
	SMTPUsername  string
	SMTPPassword  []byte
	SMTPFromName  string
	SMTPFromEmail string
	SMTPUseTLS    bool
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

func FindEmailSettings added in v0.0.43

func FindEmailSettings(provider string) (*EmailSettings, error)

func FindEmailSettingsInTransaction added in v0.0.43

func FindEmailSettingsInTransaction(tx *gorm.DB, provider string) (*EmailSettings, error)

type Factory

type Factory struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	Name           string
	Description    string
	Key            string
	// URLID is the stable workspace id used in URLs. It does not change when
	// the workspace key changes.
	URLID                   string `gorm:"column:url_id"`
	NextWorkOrderNumber     int64
	OnboardingConfig        datatypes.JSONType[FactoryOnboardingConfig]
	OnboardingCompletedAt   *time.Time
	HostedSpendBudgetCents  *int64
	PlanningEnabled         bool
	PlanningClarity         bool
	PlanningConfidence      bool
	PlanningSetupCompleted  bool
	PlanningAutoStartLineID *uuid.UUID
	// Public lets anyone with the line URL view the board. They cannot open
	// tasks, logs, or settings.
	Public              bool
	PublicBadgeEnabled  bool
	PublicBadgeShowCost bool
	PublicBadgeToken    *string
	CreatedAt           time.Time
	UpdatedAt           time.Time
	DeletedAt           gorm.DeletedAt `gorm:"index"`
}

func CreateFactory

func CreateFactory(tx *gorm.DB, organizationID uuid.UUID, name, description, key string) (*Factory, error)

func FindFactory

func FindFactory(tx *gorm.DB, organizationID, factoryID uuid.UUID) (*Factory, error)

func FindFactoryByID

func FindFactoryByID(tx *gorm.DB, factoryID uuid.UUID) (*Factory, error)

func FindFactoryByKey

func FindFactoryByKey(tx *gorm.DB, organizationID uuid.UUID, key string) (*Factory, error)

func FindFactoryByPublicBadgeToken

func FindFactoryByPublicBadgeToken(tx *gorm.DB, token string) (*Factory, error)

FindFactoryByPublicBadgeToken loads the workspace that owns a public badge link. An empty token is not a match. Soft-deleted workspaces are excluded.

func FindFactoryByRef

func FindFactoryByRef(tx *gorm.DB, organizationID uuid.UUID, ref string) (*Factory, error)

FindFactoryByRef resolves ref to a factory. ref is a UUID, a workspace key, or a `key-urlId` route segment. Workspace names are not accepted.

Names can contain spaces, so they do not belong in `/factories/{id}`. Names are also not unique in an organization.

func FindFactoryByURLID

func FindFactoryByURLID(tx *gorm.DB, organizationID uuid.UUID, urlID string) (*Factory, error)

func ListDeletedFactories

func ListDeletedFactories(tx *gorm.DB) ([]Factory, error)

func ListFactories

func ListFactories(tx *gorm.DB, organizationID uuid.UUID) ([]Factory, error)

func ListOrganizationFactoriesByRecentUpdate

func ListOrganizationFactoriesByRecentUpdate(tx *gorm.DB, organizationID uuid.UUID) ([]Factory, error)

ListOrganizationFactoriesByRecentUpdate returns non-deleted workspaces of an organization, most recently updated first. Equal update times use id descending so the order stays stable.

func LockDeletedFactory

func LockDeletedFactory(tx *gorm.DB, id uuid.UUID) (*Factory, error)

func (*Factory) AttachAnalysisSession

func (f *Factory) AttachAnalysisSession(tx *gorm.DB, params AttachAnalysisSessionParams) (*FactoryPlanningSession, error)

func (*Factory) CompleteOnboarding

func (f *Factory) CompleteOnboarding(tx *gorm.DB, patch FactoryOnboardingPatch) error

CompleteOnboarding merges an optional patch, validates readiness, and sets onboarding_completed_at. When already complete, the existing timestamp is preserved (idempotent).

func (*Factory) CountCanvases

func (f *Factory) CountCanvases(tx *gorm.DB) (int64, error)

func (*Factory) CountWorkOrders

func (f *Factory) CountWorkOrders(tx *gorm.DB, filters ListFactoryWorkOrdersFilters) (int64, error)

func (*Factory) CreateAgentResource

func (f *Factory) CreateAgentResource(tx *gorm.DB, kind, name string, enabled bool, config FactoryAgentResourceConfig) (*FactoryAgentResource, error)

func (*Factory) CreateIntake

func (f *Factory) CreateIntake(tx *gorm.DB, canvasID uuid.UUID, source string) (*FactoryIntake, error)

func (*Factory) CreateLine

func (f *Factory) CreateLine(tx *gorm.DB, name string, steps []FactoryLineStep) (*FactoryLine, error)

func (*Factory) CreatePRFeedbackHandler

func (f *Factory) CreatePRFeedbackHandler(tx *gorm.DB, canvasID uuid.UUID, subject, source string) (*FactoryPRFeedbackHandler, error)

func (*Factory) CreateWorkOrder

func (f *Factory) CreateWorkOrder(tx *gorm.DB, title, description string, createdBy *uuid.UUID, assignees []uuid.UUID, sourceRunID *uuid.UUID) (*FactoryWorkOrder, error)

func (*Factory) CreateWorkOrderWithAutoStart

func (f *Factory) CreateWorkOrderWithAutoStart(
	tx *gorm.DB,
	title, description string,
	createdBy *uuid.UUID,
	assignees []uuid.UUID,
	sourceRunID *uuid.UUID,
	autoStartLineID *uuid.UUID,
) (*FactoryWorkOrder, error)

func (*Factory) CreateWorkOrderWithOrigin

func (f *Factory) CreateWorkOrderWithOrigin(
	tx *gorm.DB,
	title, description string,
	createdBy *uuid.UUID,
	assignees []uuid.UUID,
	sourceRunID *uuid.UUID,
	origin WorkOrderOrigin,
) (*FactoryWorkOrder, error)

func (*Factory) FindAgentResource

func (f *Factory) FindAgentResource(tx *gorm.DB, resourceID uuid.UUID) (*FactoryAgentResource, error)

func (*Factory) FindIntake

func (f *Factory) FindIntake(tx *gorm.DB, intakeID uuid.UUID) (*FactoryIntake, error)

func (*Factory) FindLine

func (f *Factory) FindLine(tx *gorm.DB, lineID uuid.UUID) (*FactoryLine, error)

func (*Factory) FindLineByName

func (f *Factory) FindLineByName(tx *gorm.DB, name string) (*FactoryLine, error)

func (*Factory) FindPRFeedbackHandler

func (f *Factory) FindPRFeedbackHandler(tx *gorm.DB, handlerID uuid.UUID) (*FactoryPRFeedbackHandler, error)

func (*Factory) FindPullRequest

func (f *Factory) FindPullRequest(tx *gorm.DB, filter FactoryPullRequestLookup) (*FactoryPullRequest, error)

func (*Factory) FindSetupCommands

func (f *Factory) FindSetupCommands(tx *gorm.DB) (*FactoryAgentResource, error)

func (*Factory) FindWorkOrder

func (f *Factory) FindWorkOrder(tx *gorm.DB, orderID uuid.UUID) (*FactoryWorkOrder, error)

func (*Factory) FindWorkOrderByArtifactKey

func (f *Factory) FindWorkOrderByArtifactKey(tx *gorm.DB, key string) (*FactoryWorkOrder, error)

FindWorkOrderByArtifactKey resolves a work order from one of its artifacts' `key` values, then delegates to FindWorkOrder so the result gets the same preloads/scoping as every other lookup path.

func (*Factory) FindWorkOrderByNumber

func (f *Factory) FindWorkOrderByNumber(tx *gorm.DB, number int64) (*FactoryWorkOrder, error)

func (*Factory) FindWorkOrderByRef

func (f *Factory) FindWorkOrderByRef(tx *gorm.DB, ref string) (*FactoryWorkOrder, error)

FindWorkOrderByRef resolves ref to a work order in this factory. ref is tried as a UUID first, then as the factory-scoped sequence number, then as the display key (for example `SP-42`).

func (*Factory) HasInitialOnboardingAttempt

func (f *Factory) HasInitialOnboardingAttempt(attemptID uuid.UUID) bool

func (*Factory) IsInitialOnboarding

func (f *Factory) IsInitialOnboarding() bool

IsInitialOnboarding reports whether account onboarding created the workspace.

func (*Factory) IsOnboardingComplete

func (f *Factory) IsOnboardingComplete() bool

func (*Factory) IsPendingInitialOnboarding

func (f *Factory) IsPendingInitialOnboarding() bool

IsPendingInitialOnboarding reports whether this workspace is the unfinished first-run organization setup for an account.

func (*Factory) ListAgentResources

func (f *Factory) ListAgentResources(tx *gorm.DB, kind string) ([]FactoryAgentResource, error)

func (*Factory) ListCanvases

func (f *Factory) ListCanvases(tx *gorm.DB) ([]Canvas, error)

func (*Factory) ListCanvasesMentioningSkill

func (f *Factory) ListCanvasesMentioningSkill(tx *gorm.DB, command string) ([]Canvas, error)

ListCanvasesMentioningSkill checks saved prompt fields, including agent steps. Other configuration strings, such as shell commands, do not count as mentions.

func (*Factory) ListContextRepos

func (f *Factory) ListContextRepos(tx *gorm.DB) ([]FactoryAgentResource, error)

func (*Factory) ListEnabledContextRepos

func (f *Factory) ListEnabledContextRepos(tx *gorm.DB) ([]FactoryAgentResource, error)

func (*Factory) ListEnabledMCPServers

func (f *Factory) ListEnabledMCPServers(tx *gorm.DB) ([]FactoryAgentResource, error)

func (*Factory) ListEnabledSetupCommands

func (f *Factory) ListEnabledSetupCommands(tx *gorm.DB) ([]string, error)

func (*Factory) ListEnabledSkills

func (f *Factory) ListEnabledSkills(tx *gorm.DB) ([]FactoryAgentResource, error)

func (*Factory) ListIntakes

func (f *Factory) ListIntakes(tx *gorm.DB) ([]FactoryIntake, error)

func (*Factory) ListLines

func (f *Factory) ListLines(tx *gorm.DB) ([]FactoryLine, error)

func (*Factory) ListPRFeedbackHandlers

func (f *Factory) ListPRFeedbackHandlers(tx *gorm.DB) ([]FactoryPRFeedbackHandler, error)

func (*Factory) ListPullRequests

func (f *Factory) ListPullRequests(tx *gorm.DB, filter FactoryPullRequestFilter) ([]FactoryPullRequest, error)

func (*Factory) ListWorkOrderOriginURLsContaining

func (f *Factory) ListWorkOrderOriginURLsContaining(tx *gorm.DB, fragment string) ([]string, error)

ListWorkOrderOriginURLsContaining returns origin URLs of this factory's work orders whose origin_url contains fragment. Matching covers every state. Callers confirm the match; this lookup is a coarse filter.

func (*Factory) ListWorkOrders

func (f *Factory) ListWorkOrders(tx *gorm.DB, filters ListFactoryWorkOrdersFilters) ([]FactoryWorkOrder, error)

func (*Factory) ListWorkOrdersByArtifactKeys

func (f *Factory) ListWorkOrdersByArtifactKeys(tx *gorm.DB, keys []string) (map[string]FactoryWorkOrder, error)

ListWorkOrdersByArtifactKeys resolves work orders from artifact keys in one query. Missing keys are omitted rather than reported as not found.

func (*Factory) ListWorkOrdersByOriginURLFragment

func (f *Factory) ListWorkOrdersByOriginURLFragment(tx *gorm.DB, fragment string) ([]FactoryWorkOrder, error)

ListWorkOrdersByOriginURLFragment returns this factory's work orders whose origin_url contains fragment, in every state. Callers confirm the match and read the state; this lookup is a coarse filter.

func (*Factory) OnboardingConfigAfter

func (f *Factory) OnboardingConfigAfter(patch FactoryOnboardingPatch) (FactoryOnboardingConfig, error)

func (*Factory) OnboardingConfigValue

func (f *Factory) OnboardingConfigValue() FactoryOnboardingConfig

func (*Factory) Planning

func (f *Factory) Planning() FactoryPlanning

func (*Factory) RouteSegment

func (f *Factory) RouteSegment() string

RouteSegment is the canonical workspace URL segment: lowercase key, hyphen, then the stable url id. Example: `eng-k7m2xqab`.

func (*Factory) SetInitialOnboardingAttempt

func (f *Factory) SetInitialOnboardingAttempt(tx *gorm.DB, attemptID uuid.UUID) error

SetInitialOnboardingAttempt records the server-owned retry key for a workspace created during account onboarding. It is not part of the user-editable onboarding patch.

func (*Factory) SetPublic

func (f *Factory) SetPublic(tx *gorm.DB, public bool) error

func (*Factory) SnapshotWorkOrderRepository

func (f *Factory) SnapshotWorkOrderRepository(tx *gorm.DB, repository, defaultBranch, provider string) error

SnapshotWorkOrderRepository records the current repository before a workspace switches repositories. A nil snapshot is a legacy row, so preserve an existing value from an earlier switch. The Git host is part of that snapshot.

func (*Factory) SoftDelete

func (f *Factory) SoftDelete(tx *gorm.DB) error

func (*Factory) SoftDeleteCanvases

func (f *Factory) SoftDeleteCanvases(tx *gorm.DB) error

func (*Factory) Update

func (f *Factory) Update(tx *gorm.DB, name, description, key *string) error

func (*Factory) UpdateHostedSpendBudget

func (f *Factory) UpdateHostedSpendBudget(tx *gorm.DB, budgetCents *int64) error

func (*Factory) UpdateOnboarding

func (f *Factory) UpdateOnboarding(tx *gorm.DB, patch FactoryOnboardingPatch) error

UpdateOnboarding merges a partial patch into the stored config. It does not change completion status.

func (*Factory) UpdatePlanning

func (f *Factory) UpdatePlanning(tx *gorm.DB, planning FactoryPlanning) error

func (*Factory) UpdatePublicBadgeEnabled

func (f *Factory) UpdatePublicBadgeEnabled(tx *gorm.DB, enabled bool) error

UpdatePublicBadgeEnabled turns the public badge on or off. The first enable stores a random URL-safe token. A later enable keeps that token, including when two first enables run together, so a README link stays valid.

func (*Factory) UpdatePublicBadgeShowCost

func (f *Factory) UpdatePublicBadgeShowCost(tx *gorm.DB, showCost bool) error

UpdatePublicBadgeShowCost stores the cost switch on its own. Turning the badge off does not clear this value.

func (*Factory) WorkOrderKey

func (f *Factory) WorkOrderKey(number int64) string

WorkOrderKey returns the display identifier used for a work order that belongs to this factory. Format matches `<KEY>-<number>` (for example `SP-42`).

type FactoryAgentResource

type FactoryAgentResource struct {
	ID                 uuid.UUID
	OrganizationID     uuid.UUID
	FactoryID          uuid.UUID
	Kind               string
	Name               string
	Enabled            bool
	Config             datatypes.JSONType[FactoryAgentResourceConfig]
	OAuthStatus        string                                                `gorm:"column:oauth_status"`
	OAuthError         string                                                `gorm:"column:oauth_error"`
	OAuthConnectedBy   *uuid.UUID                                            `gorm:"column:oauth_connected_by"`
	OAuthConnectedAt   *time.Time                                            `gorm:"column:oauth_connected_at"`
	OAuthMetadata      datatypes.JSONType[FactoryAgentResourceOAuthMetadata] `gorm:"column:oauth_metadata"`
	OAuthPendingState  string                                                `gorm:"column:oauth_pending_state"`
	OAuthPendingExpiry *time.Time                                            `gorm:"column:oauth_pending_expiry"`
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

FactoryAgentResource is one workspace-scoped agent capability.

func FindFactoryAgentResourceByOAuthState

func FindFactoryAgentResourceByOAuthState(tx *gorm.DB, state string) (*FactoryAgentResource, error)

func (*FactoryAgentResource) ClearOAuthPending

func (r *FactoryAgentResource) ClearOAuthPending(tx *gorm.DB) error

func (*FactoryAgentResource) Delete

func (r *FactoryAgentResource) Delete(tx *gorm.DB) error

func (*FactoryAgentResource) DeleteSecret

func (r *FactoryAgentResource) DeleteSecret(tx *gorm.DB, name string) error

func (*FactoryAgentResource) DeleteSecrets

func (r *FactoryAgentResource) DeleteSecrets(tx *gorm.DB) error

func (*FactoryAgentResource) FindSecret

func (r *FactoryAgentResource) FindSecret(tx *gorm.DB, name string) (*FactoryAgentResourceSecret, error)

func (*FactoryAgentResource) IsSystemSkill

func (r *FactoryAgentResource) IsSystemSkill() bool

func (*FactoryAgentResource) MCPConnectionEstablished

func (r *FactoryAgentResource) MCPConnectionEstablished() bool

func (*FactoryAgentResource) OAuthState

func (r *FactoryAgentResource) OAuthState() string

func (*FactoryAgentResource) RestoreSystemSkill

func (r *FactoryAgentResource) RestoreSystemSkill(tx *gorm.DB, version int32, markdown string) error

RestoreSystemSkill replaces instructions and advances the supplied baseline. The caller resolves the template from the current SuperPlane catalog.

func (*FactoryAgentResource) SetOAuthConnector

func (r *FactoryAgentResource) SetOAuthConnector(tx *gorm.DB, userID uuid.UUID) error

func (*FactoryAgentResource) SetOAuthMetadata

func (r *FactoryAgentResource) SetOAuthMetadata(tx *gorm.DB, metadata FactoryAgentResourceOAuthMetadata) error

func (*FactoryAgentResource) SetOAuthPending

func (r *FactoryAgentResource) SetOAuthPending(tx *gorm.DB, state string, expiresAt time.Time) error

func (*FactoryAgentResource) SetOAuthStatus

func (r *FactoryAgentResource) SetOAuthStatus(tx *gorm.DB, status, message string, connectedBy *uuid.UUID) error

func (FactoryAgentResource) TableName

func (FactoryAgentResource) TableName() string

func (*FactoryAgentResource) Update

func (r *FactoryAgentResource) Update(tx *gorm.DB, name *string, enabled *bool, config *FactoryAgentResourceConfig) error

func (*FactoryAgentResource) UpsertSecret

func (r *FactoryAgentResource) UpsertSecret(tx *gorm.DB, name string, value []byte) error

type FactoryAgentResourceConfig

type FactoryAgentResourceConfig struct {
	SystemSkill         *FactorySystemSkill          `json:"systemSkill,omitempty"`
	Transport           string                       `json:"transport,omitempty"`
	URL                 string                       `json:"url,omitempty"`
	Auth                string                       `json:"auth,omitempty"`
	Headers             []FactoryAgentResourceHeader `json:"headers,omitempty"`
	Source              string                       `json:"source,omitempty"`
	Repository          string                       `json:"repository,omitempty"`
	Ref                 string                       `json:"ref,omitempty"`
	Path                string                       `json:"path,omitempty"`
	Markdown            string                       `json:"markdown,omitempty"`
	Commands            []string                     `json:"commands,omitempty"`
	VCSProvider         string                       `json:"vcsProvider,omitempty"`
	DisabledTools       []string                     `json:"disabledTools,omitempty"`
	ToolsDefaultApplied bool                         `json:"toolsDefaultApplied,omitempty"`
}

func (FactoryAgentResourceConfig) InvalidatesOAuth

InvalidatesOAuth reports whether the next MCP config cannot reuse stored OAuth tokens. A URL or auth change points at a different authorization server, so SuperPlane must drop the previous grant.

func (FactoryAgentResourceConfig) MCPAuth

func (c FactoryAgentResourceConfig) MCPAuth() string

func (FactoryAgentResourceConfig) NormalizedContextRepo

func (c FactoryAgentResourceConfig) NormalizedContextRepo() FactoryAgentResourceConfig

func (FactoryAgentResourceConfig) NormalizedMCP

func (FactoryAgentResourceConfig) NormalizedSetup

func (FactoryAgentResourceConfig) NormalizedSkill

func (FactoryAgentResourceConfig) SkillContentHash

func (c FactoryAgentResourceConfig) SkillContentHash() string

func (FactoryAgentResourceConfig) ValidateContextRepo

func (c FactoryAgentResourceConfig) ValidateContextRepo() error

func (FactoryAgentResourceConfig) ValidateMCP

func (c FactoryAgentResourceConfig) ValidateMCP() error

func (FactoryAgentResourceConfig) ValidateSetup

func (c FactoryAgentResourceConfig) ValidateSetup() error

func (FactoryAgentResourceConfig) ValidateSkill

func (c FactoryAgentResourceConfig) ValidateSkill() error

type FactoryAgentResourceHeader

type FactoryAgentResourceHeader struct {
	Name       string `json:"name"`
	SecretName string `json:"secretName"`
	SecretKey  string `json:"secretKey"`
}

type FactoryAgentResourceOAuthMetadata

type FactoryAgentResourceOAuthMetadata struct {
	AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`
	TokenEndpoint         string `json:"tokenEndpoint,omitempty"`
	RevocationEndpoint    string `json:"revocationEndpoint,omitempty"`
	RegistrationEndpoint  string `json:"registrationEndpoint,omitempty"`
	ClientID              string `json:"clientId,omitempty"`
	Resource              string `json:"resource,omitempty"`
	AccessTokenExpiresAt  string `json:"accessTokenExpiresAt,omitempty"`
}

type FactoryAgentResourceSecret

type FactoryAgentResourceSecret struct {
	ID         uuid.UUID
	ResourceID uuid.UUID
	Name       string
	Value      []byte
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

func (FactoryAgentResourceSecret) TableName

func (FactoryAgentResourceSecret) TableName() string

type FactoryAutomationRuns

type FactoryAutomationRuns struct {
	CanvasID uuid.UUID
	Name     string
	Runs     int
	Failed   int
	// FinishedRuns is the part of Runs that carries a finish time. Duration is
	// averaged over these, so a window full of running work reports no
	// duration instead of a number pulled down by runs that have not ended.
	FinishedRuns    int
	DurationSeconds float64
	CostMicros      int64
}

FactoryAutomationRuns is what one automation of a workspace did inside a window: how often it ran, how often it failed, how long its finished runs took, and what they cost.

func SummarizeFactoryAutomationRuns

func SummarizeFactoryAutomationRuns(
	tx *gorm.DB,
	factoryID uuid.UUID,
	from, to time.Time,
) ([]FactoryAutomationRuns, error)

SummarizeFactoryAutomationRuns reports one row per automation of the workspace that ran between `from` and `to`, busiest first.

Runs count against the window they started in, so a row stays comparable with the run list of the automation, which is also ordered by start time.

func (FactoryAutomationRuns) AverageDurationHours

func (a FactoryAutomationRuns) AverageDurationHours() float64

AverageDurationHours is the mean wall-clock time of the finished runs.

func (FactoryAutomationRuns) CostCents

func (a FactoryAutomationRuns) CostCents() int64

type FactoryHostedBudgetSummary

type FactoryHostedBudgetSummary struct {
	BudgetCents     *int64
	BilledMicros    int64
	RemainingMicros int64
	Warning         bool
	Capped          bool
}

FactoryHostedBudgetSummary is remaining hosted credit for one workspace.

func DescribeFactoryHostedBudget

func DescribeFactoryHostedBudget(tx *gorm.DB, factory *Factory) (FactoryHostedBudgetSummary, error)

type FactoryIntake

type FactoryIntake struct {
	ID                     uuid.UUID
	OrganizationID         uuid.UUID
	FactoryID              uuid.UUID
	CanvasID               uuid.UUID
	Source                 string
	InitialImportStatus    string
	InitialImportItemCount *int
	PausedAt               *time.Time
	CreatedAt              time.Time
	UpdatedAt              time.Time

	Canvas *Canvas `gorm:"foreignKey:CanvasID"`
}

FactoryIntake declares that a factory canvas listens to an external source, scores what it receives, and creates backlog work orders. The row owns identity; the canvas graph owns behavior.

func FindFactoryIntakeByCanvasID

func FindFactoryIntakeByCanvasID(tx *gorm.DB, canvasID uuid.UUID) (*FactoryIntake, error)

func (*FactoryIntake) CompleteInitialImport

func (i *FactoryIntake) CompleteInitialImport(tx *gorm.DB, itemCount int) error

func (*FactoryIntake) Delete

func (i *FactoryIntake) Delete(tx *gorm.DB) error

func (*FactoryIntake) FailInitialImport

func (i *FactoryIntake) FailInitialImport(tx *gorm.DB) error

func (*FactoryIntake) Name

func (i *FactoryIntake) Name() string

Name is the intake's display name, which is the canvas name. Intakes are renamed by renaming their canvas, so the name is never stored twice.

func (*FactoryIntake) Paused

func (i *FactoryIntake) Paused() bool

func (*FactoryIntake) SetPaused

func (i *FactoryIntake) SetPaused(tx *gorm.DB, paused bool) error

func (*FactoryIntake) SkipInitialImport

func (i *FactoryIntake) SkipInitialImport(tx *gorm.DB) error

func (FactoryIntake) TableName

func (FactoryIntake) TableName() string

type FactoryLLMModelAllowlist

type FactoryLLMModelAllowlist struct {
	FactoryID     uuid.UUID `gorm:"primaryKey"`
	Provider      string    `gorm:"primaryKey"`
	FundingSource string    `gorm:"primaryKey"`
	AllowedModels datatypes.JSONSlice[string]
	UpdatedAt     time.Time
}

FactoryLLMModelAllowlist is a factory subset of parent models. An empty AllowedModels list means inherit the parent list.

func FindFactoryLLMModelAllowlist

func FindFactoryLLMModelAllowlist(tx *gorm.DB, factoryID uuid.UUID, provider, fundingSource string) (*FactoryLLMModelAllowlist, error)

func UpsertFactoryLLMModelAllowlist

func UpsertFactoryLLMModelAllowlist(tx *gorm.DB, orgID, factoryID uuid.UUID, provider, fundingSource string, models datatypes.JSONSlice[string]) (*FactoryLLMModelAllowlist, error)

func (FactoryLLMModelAllowlist) TableName

func (FactoryLLMModelAllowlist) TableName() string

type FactoryLine

type FactoryLine struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	Name           string
	Steps          datatypes.JSONSlice[FactoryLineStep]
	// ColumnColors holds the board's column colors, keyed by column key
	// ("backlog", "phase-<step index>", "verify", "done"). A missing key
	// means the column uses the default color.
	ColumnColors datatypes.JSONType[map[string]string]
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func ListFactoryLinesByFactoryIDs

func ListFactoryLinesByFactoryIDs(tx *gorm.DB, organizationID uuid.UUID, factoryIDs []uuid.UUID) ([]FactoryLine, error)

func (*FactoryLine) ColumnColorsValue

func (l *FactoryLine) ColumnColorsValue() map[string]string

ColumnColorsValue returns the stored column colors, defaulting to an empty map when none have been saved yet.

func (*FactoryLine) Dispatch

Dispatch creates the line dispatch for order's traversal of l — snapshotting l's current name/steps — and starts (or queues) step 0 inside it. Both writes happen in the caller's transaction so a partial dispatch (parent created, step 0 failed) can never be observed.

func (*FactoryLine) DispatchFrom

func (l *FactoryLine) DispatchFrom(tx *gorm.DB, order *FactoryWorkOrder, startIndex int) (*FactoryWorkOrderLineDispatch, *FactoryLineStepResult, error)

DispatchFrom creates a line dispatch and starts (or queues) the step at startIndex. Rerun from the start uses 0. Rerun this step uses the current step. The model stays Auto.

func (*FactoryLine) DispatchFromWithModel

func (l *FactoryLine) DispatchFromWithModel(tx *gorm.DB, order *FactoryWorkOrder, startIndex int, model, thinkingLevel string) (*FactoryWorkOrderLineDispatch, *FactoryLineStepResult, error)

DispatchFromWithModel is DispatchFrom with optional Start model and thinking overrides. Empty model or thinking means Auto.

func (*FactoryLine) RecordPassedStageWithoutRun

func (l *FactoryLine) RecordPassedStageWithoutRun(
	tx *gorm.DB,
	order *FactoryWorkOrder,
	stepIndex int,
) (*FactoryWorkOrderLineDispatch, *FactoryWorkOrderExecution, error)

RecordPassedStageWithoutRun records a finished line traversal whose step at stepIndex passed, without a canvas run. Earlier steps stay empty. The board treats this as waiting in Verify.

func (FactoryLine) TableName

func (FactoryLine) TableName() string

func (*FactoryLine) Update

func (l *FactoryLine) Update(tx *gorm.DB, name *string, steps []FactoryLineStep, columnColors map[string]string) error

Update persists the given fields. A nil name, steps, or columnColors means "do not change" that field; an empty (non-nil) steps slice is not valid (callers must not pass one), while an empty (non-nil) columnColors map is a valid "clear all colors" request.

type FactoryLineStep

type FactoryLineStep struct {
	Type       string    `json:"type"`
	AppID      uuid.UUID `json:"app_id"`
	Entrypoint string    `json:"entrypoint"`
	// MaxParallelism caps the step's in-flight runs across all work
	// orders on the line. Unset means the default of 10; there is no
	// unbounded setting.
	MaxParallelism *int `json:"max_parallelism,omitempty"`
}

func (*FactoryLineStep) EffectiveMaxParallelism

func (s *FactoryLineStep) EffectiveMaxParallelism() int

type FactoryLineStepResult

type FactoryLineStepResult struct {
	Run       *CanvasRun
	Execution *FactoryWorkOrderExecution
	QueueItem *FactoryWorkOrderQueueItem
}

FactoryLineStepResult is the outcome of making a work order ready for a step (see FactoryLine.Dispatch and FactoryWorkOrderLineDispatch.EnqueueOrStartStep): either the run + execution created by starting it, or — when the step is at its maxParallelism — the queue item created instead (Run and Execution nil).

func AdmitQueuedForStep

func AdmitQueuedForStep(tx *gorm.DB, lineID uuid.UUID, stepIndex int) ([]*FactoryLineStepResult, error)

AdmitQueuedForStep admits queued dispatches of (lineID, stepIndex) in FIFO order, oldest first, while the step has free slots — normally one per finished run, more when the step's maxParallelism was raised mid-flight and a finished run reveals the extra capacity. Queue items whose work order is no longer open are dropped (their dispatch finishes as cancelled) without using a slot. Returns one result per admitted dispatch, oldest first; empty when nothing was admitted.

type FactoryOnboardingConfig

type FactoryOnboardingConfig struct {
	InitialOnboardingAttemptID string `json:"initial_onboarding_attempt_id,omitempty"`
	VCSIntegrationID           string `json:"vcs_integration_id,omitempty"`
	// VCSProvider is the Git host. Empty means GitHub. Existing rows stay empty.
	VCSProvider        string `json:"vcs_provider,omitempty"`
	AgentIntegrationID string `json:"agent_integration_id,omitempty"`
	AppRepository      string `json:"app_repository,omitempty"`
	AppRepositoryID    int64  `json:"app_repository_id,omitempty"`
	// AppRepositoryExternalID is the Bitbucket repository UUID. GitHub leaves it empty.
	AppRepositoryExternalID string `json:"app_repository_external_id,omitempty"`
	BacklogRepository       string `json:"backlog_repository,omitempty"`
	BacklogRepositoryID     int64  `json:"backlog_repository_id,omitempty"`
	DefaultBranch           string `json:"default_branch,omitempty"`
	IssuesSource            string `json:"issues_source,omitempty"`
	AgentHarness            string `json:"agent_harness,omitempty"`
	ProvisionedAppID        string `json:"provisioned_app_id,omitempty"`
	ProvisionedLineID       string `json:"provisioned_line_id,omitempty"`
}

FactoryOnboardingConfig stores durable wizard choices and provisioned resource IDs. Empty strings mean the field has not been saved yet.

func (FactoryOnboardingConfig) EffectiveVCSProvider

func (c FactoryOnboardingConfig) EffectiveVCSProvider() string

EffectiveVCSProvider returns the stored Git host. An empty value means GitHub.

type FactoryOnboardingPatch

type FactoryOnboardingPatch struct {
	VCSIntegrationID        *string
	VCSProvider             *string
	AgentIntegrationID      *string
	AppRepository           *string
	AppRepositoryID         *int64
	AppRepositoryExternalID *string
	BacklogRepository       *string
	BacklogRepositoryID     *int64
	DefaultBranch           *string
	IssuesSource            *string
	AgentHarness            *string
	ProvisionedAppID        *string
	ProvisionedLineID       *string
}

FactoryOnboardingPatch carries optional field updates for a partial merge. A nil pointer means "leave unchanged"; a non-nil pointer replaces the value (including clearing when the pointed string is empty, or when an enum is cleared to the empty string).

type FactoryPRFeedbackHandler

type FactoryPRFeedbackHandler struct {
	ID              uuid.UUID
	OrganizationID  uuid.UUID
	FactoryID       uuid.UUID
	CanvasID        uuid.UUID
	Subject         string
	Source          string
	MaximumAttempts *int
	CreatedAt       time.Time
	UpdatedAt       time.Time

	Canvas *Canvas `gorm:"foreignKey:CanvasID"`
}

FactoryPRFeedbackHandler declares that a factory canvas addresses pull request feedback. The row owns identity; the canvas graph owns behavior.

func FindPRFeedbackHandlerByCanvasID

func FindPRFeedbackHandlerByCanvasID(tx *gorm.DB, canvasID uuid.UUID) (*FactoryPRFeedbackHandler, error)

func FindPRFeedbackHandlerByID

func FindPRFeedbackHandlerByID(tx *gorm.DB, handlerID uuid.UUID) (*FactoryPRFeedbackHandler, error)

func (*FactoryPRFeedbackHandler) Delete

func (h *FactoryPRFeedbackHandler) Delete(tx *gorm.DB) error

func (*FactoryPRFeedbackHandler) GitHubChecksTrigger

func (h *FactoryPRFeedbackHandler) GitHubChecksTrigger(tx *gorm.DB, repository string) (*CanvasNode, error)

GitHubChecksTrigger resolves registered checks triggers from the live graph, including graphs whose trigger IDs have been renamed.

func (*FactoryPRFeedbackHandler) Name

func (h *FactoryPRFeedbackHandler) Name() string

Name is the handler's display name, which is the canvas name.

func (*FactoryPRFeedbackHandler) SetMaximumAttempts

func (h *FactoryPRFeedbackHandler) SetMaximumAttempts(tx *gorm.DB, attempts int) error

func (FactoryPRFeedbackHandler) TableName

func (FactoryPRFeedbackHandler) TableName() string

func (*FactoryPRFeedbackHandler) Touch

func (h *FactoryPRFeedbackHandler) Touch(tx *gorm.DB) error

type FactoryPlanning

type FactoryPlanning struct {
	Enabled         bool
	Clarity         bool
	Confidence      bool
	SetupCompleted  bool
	AutoStartLineID *uuid.UUID
}

FactoryPlanning is the workspace toggle for draft chat plus the two optional checks. New workspaces start with Planning and the Confidence estimate on. The Clarity check is opt-in because it makes the agent ask more questions before a task is ready.

func DefaultFactoryPlanning

func DefaultFactoryPlanning() FactoryPlanning

type FactoryPlanningSession

type FactoryPlanningSession struct {
	ID                 uuid.UUID
	OrganizationID     uuid.UUID
	FactoryID          uuid.UUID
	CreatedByUserID    *uuid.UUID
	Repository         string
	Kind               string
	State              string
	CanvasID           *uuid.UUID
	CanvasRunID        *uuid.UUID
	DraftTitle         string
	DraftDescription   string
	DraftWorkOrderID   *uuid.UUID
	WaitState          string
	WaitKind           string
	WaitText           string
	WaitWorkOrderID    *uuid.UUID
	WaitWorkOrderKey   string
	SurveyID           *uuid.UUID
	Survey             datatypes.JSONType[PlanningSessionSurvey]
	SelectableModelKey string
	HeartbeatAt        time.Time
	EndedAt            *time.Time
	CreatedAt          time.Time
	UpdatedAt          time.Time
	Messages           []PlanningSessionMessage `gorm:"-"`
}

func FindPlanningSession

func FindPlanningSession(tx *gorm.DB, organizationID, factoryID, id uuid.UUID) (*FactoryPlanningSession, error)

func FindPlanningSessionByDraftWorkOrder

func FindPlanningSessionByDraftWorkOrder(
	tx *gorm.DB,
	organizationID, factoryID, workOrderID uuid.UUID,
) (*FactoryPlanningSession, error)

func FindPlanningSessionByRun

func FindPlanningSessionByRun(tx *gorm.DB, canvasRunID uuid.UUID) (*FactoryPlanningSession, error)

func ListStaleOpenPlanningSessions

func ListStaleOpenPlanningSessions(tx *gorm.DB, now time.Time, limit int) ([]FactoryPlanningSession, error)

func (*FactoryPlanningSession) AttachAgentRun

func (s *FactoryPlanningSession) AttachAgentRun(tx *gorm.DB, runID uuid.UUID, modelKey string) error

func (*FactoryPlanningSession) BeginWait

func (s *FactoryPlanningSession) BeginWait(tx *gorm.DB) error

func (*FactoryPlanningSession) ConsumeWait

func (s *FactoryPlanningSession) ConsumeWait(tx *gorm.DB) (PlanningWaitResult, error)

func (*FactoryPlanningSession) CreatedOrders

func (s *FactoryPlanningSession) CreatedOrders(tx *gorm.DB) ([]FactoryWorkOrder, error)

func (*FactoryPlanningSession) CurrentSurvey

func (s *FactoryPlanningSession) CurrentSurvey() PlanningSessionSurvey

func (*FactoryPlanningSession) DetachAgentRun

func (s *FactoryPlanningSession) DetachAgentRun(tx *gorm.DB) error

func (*FactoryPlanningSession) Draft

func (*FactoryPlanningSession) End

func (s *FactoryPlanningSession) End(tx *gorm.DB) error

func (*FactoryPlanningSession) EndIfStale

func (s *FactoryPlanningSession) EndIfStale(tx *gorm.DB, now time.Time) (bool, error)

func (*FactoryPlanningSession) Heartbeat

func (s *FactoryPlanningSession) Heartbeat(tx *gorm.DB) error

func (*FactoryPlanningSession) IsAnalysisSession

func (s *FactoryPlanningSession) IsAnalysisSession() bool

func (*FactoryPlanningSession) LockForUpdate

func (s *FactoryPlanningSession) LockForUpdate(tx *gorm.DB) error

func (*FactoryPlanningSession) MarkUserMessagesDelivered

func (s *FactoryPlanningSession) MarkUserMessagesDelivered(tx *gorm.DB) error

func (*FactoryPlanningSession) NeedsAnalysisRestart

func (s *FactoryPlanningSession) NeedsAnalysisRestart(tx *gorm.DB) bool

func (*FactoryPlanningSession) ProposeClarity

func (s *FactoryPlanningSession) ProposeClarity(tx *gorm.DB, score float64, summary string) error

ProposeClarity is not part of the review scoring contract.

func (*FactoryPlanningSession) ProposeConfidence

func (s *FactoryPlanningSession) ProposeConfidence(tx *gorm.DB, score float64, summary string) error

ProposeConfidence is not part of the review scoring contract. A new session accepts only Clarity, Complexity, and Verifiability.

func (*FactoryPlanningSession) ProposeSpec

func (s *FactoryPlanningSession) ProposeSpec(tx *gorm.DB, body string) error

func (*FactoryPlanningSession) ProposeSurvey

func (s *FactoryPlanningSession) ProposeSurvey(tx *gorm.DB, survey PlanningSessionSurvey) error

func (*FactoryPlanningSession) ProposeUpdate

func (s *FactoryPlanningSession) ProposeUpdate(tx *gorm.DB, update PlanningSessionUpdate) error

ProposeUpdate applies scores, spec, and survey in one transaction.

func (*FactoryPlanningSession) RecordAgentMessage

func (s *FactoryPlanningSession) RecordAgentMessage(tx *gorm.DB, text string) error

func (*FactoryPlanningSession) RecordAgentMessageForActivity

func (s *FactoryPlanningSession) RecordAgentMessageForActivity(tx *gorm.DB, text string, activityID uuid.UUID) error

func (*FactoryPlanningSession) Reopen

func (s *FactoryPlanningSession) Reopen(tx *gorm.DB) error

func (*FactoryPlanningSession) RestoreWait

func (s *FactoryPlanningSession) RestoreWait(tx *gorm.DB, result PlanningWaitResult) error

func (*FactoryPlanningSession) SendUserMessage

func (s *FactoryPlanningSession) SendUserMessage(tx *gorm.DB, text string, userID uuid.UUID) error

func (FactoryPlanningSession) TableName

func (FactoryPlanningSession) TableName() string

func (*FactoryPlanningSession) UpsertActivity

func (s *FactoryPlanningSession) UpsertActivity(tx *gorm.DB, activity PlanningSessionActivity) error

func (*FactoryPlanningSession) Wait

type FactoryPlanningSessionWorkOrder

type FactoryPlanningSessionWorkOrder struct {
	SessionID   uuid.UUID `gorm:"primaryKey"`
	WorkOrderID uuid.UUID `gorm:"primaryKey"`
	CreatedAt   time.Time
}

func (FactoryPlanningSessionWorkOrder) TableName

type FactoryPullRequest

type FactoryPullRequest struct {
	ID                      uuid.UUID
	OrganizationID          uuid.UUID
	FactoryID               uuid.UUID
	WorkOrderID             uuid.UUID
	Provider                string
	ExternalID              *string
	Repository              string
	Number                  int64
	URL                     string
	Title                   string
	State                   string
	MergedAt                *time.Time
	ClosedAt                *time.Time
	CurrentRevisionID       *uuid.UUID
	ActiveMutationRunID     *uuid.UUID
	Mergeable               bool
	MergeBlockedReason      string
	MergeBlockedMessage     string
	MergeableHeadSHA        string
	MergeableAllowedMethods string
	CreatedAt               time.Time
	UpdatedAt               time.Time
}

func ListFactoryPullRequests

func ListFactoryPullRequests(tx *gorm.DB, factoryID uuid.UUID, filter FactoryPullRequestFilter) ([]FactoryPullRequest, error)

func ListGitHubFactoryPullRequestsForWebhook

func ListGitHubFactoryPullRequestsForWebhook(
	tx *gorm.DB,
	organizationID uuid.UUID,
	repository string,
	numbers []int64,
) ([]FactoryPullRequest, error)

func ListOpenGitHubFactoryPullRequestsForWebhook

func ListOpenGitHubFactoryPullRequestsForWebhook(
	tx *gorm.DB,
	organizationID uuid.UUID,
	repository string,
	numbers []int64,
	sha string,
) ([]FactoryPullRequest, error)

func (*FactoryPullRequest) CachedAllowedMethods

func (p *FactoryPullRequest) CachedAllowedMethods() []string

func (*FactoryPullRequest) CreateActivity

func (*FactoryPullRequest) HasCachedMergeability

func (p *FactoryPullRequest) HasCachedMergeability() bool

func (*FactoryPullRequest) LinkRun

func (p *FactoryPullRequest) LinkRun(tx *gorm.DB, runID uuid.UUID, description string) error

func (*FactoryPullRequest) LockForUpdate

func (p *FactoryPullRequest) LockForUpdate(tx *gorm.DB) error

func (*FactoryPullRequest) ObserveRevision

func (p *FactoryPullRequest) ObserveRevision(tx *gorm.DB, sha string) (*FactoryPullRequestObserveResult, error)

func (*FactoryPullRequest) Ref

func (*FactoryPullRequest) RequestExclusiveAccess

func (p *FactoryPullRequest) RequestExclusiveAccess(tx *gorm.DB, activity *FactoryPullRequestRun) (*FactoryPullRequestAccessResult, error)

func (*FactoryPullRequest) SetMergeability

func (p *FactoryPullRequest) SetMergeability(tx *gorm.DB, snapshot FactoryPullRequestMergeabilitySnapshot) error

func (FactoryPullRequest) TableName

func (FactoryPullRequest) TableName() string

func (*FactoryPullRequest) Update

func (p *FactoryPullRequest) Update(tx *gorm.DB, patch FactoryPullRequestPatch) error

type FactoryPullRequestAccessResult

type FactoryPullRequestAccessResult struct {
	Activity        *FactoryPullRequestRun
	CurrentRevision *FactoryPullRequestRevision
	Outcome         FactoryPullRequestActivityOutcome
}

type FactoryPullRequestActivityOutcome

type FactoryPullRequestActivityOutcome string
const (
	FactoryPullRequestActivityOutcomeReady        FactoryPullRequestActivityOutcome = "ready"
	FactoryPullRequestActivityOutcomeWaiting      FactoryPullRequestActivityOutcome = "waiting"
	FactoryPullRequestActivityOutcomeLimitReached FactoryPullRequestActivityOutcome = "limit_reached"
)

type FactoryPullRequestActivityParams

type FactoryPullRequestActivityParams struct {
	RunID             uuid.UUID
	Title             string
	Description       string
	RevisionSHA       string
	Access            string
	FeedbackHandlerID *uuid.UUID
}

type FactoryPullRequestActivityResult

type FactoryPullRequestActivityResult struct {
	Activity        *FactoryPullRequestRun
	Revision        *FactoryPullRequestRevision
	CurrentRevision *FactoryPullRequestRevision
	Outcome         FactoryPullRequestActivityOutcome
}

type FactoryPullRequestFilter

type FactoryPullRequestFilter struct {
	WorkOrderID     *uuid.UUID
	WorkOrderIDs    []uuid.UUID
	WorkOrderNumber *int64
	State           string
	MergedFrom      *time.Time
	MergedTo        *time.Time
	ClosedFrom      *time.Time
	ClosedTo        *time.Time
}

type FactoryPullRequestLinkedRun

type FactoryPullRequestLinkedRun struct {
	Run          CanvasRun
	Title        string
	Description  string
	Access       string
	State        string
	Attempt      *int
	AttemptLimit *int
	Revision     *FactoryPullRequestRevision
}

type FactoryPullRequestLookup

type FactoryPullRequestLookup struct {
	ID         uuid.UUID
	Provider   string
	ExternalID string
	Repository string
	Number     int64
	URL        string
}

type FactoryPullRequestMergeabilitySnapshot

type FactoryPullRequestMergeabilitySnapshot struct {
	Mergeable      bool
	BlockedReason  string
	BlockedMessage string
	HeadSHA        string
	AllowedMethods string
}

type FactoryPullRequestObserveResult

type FactoryPullRequestObserveResult struct {
	Revision *FactoryPullRequestRevision
	Current  bool
}

type FactoryPullRequestParams

type FactoryPullRequestParams struct {
	Provider   string
	ExternalID string
	Repository string
	Number     int64
	URL        string
	Title      string
	State      string
	MergedAt   *time.Time
	ClosedAt   *time.Time
	Automation *factory.AutomationRef
	Run        *factory.RunRef
}

type FactoryPullRequestPatch

type FactoryPullRequestPatch struct {
	ExternalID *string
	Repository *string
	URL        *string
	Title      *string
	State      *string
	MergedAt   *time.Time
	ClosedAt   *time.Time
	Automation *factory.AutomationRef
	Run        *factory.RunRef
}

type FactoryPullRequestRevision

type FactoryPullRequestRevision struct {
	ID            uuid.UUID
	PullRequestID uuid.UUID
	SHA           string
	ObservedAt    time.Time
}

func FindPullRequestRevision

func FindPullRequestRevision(tx *gorm.DB, id uuid.UUID) (*FactoryPullRequestRevision, error)

func (FactoryPullRequestRevision) TableName

func (FactoryPullRequestRevision) TableName() string

type FactoryPullRequestRun

type FactoryPullRequestRun struct {
	PullRequestID     uuid.UUID `gorm:"primaryKey"`
	RunID             uuid.UUID `gorm:"primaryKey"`
	FeedbackHandlerID *uuid.UUID
	RevisionID        *uuid.UUID
	Access            string
	State             string
	Title             string
	Description       string
	Attempt           *int
	AttemptLimit      *int
	AccessRequestedAt *time.Time
	AccessGrantedAt   *time.Time
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

func FindPullRequestActivityByRunID

func FindPullRequestActivityByRunID(tx *gorm.DB, runID uuid.UUID) (*FactoryPullRequestRun, error)

func (*FactoryPullRequestRun) Finalize

func (a *FactoryPullRequestRun) Finalize(tx *gorm.DB, run *CanvasRun) error

func (*FactoryPullRequestRun) RequestExclusiveAccess

func (a *FactoryPullRequestRun) RequestExclusiveAccess(tx *gorm.DB) (*FactoryPullRequestAccessResult, error)

func (FactoryPullRequestRun) TableName

func (FactoryPullRequestRun) TableName() string

func (*FactoryPullRequestRun) UpdateContent

func (a *FactoryPullRequestRun) UpdateContent(tx *gorm.DB, title, description *string) error

type FactoryResourceCleaner

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

FactoryResourceCleaner hard-deletes factory-owned rows in FK-safe order after all factory canvases are gone. File objects are deleted by the cleanup worker before Run. Each Run deletes at most limit rows total so large factories finish across ticks without long transactions.

func NewFactoryResourceCleaner

func NewFactoryResourceCleaner(tx *gorm.DB, factory *Factory) *FactoryResourceCleaner

func (*FactoryResourceCleaner) Run

func (c *FactoryResourceCleaner) Run() (deleted int64, complete bool, err error)

Run deletes up to limit rows. complete is true when the factory row itself was hard-deleted.

func (*FactoryResourceCleaner) WithLimit

func (c *FactoryResourceCleaner) WithLimit(limit int) *FactoryResourceCleaner

type FactoryRuntimeCleaner

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

FactoryRuntimeCleaner deletes factory runtime rows and keeps the workspace itself: apps, lines, intakes, PR feedback handlers, and integrations.

func NewFactoryRuntimeCleaner

func NewFactoryRuntimeCleaner(tx *gorm.DB, factory *Factory) *FactoryRuntimeCleaner

func (*FactoryRuntimeCleaner) Run

func (c *FactoryRuntimeCleaner) Run() error

Run wipes work orders, runs, pull requests, planning, files, and related runtime rows, then sets next_work_order_number back to 1.

type FactorySystemSkill

type FactorySystemSkill struct {
	TemplateID  string `json:"templateId"`
	Version     int32  `json:"version"`
	ContentHash string `json:"contentHash"`
}

FactorySystemSkill records the supplied template separately from editable content. It is internal metadata; public resource mutation requests cannot set it.

type FactoryVCSCapabilities

type FactoryVCSCapabilities struct {
	PRClosure       bool
	PRFeedback      bool
	PRChecks        bool
	MergeConfidence bool
	Velocity        bool
	BoardMerge      bool
	BoardClose      bool
	VCSIssueIntake  bool
}

FactoryVCSCapabilities is the set of factory automations a Git host can run.

func FactoryVCSCapabilitiesFor

func FactoryVCSCapabilitiesFor(provider string) FactoryVCSCapabilities

FactoryVCSCapabilitiesFor returns the automations a provider can run. An empty provider uses the GitHub set. Bitbucket gains capabilities one step at a time; only issue intake stays off.

type FactoryVelocityMember

type FactoryVelocityMember struct {
	UserID    uuid.UUID
	Name      string
	Email     string
	AvatarURL string
	// The column tag is required: the default naming strategy maps this field to
	// "git_hub_login", so the query alias would not bind and every member would
	// look like they have no GitHub identity.
	GitHubLogin string `gorm:"column:github_login"`
	// BitbucketUUID is the normalized linked Bitbucket account UUID. Bitbucket
	// authors match on this only, never on nicknames.
	BitbucketUUID string `gorm:"column:bitbucket_uuid"`
}

FactoryVelocityMember is an organization member with the identity fields the velocity People table renders. GitHubLogin ties the member to the pull requests they authored in the connected repository.

func ListFactoryVelocityMembers

func ListFactoryVelocityMembers(tx *gorm.DB, orgID uuid.UUID) ([]FactoryVelocityMember, error)

ListFactoryVelocityMembers returns the human members of an organization with their GitHub identity, when they linked one, and their Bitbucket account UUID, when they linked that.

A member can arrive at a GitHub login two ways: they linked a GitHub account on purpose, or they sign in with GitHub. The link wins, because a member who links an account states which author they are. Signing in with GitHub stays a fallback so members who joined that way keep their attribution. Bitbucket matches on the linked UUID only, never on nicknames.

type FactoryVelocityPullRequest

type FactoryVelocityPullRequest struct {
	WorkOrderID uuid.UUID
	Repository  string
	URL         string
	Number      int64
	MergedAt    *time.Time
	ClosedAt    *time.Time
	// Member who opened the work order. Nil when an automation opened it.
	CreatedByID *uuid.UUID
	// Members assigned to the work order, earliest assignment first. Tied
	// assignments sort by user ID so the credited member stays stable.
	AssigneeIDs []uuid.UUID
	// Source of the intake that opened the work order (for example
	// `github-issues`). Empty when the order did not come from an intake.
	IntakeSource string
	// External ticket the work order was imported from. Imported orders carry
	// no intake run, so this is the only signal of where they came from.
	OriginURL string
	// Hours from the first execution start to the close event. Nil when the
	// order never ran or is still open.
	CycleHours *float64
}

FactoryVelocityPullRequest is one factory pull request that merged or closed inside a velocity window, joined to the work order that produced it. The attribution columns let the velocity report group merges by intake source and by the member assigned to the task.

func ListFactoryVelocityPullRequests

func ListFactoryVelocityPullRequests(
	tx *gorm.DB,
	factoryID uuid.UUID,
	from, to time.Time,
) ([]FactoryVelocityPullRequest, error)

ListFactoryVelocityPullRequests returns every factory pull request that merged or closed without merging in [from, to), with the work order attribution the velocity report groups by.

Close time comes from the latest `order.status.updated` event that moved the order to closed, matching how line metrics measure a closed order.

func (*FactoryVelocityPullRequest) Merged

func (p *FactoryVelocityPullRequest) Merged() bool

Merged reports whether the pull request landed. A pull request that carries no merge stamp and a close stamp is factory waste.

type FactoryVelocityRepositoryMerge

type FactoryVelocityRepositoryMerge struct {
	ID              uuid.UUID
	OrganizationID  uuid.UUID
	FactoryID       uuid.UUID
	Provider        string
	Repository      string
	Number          int64
	Source          string
	AuthorLogin     string
	AuthorUUID      string
	AuthorName      string
	AuthorAvatarURL string
	MergedAt        time.Time
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

FactoryVelocityRepositoryMerge is one merged pull request of a workspace's repository that SuperPlane did not open. The sync worker excludes the pull requests this instance opened before it stores a window, so this table and factory_pull_requests describe disjoint sets of pull requests.

MergedAt keeps the exact merge instant, so the velocity chart buckets a merge into the correct day whatever timezone it is rendered in.

Provider qualifies the merge by Git host. Rows written before provider tracking backfilled as github. AuthorUUID carries the Bitbucket account UUID for identity matching; GitHub rows match on login and leave it empty.

func ListFactoryVelocityRepositoryMerges

func ListFactoryVelocityRepositoryMerges(
	tx *gorm.DB,
	factoryID uuid.UUID,
	from, to time.Time,
) ([]FactoryVelocityRepositoryMerge, error)

ListFactoryVelocityRepositoryMerges returns the merges of [from, to), oldest first.

func NewFactoryVelocityRepositoryMerge

func NewFactoryVelocityRepositoryMerge(
	organizationID, factoryID uuid.UUID,
	repository string,
	number int64,
	source string,
	mergedAt time.Time,
) FactoryVelocityRepositoryMerge

NewFactoryVelocityRepositoryMerge normalizes the repository so the unique index matches whatever case the provider reported. An empty provider means github, so existing callers keep writing GitHub rows.

func (FactoryVelocityRepositoryMerge) IsAgent

IsAgent reports whether the SuperPlane agent wrote the merge.

func (FactoryVelocityRepositoryMerge) TableName

type FactoryVelocitySync

type FactoryVelocitySync struct {
	FactoryID      uuid.UUID `gorm:"primaryKey"`
	Repository     string
	SyncedAt       *time.Time
	BackfilledFrom *time.Time
	// SyncState records which batch read must continue.
	SyncState int
	Error     string
	CreatedAt time.Time
	UpdatedAt time.Time
}

FactoryVelocitySync records how far a workspace's repository sync has reached. Repository is the repository the stored pull requests belong to, so a workspace that changes its app repository restarts the backfill.

func ClaimFactoryVelocitySync

func ClaimFactoryVelocitySync(
	tx *gorm.DB,
	factoryID uuid.UUID,
	claimableBefore time.Time,
) (*FactoryVelocitySync, error)

ClaimFactoryVelocitySync takes ownership of a workspace's sync for the length of the lease, and returns nil when another worker holds it.

The claim is a single conditional UPDATE that moves updated_at forward, so no transaction is held while the worker talks to GitHub. A worker that dies mid-sync releases the workspace when the lease expires.

func FindFactoryVelocitySync

func FindFactoryVelocitySync(tx *gorm.DB, factoryID uuid.UUID) (*FactoryVelocitySync, error)

FindFactoryVelocitySync returns the sync row of a workspace. A workspace that has never synced has no row, and the caller gets gorm.ErrRecordNotFound.

func (*FactoryVelocitySync) CoversRepository

func (s *FactoryVelocitySync) CoversRepository(repository string) bool

CoversRepository reports whether the stored rows belong to the repository the workspace reports on now.

func (*FactoryVelocitySync) RecordError

func (s *FactoryVelocitySync) RecordError(tx *gorm.DB, message string) error

RecordError keeps synced_at untouched so the next tick retries the same window, and leaves the rows a previous sync stored in place.

func (*FactoryVelocitySync) RecordProgress

func (s *FactoryVelocitySync) RecordProgress(tx *gorm.DB, repository string, backfilledFrom, newestReadAt time.Time) error

RecordProgress saves a short slice without marking the sync finished. newestReadAt is when the newest pages were read. A zero time clears the stamp. A later slice keeps the earlier stamp so the finishing read can include merges made after the first slice. An active sync state stays unfinished even when the stamp is set.

func (*FactoryVelocitySync) RecordSuccess

func (s *FactoryVelocitySync) RecordSuccess(tx *gorm.DB, repository string, syncedAt, backfilledFrom time.Time) error

RecordSuccess stamps a finished sync and clears any earlier failure.

func (*FactoryVelocitySync) SyncInProgress

func (s *FactoryVelocitySync) SyncInProgress() bool

SyncInProgress reports a bounded read that has not finished. SyncedAt may still hold the time the newest pages were read. That stamp is not a finished sync.

func (FactoryVelocitySync) TableName

func (FactoryVelocitySync) TableName() string

type FactoryVelocitySyncTarget

type FactoryVelocitySyncTarget struct {
	FactoryID        uuid.UUID
	OrganizationID   uuid.UUID
	IntegrationID    uuid.UUID
	Repository       string
	VCSProvider      string
	SyncedRepository string
	SyncedAt         *time.Time
	BackfilledFrom   *time.Time
	SyncState        int
}

FactoryVelocitySyncTarget is a workspace the sync worker must visit, together with the integration and repository its setup selected. SyncedRepository is the repository the stored rows were collected for, which differs from Repository when the workspace changed its app repository.

func FindFactoryVelocitySyncTarget

func FindFactoryVelocitySyncTarget(
	tx *gorm.DB,
	factoryID uuid.UUID,
) (*FactoryVelocitySyncTarget, error)

FindFactoryVelocitySyncTarget returns one workspace's sync target, whatever its schedule says. A user asking for a refresh must not be turned away because the workspace is not due yet.

It reports nil when the workspace has no repository or no version control integration to read, which is a workspace the sync has nothing to do for.

func ListFactoryVelocitySyncTargets

func ListFactoryVelocitySyncTargets(
	tx *gorm.DB,
	staleBefore, claimableBefore time.Time,
	limit int,
) ([]FactoryVelocitySyncTarget, error)

ListFactoryVelocitySyncTargets returns the workspaces whose setup selected a GitHub integration and an app repository, whose last sync is older than staleBefore, and which no other worker is syncing now. A workspace that never synced comes first.

claimableBefore is the lease horizon: a row touched more recently than that is either freshly synced or in flight, and either way must be left alone.

type FactoryWorkOrder

type FactoryWorkOrder struct {
	ID              uuid.UUID
	OrganizationID  uuid.UUID
	FactoryID       uuid.UUID
	Number          int64
	Title           string
	Description     string
	State           string
	Result          string
	CreatedByID     *uuid.UUID
	SourceRunID     *uuid.UUID
	OriginURL       *string
	OriginLabel     *string
	Repository      *string
	DefaultBranch   *string
	VCSProvider     *string // Git host saved with the repository. Empty means a legacy GitHub row.
	AutoStartLineID *uuid.UUID
	MCPClientID     *string
	MCPClientName   *string
	// StatusNote is the jsonb array of current-wait announcements (see
	// FactoryWorkOrderStatusNote). Cleared on every state transition.
	StatusNote datatypes.JSON
	CreatedAt  time.Time
	UpdatedAt  time.Time

	CreatedBy *User                      `gorm:"foreignKey:CreatedByID"`
	Assignees []FactoryWorkOrderAssignee `gorm:"foreignKey:WorkOrderID"`
}

func FindPlanningWorkOrder

func FindPlanningWorkOrder(tx *gorm.DB, organizationID, factoryID, orderID uuid.UUID) (*FactoryWorkOrder, error)

func FindUnscopedWorkOrder

func FindUnscopedWorkOrder(db *gorm.DB, id uuid.UUID) (*FactoryWorkOrder, error)

NOTE: this is only OK to be used in the workers. For APIs, always use the factory.FindWorkOrder method.

func (*FactoryWorkOrder) AbandonActiveLineDispatch

func (o *FactoryWorkOrder) AbandonActiveLineDispatch(tx *gorm.DB) ([]*FactoryLineStepResult, error)

AbandonActiveLineDispatch finishes the current traversal as cancelled so a new dispatch can start. No-op when no active dispatch exists. The return lists every step this abandon started, because the traversal releases its parallelism slots and waiters move in. The caller must publish those runs after commit.

func (*FactoryWorkOrder) AddAssignee

func (o *FactoryWorkOrder) AddAssignee(tx *gorm.DB, userID uuid.UUID, actor uuid.UUID) (bool, error)

AddAssignee adds one person to the owners and keeps the others. It reports whether the list changed; it is a no-op when the person is already assigned. Used when someone takes part in refining a draft: a reply in the chat makes them an owner.

func (*FactoryWorkOrder) AssigneeIDs

func (o *FactoryWorkOrder) AssigneeIDs() []uuid.UUID

func (*FactoryWorkOrder) ClaimAutoStart

func (o *FactoryWorkOrder) ClaimAutoStart(tx *gorm.DB, lineID uuid.UUID) (bool, error)

func (*FactoryWorkOrder) ClearAutoStart

func (o *FactoryWorkOrder) ClearAutoStart(tx *gorm.DB) (bool, error)

func (*FactoryWorkOrder) ClearStatusNote

func (o *FactoryWorkOrder) ClearStatusNote(tx *gorm.DB, key string) error

ClearStatusNote removes the note with the given key. Unknown keys are a no-op. Lifecycle transitions clear the whole set in UpdateStatus.

func (*FactoryWorkOrder) ClearStatusNotes

func (o *FactoryWorkOrder) ClearStatusNotes(tx *gorm.DB) error

ClearStatusNotes removes every note without a state transition, for waits that all resolve while the order stays open.

func (*FactoryWorkOrder) Close

func (o *FactoryWorkOrder) Close(db *gorm.DB, result string, closedBy *uuid.UUID) (*FactoryWorkOrder, error)

Close is kept for backwards compatibility with existing handlers. New code should call UpdateStatus directly.

func (*FactoryWorkOrder) CountEvents

func (o *FactoryWorkOrder) CountEvents(tx *gorm.DB) (int64, error)

func (*FactoryWorkOrder) CreateArtifact

CreateArtifact writes the row and its `order.artifact.added` event in the same transaction so the timeline can't diverge from the list.

func (*FactoryWorkOrder) CreatePullRequest

func (o *FactoryWorkOrder) CreatePullRequest(
	tx *gorm.DB,
	params FactoryPullRequestParams,
) (*FactoryPullRequest, error)

func (*FactoryWorkOrder) DeleteArtifacts

func (o *FactoryWorkOrder) DeleteArtifacts(tx *gorm.DB, actor *uuid.UUID) (int, error)

DeleteArtifacts removes every artifact row for this order and records one timeline event. It does not delete git branches.

func (*FactoryWorkOrder) FindActiveLineDispatch

func (o *FactoryWorkOrder) FindActiveLineDispatch(tx *gorm.DB) (*FactoryWorkOrderLineDispatch, error)

FindActiveLineDispatch is a single indexed lookup ("does an active traversal exist for this work order") replacing a scan over child executions by status.

func (*FactoryWorkOrder) FindArtifactByKey

func (o *FactoryWorkOrder) FindArtifactByKey(tx *gorm.DB, key string) (*FactoryWorkOrderArtifact, error)

UpdateArtifactData resolves the artifact tagged with `key` under this work order (the same key an earlier CreateArtifact call set via FactoryWorkOrderArtifactParams.Key, typically the PR's URL), shallow- merges `updates` into its existing `data` map, and re-saves it in place. Unlike CreateArtifact, this does not append a new `order.artifact.*` timeline event — a PR flipping open → draft → merged should update the live chip, not spam the timeline with one entry per transition. Callers still notify the websocket channel (see FactoryContext websocket notify) so the UI refreshes.

func (*FactoryWorkOrder) IsArchived

func (o *FactoryWorkOrder) IsArchived() bool

shortcut: legacy rejected records may be archives; classify them before making them visible.

func (*FactoryWorkOrder) IsClosed

func (o *FactoryWorkOrder) IsClosed() bool

func (*FactoryWorkOrder) IsDispatchable

func (o *FactoryWorkOrder) IsDispatchable() bool

IsDispatchable reports whether the work order can be dispatched; the first dispatch from `draft` also promotes it to `open`.

func (*FactoryWorkOrder) IsOpen

func (o *FactoryWorkOrder) IsOpen() bool

func (*FactoryWorkOrder) ListArtifacts

func (o *FactoryWorkOrder) ListArtifacts(tx *gorm.DB) ([]FactoryWorkOrderArtifact, error)

func (*FactoryWorkOrder) ListAssignees

func (o *FactoryWorkOrder) ListAssignees(tx *gorm.DB) ([]FactoryWorkOrderAssignee, error)

func (*FactoryWorkOrder) ListChecks

func (o *FactoryWorkOrder) ListChecks(tx *gorm.DB) ([]FactoryWorkOrderCheck, error)

func (*FactoryWorkOrder) ListComments

func (o *FactoryWorkOrder) ListComments(tx *gorm.DB) ([]FactoryWorkOrderComment, error)

ListComments returns the work order's comment thread, oldest first — unlike ListEvents (which is DESC for activity feeds), a comment thread reads chronologically oldest→newest.

func (*FactoryWorkOrder) ListEvents

func (o *FactoryWorkOrder) ListEvents(tx *gorm.DB, limit int, before *time.Time) ([]FactoryWorkOrderEvent, error)

func (*FactoryWorkOrder) ListRuns

func (o *FactoryWorkOrder) ListRuns(tx *gorm.DB) ([]CanvasRun, error)

ListRuns includes task automations, line steps, PR activity, and their descendants. A creator run shared by other tasks is left out, including as a root for descendants.

func (*FactoryWorkOrder) LockForUpdate

func (o *FactoryWorkOrder) LockForUpdate(tx *gorm.DB) error

func (*FactoryWorkOrder) MCPClient

func (o *FactoryWorkOrder) MCPClient() *WorkOrderMCPClient

func (*FactoryWorkOrder) Origin

func (o *FactoryWorkOrder) Origin() *WorkOrderOrigin

func (*FactoryWorkOrder) RecordArtifactAdded

func (o *FactoryWorkOrder) RecordArtifactAdded(
	tx *gorm.DB,
	artifact *factory.ArtifactRef,
	actor *uuid.UUID,
	automation *factory.AutomationRef,
	run *factory.RunRef,
) error

func (*FactoryWorkOrder) RecordArtifactsCleared

func (o *FactoryWorkOrder) RecordArtifactsCleared(tx *gorm.DB, count int, actor *uuid.UUID) error

func (*FactoryWorkOrder) RecordAssigneesUpdated

func (o *FactoryWorkOrder) RecordAssigneesUpdated(
	tx *gorm.DB,
	updatedBy uuid.UUID,
	assigned []factory.UserRef,
	unassigned []factory.UserRef,
) error

func (*FactoryWorkOrder) RecordCommentAdded

func (o *FactoryWorkOrder) RecordCommentAdded(
	tx *gorm.DB,
	params FactoryWorkOrderCommentParams,
) (*FactoryWorkOrderComment, error)

func (*FactoryWorkOrder) RecordPullRequestAdded

func (o *FactoryWorkOrder) RecordPullRequestAdded(
	tx *gorm.DB,
	pullRequest *factory.PullRequestRef,
	automation *factory.AutomationRef,
	run *factory.RunRef,
) error

func (*FactoryWorkOrder) RecordPullRequestUpdated

func (o *FactoryWorkOrder) RecordPullRequestUpdated(
	tx *gorm.DB,
	pullRequest *factory.PullRequestRef,
	automation *factory.AutomationRef,
	run *factory.RunRef,
) error

func (*FactoryWorkOrder) RecordStatusUpdated

func (o *FactoryWorkOrder) RecordStatusUpdated(tx *gorm.DB, r statusUpdatedRecord) error

func (*FactoryWorkOrder) Ref

func (*FactoryWorkOrder) ReplaceAssignees

func (o *FactoryWorkOrder) ReplaceAssignees(tx *gorm.DB, assigneeIDs []uuid.UUID) error

func (*FactoryWorkOrder) ReportCheck

ReportCheck upserts the check row keyed by (work order, key) and records an `order.check.reported` event in the same transaction. A re-report of an existing key keeps that report's score as PreviousScore so the UI can show the movement.

func (*FactoryWorkOrder) RetryLineStep

func (o *FactoryWorkOrder) RetryLineStep(tx *gorm.DB, line *FactoryLine, stepIndex int) (*FactoryLineStepResult, []*FactoryLineStepResult, error)

RetryLineStep starts stepIndex again on a traversal that already ran earlier steps. It does not open a new dispatch, so earlier steps stay on the same history. The second return lists every started step that has a canvas run, including waiters this retry admitted. The caller must publish those runs after commit.

func (*FactoryWorkOrder) SetMCPClient

func (o *FactoryWorkOrder) SetMCPClient(tx *gorm.DB, id, name string) error

func (*FactoryWorkOrder) SetStatusNote

SetStatusNote validates and upserts the note by Key. Only open orders can carry notes: a draft was never dispatched and a closed order is not waiting on anything. The write locks the row and reloads the stored list so concurrent sets with different keys keep both notes, and a close that already committed is not overwritten.

func (*FactoryWorkOrder) StatusNotes

func (o *FactoryWorkOrder) StatusNotes() ([]FactoryWorkOrderStatusNote, error)

StatusNotes decodes the notes stored on the row. Returns nil when the order has no status notes.

func (*FactoryWorkOrder) StorePlanningSpec

func (o *FactoryWorkOrder) StorePlanningSpec(tx *gorm.DB, body string) error

func (FactoryWorkOrder) TableName

func (FactoryWorkOrder) TableName() string

func (*FactoryWorkOrder) TransitionOnDispatch

func (o *FactoryWorkOrder) TransitionOnDispatch(tx *gorm.DB, actor *uuid.UUID) error

TransitionOnDispatch promotes a draft order to open; open is a no-op. Any other state rejects the dispatch.

func (*FactoryWorkOrder) URLPath

func (o *FactoryWorkOrder) URLPath(factoryRouteSegment string) string

URLPath is the canonical UI permalink of the work order, relative to the server base URL. `factoryRouteSegment` is the workspace URL segment (`key-urlId`). Callers that only hold the order must load the factory that owns it and pass Factory.RouteSegment().

func (*FactoryWorkOrder) UpdateArtifactData

func (o *FactoryWorkOrder) UpdateArtifactData(
	tx *gorm.DB,
	key string,
	updates map[string]any,
) (*FactoryWorkOrderArtifact, error)

func (*FactoryWorkOrder) UpdateAssignees

func (o *FactoryWorkOrder) UpdateAssignees(tx *gorm.DB, assigneeIDs []uuid.UUID, updatedBy uuid.UUID) error

func (*FactoryWorkOrder) UpdateContent

func (o *FactoryWorkOrder) UpdateContent(tx *gorm.DB, title *string, description *string) error

func (*FactoryWorkOrder) UpdateStatus

func (o *FactoryWorkOrder) UpdateStatus(db *gorm.DB, update FactoryWorkOrderStatusUpdate) (bool, error)

UpdateStatus is the single writer for the work order lifecycle: it validates the transition, updates the row, and records an `order.status.updated` event enriched with the caller's attribution (actor / automation / run + app). On the initial `draft → open` we also snapshot the originating run/app from `o.SourceRunID`, so the timeline can always trace an order back to the run that created it. When a person opens the draft, they become the owner.

The bool return reports whether a transition was actually recorded: `true` on a real state change, `false` when SkipSame swallowed a no-op (target state equals current state). Callers that fan out an `order.status.updated` event downstream must check this so a re-run doesn't emit a phantom transition — see FactoryContext.

func (*FactoryWorkOrder) UpsertArtifact

UpsertArtifact creates the artifact, or replaces its data when a key already points at one on this work order. The bool is true when a new row was inserted. An empty key always inserts.

func (*FactoryWorkOrder) UpsertArtifactByTypeAndTitle

func (o *FactoryWorkOrder) UpsertArtifactByTypeAndTitle(
	db *gorm.DB,
	params FactoryWorkOrderArtifactParams,
) (*FactoryWorkOrderArtifact, bool, error)

UpsertArtifactByTypeAndTitle creates an unkeyed artifact, or replaces the newest unkeyed artifact on this work order with the same type and trimmed title. Rows that already have a key stay unchanged. The bool is true when a new row was inserted. A blank title fails. Replacement is wholesale and does not write a timeline event. The work order row stays locked from the lookup through the write so two first updates cannot both insert.

type FactoryWorkOrderArtifact

type FactoryWorkOrderArtifact struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	Type           string
	Data           datatypes.JSON
	Key            *string
	CreatedByID    *uuid.UUID
	CreatedAt      time.Time

	CreatedBy *User `gorm:"foreignKey:CreatedByID"`
}

func (FactoryWorkOrderArtifact) TableName

func (FactoryWorkOrderArtifact) TableName() string

type FactoryWorkOrderArtifactParams

type FactoryWorkOrderArtifactParams struct {
	Type       string
	Data       map[string]any
	Key        string
	CreatedBy  *uuid.UUID
	Automation *factory.AutomationRef
	Run        *factory.RunRef
}

type FactoryWorkOrderAssignee

type FactoryWorkOrderAssignee struct {
	WorkOrderID uuid.UUID `gorm:"primaryKey"`
	UserID      uuid.UUID `gorm:"primaryKey"`
	CreatedAt   time.Time

	User *User `gorm:"foreignKey:UserID"`
}

func (FactoryWorkOrderAssignee) TableName

func (FactoryWorkOrderAssignee) TableName() string

type FactoryWorkOrderCheck

type FactoryWorkOrderCheck struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	Key            string
	Name           string
	Score          float64
	MaxScore       float64
	Format         string
	Level          string
	PreviousScore  *float64
	// RecentScores holds the latest report scores, oldest first and
	// ending with Score, capped at MaxFactoryWorkOrderCheckRecentScores.
	RecentScores datatypes.JSONSlice[float64]
	Summary      string
	Analysis     string
	Automation   datatypes.JSON
	RunID        *uuid.UUID
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

FactoryWorkOrderCheck is latest-only state: one row per (work order, key), updated in place on every report. History lives in `order.check.reported` timeline events, not in extra rows.

func (*FactoryWorkOrderCheck) AutomationRef

func (c *FactoryWorkOrderCheck) AutomationRef() (*factory.AutomationRef, error)

AutomationRef decodes the automation snapshot stored on the row. Returns nil when the check has no automation attribution.

func (FactoryWorkOrderCheck) TableName

func (FactoryWorkOrderCheck) TableName() string

type FactoryWorkOrderCheckParams

type FactoryWorkOrderCheckParams struct {
	Key        string
	Name       string
	Score      float64
	MaxScore   float64
	Format     string
	Level      string
	Summary    string
	Analysis   string
	Automation *factory.AutomationRef
	Run        *factory.RunRef
}

type FactoryWorkOrderComment

type FactoryWorkOrderComment struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	AuthorUserID   *uuid.UUID
	AuthorKind     string
	Automation     datatypes.JSON
	SourceRunID    *uuid.UUID
	Body           string
	CreatedAt      time.Time
	UpdatedAt      time.Time

	// MentionedUserIDs is filled after RecordCommentAdded persists
	// mention rows. It is not a database column.
	MentionedUserIDs []uuid.UUID `gorm:"-"`
}

FactoryWorkOrderComment is a first-class work order comment. Timeline events still record `order.comment.added`; this row is the source of truth for the thread, mentions, and `order().comments`.

func (*FactoryWorkOrderComment) Author

Author reconstructs the timeline author payload from the comment row.

func (*FactoryWorkOrderComment) RunRef

func (c *FactoryWorkOrderComment) RunRef() *factory.RunRef

func (FactoryWorkOrderComment) TableName

func (FactoryWorkOrderComment) TableName() string

type FactoryWorkOrderCommentMention

type FactoryWorkOrderCommentMention struct {
	CommentID uuid.UUID
	UserID    uuid.UUID
	CreatedAt time.Time
}

func (FactoryWorkOrderCommentMention) TableName

type FactoryWorkOrderCommentParams

type FactoryWorkOrderCommentParams struct {
	Body             string
	Author           factory.WorkOrderCommentAuthor
	Run              *factory.RunRef
	MentionedUserIDs []uuid.UUID
}

FactoryWorkOrderCommentParams carries the fields RecordCommentAdded needs to persist a comment, its mentions, and the timeline event.

type FactoryWorkOrderEvent

type FactoryWorkOrderEvent struct {
	ID          uuid.UUID
	WorkOrderID uuid.UUID
	Type        string
	Data        datatypes.JSON
	CreatedAt   time.Time
}

type FactoryWorkOrderExecution

type FactoryWorkOrderExecution struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	LineID         uuid.UUID
	// LineDispatchID is the parent traversal this step run belongs to. Its
	// steps snapshot is authoritative for what StepIndex refers to —
	// see FactoryWorkOrderLineDispatch. StepName is the automation
	// (canvas) name captured when the step started.
	LineDispatchID uuid.UUID
	StepIndex      int
	StepName       string
	RunID          *uuid.UUID
	Status         string
	Result         string
	// Aggregate usage populated by runners. All default to zero; the API
	// only surfaces non-zero values to the UI.
	TotalTokens     int64
	DurationSeconds int64
	CostCents       int64
	// FailureReason explains why the step failed before it could run.
	// Only SuperPlane hosted credit failures set it; see
	// WorkOrderExecutionFailureReasonFor.
	FailureReason *string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	FinishedAt    *time.Time
}

func FindWorkOrderExecutionByRunID

func FindWorkOrderExecutionByRunID(tx *gorm.DB, runID uuid.UUID) (*FactoryWorkOrderExecution, error)

func FindWorkOrderExecutionForRun

func FindWorkOrderExecutionForRun(tx *gorm.DB, runID uuid.UUID) (*FactoryWorkOrderExecution, error)

FindWorkOrderExecutionForRun returns the factory step for this run or an ancestor. Child runs created by ctx.Runs.Create keep a different run ID than the factory line step, so a direct lookup would drop their spend.

func (*FactoryWorkOrderExecution) MarkFinished

func (e *FactoryWorkOrderExecution) MarkFinished(tx *gorm.DB, result string) error

func (*FactoryWorkOrderExecution) MarkRunning

func (e *FactoryWorkOrderExecution) MarkRunning(tx *gorm.DB) error

func (*FactoryWorkOrderExecution) RecordFinished

func (e *FactoryWorkOrderExecution) RecordFinished(tx *gorm.DB, result string) error

func (*FactoryWorkOrderExecution) RollupUsage

func (e *FactoryWorkOrderExecution) RollupUsage(tx *gorm.DB) error

RollupUsage copies ledger totals into the cached execution columns. It locks the step row so concurrent RecordUsage calls cannot write a stale sum over a newer one.

type FactoryWorkOrderExecutionRecord

type FactoryWorkOrderExecutionRecord struct {
	FactoryWorkOrderExecution
	CanvasID   *uuid.UUID
	CanvasName string
	RunState   string
	RunResult  string
}

FactoryWorkOrderExecutionRecord is a step execution enriched with the canvas run details the API/UI need to render it. Its line/steps information now lives on the parent FactoryWorkOrderLineDispatch instead of being joined/serialized per execution.

type FactoryWorkOrderLineDispatch

type FactoryWorkOrderLineDispatch struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	LineID         uuid.UUID
	LineName       string
	Steps          datatypes.JSONSlice[FactoryLineStep]
	State          string
	Result         string
	// Model is the optional Start override for this traversal. Empty means
	// Auto: each runner keeps the model stored on the live canvas.
	Model string
	// ThinkingLevel is the optional Start thinking override. Empty means
	// Auto: each runner keeps the thinking level stored on the live canvas.
	ThinkingLevel string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	FinishedAt    *time.Time
}

FactoryWorkOrderLineDispatch is one traversal of a work order through a factory line: "this work order's pass through Line 1". It snapshots the line's steps at dispatch time and carries the traversal's state/result, so both are read directly instead of being derived from child step executions every time they're needed. See issue #6737.

func FindWorkOrderLineDispatch

func FindWorkOrderLineDispatch(tx *gorm.DB, id uuid.UUID) (*FactoryWorkOrderLineDispatch, error)

func LockWorkOrderLineDispatch

func LockWorkOrderLineDispatch(tx *gorm.DB, id uuid.UUID) (*FactoryWorkOrderLineDispatch, error)

LockWorkOrderLineDispatch reads the traversal with a row lock. The finalizer takes it before it decides how the traversal continues, so a rerun cannot reactivate the traversal and start a step between the open-work check and the state change.

func (*FactoryWorkOrderLineDispatch) EnqueueOrStartStep

func (l *FactoryWorkOrderLineDispatch) EnqueueOrStartStep(tx *gorm.DB, order *FactoryWorkOrder, stepIndex int) (*FactoryLineStepResult, error)

EnqueueOrStartStep starts the step at stepIndex when it has a free slot, or queues the dispatch for admission when the step is at its maxParallelism. The step's queue is FIFO: when other dispatches already wait for the step, the newcomer joins the back of the queue even if a slot is free (a raised maxParallelism can leave free slots behind queued work). It takes the line's admission lock, so concurrent decisions for the same line cannot both see the last free slot.

func (*FactoryWorkOrderLineDispatch) Finish

func (l *FactoryWorkOrderLineDispatch) Finish(tx *gorm.DB, result string) error

func (*FactoryWorkOrderLineDispatch) HasOpenWork

func (l *FactoryWorkOrderLineDispatch) HasOpenWork(tx *gorm.DB) (bool, error)

HasOpenWork reports whether a step of the traversal is queued, pending, or running. A traversal with open work has a live owner: it must not finish, and no other step run may advance it.

func (*FactoryWorkOrderLineDispatch) IsActive

func (l *FactoryWorkOrderLineDispatch) IsActive() bool

func (*FactoryWorkOrderLineDispatch) Reactivate

func (l *FactoryWorkOrderLineDispatch) Reactivate(tx *gorm.DB) error

Reactivate opens a finished traversal again so a later step can start on the same history. No-op if the dispatch is already active.

func (*FactoryWorkOrderLineDispatch) RecordStepExecutionCreated

func (l *FactoryWorkOrderLineDispatch) RecordStepExecutionCreated(
	tx *gorm.DB,
	order *FactoryWorkOrder,
	execution *FactoryWorkOrderExecution,
	run *CanvasRun,
) error

func (*FactoryWorkOrderLineDispatch) RecordStepExecutionQueued

func (l *FactoryWorkOrderLineDispatch) RecordStepExecutionQueued(
	tx *gorm.DB,
	order *FactoryWorkOrder,
	item *FactoryWorkOrderQueueItem,
	step *FactoryLineStep,
) error

func (*FactoryWorkOrderLineDispatch) Ref

func (*FactoryWorkOrderLineDispatch) StartStep

func (l *FactoryWorkOrderLineDispatch) StartStep(tx *gorm.DB, order *FactoryWorkOrder, stepIndex int) (*FactoryLineStepResult, error)

StartStep launches the step at stepIndex in the dispatch's steps snapshot — not the line's live steps — so a line edited mid-traversal can't change what runs next for an in-flight dispatch.

func (FactoryWorkOrderLineDispatch) TableName

type FactoryWorkOrderLineDispatchRecord

type FactoryWorkOrderLineDispatchRecord struct {
	FactoryWorkOrderLineDispatch
	Executions []FactoryWorkOrderExecutionRecord
	QueueItem  *FactoryWorkOrderQueueItemRecord
}

FactoryWorkOrderLineDispatchRecord is a line dispatch with its child step executions — and, when the dispatch is waiting for step admission, its queue item — preloaded, as used by the serialization layer.

type FactoryWorkOrderQueueItem

type FactoryWorkOrderQueueItem struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	WorkOrderID    uuid.UUID
	LineID         uuid.UUID
	LineDispatchID uuid.UUID
	StepIndex      int
	StepName       string
	CreatedAt      time.Time
}

FactoryWorkOrderQueueItem is a line dispatch waiting for admission into a step that is at its maxParallelism. No run or execution exists for it yet; both are created when the step admits the dispatch, and the queue item is deleted. A dispatch waits at no more than one step at a time (line_dispatch_id is unique).

func (*FactoryWorkOrderQueueItem) Delete

func (i *FactoryWorkOrderQueueItem) Delete(tx *gorm.DB) error

type FactoryWorkOrderQueueItemRecord

type FactoryWorkOrderQueueItemRecord struct {
	FactoryWorkOrderQueueItem
	Position int
}

FactoryWorkOrderQueueItemRecord is a queue item joined with its 1-based position inside the step's queue, for API serialization.

type FactoryWorkOrderStatusNote

type FactoryWorkOrderStatusNote struct {
	Key      string `json:"key"`
	Kind     string `json:"kind"`
	Headline string `json:"headline"`
	Body     string `json:"body,omitempty"`
	CtaLabel string `json:"ctaLabel,omitempty"`
	CtaURL   string `json:"ctaUrl,omitempty"`
	// ShowOnlyWhenWaiting hides the note on the work order page while a
	// line is running. The default is false: the note stays visible
	// for the whole open wait, including an active dispatch.
	ShowOnlyWhenWaiting bool `json:"showOnlyWhenWaiting,omitempty"`
	// Automation and Run snapshot who announced the wait, captured at
	// write time like check attribution.
	Automation *factory.AutomationRef `json:"automation,omitempty"`
	Run        *factory.RunRef        `json:"run,omitempty"`
	UpdatedAt  time.Time              `json:"updatedAt"`
}

FactoryWorkOrderStatusNote is one current-wait announcement. Notes live as a jsonb array on the work order row, keyed like checks: the first set of a key creates the note, a later set with the same key updates it in place, and a different key sits beside it. Kind is the payload shape (`info` today), not the identity. Any lifecycle transition clears the whole set (see FactoryWorkOrder.UpdateStatus).

type FactoryWorkOrderStatusNoteParams

type FactoryWorkOrderStatusNoteParams struct {
	Key                 string
	Kind                string
	Headline            string
	Body                string
	CtaLabel            string
	CtaURL              string
	ShowOnlyWhenWaiting bool
	Automation          *factory.AutomationRef
	Run                 *factory.RunRef
}

type FactoryWorkOrderStatusUpdate

type FactoryWorkOrderStatusUpdate struct {
	ToState         string
	Result          string
	Actor           *uuid.UUID
	Automation      *factory.AutomationRef
	Run             *factory.RunRef
	App             *factory.AppRef
	SkipSame        bool // when true, no-op transitions to the current state succeed silently
	OnRunsCancelled func([]*RunCancellationResult)
}

FactoryWorkOrderStatusUpdate captures a requested transition through the shared status FSM. Actor / Automation / Run + App are optional attribution fields that populate the emitted `order.status.updated` event.

type File

type File struct {
	ID             uuid.UUID
	InstallationID string
	Scope          string
	OrganizationID *uuid.UUID
	FactoryID      *uuid.UUID
	WorkOrderID    *uuid.UUID
	Filename       string
	ContentType    string
	SizeBytes      int64
	Checksum       *string
	StorageKey     string
	State          string
	Purpose        string `gorm:"default:attachment"`
	PublicID       *uuid.UUID
	CreatedByID    *uuid.UUID
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

func CreatePendingFile

func CreatePendingFile(tx *gorm.DB, params CreateFileParams) (*File, error)

func FindFile

func FindFile(tx *gorm.DB, id uuid.UUID) (*File, error)

func FindReadyArtifactFileByPublicID

func FindReadyArtifactFileByPublicID(tx *gorm.DB, publicID uuid.UUID) (*File, error)

func ListFilesByIDs

func ListFilesByIDs(tx *gorm.DB, ids []uuid.UUID) ([]File, error)

func ListFilesForFactory

func ListFilesForFactory(tx *gorm.DB, factoryID uuid.UUID, limit int) ([]File, error)

func ListFilesForOrganization

func ListFilesForOrganization(tx *gorm.DB, organizationID uuid.UUID, limit int) ([]File, error)

func ListReadyTaskFiles

func ListReadyTaskFiles(tx *gorm.DB, workOrderID uuid.UUID) ([]File, error)

func ListReadyWorkspaceFiles

func ListReadyWorkspaceFiles(tx *gorm.DB, factoryID uuid.UUID) ([]File, error)

func ListStalePendingFiles

func ListStalePendingFiles(tx *gorm.DB, before time.Time, limit int) ([]File, error)

func (*File) Delete

func (f *File) Delete(tx *gorm.DB) error

func (File) IsDispatchable

func (f File) IsDispatchable(organizationID, factoryID, workOrderID uuid.UUID) bool

func (*File) MarkFailed

func (f *File) MarkFailed(tx *gorm.DB) error

func (*File) MarkReady

func (f *File) MarkReady(tx *gorm.DB, sizeBytes int64, checksum string) error

func (File) MaxBytes

func (f File) MaxBytes() int64

func (*File) ReparentToTask

func (f *File) ReparentToTask(tx *gorm.DB, workOrderID uuid.UUID, storageKey string) error

func (File) TableName

func (File) TableName() string

type FleetStateCount

type FleetStateCount struct {
	FleetID    uuid.UUID
	FleetSlug  string
	FleetScope string
	State      string
	Count      int64
}

func ListRunnerCountsByFleetState

func ListRunnerCountsByFleetState(tx *gorm.DB) ([]FleetStateCount, error)

func ListRunnerTaskCountsByFleetState

func ListRunnerTaskCountsByFleetState(tx *gorm.DB) ([]FleetStateCount, error)

type GroupMetadata

type GroupMetadata struct {
	ID          uuid.UUID `json:"id" gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	GroupName   string    `json:"group_name" gorm:"not null;index"`
	DomainType  string    `json:"domain_type" gorm:"not null;index"`
	DomainID    string    `json:"domain_id" gorm:"not null;index"`
	DisplayName string    `json:"display_name" gorm:"not null"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

func FindGroupMetadata

func FindGroupMetadata(groupName, domainType, domainID string) (*GroupMetadata, error)

func (*GroupMetadata) BeforeCreate

func (gm *GroupMetadata) BeforeCreate(tx *gorm.DB) error

func (*GroupMetadata) Create

func (gm *GroupMetadata) Create() error

func (*GroupMetadata) CreateInTransaction

func (gm *GroupMetadata) CreateInTransaction(tx *gorm.DB) error

func (*GroupMetadata) Update

func (gm *GroupMetadata) Update() error

func (*GroupMetadata) UpdateInTransaction

func (gm *GroupMetadata) UpdateInTransaction(tx *gorm.DB) error

type HostedLLMProvider

type HostedLLMProvider struct {
	ID            uuid.UUID
	Provider      string
	Enabled       bool
	APIKey        []byte
	ManagementKey []byte
	BaseURL       string
	AllowedModels datatypes.JSONSlice[string]
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

HostedLLMProvider is one SuperPlane-held provider key and model allowlist.

func FindHostedLLMProvider

func FindHostedLLMProvider(tx *gorm.DB, provider string) (*HostedLLMProvider, error)

func ListHostedLLMProviders

func ListHostedLLMProviders(tx *gorm.DB) ([]HostedLLMProvider, error)

func RequireEnabledHostedLLMProvider

func RequireEnabledHostedLLMProvider(tx *gorm.DB, provider string) (*HostedLLMProvider, error)

func UpsertHostedLLMProvider

func UpsertHostedLLMProvider(tx *gorm.DB, provider HostedLLMProvider) (*HostedLLMProvider, error)

func (HostedLLMProvider) AllowsModel

func (p HostedLLMProvider) AllowsModel(model string) bool

func (HostedLLMProvider) CanRunHosted

func (p HostedLLMProvider) CanRunHosted() bool

func (HostedLLMProvider) HasAPIKey

func (p HostedLLMProvider) HasAPIKey() bool

func (HostedLLMProvider) HasAllowedModel

func (p HostedLLMProvider) HasAllowedModel() bool

func (HostedLLMProvider) HasManagementKey

func (p HostedLLMProvider) HasManagementKey() bool

func (HostedLLMProvider) OffersHostedModels

func (p HostedLLMProvider) OffersHostedModels() bool

OffersHostedModels is true when SuperPlane can resolve hosted credentials. A saved API key and allowlist are enough, even if the admin enable switch is off.

func (HostedLLMProvider) TableName

func (HostedLLMProvider) TableName() string

type IncludedUsageSync

type IncludedUsageSync struct {
	OrganizationID   uuid.UUID
	SubscriptionID   string
	PeriodEnd        *time.Time
	GrantIncluded    bool
	IsActiveBusiness bool
}

type InstallationGitHubApp

type InstallationGitHubApp struct {
	ID                     int   `gorm:"primary_key"`
	GitHubAppID            int64 `gorm:"column:github_app_id"`
	Slug                   string
	EncryptedPrivateKey    []byte
	EncryptedWebhookSecret []byte
	CreatedAt              time.Time
	UpdatedAt              time.Time
}

InstallationGitHubApp stores the public SuperPlane GitHub App for a self-hosted installation. There is at most one row. Cloud keeps the same credentials in process environment instead of this table.

func FindInstallationGitHubApp

func FindInstallationGitHubApp(tx *gorm.DB) (*InstallationGitHubApp, error)

func (InstallationGitHubApp) TableName

func (InstallationGitHubApp) TableName() string

type InstallationLLMSettings

type InstallationLLMSettings struct {
	ID                    int `gorm:"primary_key"`
	WelcomeGrantCents     int64
	MarkupBPS             int
	WarningThresholdBPS   int
	DefaultHostedProvider *string
	DefaultHostedModel    *string
	CreatedAt             time.Time
	UpdatedAt             time.Time
}

InstallationLLMSettings is the singleton hosted-LLM catalog policy.

func GetInstallationLLMSettings

func GetInstallationLLMSettings(tx *gorm.DB) (*InstallationLLMSettings, error)

func UpdateInstallationLLMSettings

func UpdateInstallationLLMSettings(tx *gorm.DB, settings InstallationLLMSettings) (*InstallationLLMSettings, error)

func (InstallationLLMSettings) TableName

func (InstallationLLMSettings) TableName() string

type InstallationLicense

type InstallationLicense struct {
	ID               int `gorm:"primary_key"`
	EncryptedLicense []byte
	InstalledBy      *uuid.UUID
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

InstallationLicense stores the encrypted Enterprise license for the whole installation. There is at most one row.

func FindInstallationLicense

func FindInstallationLicense(tx *gorm.DB) (*InstallationLicense, error)

FindInstallationLicense returns gorm.ErrRecordNotFound when no license is installed.

func (InstallationLicense) TableName

func (InstallationLicense) TableName() string

type InstallationLicenseKeys

type InstallationLicenseKeys struct {
	ID        int `gorm:"primary_key"`
	Document  string
	Version   int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

InstallationLicenseKeys caches the newest root-signed list of license signing keys. The document is public and signed, so it is not encrypted, and readers verify it before they trust it. There is at most one row.

func FindInstallationLicenseKeys

func FindInstallationLicenseKeys(tx *gorm.DB) (*InstallationLicenseKeys, error)

FindInstallationLicenseKeys returns gorm.ErrRecordNotFound when no key list is cached.

func (InstallationLicenseKeys) TableName

func (InstallationLicenseKeys) TableName() string

type InstallationLicenseRevocations

type InstallationLicenseRevocations struct {
	ID        int `gorm:"primary_key"`
	Document  string
	Version   int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

InstallationLicenseRevocations caches the newest root-signed list of revoked license ids. The document is public and signed, so it is not encrypted, and readers verify it before they trust it. There is at most one row.

func FindInstallationLicenseRevocations

func FindInstallationLicenseRevocations(tx *gorm.DB) (*InstallationLicenseRevocations, error)

FindInstallationLicenseRevocations returns gorm.ErrRecordNotFound when no revocation list is cached.

func (InstallationLicenseRevocations) TableName

type InstallationMetadata added in v0.1.0

type InstallationMetadata struct {
	ID                        int    `gorm:"primary_key"`
	InstallationID            string `gorm:"type:varchar(64)"`
	AllowPrivateNetworkAccess bool
	SignupsEnabled            bool
	CreatedAt                 time.Time
	UpdatedAt                 time.Time
}

func GetInstallationMetadata added in v0.15.0

func GetInstallationMetadata(tx *gorm.DB) (*InstallationMetadata, error)

type Integration

type Integration struct {
	ID               uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	OrganizationID   uuid.UUID
	AppName          string
	InstallationName string
	State            string
	StateDescription string
	CreatedAt        *time.Time
	UpdatedAt        *time.Time
	DeletedAt        gorm.DeletedAt `gorm:"index"`

	//
	// These are fields used by the old integrations.
	// Should be removed once all integration implementations
	// are migrated to use core.IntegrationSetupProvider
	//
	Configuration datatypes.JSONType[map[string]any]
	Metadata      datatypes.JSONType[map[string]any]
	BrowserAction *datatypes.JSONType[BrowserAction]

	//
	// Fields required for integrations set up using core.IntegrationSetupProvider
	// All integrations should use this
	//
	SetupState   *datatypes.JSONType[SetupState]
	Properties   datatypes.JSONSlice[core.IntegrationPropertyDefinition]
	Capabilities datatypes.JSONSlice[CapabilityState]
}

func ClaimHostedJiraOAuthState

func ClaimHostedJiraOAuthState(tx *gorm.DB, state string) (*Integration, error)

ClaimHostedJiraOAuthState finds the pending hosted Jira connection for this CSRF state and removes that state in the same transaction. A later callback with the same state then fails to find the connection. The returned integration still holds the claimed state in memory so this request can finish authorization.

func ClaimHostedLinearOAuthState

func ClaimHostedLinearOAuthState(tx *gorm.DB, state string) (*Integration, error)

ClaimHostedLinearOAuthState finds the pending hosted Linear connection for this CSRF state and removes that state in the same transaction. A later callback with the same state then fails to find the connection. The returned integration still holds the claimed state in memory so this request can finish authorization.

func CreateIntegration

func CreateIntegration(id, orgID uuid.UUID, appName string, installationName string, config map[string]any) (*Integration, error)

func FindGitHubIntegrationByAppState

func FindGitHubIntegrationByAppState(tx *gorm.DB, state string) (*Integration, error)

FindGitHubIntegrationByAppState finds the pending GitHub connection that started an install with this CSRF state.

func FindIntegration added in v0.6.0

func FindIntegration(orgID, integrationID uuid.UUID) (*Integration, error)

func FindIntegrationByName

func FindIntegrationByName(db *gorm.DB, orgID uuid.UUID, integrationName string) (*Integration, error)

func FindIntegrationInTransaction added in v0.17.0

func FindIntegrationInTransaction(tx *gorm.DB, orgID, integrationID uuid.UUID) (*Integration, error)

func FindJiraIntegrationByOAuthState

func FindJiraIntegrationByOAuthState(tx *gorm.DB, state string) (*Integration, error)

FindJiraIntegrationByOAuthState finds the pending Jira connection that started authorization with this CSRF state.

func FindMaybeDeletedIntegrationInTransaction added in v0.6.0

func FindMaybeDeletedIntegrationInTransaction(tx *gorm.DB, integrationID uuid.UUID) (*Integration, error)

func FindOrCreateBitbucketForgeIntegration

func FindOrCreateBitbucketForgeIntegration(
	tx *gorm.DB,
	organizationID uuid.UUID,
	installationID, workspaceSlug string,
) (*Integration, error)

FindOrCreateBitbucketForgeIntegration binds an organization to one Forge installation. The integration stores no token. Runners read the cached system token from the installation row.

func FindOrCreateVCSProviderBinding

func FindOrCreateVCSProviderBinding(
	tx *gorm.DB,
	organizationID uuid.UUID,
	provider string,
	installationID int64,
	accountLogin string,
) (*Integration, error)

func FindPendingHostedSentryIntegration

func FindPendingHostedSentryIntegration(tx *gorm.DB, startedByUserID string) (*Integration, error)

FindPendingHostedSentryIntegration finds the newest unbound hosted Sentry connection started by this SuperPlane user.

func FindReadyBYOKIntegration

func FindReadyBYOKIntegration(tx *gorm.DB, orgID uuid.UUID, provider string) (*Integration, error)

func FindReadyHostedSentryIntegration

func FindReadyHostedSentryIntegration(tx *gorm.DB, organizationID, excludeID uuid.UUID) (*Integration, error)

FindReadyHostedSentryIntegration finds a SuperPlane Sentry connection that already holds a public Sentry app install for this organization.

func FindSentryIntegrationByAppState

func FindSentryIntegrationByAppState(tx *gorm.DB, state string) (*Integration, error)

FindSentryIntegrationByAppState finds the pending Sentry connection that started an install with this CSRF state.

func FindUnscopedIntegration added in v0.6.0

func FindUnscopedIntegration(integrationID uuid.UUID) (*Integration, error)

func FindUnscopedIntegrationInTransaction added in v0.6.0

func FindUnscopedIntegrationInTransaction(tx *gorm.DB, integrationID uuid.UUID) (*Integration, error)

func ListDeletedIntegrations added in v0.6.0

func ListDeletedIntegrations() ([]Integration, error)

func ListGitHubIntegrationsByInstallationID

func ListGitHubIntegrationsByInstallationID(tx *gorm.DB, installationID string) ([]Integration, error)

ListGitHubIntegrationsByInstallationID finds GitHub connections bound to a GitHub App installation. One installation can belong to more than one SuperPlane organization.

func ListIntegrations

func ListIntegrations(db *gorm.DB, orgID uuid.UUID) ([]Integration, error)

func ListIntegrationsPage

func ListIntegrationsPage(tx *gorm.DB, orgID uuid.UUID, search string, limit, offset int) ([]Integration, int64, error)

ListIntegrationsPage returns one page of connections for an organization. Search matches the app name or the connection name. Results are ordered by app name, then connection name.

func ListLinearIntegrationsForAppWebhook

func ListLinearIntegrationsForAppWebhook(tx *gorm.DB, organizationID, urlKey string) ([]Integration, error)

ListLinearIntegrationsForAppWebhook finds ready Linear connections for one workspace. organizationID is Linear's organization id. urlKey is the workspace key in issue URLs. Either value can be empty. A connection matches when one of the stored values equals the event.

func ListMaybeDeletedIntegrationsByOrganizationInTransaction added in v0.13.0

func ListMaybeDeletedIntegrationsByOrganizationInTransaction(tx *gorm.DB, orgID uuid.UUID) ([]Integration, error)

func ListSentryIntegrationsByInstallationUUID

func ListSentryIntegrationsByInstallationUUID(tx *gorm.DB, installationUUID string) ([]Integration, error)

ListSentryIntegrationsByInstallationUUID finds Sentry connections bound to a public Sentry app installation.

func LockIntegration added in v0.6.0

func LockIntegration(tx *gorm.DB, ID uuid.UUID) (*Integration, error)

func NewIntegration

func NewIntegration(id, orgID uuid.UUID, appName string, installationName string, config map[string]any) *Integration

func (*Integration) AssignUniqueInstallationName

func (a *Integration) AssignUniqueInstallationName(tx *gorm.DB, name string) error

AssignUniqueInstallationName sets InstallationName to name, or name (1), name (2), when another integration in the organization already uses it. The advisory lock is held until the caller commits tx.

func (*Integration) CreateActionRequest added in v0.6.0

func (a *Integration) CreateActionRequest(tx *gorm.DB, actionName string, parameters any, runAt *time.Time) error

func (*Integration) CreateSyncRequest added in v0.6.0

func (a *Integration) CreateSyncRequest(tx *gorm.DB, runAt *time.Time) error

func (*Integration) GetRequest added in v0.6.0

func (a *Integration) GetRequest(ID string) (*IntegrationRequest, error)

func (*Integration) HasCapabilityEnabled added in v0.20.0

func (a *Integration) HasCapabilityEnabled(name string) bool

func (*Integration) IsLegacy added in v0.20.0

func (a *Integration) IsLegacy() bool

func (*Integration) ListRequests added in v0.6.0

func (a *Integration) ListRequests(reqType string) ([]IntegrationRequest, error)

func (*Integration) LockInTransaction added in v0.26.0

func (a *Integration) LockInTransaction(tx *gorm.DB) error

LockInTransaction takes a row-level FOR UPDATE lock on the installation, serializing concurrent request scheduling for it. ScheduleActionCall relies on this so its complete+create always observes successors created by other workers processing the same installation in parallel (#5386); without it, READ COMMITTED snapshots let each transaction insert a successor the others cannot see, leaving multiple chains that never drain.

func (*Integration) SoftDelete added in v0.6.0

func (a *Integration) SoftDelete() error

func (*Integration) SoftDeleteInTransaction added in v0.6.0

func (a *Integration) SoftDeleteInTransaction(tx *gorm.DB) error

func (*Integration) TableName added in v0.6.0

func (a *Integration) TableName() string

type IntegrationInvokeAction added in v0.6.0

type IntegrationInvokeAction struct {
	ActionName string `json:"action_name"`
	Parameters any    `json:"parameters"`
}

type IntegrationRequest added in v0.6.0

type IntegrationRequest struct {
	ID                uuid.UUID
	AppInstallationID uuid.UUID
	State             string
	Type              string
	Spec              datatypes.JSONType[IntegrationRequestSpec]
	RunAt             time.Time
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

func FindPendingRequestForIntegration added in v0.6.0

func FindPendingRequestForIntegration(tx *gorm.DB, installationID uuid.UUID) (*IntegrationRequest, error)

func LeaseIntegrationRequest added in v0.26.0

func LeaseIntegrationRequest(tx *gorm.DB, id uuid.UUID, lease time.Duration) (*IntegrationRequest, error)

LeaseIntegrationRequest atomically leases a due pending request for processing. It locks the row with SKIP LOCKED, gated on the request being pending and due (run_at <= now), then pushes run_at past the work window. The poll loop only lists due pending requests, so the leased request drops out until either it is completed or the lease expires - at which point it becomes due again and is retried automatically, with no separate state or reset mechanism.

func ListIntegrationRequests added in v0.6.0

func ListIntegrationRequests() ([]IntegrationRequest, error)

func (*IntegrationRequest) Complete added in v0.6.0

func (r *IntegrationRequest) Complete(tx *gorm.DB) error

func (*IntegrationRequest) TableName added in v0.6.0

func (r *IntegrationRequest) TableName() string

type IntegrationRequestSpec added in v0.6.0

type IntegrationRequestSpec struct {
	InvokeAction *IntegrationInvokeAction `json:"invoke_action,omitempty"`
}

type IntegrationSecret added in v0.6.0

type IntegrationSecret struct {
	ID             uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	OrganizationID uuid.UUID
	InstallationID uuid.UUID
	Name           string
	Label          string
	Description    string
	Value          []byte
	Editable       bool
	CreatedAt      *time.Time
	UpdatedAt      *time.Time
}

func ListIntegrationSecrets added in v0.19.0

func ListIntegrationSecrets(installationID uuid.UUID) ([]IntegrationSecret, error)

func ListIntegrationSecretsInTransaction added in v0.19.0

func ListIntegrationSecretsInTransaction(tx *gorm.DB, installationID uuid.UUID) ([]IntegrationSecret, error)

func (*IntegrationSecret) TableName added in v0.6.0

func (a *IntegrationSecret) TableName() string

type IntegrationSubscription added in v0.6.0

type IntegrationSubscription struct {
	ID             uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	InstallationID uuid.UUID
	WorkflowID     uuid.UUID
	NodeID         string
	Configuration  datatypes.JSONType[any]
	CreatedAt      *time.Time
	UpdatedAt      *time.Time
}

func CreateIntegrationSubscription added in v0.6.0

func CreateIntegrationSubscription(node *CanvasNode, integration *Integration, configuration any) (*IntegrationSubscription, error)

func CreateIntegrationSubscriptionInTransaction added in v0.6.0

func CreateIntegrationSubscriptionInTransaction(tx *gorm.DB, node *CanvasNode, integration *Integration, configuration any) (*IntegrationSubscription, error)

func (*IntegrationSubscription) TableName added in v0.6.0

func (a *IntegrationSubscription) TableName() string

type InvokeAction

type InvokeAction struct {
	ActionName string         `json:"action_name"`
	Parameters map[string]any `json:"parameters"`
}

type JSONValue added in v0.23.0

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

JSONValue stores arbitrary JSON while preserving JSON number tokens as json.Number when decoding (DB scan, API ingress, and in-memory UnmarshalJSON). Writes marshal the stored value as-is, so tokens survive round-trips once ingress avoids float64.

func NewJSONValue added in v0.23.0

func NewJSONValue(data any) JSONValue

func (JSONValue) Data added in v0.23.0

func (j JSONValue) Data() any

func (JSONValue) GormDBDataType added in v0.23.0

func (JSONValue) GormDBDataType(db *gorm.DB, _ *schema.Field) string

func (JSONValue) GormDataType added in v0.23.0

func (JSONValue) GormDataType() string

func (JSONValue) GormValue added in v0.23.0

func (j JSONValue) GormValue(_ context.Context, db *gorm.DB) clause.Expr

func (JSONValue) MarshalJSON added in v0.23.0

func (j JSONValue) MarshalJSON() ([]byte, error)

func (*JSONValue) Scan added in v0.23.0

func (j *JSONValue) Scan(value any) error

func (*JSONValue) UnmarshalJSON added in v0.23.0

func (j *JSONValue) UnmarshalJSON(data []byte) error

func (JSONValue) Value added in v0.23.0

func (j JSONValue) Value() (driver.Value, error)

type LinearWebhookReceipt

type LinearWebhookReceipt struct {
	ID                uuid.UUID `gorm:"primaryKey"`
	ReceivedAt        time.Time
	IntegrationID     uuid.UUID
	OrganizationID    uuid.UUID
	WebhookID         uuid.UUID
	EventType         string
	Action            string
	IssueIdentifier   string
	IssueID           string
	TeamKey           string
	WorkspaceKey      string
	HTTPStatus        int
	Outcome           string
	SubscriptionCount int
	// TaskIDs lists SuperPlane tasks this webhook created. IDs are comma-separated.
	TaskIDs string
	// DeliveryKey identifies the Linear payload. A later retry of the same
	// payload uses this key to skip a subscription that already accepted it.
	DeliveryKey string
}

LinearWebhookReceipt is one incoming Linear webhook. It stores the event type and the result. It does not store the payload, signature, or tokens.

func ListLinearWebhookReceipts

func ListLinearWebhookReceipts(tx *gorm.DB, limit, offset int) ([]LinearWebhookReceipt, int64, error)

func (LinearWebhookReceipt) TableName

func (LinearWebhookReceipt) TableName() string

func (LinearWebhookReceipt) TaskIDList

func (r LinearWebhookReceipt) TaskIDList() []string

type ListFactoryWorkOrdersFilters

type ListFactoryWorkOrdersFilters struct {
	States     []string
	Results    []string
	Unassigned *bool
	UserID     *uuid.UUID
	// Limit pages the result. Zero uses DefaultFactoryWorkOrderListLimit.
	Limit int
	// BeforeID is a keyset cursor. The query returns rows older than that
	// order in updated_at DESC, id DESC order.
	BeforeID *uuid.UUID
	// LineID keeps orders that ran on this line, plus orders with no line.
	LineID *uuid.UUID
	// PublicBoard keeps the orders a public line board can show. Drafts stay
	// even after a run on another line. Archives do not consume the page.
	PublicBoard     bool
	ExcludeArchived bool
}

type ListPage

type ListPage struct {
	States  []string
	Limit   int
	AfterID *uuid.UUID
}

type LiveCanvasSpec added in v0.28.0

type LiveCanvasSpec struct {
	Nodes []Node
	Edges []Edge
}

type MCPOAuthClient

type MCPOAuthClient struct {
	ID           uuid.UUID
	ClientID     string
	ClientName   string
	RedirectURIs datatypes.JSONSlice[string]
	CreatedAt    time.Time
}

func CreateMCPOAuthClient

func CreateMCPOAuthClient(tx *gorm.DB, clientID, clientName string, redirectURIs []string) (*MCPOAuthClient, error)

func FindMCPOAuthClient

func FindMCPOAuthClient(tx *gorm.DB, clientID string) (*MCPOAuthClient, error)

func ListMCPOAuthClientsByClientIDs

func ListMCPOAuthClientsByClientIDs(tx *gorm.DB, clientIDs []string) ([]MCPOAuthClient, error)

func (MCPOAuthClient) TableName

func (MCPOAuthClient) TableName() string

type MCPOAuthCode

type MCPOAuthCode struct {
	ID                  uuid.UUID
	CodeHash            string
	ClientID            string
	RedirectURI         string
	Resource            string
	CodeChallenge       string
	CodeChallengeMethod string
	UserID              uuid.UUID
	OrganizationID      uuid.UUID
	FactoryID           uuid.UUID
	Scopes              datatypes.JSONSlice[string]
	ExpiresAt           time.Time
	CreatedAt           time.Time
}

func FindMCPOAuthCode

func FindMCPOAuthCode(tx *gorm.DB, codeHash string, now time.Time) (*MCPOAuthCode, error)

func (MCPOAuthCode) TableName

func (MCPOAuthCode) TableName() string

type MCPOAuthRefreshToken

type MCPOAuthRefreshToken struct {
	ID             uuid.UUID
	TokenHash      string
	ClientID       string
	UserID         uuid.UUID
	OrganizationID uuid.UUID
	FactoryID      uuid.UUID
	Resource       string
	Scopes         datatypes.JSONSlice[string]
	ExpiresAt      time.Time
	CreatedAt      time.Time
}

func FindMCPOAuthRefreshToken

func FindMCPOAuthRefreshToken(tx *gorm.DB, tokenHash string, now time.Time) (*MCPOAuthRefreshToken, error)

func FindMCPOAuthRefreshTokenForFactory

func FindMCPOAuthRefreshTokenForFactory(tx *gorm.DB, organizationID, factoryID, id uuid.UUID) (*MCPOAuthRefreshToken, error)

func ListMCPOAuthRefreshTokensForFactory

func ListMCPOAuthRefreshTokensForFactory(tx *gorm.DB, organizationID, factoryID uuid.UUID, now time.Time) ([]MCPOAuthRefreshToken, error)

func (MCPOAuthRefreshToken) TableName

func (MCPOAuthRefreshToken) TableName() string

type Node

type Node struct {
	ID             string           `json:"id"`
	Name           string           `json:"name"`
	Type           string           `json:"type"`
	Ref            NodeRef          `json:"ref"`
	Configuration  map[string]any   `json:"configuration"`
	Metadata       map[string]any   `json:"metadata"`
	Position       Position         `json:"position"`
	IsCollapsed    bool             `json:"isCollapsed"`
	Concurrency    *ConcurrencySpec `json:"concurrency,omitempty"`
	IntegrationID  *string          `json:"integrationId,omitempty"`
	ErrorMessage   *string          `json:"errorMessage,omitempty"`
	WarningMessage *string          `json:"warningMessage,omitempty"`
}

func (*Node) ComponentName added in v0.29.0

func (c *Node) ComponentName() string

type NodeExecutionRequestSpec

type NodeExecutionRequestSpec struct {
	PullRequestChecksStart *PullRequestChecksStartRequest `json:"pull_request_checks_start,omitempty"`
	InvokeAction           *InvokeAction                  `json:"invoke_action,omitempty"`
	VisualEvidenceCapture  *VisualEvidenceCaptureRequest  `json:"visual_evidence_capture,omitempty"`
}

type NodeRef

type NodeRef struct {
	Component *ComponentRef `json:"component,omitempty"`
	Trigger   *TriggerRef   `json:"trigger,omitempty"`
	Widget    *WidgetRef    `json:"widget,omitempty"`
}

type NodeSubscription added in v0.0.45

type NodeSubscription struct {
	WorkflowID    uuid.UUID
	NodeID        string
	NodeType      string
	NodeRef       datatypes.JSONType[NodeRef]
	Configuration datatypes.JSONType[any]
}

func ListIntegrationSubscriptions added in v0.6.0

func ListIntegrationSubscriptions(tx *gorm.DB, installationID uuid.UUID) ([]NodeSubscription, error)

type NotificationWorkspaceFilter

type NotificationWorkspaceFilter struct {
	WorkspaceID string   `json:"workspace_id"`
	EventTypes  []string `json:"event_types"`
}

NotificationWorkspaceFilter selects event types for one workspace when the scope is filtered.

type OpenCanvasRunWork added in v0.26.0

type OpenCanvasRunWork struct {
	HasActiveExecutions bool
	HasQueueItems       bool
	HasPendingEvents    bool
}

type Organization

type Organization struct {
	ID uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	// Name is a display label and is not required to be unique: two
	// organizations may share a name (for example, onboarding keeps an
	// organization's name equal to its GitHub owner across slug-collision
	// retries). Only Slug is unique among active organizations.
	Name string
	// Slug is the URL-friendly identifier used to route to this organization
	// in the frontend. Uniqueness among non-deleted organizations is enforced
	// by a partial unique index added in the add-organization-slug migration,
	// not by a gorm tag.
	Slug                        string
	Description                 string
	CreatedByAccountID          *uuid.UUID
	AllowedProviders            datatypes.JSONSlice[string]
	EnabledExperimentalFeatures datatypes.JSONSlice[string]
	UsageRetentionWindowDays    *int32
	CreatedAt                   *time.Time
	UpdatedAt                   *time.Time
	DeletedAt                   gorm.DeletedAt `gorm:"index"`
}

func CreateOrganization

func CreateOrganization(name, description string) (*Organization, error)

func CreateOrganizationInTransaction

func CreateOrganizationInTransaction(tx *gorm.DB, name, description string) (*Organization, error)

func FindOrganizationByID

func FindOrganizationByID(id string) (*Organization, error)

func FindOrganizationByIDInTransaction added in v0.11.0

func FindOrganizationByIDInTransaction(tx *gorm.DB, id string) (*Organization, error)

func FindOrganizationByIDOrSlug

func FindOrganizationByIDOrSlug(tx *gorm.DB, ref string) (*Organization, error)

FindOrganizationByIDOrSlug resolves ref to an organization. ref is tried as a UUID first; if it does not parse as one, it is looked up as a slug. This lets API callers pass either identifier at the choke points where the client supplies an organization reference.

func FindOrganizationByName

func FindOrganizationByName(name string) (*Organization, error)

func FindOrganizationBySlug

func FindOrganizationBySlug(tx *gorm.DB, slug string) (*Organization, error)

FindOrganizationBySlug returns the active organization with the given slug.

func FindOrganizationsForAccount

func FindOrganizationsForAccount(email string) ([]Organization, error)

func ListDeletedOrganizations added in v0.13.0

func ListDeletedOrganizations() ([]Organization, error)

func ListDeletedOrganizationsInTransaction added in v0.13.0

func ListDeletedOrganizationsInTransaction(tx *gorm.DB) ([]Organization, error)

func ListOrganizationsByIDs

func ListOrganizationsByIDs(ids []string) ([]Organization, error)

func ListOrganizationsCreatedByAccount

func ListOrganizationsCreatedByAccount(tx *gorm.DB, accountID uuid.UUID) ([]Organization, error)

func ListOrganizationsPendingAccountDeletion

func ListOrganizationsPendingAccountDeletion(tx *gorm.DB, accountID uuid.UUID) ([]Organization, error)

func LockDeletedOrganization added in v0.13.0

func LockDeletedOrganization(tx *gorm.DB, id uuid.UUID) (*Organization, error)

func LockOrganization

func LockOrganization(tx *gorm.DB, orgID uuid.UUID) (*Organization, error)

func (*Organization) HasExperimentalFeature added in v0.21.0

func (o *Organization) HasExperimentalFeature(id string) bool

HasExperimentalFeature reports whether the given feature id is active for this organization. Released features (per the features registry) are always considered active regardless of per-organization state.

func (*Organization) IsProviderAllowed

func (o *Organization) IsProviderAllowed(provider string) bool

type OrganizationBYOKModelAllowlist

type OrganizationBYOKModelAllowlist struct {
	OrganizationID uuid.UUID `gorm:"primaryKey"`
	Provider       string    `gorm:"primaryKey"`
	AllowedModels  datatypes.JSONSlice[string]
	UpdatedAt      time.Time
}

OrganizationBYOKModelAllowlist is the org-selected BYOK model list for one provider.

func FindOrganizationBYOKModelAllowlist

func FindOrganizationBYOKModelAllowlist(tx *gorm.DB, orgID uuid.UUID, provider string) (*OrganizationBYOKModelAllowlist, error)

func UpsertOrganizationBYOKModelAllowlist

func UpsertOrganizationBYOKModelAllowlist(tx *gorm.DB, orgID uuid.UUID, provider string, models datatypes.JSONSlice[string]) (*OrganizationBYOKModelAllowlist, error)

func (OrganizationBYOKModelAllowlist) TableName

type OrganizationBillingPlan

type OrganizationBillingPlan struct {
	OrganizationID          uuid.UUID `gorm:"primary_key"`
	Plan                    string
	PlanSource              string
	PolarSubscriptionID     *string
	PolarSubscriptionStatus string
	CancelAtPeriodEnd       bool
	PolarModifiedAt         *time.Time
	CurrentPeriodStart      *time.Time
	CurrentPeriodEnd        *time.Time
	TrialStartedAt          *time.Time
	TrialEndsAt             *time.Time
	UpdatedAt               time.Time
}

OrganizationBillingPlan is the org plan and Polar subscription period.

func ApplyPolarSubscription

func ApplyPolarSubscription(tx *gorm.DB, orgID uuid.UUID, sub PolarSubscriptionApply) (*OrganizationBillingPlan, bool, error)

func EnsureOrganizationBillingPlan

func EnsureOrganizationBillingPlan(tx *gorm.DB, orgID uuid.UUID) (*OrganizationBillingPlan, error)

func FindOrganizationBillingPlan

func FindOrganizationBillingPlan(tx *gorm.DB, orgID uuid.UUID) (*OrganizationBillingPlan, error)

func ResolveOrganizationBillingPlan

func ResolveOrganizationBillingPlan(tx *gorm.DB, orgID uuid.UUID) (*OrganizationBillingPlan, error)

ResolveOrganizationBillingPlan loads the org plan and writes plan=none when there is no row or the trial window has ended.

func SetAdminOrganizationPlan

func SetAdminOrganizationPlan(tx *gorm.DB, orgID uuid.UUID, planName string, trialEndsAt *time.Time) (*OrganizationBillingPlan, error)

func (*OrganizationBillingPlan) AllowsCreditPurchase

func (p *OrganizationBillingPlan) AllowsCreditPurchase() bool

func (*OrganizationBillingPlan) AllowsHostedExecution

func (p *OrganizationBillingPlan) AllowsHostedExecution(now time.Time) bool

func (*OrganizationBillingPlan) IsActiveBusiness

func (p *OrganizationBillingPlan) IsActiveBusiness() bool

func (*OrganizationBillingPlan) IsOpenTrial

func (p *OrganizationBillingPlan) IsOpenTrial(now time.Time) bool

func (OrganizationBillingPlan) TableName

func (OrganizationBillingPlan) TableName() string

type OrganizationHostedModelAllowlist

type OrganizationHostedModelAllowlist struct {
	OrganizationID uuid.UUID `gorm:"primaryKey"`
	Provider       string    `gorm:"primaryKey"`
	AllowedModels  datatypes.JSONSlice[string]
	UpdatedAt      time.Time
}

OrganizationHostedModelAllowlist narrows the installation list for one provider. A missing row inherits the installation list. An empty saved list allows no models.

func FindOrganizationHostedModelAllowlist

func FindOrganizationHostedModelAllowlist(tx *gorm.DB, orgID uuid.UUID, provider string) (*OrganizationHostedModelAllowlist, error)

func UpsertOrganizationHostedModelAllowlist

func UpsertOrganizationHostedModelAllowlist(tx *gorm.DB, orgID uuid.UUID, provider string, models datatypes.JSONSlice[string]) (*OrganizationHostedModelAllowlist, error)

func (OrganizationHostedModelAllowlist) TableName

type OrganizationInviteLink struct {
	ID             uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	OrganizationID uuid.UUID `gorm:"uniqueIndex"`
	Token          uuid.UUID `gorm:"type:uuid;uniqueIndex"`
	Enabled        bool
	CreatedAt      time.Time
	UpdatedAt      time.Time
}
func CreateInviteLink(tx *gorm.DB, organizationID uuid.UUID) (*OrganizationInviteLink, error)

func FindInviteLinkByOrganizationID added in v0.0.43

func FindInviteLinkByOrganizationID(tx *gorm.DB, organizationID string) (*OrganizationInviteLink, error)

func FindInviteLinkByToken added in v0.0.43

func FindInviteLinkByToken(tx *gorm.DB, token string) (*OrganizationInviteLink, error)
func FindOrCreateInviteLink(tx *gorm.DB, organizationID uuid.UUID) (*OrganizationInviteLink, error)

type OrganizationLLMCreditGrant

type OrganizationLLMCreditGrant struct {
	ID             uuid.UUID
	OrganizationID uuid.UUID
	Kind           string
	AmountMicros   int64
	Note           string
	ActorAccountID *uuid.UUID
	PolarOrderID   *string
	PolarRefundID  *string
	CreatedAt      time.Time
	ExpiresAt      *time.Time
}

OrganizationLLMCreditGrant is one append-only credit addition.

func AddAdminLLMCreditGrant

func AddAdminLLMCreditGrant(tx *gorm.DB, orgID uuid.UUID, amountMicros int64, note string, actorAccountID *uuid.UUID) (*OrganizationLLMCreditGrant, error)

func AddIncludedLLMCreditGrant

func AddIncludedLLMCreditGrant(tx *gorm.DB, orgID uuid.UUID, amountMicros int64, polarOrderID string, expiresAt time.Time) (*OrganizationLLMCreditGrant, error)

func AddPolarLLMCreditGrant

func AddPolarLLMCreditGrant(tx *gorm.DB, orgID uuid.UUID, amountMicros int64, polarOrderID string) (*OrganizationLLMCreditGrant, error)

func AddPolarLLMCreditRefund

func AddPolarLLMCreditRefund(tx *gorm.DB, orgID uuid.UUID, amountMicros int64, polarOrderID, polarRefundID string) (*OrganizationLLMCreditGrant, error)

func AddTopupLLMCreditGrant

func AddTopupLLMCreditGrant(tx *gorm.DB, orgID uuid.UUID, amountMicros int64, polarOrderID string) (*OrganizationLLMCreditGrant, error)

func AdjustOrganizationLLMCreditBalance

func AdjustOrganizationLLMCreditBalance(tx *gorm.DB, adjustment CreditBalanceAdjustment) (*OrganizationLLMCreditGrant, error)

AdjustOrganizationLLMCreditBalance appends a signed adjustment row so the remaining balance of one credit type equals the target. It returns nil when the balance already equals the target. An open non-Polar Trial with no live welcome grant receives a welcome grant sized so remaining trial credit equals the target after hosted usage is charged to that grant.

func FindLLMCreditGrantByPolarOrderID

func FindLLMCreditGrantByPolarOrderID(tx *gorm.DB, polarOrderID string) (*OrganizationLLMCreditGrant, error)

func FindLLMCreditRefundByPolarRefundID

func FindLLMCreditRefundByPolarRefundID(tx *gorm.DB, polarRefundID string) (*OrganizationLLMCreditGrant, error)

func ListOrganizationLLMCreditGrants

func ListOrganizationLLMCreditGrants(tx *gorm.DB, orgID uuid.UUID) ([]OrganizationLLMCreditGrant, error)

func (OrganizationLLMCreditGrant) IsExpired

func (g OrganizationLLMCreditGrant) IsExpired(now time.Time) bool

func (OrganizationLLMCreditGrant) TableName

func (OrganizationLLMCreditGrant) TableName() string

type OrganizationLLMCreditSummary

type OrganizationLLMCreditSummary struct {
	GrantMicros              int64
	SuperPlaneGrantMicros    int64
	PurchasedCreditMicros    int64
	BilledMicros             int64
	RemainingMicros          int64
	IncludedRemainingMicros  int64
	PurchasedRemainingMicros int64
	WelcomeRemainingMicros   int64
	AdminRemainingMicros     int64
	MarkupBPS                int
	Warning                  bool
	WelcomeCreditExpiresAt   *time.Time
}

OrganizationLLMCreditSummary is remaining hosted credit for an org.

func DescribeOrganizationLLMCredit

func DescribeOrganizationLLMCredit(tx *gorm.DB, orgID uuid.UUID) (OrganizationLLMCreditSummary, error)

type OrganizationLLMSettings

type OrganizationLLMSettings struct {
	OrganizationID  uuid.UUID `gorm:"primary_key"`
	MarkupBPS       *int
	PolarCustomerID *string
	UpdatedAt       time.Time
}

OrganizationLLMSettings holds the hidden per-org markup override.

func FindOrganizationLLMSettings

func FindOrganizationLLMSettings(tx *gorm.DB, orgID uuid.UUID) (*OrganizationLLMSettings, error)

func (OrganizationLLMSettings) TableName

func (OrganizationLLMSettings) TableName() string

type OrganizationWithCounts added in v0.16.0

type OrganizationWithCounts struct {
	Organization
	CanvasCount           int64  `gorm:"column:canvas_count"`
	TaskCount             int64  `gorm:"column:task_count"`
	DoneTaskCount         int64  `gorm:"column:done_task_count"`
	MemberCount           int64  `gorm:"column:member_count"`
	WorkspaceCount        int64  `gorm:"column:workspace_count"`
	RepositoryCount       int64  `gorm:"column:repository_count"`
	RemainingCreditMicros *int64 `gorm:"-"`
}

func FindOrganizationWithCounts

func FindOrganizationWithCounts(tx *gorm.DB, id uuid.UUID) (*OrganizationWithCounts, error)

func ListAllOrganizations added in v0.14.0

func ListAllOrganizations(tx *gorm.DB, search string, limit, offset int, sortBy, sortDirection string) ([]OrganizationWithCounts, int64, error)

type PlanningReviewScores

type PlanningReviewScores struct {
	Clarity       PlanningScoreValue
	Complexity    PlanningScoreValue
	Verifiability PlanningScoreValue
}

PlanningReviewScores is the full set of review sub-parameters. All three must be present when the group is sent.

type PlanningScoreValue

type PlanningScoreValue struct {
	Score   float64
	Summary string
}

PlanningScoreValue is one 1 through 3 sub-parameter with a one-sentence summary.

type PlanningSessionActivity

type PlanningSessionActivity struct {
	ID            uuid.UUID
	SessionID     uuid.UUID
	SchemaVersion int
	Provider      string
	Status        string
	LastSequence  int64
	Snapshot      datatypes.JSONType[PlanningSessionActivitySnapshot]
	StartedAt     time.Time
	CompletedAt   *time.Time
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

func FindPlanningSessionActivity

func FindPlanningSessionActivity(tx *gorm.DB, sessionID, activityID uuid.UUID) (*PlanningSessionActivity, error)

func ListPlanningSessionActivities

func ListPlanningSessionActivities(tx *gorm.DB, sessionID uuid.UUID) ([]PlanningSessionActivity, error)

func (PlanningSessionActivity) TableName

func (PlanningSessionActivity) TableName() string

type PlanningSessionActivityItem

type PlanningSessionActivityItem struct {
	Type          string                          `json:"type"`
	ID            string                          `json:"id"`
	Kind          string                          `json:"kind,omitempty"`
	Text          string                          `json:"text,omitempty"`
	Name          string                          `json:"name,omitempty"`
	Input         string                          `json:"input,omitempty"`
	Output        string                          `json:"output,omitempty"`
	OutputStreams []PlanningSessionActivityOutput `json:"output_streams,omitempty"`
	Status        string                          `json:"status,omitempty"`
	Code          string                          `json:"code,omitempty"`
	StartedAt     int64                           `json:"started_at,omitempty"`
	DurationMs    int64                           `json:"duration_ms,omitempty"`
	ExitCode      *int                            `json:"exit_code,omitempty"`
	Signal        string                          `json:"signal,omitempty"`
	Truncated     bool                            `json:"truncated,omitempty"`
}

type PlanningSessionActivityOutput

type PlanningSessionActivityOutput struct {
	Stream string `json:"stream,omitempty"`
	Text   string `json:"text,omitempty"`
}

type PlanningSessionActivitySnapshot

type PlanningSessionActivitySnapshot struct {
	SchemaVersion int                           `json:"schema_version"`
	ActivityID    string                        `json:"activity_id"`
	Provider      string                        `json:"provider"`
	Turn          int                           `json:"turn"`
	Sequence      int64                         `json:"sequence"`
	Status        string                        `json:"status"`
	StartedAt     int64                         `json:"started_at"`
	CompletedAt   *int64                        `json:"completed_at,omitempty"`
	Items         []PlanningSessionActivityItem `json:"items"`
	Truncated     bool                          `json:"truncated,omitempty"`
}

type PlanningSessionDraft

type PlanningSessionDraft struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	WorkOrderID string `json:"work_order_id,omitempty"`
}

type PlanningSessionMessage

type PlanningSessionMessage struct {
	ID         uuid.UUID
	SessionID  uuid.UUID
	Role       string
	Text       string
	Delivered  bool
	UserID     *uuid.UUID
	ActivityID *uuid.UUID
	CreatedAt  time.Time
}

func ListPlanningSessionMessages

func ListPlanningSessionMessages(tx *gorm.DB, sessionID uuid.UUID) ([]PlanningSessionMessage, error)

func (PlanningSessionMessage) TableName

func (PlanningSessionMessage) TableName() string

type PlanningSessionSurvey

type PlanningSessionSurvey struct {
	Questions []PlanningSessionSurveyQuestion `json:"questions,omitempty"`
}

type PlanningSessionSurveyQuestion

type PlanningSessionSurveyQuestion struct {
	Prompt  string   `json:"prompt"`
	Options []string `json:"options"`
}

type PlanningSessionUpdate

type PlanningSessionUpdate struct {
	Scores *PlanningReviewScores
	Spec   string
	Survey *PlanningSessionSurvey
}

PlanningSessionUpdate is one atomic plan-turn publish: scores, spec, and an optional survey. At least one field is required.

type PlanningWaitResult

type PlanningWaitResult struct {
	Kind         string `json:"kind,omitempty"`
	Text         string `json:"text,omitempty"`
	WorkOrderID  string `json:"work_order_id,omitempty"`
	WorkOrderKey string `json:"work_order_key,omitempty"`
}

type PolarSubscriptionApply

type PolarSubscriptionApply struct {
	ID                string
	Status            string
	PeriodStart       *time.Time
	PeriodEnd         *time.Time
	CancelAtPeriodEnd bool
	ModifiedAt        *time.Time
}

PolarSubscriptionApply is the Polar subscription snapshot to persist.

type Position

type Position struct {
	X int `json:"x"`
	Y int `json:"y"`
}

type PullRequestChecksStartRequest

type PullRequestChecksStartRequest struct {
	OrganizationID string `json:"organization_id"`
	FactoryID      string `json:"factory_id"`
	PullRequestID  string `json:"pull_request_id"`
	Attempts       int    `json:"attempts,omitempty"`
}

type RoleMetadata

type RoleMetadata struct {
	ID          uuid.UUID `json:"id" gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	RoleName    string    `json:"role_name" gorm:"not null;index"`
	DomainType  string    `json:"domain_type" gorm:"not null;index"`
	DomainID    string    `json:"domain_id" gorm:"not null;index"`
	DisplayName string    `json:"display_name" gorm:"not null"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

func FindRoleMetadata

func FindRoleMetadata(roleName, domainType, domainID string) (*RoleMetadata, error)

func (*RoleMetadata) BeforeCreate

func (rm *RoleMetadata) BeforeCreate(tx *gorm.DB) error

func (*RoleMetadata) Create

func (rm *RoleMetadata) Create() error

func (*RoleMetadata) CreateInTransaction

func (rm *RoleMetadata) CreateInTransaction(tx *gorm.DB) error

func (*RoleMetadata) Update

func (rm *RoleMetadata) Update() error

func (*RoleMetadata) UpdateInTransaction

func (rm *RoleMetadata) UpdateInTransaction(tx *gorm.DB) error

type RunCancellationDrainResult added in v0.30.0

type RunCancellationDrainResult struct {
	RequestedExecutionIDs []uuid.UUID
	DeletedQueueItems     []CanvasNodeQueueItem
	SupersededEvents      []CanvasEvent
	ChildRuns             []*RunCancellationResult
}

type RunCancellationResult

type RunCancellationResult struct {
	Run             *CanvasRun
	Drain           *RunCancellationDrainResult
	NewlyCancelling bool
}

type RunDeletionSummary added in v0.30.0

type RunDeletionSummary struct {
	Runs             int64
	Events           int64
	NodeExecutions   int64
	NodeRequests     int64
	NodeExecutionKVs int64
	NodeQueueItems   int64
}

func (*RunDeletionSummary) TotalRecords added in v0.30.0

func (s *RunDeletionSummary) TotalRecords() int64

type RunError

type RunError struct {
	Message string `json:"message"`
}

type Runner

type Runner struct {
	ID                     uuid.UUID
	FleetID                uuid.UUID
	State                  string
	RunnerVersion          string
	OS                     string
	Arch                   string
	Hostname               string
	IP                     string
	Tags                   datatypes.JSONType[map[string]string]
	Ephemeral              bool
	RegisteredAt           *time.Time
	LastSeenAt             *time.Time
	CurrentConnectionID    *uuid.UUID
	TerminationReason      *string
	CreatedAt              time.Time
	UpdatedAt              time.Time
	TerminatedAt           *time.Time
	CreationIdempotencyKey *string
	CreationRequestHash    *string
}

* Runner is a durable record for one provisioned execution agent. * SuperPlane creates it in the pending state before infrastructure starts, * then uses it to track registration, connectivity, workload state, and termination. * * Ephemeral runners terminate after their first task. Reusable runners return * to idle. This is an instance property because one fleet can contain both. * * CreationIdempotencyKey is optional for generic capacity. Task-specific * runners require it so a lost create response can recover the runner and * registration token without leaving the task reserved until expiry. * Termination releases the key because a retry after a failed provisioning * attempt must create a replacement runner for the same task. * * CreationRequestHash binds the idempotency key to its original fleet and * task inputs so a client cannot reuse the key for a different request.

func FindInstallationRunnerByCreationIdempotencyKey

func FindInstallationRunnerByCreationIdempotencyKey(tx *gorm.DB, key string) (*Runner, error)

func FindRunner

func FindRunner(tx *gorm.DB, id uuid.UUID) (*Runner, error)

func FindRunnerByAccessTokenHash

func FindRunnerByAccessTokenHash(tx *gorm.DB, accessTokenHash string) (*Runner, error)

func LockRunner

func LockRunner(tx *gorm.DB, id uuid.UUID) (*Runner, error)

func (*Runner) CloseConnection

func (r *Runner) CloseConnection(tx *gorm.DB, connectionID uuid.UUID, now time.Time) error

func (*Runner) Expire

func (r *Runner) Expire(tx *gorm.DB, now time.Time) error

func (*Runner) FindActiveTask

func (r *Runner) FindActiveTask(tx *gorm.DB) (*RunnerTask, error)

func (*Runner) MarkLost

func (r *Runner) MarkLost(tx *gorm.DB, lastSeenBefore, now time.Time) (*RunnerTask, error)

MarkLost returns the running task it ended, if any.

func (*Runner) OpenConnection

func (r *Runner) OpenConnection(tx *gorm.DB, connectionID uuid.UUID, now time.Time) error

func (*Runner) Register

func (r *Runner) Register(
	tx *gorm.DB,
	jti uuid.UUID,
	fleetSlug string,
	taskID *uuid.UUID,
	version string,
	host RunnerHost,
	accessTokenHash string,
	now time.Time,
) error

* Register consumes one registration grant and creates the long-lived * credential for this runner. The row locks make token consumption and runner * activation atomic when duplicate registration requests arrive. * * A task-bound grant must match the task reserved during runner creation. * Generic grants must not register a runner that gained an assignment through * another path.

func (*Runner) ReserveNextTask

func (r *Runner) ReserveNextTask(tx *gorm.DB) (*RunnerTask, error)

func (*Runner) Terminate

func (r *Runner) Terminate(tx *gorm.DB, reason string) error

func (*Runner) TouchConnection

func (r *Runner) TouchConnection(tx *gorm.DB, connectionID uuid.UUID, now time.Time) error

type RunnerCredential

type RunnerCredential struct {
	RunnerID        uuid.UUID `gorm:"primaryKey"`
	AccessTokenHash string
	CreatedAt       time.Time
	RevokedAt       *time.Time
}

* RunnerCredential stores the hash of the bearer token that authenticates a * registered runner. The plaintext token is returned once at registration and * is never persisted. A recently completed ephemeral runner can reconnect to * retry its idempotent completion until credential cleanup revokes the token.

type RunnerFleet

type RunnerFleet struct {
	ID            uuid.UUID
	Slug          string
	ScopeType     string
	ScopeID       *uuid.UUID
	Enabled       bool
	Spec          datatypes.JSONType[RunnerFleetSpec]
	RunnerVersion string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	DeletedAt     gorm.DeletedAt
}

* RunnerFleet is SuperPlane's authoritative definition of a class of runner. * It identifies the installation or organization that can use the fleet and * defines the runner release and opaque provisioning specification that a * fleet manager must use. Spec remains JSON while fleet requirements evolve. * Promote stable, frequently queried values from Spec to columns when needed. * * ID is an internal relational key that keeps foreign keys narrow. * Slug is the stable, scope-local fleet ID exposed to users and used in * node and Fleet Manager configuration, for example "e1-large-amd64".

func DefaultInstallationRunnerFleets

func DefaultInstallationRunnerFleets(runnerVersion string) []RunnerFleet

DefaultInstallationRunnerFleets is the initial fleet catalog for a new installation. Providers decide how to satisfy these specifications.

func FindEnabledRunnerFleetForOrganization

func FindEnabledRunnerFleetForOrganization(
	tx *gorm.DB,
	organizationID uuid.UUID,
	slug string,
) (*RunnerFleet, error)

func FindInstallationRunnerFleet

func FindInstallationRunnerFleet(tx *gorm.DB, slug string) (*RunnerFleet, error)

func FindRunnerFleet

func FindRunnerFleet(tx *gorm.DB, id uuid.UUID) (*RunnerFleet, error)

func ListEnabledRunnerFleetsForOrganization

func ListEnabledRunnerFleetsForOrganization(tx *gorm.DB, organizationID uuid.UUID) ([]RunnerFleet, error)

func ListInstallationRunnerFleets

func ListInstallationRunnerFleets(tx *gorm.DB) ([]RunnerFleet, error)

func (*RunnerFleet) CountRunnersByState

func (f *RunnerFleet) CountRunnersByState(tx *gorm.DB) (map[string]int64, error)

func (*RunnerFleet) CountTasks

func (f *RunnerFleet) CountTasks(tx *gorm.DB, state string) (int64, error)

func (*RunnerFleet) Create

func (f *RunnerFleet) Create(tx *gorm.DB) error

* The required rules for fleet slugs are: * - Installation fleet IDs are unique. * - Organization fleet IDs are unique within each organization. * - Different organizations can reuse the same fleet ID. * - Organization fleet IDs cannot match any installation fleet ID. * * Create serializes fleet creation by slug before checking scope conflicts. * The transaction-scoped advisory lock prevents concurrent installation * and organization creates from both passing the conflict check before either row exists.

func (*RunnerFleet) FindRunner

func (f *RunnerFleet) FindRunner(tx *gorm.DB, id uuid.UUID) (*Runner, error)

func (*RunnerFleet) ListRunners

func (f *RunnerFleet) ListRunners(tx *gorm.DB, page ListPage) (RunnerListPage, error)

func (*RunnerFleet) ListTasks

func (f *RunnerFleet) ListTasks(tx *gorm.DB, page ListPage) (TaskListPage, error)

func (*RunnerFleet) MetricScope

func (f *RunnerFleet) MetricScope(tx *gorm.DB) (string, error)

MetricScope distinguishes installation fleets from organization fleets that share a slug.

func (*RunnerFleet) PinRunnerVersion

func (f *RunnerFleet) PinRunnerVersion(tx *gorm.DB, version string) error

func (*RunnerFleet) SetEnabled

func (f *RunnerFleet) SetEnabled(tx *gorm.DB, enabled bool) error

type RunnerFleetSpec

type RunnerFleetSpec struct {
	OperatingSystem string   `json:"operating_system,omitempty"`
	Architecture    string   `json:"architecture,omitempty"`
	CPUMillicores   int32    `json:"cpu_millicores,omitempty"`
	MemoryMB        int32    `json:"memory_mb,omitempty"`
	DiskGB          int32    `json:"disk_gb,omitempty"`
	Capabilities    []string `json:"capabilities,omitempty"`
}

type RunnerHost

type RunnerHost struct {
	OS       string
	Arch     string
	Hostname string
	IP       string
	Tags     map[string]string
}

type RunnerListPage

type RunnerListPage struct {
	Runners     []Runner
	TotalCount  int64
	HasNextPage bool
}

type RunnerRegistration

type RunnerRegistration struct {
	JTI        uuid.UUID `gorm:"primaryKey"`
	RunnerID   uuid.UUID
	ExpiresAt  time.Time
	ConsumedAt *time.Time
	RevokedAt  *time.Time
	CreatedAt  time.Time
}

* RunnerRegistration is a short-lived, single-use grant for converting a * pending runner into an authenticated runner. Its JTI is embedded in the * registration JWT so SuperPlane can reject replayed, expired, or revoked * grants without storing the JWT itself.

func FindRunnerRegistration

func FindRunnerRegistration(tx *gorm.DB, runnerID uuid.UUID) (*RunnerRegistration, error)

type RunnerTask

type RunnerTask struct {
	ID                uuid.UUID
	OrganizationID    uuid.UUID
	FleetID           uuid.UUID
	RunnerID          *uuid.UUID
	Backend           string
	State             string
	Result            datatypes.JSON
	ExitCode          *int32
	ErrorMessage      *string
	CancelRequestedAt *time.Time
	QueuedAt          time.Time
	ReservedAt        *time.Time
	StartedAt         *time.Time
	FinishedAt        *time.Time
	CreatedAt         time.Time
	UpdatedAt         time.Time

	/*
	 * PayloadCiphertext protects task inputs, which can contain credentials and other secrets.
	 */
	PayloadCiphertext []byte

	/*
	 * CompletionHash makes runner completion idempotent across reconnects.
	 * The WebSocket request ID only correlates an in-flight acknowledgement,
	 * while this hash detects a retry with the same terminal task result.
	 */
	CompletionHash *string
}

* RunnerTask is the durable execution unit assigned to one fleet runner.

func FindRunnerTask

func FindRunnerTask(tx *gorm.DB, id uuid.UUID) (*RunnerTask, error)

func (*RunnerTask) Complete

func (t *RunnerTask) Complete(
	tx *gorm.DB,
	runner *Runner,
	completionHash string,
	result datatypes.JSON,
	exitCode int32,
	errorMessage string,
	canceled bool,
	now time.Time,
) (bool, error)

func (*RunnerTask) FindLifecycle

func (t *RunnerTask) FindLifecycle(tx *gorm.DB) (*RunnerTaskLogLifecycle, error)

func (*RunnerTask) IsTerminal

func (t *RunnerTask) IsTerminal() bool

func (*RunnerTask) RequestCancel

func (t *RunnerTask) RequestCancel(tx *gorm.DB, now time.Time) error

* RequestCancel is idempotent. * A queued task can be canceled immediately because no runner has observed it. * Assigned tasks retain their state and expose a cancellation request to the connected runner.

func (*RunnerTask) Reserve

func (t *RunnerTask) Reserve(tx *gorm.DB, runnerID uuid.UUID) error

func (*RunnerTask) Start

func (t *RunnerTask) Start(tx *gorm.DB, runner *Runner, activeLogStore string, now time.Time) error

type RunnerTaskLogLifecycle

type RunnerTaskLogLifecycle struct {
	TaskID          uuid.UUID `gorm:"primaryKey"`
	ActiveStore     string
	State           string
	FinalObjectKey  *string
	FinalCursor     *string
	Truncated       bool
	CleanupAfter    *time.Time
	ProcessingUntil *time.Time
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

* RunnerTaskLogLifecycle coordinates an active store with final blob storage. * RunnerTask.Start creates this record when a reserved task starts running. * * Its state transitions are: * - active: the runner can append chunks to the selected active store. * - archivable: task completion moves the record to this state after the * runner receives acknowledgements for all retained chunks. A running task * that loses its runner also moves to this state. * - archiving: the compactor claimed the record and is writing the final * blob object. * - archived: the final blob is available. CleanupAfter controls when the * compactor deletes the now-redundant active-store data. * * After active-store cleanup, the record remains archived, FinalObjectKey * continues to identify the blob, and CleanupAfter is cleared. * * The selected active store owns append-frequency metadata such as the next * sequence, retained byte count, and authoritative truncation state. This * record can keep a low-frequency lifecycle summary, but the append path must * not update it for each chunk. When an external active store is selected, * accepting a new chunk must not cause a write to the application PostgreSQL * database.

type Secret

type Secret struct {
	ID         uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	DomainType string
	DomainID   uuid.UUID
	Name       string
	CreatedAt  *time.Time
	CreatedBy  uuid.UUID
	UpdatedAt  *time.Time
	Provider   string
	Data       []byte
}

func CreateSecret

func CreateSecret(name, provider, requesterID, domainType string, domainID uuid.UUID, data []byte) (*Secret, error)

func FindSecretByID

func FindSecretByID(domainType string, domainID uuid.UUID, id string) (*Secret, error)

func FindSecretByIDInTransaction added in v0.7.0

func FindSecretByIDInTransaction(tx *gorm.DB, domainType string, domainID uuid.UUID, id string) (*Secret, error)

func FindSecretByName

func FindSecretByName(domainType string, domainID uuid.UUID, name string) (*Secret, error)

func FindSecretByNameInTransaction

func FindSecretByNameInTransaction(tx *gorm.DB, domainType string, domainID uuid.UUID, name string) (*Secret, error)

func ListSecrets

func ListSecrets(domainType string, domainID uuid.UUID) ([]Secret, error)

func (*Secret) Delete

func (s *Secret) Delete() error

func (*Secret) UpdateData

func (s *Secret) UpdateData(data []byte) (*Secret, error)

func (*Secret) UpdateNameAndData added in v0.28.0

func (s *Secret) UpdateNameAndData(tx *gorm.DB, name string, data []byte) (*Secret, error)

type SecretData

type SecretData struct {
	Local map[string]string `json:"local"`
}

type SelectableLLMModel

type SelectableLLMModel struct {
	Source   SelectableLLMNamedID
	Provider SelectableLLMNamedID
	Model    SelectableLLMNamedID
	Key      string
	Label    string
}

func FindSelectableLLMModel

func FindSelectableLLMModel(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID, key string) (SelectableLLMModel, error)

func ListSelectableLLMModels

func ListSelectableLLMModels(tx *gorm.DB, orgID uuid.UUID, factoryID *uuid.UUID) ([]SelectableLLMModel, error)

ListSelectableLLMModels returns hosted plus BYOK selected models for a picker.

func ParseSelectableLLMModelKey

func ParseSelectableLLMModelKey(value string) (SelectableLLMModel, error)

type SelectableLLMNamedID

type SelectableLLMNamedID struct {
	ID   string
	Name string
}

type SentryAppInstallGrant

type SentryAppInstallGrant struct {
	InstallationUUID     string `gorm:"primaryKey"`
	CodeDigest           string
	OrganizationSlug     string
	AccessToken          []byte
	RefreshToken         []byte
	TokenExpiresAt       string
	ClaimedIntegrationID *string
	ExpiresAt            time.Time
	CreatedAt            time.Time
	UpdatedAt            time.Time
}

SentryAppInstallGrant holds a public Sentry app install that the installation webhook received before the browser callback arrived. Sentry accepts the install code one time only, so the process that answers the callback must read the result of that exchange from here.

func ClaimSentryAppInstallGrant

func ClaimSentryAppInstallGrant(tx *gorm.DB, installationUUID, codeDigest, integrationID string, now time.Time) (*SentryAppInstallGrant, error)

ClaimSentryAppInstallGrant assigns an unexpired grant to one integration. The first caller with the matching code wins. The same integration can claim again after a failed bind. A different integration cannot.

func FindSentryAppInstallGrant

func FindSentryAppInstallGrant(tx *gorm.DB, installationUUID, codeDigest string, now time.Time) (*SentryAppInstallGrant, error)

FindSentryAppInstallGrant returns the grant of an installation when the caller presents the same install code. It leaves the row in place so a later callback can retry if decrypting the tokens or binding the integration fails. It returns nil when no unexpired grant matches, so a caller without the code cannot claim an installation it does not own.

func (SentryAppInstallGrant) TableName

func (SentryAppInstallGrant) TableName() string

type SentryWebhookReceipt

type SentryWebhookReceipt struct {
	ID               uuid.UUID `gorm:"primaryKey"`
	ReceivedAt       time.Time
	HookResource     string
	Action           string
	InstallationUUID string
	OrganizationSlug string
	ProjectSlug      string
	IssueID          string
	IssueShortID     string
	HTTPStatus       int
	Outcome          string
	IntegrationCount int
	// TaskIDs lists SuperPlane tasks this webhook created. IDs are comma-separated.
	TaskIDs string
}

SentryWebhookReceipt is one incoming Sentry webhook. It stores the event type and the result. It does not store the payload, signature, or tokens.

func ListSentryWebhookReceipts

func ListSentryWebhookReceipts(tx *gorm.DB, limit, offset int, project string) ([]SentryWebhookReceipt, int64, error)

ListSentryWebhookReceipts returns one page of receipts, newest first. An empty project returns every receipt. A project value matches project_slug as a case-insensitive substring. Percent, underscore, and backslash stay literal.

func (SentryWebhookReceipt) TableName

func (SentryWebhookReceipt) TableName() string

func (SentryWebhookReceipt) TaskIDList

func (r SentryWebhookReceipt) TaskIDList() []string

type SetupState added in v0.19.0

type SetupState struct {
	CurrentStep   *core.SetupStep  `json:"current_step,omitempty"`
	PreviousSteps []core.SetupStep `json:"previous_steps,omitempty"`
}

type SpendingBreakdownRow

type SpendingBreakdownRow struct {
	ID              string
	TotalTokens     int64
	DurationSeconds int64
	CostMicros      int64
}

SpendingBreakdownRow is one grouped row in the spending explorer table.

func (SpendingBreakdownRow) CostCents

func (r SpendingBreakdownRow) CostCents() int64

type SpendingCatalogItem

type SpendingCatalogItem struct {
	ID    string
	Label string
}

SpendingCatalogItem is one filter or label option in the spending explorer.

type SpendingCatalogs

type SpendingCatalogs struct {
	Workspaces []SpendingCatalogItem
	Users      []SpendingCatalogItem
	Models     []SpendingCatalogItem
	Machines   []SpendingCatalogItem
}

SpendingCatalogs lists filter options for the spending explorer.

func ListSpendingFilterCatalogs

func ListSpendingFilterCatalogs(tx *gorm.DB, filter UsageReportFilter) (SpendingCatalogs, error)

ListSpendingFilterCatalogs returns workspace, user, model, and machine filter options.

type SpendingExplorerReport

type SpendingExplorerReport struct {
	Totals     SpendingKPITotals
	Breakdown  []SpendingBreakdownRow
	SeriesKeys []SpendingSeriesKey
	Series     []SpendingSeriesPoint
}

SpendingExplorerReport is the filtered chart and table payload for one usage kind.

func SummarizeSpendingExplorer

func SummarizeSpendingExplorer(
	tx *gorm.DB,
	filter UsageReportFilter,
	groupBy string,
	grain string,
) (SpendingExplorerReport, error)

SummarizeSpendingExplorer returns filtered totals, breakdown rows, and stacked series.

type SpendingKPITotals

type SpendingKPITotals struct {
	CostMicros       int64
	TotalTokens      int64
	DurationSeconds  int64
	HostedCostMicros int64
	BYOKCostMicros   int64
}

SpendingKPITotals is the org-wide spend summary for a time window.

func SummarizeSpendingKPITotals

func SummarizeSpendingKPITotals(tx *gorm.DB, filter UsageReportFilter) (SpendingKPITotals, error)

SummarizeSpendingKPITotals returns org-wide totals for model and compute usage in a window.

func (SpendingKPITotals) BYOKCostCents

func (t SpendingKPITotals) BYOKCostCents() int64

func (SpendingKPITotals) CostCents

func (t SpendingKPITotals) CostCents() int64

func (SpendingKPITotals) HostedCostCents

func (t SpendingKPITotals) HostedCostCents() int64

type SpendingSeriesKey

type SpendingSeriesKey struct {
	ID    string
	Label string
}

SpendingSeriesKey identifies one stacked chart segment.

type SpendingSeriesPoint

type SpendingSeriesPoint struct {
	Key        string
	Label      string
	TotalCents int64
	Values     map[string]int64
}

SpendingSeriesPoint is one time bucket in the stacked spending chart.

type StaleRunner

type StaleRunner struct {
	ID         uuid.UUID
	FleetSlug  string
	FleetScope string
}

func ListStaleRunners

func ListStaleRunners(tx *gorm.DB, lastSeenBefore time.Time, limit int) ([]StaleRunner, error)

type TaskListPage

type TaskListPage struct {
	Tasks       []RunnerTask
	TotalCount  int64
	HasNextPage bool
}

type TriggerRef

type TriggerRef struct {
	Name string `json:"name"`
}

type UsageByMachineType

type UsageByMachineType struct {
	MachineType     string
	DurationSeconds int64
	CostMicros      int64
}

UsageByMachineType is one fleet machine-type bucket in a compute report.

func (UsageByMachineType) CostCents

func (r UsageByMachineType) CostCents() int64

type UsageByModel

type UsageByModel struct {
	Provider    string
	Model       string
	TotalTokens int64
	CostMicros  int64
}

UsageByModel is one model bucket in a spend report.

func (UsageByModel) CostCents

func (r UsageByModel) CostCents() int64

type UsagePriceBook

type UsagePriceBook struct {
	Version     string `gorm:"primaryKey"`
	EffectiveAt time.Time
	CreatedAt   time.Time
	IsCurrent   bool
}

UsagePriceBook is one versioned catalog of model and compute rates.

func FindCurrentUsagePriceBook

func FindCurrentUsagePriceBook(tx *gorm.DB) (*UsagePriceBook, error)

FindCurrentUsagePriceBook returns the catalog marked current.

func FindUsagePriceBook

func FindUsagePriceBook(tx *gorm.DB, version string) (*UsagePriceBook, error)

FindUsagePriceBook returns one catalog version.

func ListUsagePriceBooks

func ListUsagePriceBooks(tx *gorm.DB) ([]UsagePriceBook, error)

ListUsagePriceBooks returns every catalog version, newest effective_at first.

func PublishUsagePriceBook

func PublishUsagePriceBook(tx *gorm.DB, rates []UsagePriceBookRate, expectedCurrentVersion string) (*UsagePriceBook, error)

PublishUsagePriceBook inserts a new current catalog. expectedCurrentVersion must match the locked current row. It does not touch the in-memory book, because the caller can still roll the transaction back. Call LoadCurrentPriceBook after the commit.

func (UsagePriceBook) TableName

func (UsagePriceBook) TableName() string

type UsagePriceBookRate

type UsagePriceBookRate struct {
	ID                        uuid.UUID
	Version                   string
	UsageKind                 string
	Provider                  string
	MatchKey                  string
	MatchMode                 string
	InputCentsPerMillion      int64
	OutputCentsPerMillion     int64
	CacheReadCentsPerMillion  int64
	CacheWriteCentsPerMillion int64
	ReasoningCentsPerMillion  int64
	MicrosPerSecond           int64
}

UsagePriceBookRate is one match rule inside a price book version.

func ApplyCatalogPrices

func ApplyCatalogPrices(rows []UsagePriceBookRate, prices []CatalogModelPrice) ([]UsagePriceBookRate, int, int)

ApplyCatalogPrices updates or adds exact rows for catalog prices. It copies other providers and compute rates unchanged.

func CloneUsagePriceBookRates

func CloneUsagePriceBookRates(rows []UsagePriceBookRate) []UsagePriceBookRate

CloneUsagePriceBookRates copies rates without ids or version stamps.

func ListUsagePriceBookRates

func ListUsagePriceBookRates(tx *gorm.DB, version string) ([]UsagePriceBookRate, error)

ListUsagePriceBookRates returns the match rules for one catalog version.

func NormalizeUsagePriceBookRate

func NormalizeUsagePriceBookRate(row UsagePriceBookRate) UsagePriceBookRate

NormalizeUsagePriceBookRate trims identity fields and lowercases the match key.

func (UsagePriceBookRate) TableName

func (UsagePriceBookRate) TableName() string

type UsageReportFilter

type UsageReportFilter struct {
	OrganizationID uuid.UUID
	FactoryID      *uuid.UUID
	WorkOrderID    *uuid.UUID
	UsageKind      string
	Since          time.Time
	Until          time.Time
	Provider       string
	Model          string
	MachineType    string
	TaskOwnerID    *uuid.UUID
	FundingSource  string
}

UsageReportFilter scopes ledger aggregates.

type UsageSplit

type UsageSplit struct {
	// Model is spend on model tokens.
	Model UsageTotals
	// Compute is spend on runner machine time.
	Compute UsageTotals
}

UsageSplit is the ledger of one subject, divided by what the spend paid for.

func SummarizeUsageByLocalDay

func SummarizeUsageByLocalDay(tx *gorm.DB, filter UsageReportFilter, bounds []time.Time) ([]UsageSplit, error)

SummarizeUsageByLocalDay returns ledger spend for the filter, grouped into the local days between bounds. bounds is the sorted starts of those days plus the exclusive end of the last day. An event before the first start, or at or after the last end, is ignored.

The database groups by those exact instants. It does not load each event, and it does not use a SQL time zone. time.Local has no IANA name, and a daylight-saving day is not 24 hours.

A kind other than compute counts as model spend, so the two bands add up to the filtered ledger.

func (UsageSplit) Total

func (s UsageSplit) Total() UsageTotals

Total is the whole ledger of the subject, both bands together.

type UsageTotals

type UsageTotals struct {
	TotalTokens     int64
	DurationSeconds int64
	CostMicros      int64
}

UsageTotals is a token, duration, and cost sum.

func (UsageTotals) Add

func (t UsageTotals) Add(other UsageTotals) UsageTotals

Add returns the field-wise sum of two ledger totals.

func (UsageTotals) CostCents

func (t UsageTotals) CostCents() int64

type User

type User struct {
	ID              uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	OrganizationID  uuid.UUID
	AccountID       *uuid.UUID
	Account         *Account `gorm:"foreignKey:AccountID"`
	Email           *string
	Name            string
	Type            string
	Description     *string
	CreatedBy       *uuid.UUID
	TokenHash       string
	APIKeyExpiresAt *time.Time                  `gorm:"column:api_key_expires_at"`
	APIKeyCanvasIDs datatypes.JSONSlice[string] `gorm:"column:api_key_canvas_ids"`
	IsOwner         bool
	CreatedAt       time.Time
	UpdatedAt       time.Time
	DeletedAt       gorm.DeletedAt
}

func CreateAPIKey added in v0.30.0

func CreateAPIKey(tx *gorm.DB, orgID uuid.UUID, name string, description *string, createdBy uuid.UUID, expiresAt *time.Time, canvasIDs []string) (*User, error)

func CreateUser

func CreateUser(orgID, accountID uuid.UUID, email, name string) (*User, error)

func CreateUserInTransaction

func CreateUserInTransaction(tx *gorm.DB, orgID, accountID uuid.UUID, email, name string) (*User, error)

func FindAPIKeysByOrganization added in v0.30.0

func FindAPIKeysByOrganization(db *gorm.DB, orgID string) ([]User, error)

func FindActiveHumanUserByAccountAndOrganization

func FindActiveHumanUserByAccountAndOrganization(tx *gorm.DB, orgID, accountID uuid.UUID) (*User, error)

func FindActiveUserByEmail

func FindActiveUserByEmail(orgID, email string) (*User, error)

func FindActiveUserByEmailInTransaction added in v0.26.0

func FindActiveUserByEmailInTransaction(tx *gorm.DB, orgID, email string) (*User, error)

func FindActiveUserByID

func FindActiveUserByID(orgID, id string) (*User, error)

func FindActiveUserByIDAnyOrg

func FindActiveUserByIDAnyOrg(tx *gorm.DB, id uuid.UUID) (*User, error)

FindActiveUserByIDAnyOrg loads an active user by ID without scoping to an organization. Used by the personal API token auth path, which resolves a user from a token hash before the request's organization is known.

func FindActiveUserByIDInTransaction

func FindActiveUserByIDInTransaction(tx *gorm.DB, orgID, id string) (*User, error)

func FindActiveUserByTokenHash

func FindActiveUserByTokenHash(tokenHash string) (*User, error)

func FindActiveUserByTokenHashInTransaction added in v0.26.0

func FindActiveUserByTokenHashInTransaction(tx *gorm.DB, tokenHash string) (*User, error)

func FindAnyUserByEmail

func FindAnyUserByEmail(email string) (*User, error)

func FindFirstHumanUserByOrganization added in v0.13.0

func FindFirstHumanUserByOrganization(orgID string) (*User, error)

func FindFirstHumanUserByOrganizationInTransaction added in v0.13.0

func FindFirstHumanUserByOrganizationInTransaction(tx *gorm.DB, orgID string) (*User, error)

func FindHumanUsersByIDs added in v0.9.0

func FindHumanUsersByIDs(ids []string) ([]User, error)

func FindMaybeDeletedUserByEmail

func FindMaybeDeletedUserByEmail(orgID, email string) (*User, error)

func FindMaybeDeletedUserByEmailInTransaction added in v0.0.43

func FindMaybeDeletedUserByEmailInTransaction(tx *gorm.DB, orgID, email string) (*User, error)

func FindMaybeDeletedUserByID

func FindMaybeDeletedUserByID(orgID, id string) (*User, error)

NOTE: this method returns soft deleted users too. Make sure you really need to use it this one, and not FindActiveUserByID instead.

func FindMaybeDeletedUserByIDInTransaction added in v0.26.0

func FindMaybeDeletedUserByIDInTransaction(tx *gorm.DB, orgID, id string) (*User, error)

func FindMaybeDeletedUsersByIDs added in v0.0.43

func FindMaybeDeletedUsersByIDs(tx *gorm.DB, ids []uuid.UUID) ([]User, error)

func FindUnscopedUserByID

func FindUnscopedUserByID(id string) (*User, error)

func FindUnscopedUsersByIDs

func FindUnscopedUsersByIDs(tx *gorm.DB, ids []uuid.UUID) ([]User, error)

func FindUsersByIDs added in v0.9.0

func FindUsersByIDs(ids []string) ([]User, error)

func FindUsersByIDsInOrganization added in v0.19.0

func FindUsersByIDsInOrganization(db *gorm.DB, orgID string, ids []string) ([]User, error)

func ListActiveHumanUsersForAccount

func ListActiveHumanUsersForAccount(tx *gorm.DB, accountID uuid.UUID) ([]User, error)

func ListActiveUsersByID added in v0.0.43

func ListActiveUsersByID(orgID string, ids []string) ([]User, error)

func ListActiveUsersByIDInTransaction added in v0.0.43

func ListActiveUsersByIDInTransaction(tx *gorm.DB, orgID string, ids []string) ([]User, error)

func ListActiveUsersByOrganization added in v0.14.0

func ListActiveUsersByOrganization(orgID, search string, limit, offset int) ([]User, int64, error)

func ListAllActiveUsersInOrganization added in v0.16.0

func ListAllActiveUsersInOrganization(orgID string) ([]User, error)

func ListOrganizationOwners

func ListOrganizationOwners(tx *gorm.DB, orgID uuid.UUID) ([]User, error)

func LockOrganizationOwners

func LockOrganizationOwners(tx *gorm.DB, orgID uuid.UUID) ([]User, error)

func (*User) Delete

func (u *User) Delete() error

func (*User) GetEmail added in v0.9.0

func (u *User) GetEmail() string

func (*User) HasAPIKeyCanvasScope added in v0.30.0

func (u *User) HasAPIKeyCanvasScope() bool

func (*User) IsAPIKey added in v0.30.0

func (u *User) IsAPIKey() bool

func (*User) IsExpiredAPIKey added in v0.30.0

func (u *User) IsExpiredAPIKey() bool

func (*User) IsHuman

func (u *User) IsHuman() bool

func (*User) Restore

func (u *User) Restore() error

func (*User) RestoreInTransaction

func (u *User) RestoreInTransaction(tx *gorm.DB) error

func (*User) SoftDelete

func (u *User) SoftDelete(tx *gorm.DB, now time.Time, tombstoneEmail string) error

func (*User) UpdateTokenHash

func (u *User) UpdateTokenHash(tokenHash string) error

type UserAPIToken

type UserAPIToken struct {
	ID         uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	UserID     uuid.UUID
	Name       string
	TokenHash  string
	CreatedAt  time.Time
	LastUsedAt *time.Time
}

UserAPIToken is a single named personal API token belonging to a human user. A user can hold several tokens at once; each authenticates as the owning user. Revoking a token hard-deletes its row so the other tokens belonging to the same user keep working.

func FindUserAPIToken

func FindUserAPIToken(tx *gorm.DB, userID, id uuid.UUID) (*UserAPIToken, error)

func FindUserAPITokenByHash

func FindUserAPITokenByHash(tx *gorm.DB, tokenHash string) (*UserAPIToken, error)

func ListUserAPITokens

func ListUserAPITokens(tx *gorm.DB, userID uuid.UUID) ([]UserAPIToken, error)

func NewUserAPIToken

func NewUserAPIToken(userID uuid.UUID, name, tokenHash string) *UserAPIToken

func (*UserAPIToken) HardDelete

func (t *UserAPIToken) HardDelete(tx *gorm.DB) error

HardDelete permanently removes the token so it stops authenticating immediately. Other tokens belonging to the same user are unaffected.

func (*UserAPIToken) TableName

func (t *UserAPIToken) TableName() string

type UserAccountProvider added in v0.16.0

type UserAccountProvider struct {
	AccountProvider
	UserID string
}

func FindUserAccountProviders added in v0.16.0

func FindUserAccountProviders(users []User) ([]UserAccountProvider, error)

type UserCanvasPreference added in v0.28.0

type UserCanvasPreference struct {
	OrganizationID uuid.UUID `gorm:"primaryKey"`
	UserID         uuid.UUID `gorm:"primaryKey"`
	CanvasID       uuid.UUID `gorm:"primaryKey"`
	StarredAt      *time.Time
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

func SetUserCanvasPreference added in v0.28.0

func SetUserCanvasPreference(
	tx *gorm.DB,
	organizationID uuid.UUID,
	userID uuid.UUID,
	canvasID uuid.UUID,
	starred *bool,
) (*UserCanvasPreference, error)

func (*UserCanvasPreference) TableName added in v0.28.0

func (p *UserCanvasPreference) TableName() string

type UserLastLocation

type UserLastLocation struct {
	OrganizationID uuid.UUID `gorm:"primaryKey"`
	UserID         uuid.UUID `gorm:"primaryKey"`
	Path           string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

UserLastLocation is the last in-app screen a user visited, scoped to the organization they were in at the time. It powers "resume where you left off" on login: if the user closes the browser (or opens a new one) while waiting on something like a pending approval, they land back on that exact screen instead of the organization home page.

func FindUserLastLocation

func FindUserLastLocation(tx *gorm.DB, organizationID, userID uuid.UUID) (*UserLastLocation, error)

func ListUserLastLocationsForAccount

func ListUserLastLocationsForAccount(tx *gorm.DB, accountID uuid.UUID) ([]UserLastLocation, error)

ListUserLastLocationsForAccount returns saved resume paths for every active organization the account still belongs to.

func SetUserLastLocation

func SetUserLastLocation(tx *gorm.DB, organizationID, userID uuid.UUID, path string) (*UserLastLocation, error)

SetUserLastLocation upserts the calling user's last known location for the organization. It returns ErrUserLastLocationPathInvalid if path is not a safe relative in-app path.

func (*UserLastLocation) TableName

func (l *UserLastLocation) TableName() string

type UserNotificationSettings

type UserNotificationSettings struct {
	ID                      uuid.UUID
	OrganizationID          uuid.UUID
	UserID                  uuid.UUID
	WorkspaceScope          string
	WorkspaceFilters        datatypes.JSONType[[]NotificationWorkspaceFilter]
	EventTypes              datatypes.JSONType[[]string]
	BrowserWorkspaceScope   string
	BrowserWorkspaceFilters datatypes.JSONType[[]NotificationWorkspaceFilter]
	BrowserEventTypes       datatypes.JSONType[[]string]
	BrowserShowWhileViewing bool
	CreatedAt               time.Time
	UpdatedAt               time.Time
}

UserNotificationSettings holds a user's organization-wide notification configuration for workspace work order activity. A user without a row uses DefaultUserNotificationSettings: email for all events from all workspaces, and the browser channel off.

func DefaultUserNotificationSettings

func DefaultUserNotificationSettings() UserNotificationSettings

DefaultUserNotificationSettings is the configuration SuperPlane uses when the user has not saved settings yet.

func FindUserNotificationSettings

func FindUserNotificationSettings(tx *gorm.DB, organizationID, userID uuid.UUID) (*UserNotificationSettings, error)

func UpsertUserNotificationSettings

func UpsertUserNotificationSettings(
	tx *gorm.DB,
	organizationID uuid.UUID,
	userID uuid.UUID,
	params UserNotificationSettingsParams,
) (*UserNotificationSettings, error)

func (*UserNotificationSettings) Notifies

func (s *UserNotificationSettings) Notifies(workspaceID uuid.UUID, notificationType string) bool

Notifies reports whether the settings allow an email for the given workspace and notification type.

func (*UserNotificationSettings) NotifiesChannel

func (s *UserNotificationSettings) NotifiesChannel(channel string, workspaceID uuid.UUID, notificationType string) bool

NotifiesChannel reports whether the settings allow a notification on the given channel for the workspace and notification type.

func (UserNotificationSettings) TableName

func (UserNotificationSettings) TableName() string

type UserNotificationSettingsParams

type UserNotificationSettingsParams struct {
	WorkspaceScope          string
	WorkspaceFilters        []NotificationWorkspaceFilter
	EventTypes              []string
	BrowserWorkspaceScope   string
	BrowserWorkspaceFilters []NotificationWorkspaceFilter
	BrowserEventTypes       []string
	BrowserShowWhileViewing *bool
}

UserNotificationSettingsParams carries the caller-editable fields for UpsertUserNotificationSettings.

type VCSProviderInstallRequest

type VCSProviderInstallRequest struct {
	Provider       string `gorm:"primaryKey"`
	RequestID      int64  `gorm:"primaryKey"`
	AccountID      *int64
	AccountLogin   string
	AccountType    string
	RequesterID    int64
	RequesterLogin string
	RequestedAt    time.Time
	UpdatedAt      time.Time
}

func ListPendingVCSProviderInstallRequests

func ListPendingVCSProviderInstallRequests(tx *gorm.DB, provider string) ([]VCSProviderInstallRequest, error)

ListVCSProviderInstallRequests lists the requests that still wait for approval.

func ListVCSProviderInstallRequests

func ListVCSProviderInstallRequests(tx *gorm.DB, provider string, requesterID int64) ([]VCSProviderInstallRequest, error)

func (VCSProviderInstallRequest) TableName

func (VCSProviderInstallRequest) TableName() string

type VCSProviderInstallRequestRefresh

type VCSProviderInstallRequestRefresh struct {
	Provider     string `gorm:"primaryKey"`
	RefreshUntil time.Time
	UpdatedAt    time.Time
}

VCSProviderInstallRequestRefresh asks the catalog worker to read the provider's install request list often until RefreshUntil.

func (VCSProviderInstallRequestRefresh) TableName

type VCSProviderInstallation

type VCSProviderInstallation struct {
	Provider            string `gorm:"primaryKey"`
	InstallationID      int64  `gorm:"primaryKey"`
	AccountID           *int64
	AccountLogin        string
	AccountType         string
	HTMLURL             string `gorm:"column:html_url"`
	RepositorySelection string
	SuspendedAt         *time.Time
	CreatedAt           time.Time
	UpdatedAt           time.Time
}

func FindVCSProviderInstallation

func FindVCSProviderInstallation(tx *gorm.DB, provider string, installationID int64) (*VCSProviderInstallation, error)

func (VCSProviderInstallation) TableName

func (VCSProviderInstallation) TableName() string

type VCSProviderInstallationReconcileJob

type VCSProviderInstallationReconcileJob struct {
	Provider       string `gorm:"primaryKey"`
	InstallationID int64  `gorm:"primaryKey"`
	RunAt          time.Time
	Attempts       int
	LockedAt       *time.Time
	LastError      string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

func ClaimVCSProviderInstallationReconciliation

func ClaimVCSProviderInstallationReconciliation(
	tx *gorm.DB,
	provider string,
	now, claimableBefore time.Time,
) (*VCSProviderInstallationReconcileJob, error)

func (VCSProviderInstallationReconcileJob) TableName

type VCSProviderInstallationReconcileRequester

type VCSProviderInstallationReconcileRequester struct {
	Provider       string    `gorm:"primaryKey"`
	InstallationID int64     `gorm:"primaryKey"`
	OrganizationID uuid.UUID `gorm:"primaryKey"`
	CreatedAt      time.Time
}

VCSProviderInstallationReconcileRequester links an installation to the organization that installed or updated it. The row outlives the reconcile job until the collaborator sync of that installation finishes, so the organization sees that sync.

func (VCSProviderInstallationReconcileRequester) TableName

type VCSProviderIntegrationBinding

type VCSProviderIntegrationBinding struct {
	IntegrationID  uuid.UUID `gorm:"primaryKey"`
	OrganizationID uuid.UUID
	Provider       string
	InstallationID int64
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

func FindVCSProviderIntegrationBinding

func FindVCSProviderIntegrationBinding(tx *gorm.DB, integrationID uuid.UUID) (*VCSProviderIntegrationBinding, error)

func ListVCSProviderIntegrationBindings

func ListVCSProviderIntegrationBindings(
	tx *gorm.DB,
	provider string,
	installationID int64,
) ([]VCSProviderIntegrationBinding, error)

func (VCSProviderIntegrationBinding) TableName

type VCSProviderIntegrationRepository

type VCSProviderIntegrationRepository struct {
	IntegrationID uuid.UUID `gorm:"primaryKey"`
	Provider      string    `gorm:"primaryKey"`
	RepositoryID  int64     `gorm:"primaryKey"`
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

func (VCSProviderIntegrationRepository) TableName

type VCSProviderReconcileJob

type VCSProviderReconcileJob struct {
	Provider  string `gorm:"primaryKey"`
	RunAt     time.Time
	Attempts  int
	LockedAt  *time.Time
	LastError string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func ClaimVCSProviderReconciliation

func ClaimVCSProviderReconciliation(
	tx *gorm.DB,
	provider string,
	now, claimableBefore time.Time,
) (*VCSProviderReconcileJob, error)

func (VCSProviderReconcileJob) TableName

func (VCSProviderReconcileJob) TableName() string

type VCSProviderRepository

type VCSProviderRepository struct {
	Provider       string `gorm:"primaryKey"`
	RepositoryID   int64  `gorm:"primaryKey"`
	InstallationID int64
	FullName       string
	Private        bool
	DefaultBranch  string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

func FindVCSProviderRepository

func FindVCSProviderRepository(tx *gorm.DB, provider string, repositoryID int64) (*VCSProviderRepository, error)

func ListVCSProviderBindingRepositories

func ListVCSProviderBindingRepositories(tx *gorm.DB, integrationID uuid.UUID) ([]VCSProviderRepository, error)

func ListVCSProviderRepositories

func ListVCSProviderRepositories(tx *gorm.DB, provider string, installationID int64) ([]VCSProviderRepository, error)

func (VCSProviderRepository) TableName

func (VCSProviderRepository) TableName() string

type VCSProviderRepositoryCollaborator

type VCSProviderRepositoryCollaborator struct {
	Provider       string `gorm:"primaryKey"`
	RepositoryID   int64  `gorm:"primaryKey"`
	ProviderUserID int64  `gorm:"primaryKey"`
	ProviderLogin  string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

func (VCSProviderRepositoryCollaborator) TableName

type VCSProviderRepositorySyncJob

type VCSProviderRepositorySyncJob struct {
	Provider     string `gorm:"primaryKey"`
	RepositoryID int64  `gorm:"primaryKey"`
	RunAt        time.Time
	Priority     VCSProviderRepositorySyncPriority
	Attempts     int
	LockedAt     *time.Time
	LastError    string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func ClaimVCSProviderRepositorySync

func ClaimVCSProviderRepositorySync(
	tx *gorm.DB,
	provider string,
	now, claimableBefore time.Time,
) (*VCSProviderRepositorySyncJob, error)

func (VCSProviderRepositorySyncJob) TableName

type VCSProviderRepositorySyncPriority

type VCSProviderRepositorySyncPriority int16
const (
	VCSProviderRepositorySyncPriorityBackground  VCSProviderRepositorySyncPriority = 0
	VCSProviderRepositorySyncPriorityInteractive VCSProviderRepositorySyncPriority = 100
)

type VisualEvidenceCaptureRequest

type VisualEvidenceCaptureRequest struct {
	OrganizationID string `json:"organization_id"`
	FactoryID      string `json:"factory_id"`
	PullRequestID  string `json:"pull_request_id"`
	Attempts       int    `json:"attempts,omitempty"`
}

type Webhook

type Webhook struct {
	ID                uuid.UUID `gorm:"primary_key;default:uuid_generate_v4()"`
	State             string
	Secret            []byte
	Configuration     datatypes.JSONType[any]
	Metadata          datatypes.JSONType[any]
	AppInstallationID *uuid.UUID
	RetryCount        int `gorm:"default:0"`
	MaxRetries        int `gorm:"default:3"`
	CreatedAt         *time.Time
	UpdatedAt         *time.Time
	DeletedAt         gorm.DeletedAt `gorm:"index"`
}

func FindWebhook

func FindWebhook(id uuid.UUID) (*Webhook, error)

func FindWebhookInTransaction

func FindWebhookInTransaction(tx *gorm.DB, id uuid.UUID) (*Webhook, error)

func ListBitbucketForgeWebhooks

func ListBitbucketForgeWebhooks(tx *gorm.DB, installationID, repositoryUUID string) ([]Webhook, error)

func ListDeletedWebhooks

func ListDeletedWebhooks() ([]Webhook, error)

func ListIntegrationWebhooks added in v0.6.0

func ListIntegrationWebhooks(tx *gorm.DB, integrationID uuid.UUID) ([]Webhook, error)

func ListPendingWebhooks

func ListPendingWebhooks() ([]Webhook, error)

func ListUnscopedIntegrationWebhooks added in v0.6.0

func ListUnscopedIntegrationWebhooks(tx *gorm.DB, integrationID uuid.UUID) ([]Webhook, error)

func LockDeletedWebhook added in v0.12.0

func LockDeletedWebhook(tx *gorm.DB, ID uuid.UUID) (*Webhook, error)

LockDeletedWebhook acquires a row-level lock on a soft-deleted webhook regardless of its state. Used by WebhookCleanupWorker to clean up webhooks that were in any state (ready, failed, etc.) when deleted.

func LockWebhook

func LockWebhook(tx *gorm.DB, ID uuid.UUID) (*Webhook, error)

func (*Webhook) HasExceededRetries

func (w *Webhook) HasExceededRetries() bool

func (*Webhook) IncrementRetry

func (w *Webhook) IncrementRetry(tx *gorm.DB) error

func (*Webhook) MarkFailed

func (w *Webhook) MarkFailed(tx *gorm.DB) error

func (*Webhook) MarkProvisioning added in v0.12.0

func (w *Webhook) MarkProvisioning(tx *gorm.DB) error

func (*Webhook) Ready

func (w *Webhook) Ready(tx *gorm.DB) error

func (*Webhook) ReadyWithMetadata

func (w *Webhook) ReadyWithMetadata(tx *gorm.DB, metadata any) error

func (*Webhook) Reprovision

func (w *Webhook) Reprovision(tx *gorm.DB, configuration any) (bool, error)

Reprovision marks a ready or failed webhook pending so Setup runs again. A webhook that is already pending or provisioning is left unchanged, so a second sync cannot start another remote webhook while the first is in progress. The bool is true when this call changed the row.

func (*Webhook) UpdateConfiguration

func (w *Webhook) UpdateConfiguration(tx *gorm.DB, configuration any) error

UpdateConfiguration stores a new configuration and leaves the state unchanged.

type WebhookResource

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

type WidgetRef added in v0.0.18

type WidgetRef struct {
	Name string `json:"name"`
}

type WorkOrderMCPClient

type WorkOrderMCPClient struct {
	ID   string
	Name string
}

WorkOrderMCPClient is the MCP OAuth client that handed this task off.

type WorkOrderOrigin

type WorkOrderOrigin struct {
	URL   string
	Label string
}

WorkOrderOrigin is the external ticket a work order was created from.

func OriginFromImportedIntakeItem

func OriginFromImportedIntakeItem(itemURL, title string) WorkOrderOrigin

func OriginFromIntakePayload

func OriginFromIntakePayload(payload map[string]any) *WorkOrderOrigin

func OriginFromIntakeRootEvent

func OriginFromIntakeRootEvent(event *CanvasEvent) *WorkOrderOrigin

type WorkOrderRunUsage

type WorkOrderRunUsage struct {
	WorkOrderExecutionID uuid.UUID
	WorkOrderID          uuid.UUID
	WorkOrderNumber      int64
	Title                string
	LastOccurredAt       time.Time
	UserID               *uuid.UUID
	UserName             string
	UserEmail            string
	TotalTokens          int64
	DurationSeconds      int64
	CostMicros           int64
	HostedCostMicros     int64
	BYOKCostMicros       int64
	Models               []string
	BYOKModels           []string
	MachineTypes         []string
}

WorkOrderRunUsage is one task-run spend row grouped from the ledger.

func ListAllWorkOrderRunUsage

func ListAllWorkOrderRunUsage(tx *gorm.DB, filter UsageReportFilter) ([]WorkOrderRunUsage, error)

ListAllWorkOrderRunUsage returns every task-run spend row in the ledger for the filter's scope, with no date window and no pagination. It backs the full-history CSV export; the paginated ListWorkOrderRunUsage stays bound to a reporting period and page size for the table.

func ListWorkOrderRunUsage

func ListWorkOrderRunUsage(tx *gorm.DB, filter UsageReportFilter, limit, offset int) ([]WorkOrderRunUsage, int64, error)

ListWorkOrderRunUsage returns paginated task-run spend from the ledger. It does not write usage or change remaining hosted credit.

func (WorkOrderRunUsage) BYOKCostCents

func (r WorkOrderRunUsage) BYOKCostCents() int64

func (WorkOrderRunUsage) ComputeCostMicros

func (r WorkOrderRunUsage) ComputeCostMicros() int64

func (WorkOrderRunUsage) CostCents

func (r WorkOrderRunUsage) CostCents() int64

func (WorkOrderRunUsage) HostedCostCents

func (r WorkOrderRunUsage) HostedCostCents() int64

func (WorkOrderRunUsage) TokenCostMicros

func (r WorkOrderRunUsage) TokenCostMicros() int64

type WorkflowStagedFile added in v0.28.0

type WorkflowStagedFile struct {
	ID             uuid.UUID `gorm:"type:uuid;primaryKey;default:uuid_generate_v4()"`
	OrganizationID uuid.UUID `gorm:"type:uuid;not null"`
	WorkflowID     uuid.UUID `gorm:"type:uuid;not null"`
	UserID         uuid.UUID `gorm:"type:uuid;not null"`
	BaseVersionID  uuid.UUID `gorm:"type:uuid;not null"`
	Path           string    `gorm:"type:text;not null"`
	Content        string    `gorm:"type:text;not null;default:''"`
	UpdatedAt      time.Time `gorm:"not null"`

	//
	// Deleted marks a leftover staged file removal (row kept). Effective read
	// returns empty content when true. DiscardWorkflowStaging hard-deletes rows
	// to revert staging. New staging updates cannot mark paths deleted.
	//
	Deleted bool `gorm:"not null;default:false"`
}

func FindStagedFileForUser added in v0.28.0

func FindStagedFileForUser(db *gorm.DB, workflowID, userID uuid.UUID, path string) (*WorkflowStagedFile, error)

func ListStagedFilesForUser added in v0.28.0

func ListStagedFilesForUser(db *gorm.DB, workflowID, userID uuid.UUID) ([]WorkflowStagedFile, error)

func UpsertStagedFile added in v0.28.0

func UpsertStagedFile(
	db *gorm.DB,
	workflowID, userID, baseVersionID, organizationID uuid.UUID,
	path, content string,
) (*WorkflowStagedFile, error)

func (WorkflowStagedFile) TableName added in v0.28.0

func (WorkflowStagedFile) TableName() string

type WorkspaceUsageEvent

type WorkspaceUsageEvent struct {
	ID                   uuid.UUID
	OrganizationID       uuid.UUID
	FactoryID            *uuid.UUID
	WorkOrderID          *uuid.UUID
	LineID               *uuid.UUID
	LineDispatchID       *uuid.UUID
	WorkOrderExecutionID *uuid.UUID
	CanvasRunID          uuid.UUID
	NodeExecutionID      uuid.UUID
	NodeID               string
	Provider             string
	Model                string
	UsageKind            string
	FundingSource        string
	InputTokens          int64
	OutputTokens         int64
	CacheReadTokens      int64
	CacheWriteTokens     int64
	ReasoningTokens      int64
	TotalTokens          int64
	DurationSeconds      int64
	MachineType          string
	FleetID              string
	CostMicros           int64
	ProviderCostMicros   int64
	Currency             string
	PriceBookVersion     string
	IdempotencyKey       string
	OccurredAt           time.Time
	CreatedAt            time.Time
}

WorkspaceUsageEvent is one append-only spend row (model tokens or VM seconds). It is the source of truth for reports. Factory execution token/cost/duration columns are cached rollups.

func (WorkspaceUsageEvent) TableName

func (WorkspaceUsageEvent) TableName() string

type WorkspaceUsageEventInput

type WorkspaceUsageEventInput struct {
	OrganizationID   uuid.UUID
	CanvasRunID      uuid.UUID
	NodeExecutionID  uuid.UUID
	NodeID           string
	Provider         string
	Model            string
	FundingSource    string
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	TotalTokens      int64
	CostMicros       *int64
	IdempotencyKey   string
}

WorkspaceUsageEventInput is the call-site payload before factory scope is resolved.

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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