Documentation
¶
Index ¶
- Constants
- Variables
- func AddFilesToTargetRepos(ctx context.Context, config *configs.Config, ...)
- func AppendWebhookTrace(c *ServiceContainer, e WebhookTraceEntry)
- func CloseGoogleLogger()
- func ConfigDiagnosticHandler(container *ServiceContainer, version string) http.HandlerFunc
- func ConfigurePermissions(ctx context.Context, config *configs.Config) error
- func ContextWithLogBuffer(ctx context.Context, deliveryID string, buf *DeliveryLogBuffer) context.Context
- func DeleteBranchIfExistsExported(ctx context.Context, client *github.Client, defaultOwner, repo string, ...) error
- func GetFilesChangedInPr(ctx context.Context, config *configs.Config, owner string, repo string, ...) ([]types.ChangedFile, error)
- func GetGraphQLClient(ctx context.Context, config *configs.Config) (*graphql.Client, error)
- func GetGraphQLClientForOrg(ctx context.Context, config *configs.Config, org string) (*graphql.Client, error)
- func GetRestClient() *github.Client
- func GetRestClientForOrg(ctx context.Context, config *configs.Config, org string) (*github.Client, error)
- func HandleWebhookWithContainer(w http.ResponseWriter, r *http.Request, config *configs.Config, ...)
- func HealthHandler(startTime time.Time, version string) http.HandlerFunc
- func InitializeLogger(config *configs.Config)
- func IsPermanentError(err error) bool
- func LoadAnthropicAPIKey(ctx context.Context, config *configs.Config) error
- func LoadMongoURI(ctx context.Context, config *configs.Config) error
- func LoadWebhookSecret(ctx context.Context, config *configs.Config) error
- func LogAndReturnError(ctx context.Context, operation string, message string, err error)
- func LogCritical(message string, args ...any)
- func LogDebug(message string, args ...any)
- func LogError(message string, args ...any)
- func LogErrorCtx(ctx context.Context, message string, err error, fields map[string]interface{})
- func LogFileOperation(ctx context.Context, operation string, sourcePath string, targetRepo string, ...)
- func LogInfo(message string, args ...any)
- func LogInfoCtx(ctx context.Context, message string, fields map[string]interface{})
- func LogWarning(message string, args ...any)
- func LogWarningCtx(ctx context.Context, message string, fields map[string]interface{})
- func LogWebhookOperation(ctx context.Context, operation string, message string, err error, ...)
- func MergePRBodyWithTemplate(configuredBody, template string) string
- func MetricsHandler(metricsCollector *MetricsCollector, fileStateService FileStateService) http.HandlerFunc
- func ReadinessHandler(container *ServiceContainer) http.HandlerFunc
- func RegisterOperatorRoutes(mux *http.ServeMux, cfg *configs.Config, container *ServiceContainer, ...)
- func RetrieveFileContents(ctx context.Context, config *configs.Config, filePath string) (github.RepositoryContent, error)
- func RetrieveFileContentsWithConfigAndBranch(ctx context.Context, config *configs.Config, filePath string, branch string, ...) (*github.RepositoryContent, error)
- func SetInstallationTokenForOrg(org, token string)
- func UpdateDeprecationFile(ctx context.Context, config *configs.Config, ...)
- func WithRequestID(r *http.Request) (context.Context, string)
- type AuditEvent
- type AuditEventType
- type AuditListQuery
- type AuditLogger
- type AuditLoggerHealthStatus
- type CachedConfigLoader
- type ConfigDiagnosticResponse
- type ConfigDiagnosticWorkflow
- type ConfigEnvironment
- type ConfigLoader
- type DailyStats
- type DefaultConfigLoader
- type DefaultFileStateService
- func (fss *DefaultFileStateService) AddFileToDeprecate(deprecationFile string, entry types.DeprecatedFileEntry)
- func (fss *DefaultFileStateService) AddFileToUpload(key types.UploadKey, content types.UploadFileContent)
- func (fss *DefaultFileStateService) ClearFilesToDeprecate()
- func (fss *DefaultFileStateService) ClearFilesToUpload()
- func (fss *DefaultFileStateService) GetFilesToDeprecate() map[string][]types.DeprecatedFileEntry
- func (fss *DefaultFileStateService) GetFilesToUpload() map[types.UploadKey]types.UploadFileContent
- type DefaultMainConfigLoader
- func (mcl *DefaultMainConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
- func (mcl *DefaultMainConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
- func (mcl *DefaultMainConfigLoader) LoadMainConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
- func (mcl *DefaultMainConfigLoader) LoadMainConfigFromContent(ctx context.Context, content string, config *configs.Config) (*types.YAMLConfig, error)
- type DefaultMessageTemplater
- func (mt *DefaultMessageTemplater) RenderCommitMessage(template string, ctx *types.MessageContext) string
- func (mt *DefaultMessageTemplater) RenderPRBody(template string, ctx *types.MessageContext) string
- func (mt *DefaultMessageTemplater) RenderPRTitle(template string, ctx *types.MessageContext) string
- type DefaultPRTemplateFetcher
- type DefaultPathTransformer
- type DefaultPatternMatcher
- type DefaultSlackNotifier
- func (sn *DefaultSlackNotifier) IsEnabled() bool
- func (sn *DefaultSlackNotifier) NotifyDeprecation(ctx context.Context, event *DeprecationEvent) error
- func (sn *DefaultSlackNotifier) NotifyError(ctx context.Context, event *ErrorEvent) error
- func (sn *DefaultSlackNotifier) NotifyFilesCopied(ctx context.Context, event *FilesCopiedEvent) error
- func (sn *DefaultSlackNotifier) NotifyPRProcessed(ctx context.Context, event *PRProcessedEvent) error
- type DeliveryLogBuffer
- type DeliverySnapshot
- type DeliveryTracker
- type DeprecationEvent
- type ErrorEvent
- type FileMetrics
- type FileStateService
- type FilesCopiedEvent
- type GitHubAPIMetrics
- type GitHubHealthStatus
- type HealthStatus
- type LLMClient
- type LLMClientOptions
- type LLMModel
- type LLMPullProgress
- type LogEntry
- type MessageTemplater
- type MetricsCollector
- func (mc *MetricsCollector) GetFilesMatched() int
- func (mc *MetricsCollector) GetFilesUploadFailed() int
- func (mc *MetricsCollector) GetFilesUploaded() int
- func (mc *MetricsCollector) GetMetrics(fileStateService FileStateService) MetricsData
- func (mc *MetricsCollector) RecordFileDeprecated()
- func (mc *MetricsCollector) RecordFileMatched()
- func (mc *MetricsCollector) RecordFileUploadFailed()
- func (mc *MetricsCollector) RecordFileUploaded(duration time.Duration)
- func (mc *MetricsCollector) RecordGitHubAPICall()
- func (mc *MetricsCollector) RecordGitHubAPIError()
- func (mc *MetricsCollector) RecordWebhookFailed()
- func (mc *MetricsCollector) RecordWebhookIgnored(eventType string)
- func (mc *MetricsCollector) RecordWebhookProcessed(duration time.Duration)
- func (mc *MetricsCollector) RecordWebhookReceived()
- type MetricsData
- type MongoAuditLogger
- func (mal *MongoAuditLogger) Close(ctx context.Context) error
- func (mal *MongoAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
- func (mal *MongoAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
- func (mal *MongoAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (mal *MongoAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (mal *MongoAuditLogger) GetStatsByRule(ctx context.Context) (map[string]RuleStats, error)
- func (mal *MongoAuditLogger) LogConfigChangeEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
- func (mal *MongoAuditLogger) Ping(ctx context.Context) error
- func (mal *MongoAuditLogger) QueryAuditEvents(ctx context.Context, q AuditListQuery) ([]AuditEvent, error)
- type NoOpAuditLogger
- func (nal *NoOpAuditLogger) Close(ctx context.Context) error
- func (nal *NoOpAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
- func (nal *NoOpAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
- func (nal *NoOpAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (nal *NoOpAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
- func (nal *NoOpAuditLogger) GetStatsByRule(ctx context.Context) (map[string]RuleStats, error)
- func (nal *NoOpAuditLogger) LogConfigChangeEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
- func (nal *NoOpAuditLogger) Ping(ctx context.Context) error
- func (nal *NoOpAuditLogger) QueryAuditEvents(ctx context.Context, q AuditListQuery) ([]AuditEvent, error)
- type OperatorDeploymentInfo
- type OperatorRole
- type OperatorUser
- type PRProcessedEvent
- type PRTemplateFetcher
- type PathTransformer
- type PatternMatcher
- type ProcessingTimeStats
- type QueueHealthStatus
- type QueueMetrics
- type RateLimitInfo
- type RateLimitState
- type ReleaseAPIMode
- type RuleStats
- type ServiceContainer
- type SlackAttachment
- type SlackField
- type SlackMessage
- type SlackNotifier
- type SystemMetrics
- type TokenManager
- func (tm *TokenManager) GetCachedJWT() (string, bool)
- func (tm *TokenManager) GetHTTPClient() *http.Client
- func (tm *TokenManager) GetInstallationAccessToken() string
- func (tm *TokenManager) GetTokenForOrg(org string) (string, bool)
- func (tm *TokenManager) SetCachedJWT(token string, expiry time.Time)
- func (tm *TokenManager) SetHTTPClient(client *http.Client)
- func (tm *TokenManager) SetInstallationAccessToken(token string)
- func (tm *TokenManager) SetTokenForOrg(org, token string, expiresAt time.Time)
- func (tm *TokenManager) SetTokenForOrgNoExpiry(org, token string)
- type WebhookMetrics
- type WebhookTraceBuffer
- type WebhookTraceEntry
- type WorkflowProcessor
Constants ¶
const LevelCritical = slog.Level(12)
LevelCritical is a custom slog level above Error for critical/fatal issues. slog defines Debug=-4, Info=0, Warn=4, Error=8; we use 12 for Critical.
const SuggestRuleSystemPrompt = `` /* 3760-byte string literal not displayed */
SuggestRuleSystemPrompt is the system prompt used by the AI rule suggester. Exported so cmd/test-llm can exercise the real prompt end-to-end against the configured provider (same prompt writers will hit via the UI).
Variables ¶
var ( // ErrAuthentication indicates a GitHub App authentication failure // (invalid PEM, expired key, bad JWT, etc.). ErrAuthentication = errors.New("github app authentication failed") // ErrSecretAccess indicates a failure to retrieve a secret from // GCP Secret Manager or from the local environment fallback. ErrSecretAccess = errors.New("secret access failed") // ErrConfigLoad indicates a failure to load or parse the YAML configuration file. ErrConfigLoad = errors.New("config load failed") // ErrConfigValidation indicates the configuration was loaded but failed validation. ErrConfigValidation = errors.New("config validation failed") // ErrContentNil indicates that the GitHub API returned a nil content body // for a file that was expected to exist. ErrContentNil = errors.New("file content is nil") // ErrInstallationNotFound indicates that no GitHub App installation was found // for the given organization. ErrInstallationNotFound = errors.New("no installation found for organization") // ErrMergeConflict indicates a PR or ref update could not be completed // due to merge conflicts or non-fast-forward push. ErrMergeConflict = errors.New("merge conflict") )
Sentinel errors for common failure modes. Wrap these with fmt.Errorf("%w", ...) so callers can use errors.Is() to detect specific failure categories.
var ErrModelManagementNotSupported = errors.New("model management not supported for this provider")
ErrModelManagementNotSupported is returned by providers (e.g. Anthropic) where model pulls/deletes don't apply. Handlers should map this to a 400-class response rather than a 502, since it's a client-intent error, not a backend failure.
var GlobalRateLimitState = &RateLimitState{remaining: -1} // -1 = not yet observed
GlobalRateLimitState is the shared rate limit state read by the health/metrics endpoints.
Functions ¶
func AddFilesToTargetRepos ¶
func AddFilesToTargetRepos(ctx context.Context, config *configs.Config, filesToUpload map[types.UploadKey]types.UploadFileContent, prTemplateFetcher PRTemplateFetcher, metricsCollector *MetricsCollector, auditLogger AuditLogger)
AddFilesToTargetRepos uploads files to target repository branches. It accepts the upload map as a parameter for concurrency safety. When auditLogger is non-nil, each file copy is recorded (success or failure) for MongoDB audit.
func AppendWebhookTrace ¶ added in v0.4.0
func AppendWebhookTrace(c *ServiceContainer, e WebhookTraceEntry)
AppendWebhookTrace records one webhook row for the operator dashboard.
func CloseGoogleLogger ¶
func CloseGoogleLogger()
CloseGoogleLogger flushes and closes the underlying Google logging client, if any.
func ConfigDiagnosticHandler ¶
func ConfigDiagnosticHandler(container *ServiceContainer, version string) http.HandlerFunc
ConfigDiagnosticHandler handles the GET /config endpoint. It returns a read-only view of the resolved runtime configuration with all secrets redacted, useful for debugging workflow-matching issues.
func ConfigurePermissions ¶
ConfigurePermissions sets up the necessary permissions to interact with the GitHub API. It retrieves the GitHub App's private key from Google Secret Manager, generates a JWT, and exchanges it for an installation access token stored in the TokenManager.
func ContextWithLogBuffer ¶ added in v0.4.0
func ContextWithLogBuffer(ctx context.Context, deliveryID string, buf *DeliveryLogBuffer) context.Context
ContextWithLogBuffer returns a context that carries a delivery ID for log capture.
func DeleteBranchIfExistsExported ¶
func DeleteBranchIfExistsExported(ctx context.Context, client *github.Client, defaultOwner, repo string, ref *github.Reference) error
DeleteBranchIfExistsExported is an exported wrapper for testing deleteBranchIfExists
func GetFilesChangedInPr ¶
func GetFilesChangedInPr(ctx context.Context, config *configs.Config, owner string, repo string, pr_number int) ([]types.ChangedFile, error)
GetFilesChangedInPr retrieves the list of files changed in a specified pull request. It returns a slice of ChangedFile structures containing details about each changed file. Parameters:
- owner: The repository owner (e.g., "mongodb")
- repo: The repository name (e.g., "docs-sample-apps")
- pr_number: The pull request number
func GetGraphQLClient ¶
GetGraphQLClient returns a GitHub GraphQL API client authenticated with the default installation access token.
func GetGraphQLClientForOrg ¶
func GetGraphQLClientForOrg(ctx context.Context, config *configs.Config, org string) (*graphql.Client, error)
GetGraphQLClientForOrg returns a GitHub GraphQL API client authenticated for a specific organization. Uses the TokenManager for thread-safe token caching with expiry tracking.
func GetRestClient ¶
GetRestClient returns a GitHub REST API client authenticated with the default installation access token.
func GetRestClientForOrg ¶
func GetRestClientForOrg(ctx context.Context, config *configs.Config, org string) (*github.Client, error)
GetRestClientForOrg returns a GitHub REST API client authenticated for a specific organization.
func HandleWebhookWithContainer ¶
func HandleWebhookWithContainer(w http.ResponseWriter, r *http.Request, config *configs.Config, container *ServiceContainer)
HandleWebhookWithContainer handles incoming GitHub webhook requests using the service container
func HealthHandler ¶
func HealthHandler(startTime time.Time, version string) http.HandlerFunc
HealthHandler handles /health (liveness) endpoint. Returns 200 if the process is running. This is a lightweight check suitable for Cloud Run / Kubernetes liveness probes.
func InitializeLogger ¶
InitializeLogger sets up the slog-based logger with JSON output and optional GCP Cloud Logging integration. Call this once at startup.
func IsPermanentError ¶
IsPermanentError returns true if err represents a failure that will not resolve by retrying the same operation. The retry loop should break immediately when this returns true.
Permanent errors include:
- Known sentinel errors (config validation, installation not found, merge conflict)
- GitHub API responses with 403, 404, 409, 410, or 422 status codes
Note: HTTP 403 from rate limiting is handled separately by rateLimitTransport before it reaches this layer. A 403 that reaches here is a true permission denial.
func LoadAnthropicAPIKey ¶ added in v0.4.0
LoadAnthropicAPIKey loads the Anthropic API key from Secret Manager or environment variable. Only called when the LLM provider is "anthropic". Missing value is non-fatal: NewLLMClient will refuse to construct a client, the operator UI will show "not configured", and the rest of the app runs.
func LoadMongoURI ¶
LoadMongoURI loads the MongoDB URI from Secret Manager or environment variable
func LoadWebhookSecret ¶
LoadWebhookSecret loads the webhook secret from Secret Manager or environment variable
func LogAndReturnError ¶
LogAndReturnError logs an error and returns (convenience for early-return error paths).
func LogCritical ¶
LogCritical writes a critical-level log (above Error).
func LogDebug ¶
LogDebug writes a debug-level log. Only emits when LOG_LEVEL=debug or COPIER_DEBUG=true.
func LogErrorCtx ¶
LogErrorCtx writes an error-level log with context and an optional error.
func LogFileOperation ¶
func LogFileOperation(ctx context.Context, operation string, sourcePath string, targetRepo string, message string, err error, fields ...map[string]interface{})
LogFileOperation logs file-related operations.
func LogInfoCtx ¶
LogInfoCtx writes an info-level log with context.
func LogWarning ¶
LogWarning writes a warning-level log.
func LogWarningCtx ¶
LogWarningCtx writes a warning-level log with context.
func LogWebhookOperation ¶
func LogWebhookOperation(ctx context.Context, operation string, message string, err error, fields ...map[string]interface{})
LogWebhookOperation logs webhook-related operations.
func MergePRBodyWithTemplate ¶
MergePRBodyWithTemplate merges a configured PR body with a PR template The template is placed first, then the configured body is appended, separated by a horizontal rule
func MetricsHandler ¶
func MetricsHandler(metricsCollector *MetricsCollector, fileStateService FileStateService) http.HandlerFunc
MetricsHandler handles /metrics endpoint
func ReadinessHandler ¶
func ReadinessHandler(container *ServiceContainer) http.HandlerFunc
ReadinessHandler handles /ready endpoint. Checks actual dependency connectivity (GitHub API auth, MongoDB). Returns 200 if all dependencies are reachable, 503 otherwise. Suitable for Cloud Run / Kubernetes readiness probes.
func RegisterOperatorRoutes ¶ added in v0.4.0
func RegisterOperatorRoutes(mux *http.ServeMux, cfg *configs.Config, container *ServiceContainer, version string)
RegisterOperatorRoutes mounts the operator HTML UI and JSON APIs under /operator/. Call only when cfg.OperatorUIEnabled is true. Works with any HTTP origin (local dev, Cloud Run, Kubernetes, etc.). Every secured API requires an Authorization: Bearer <github-pat> header. The user's permission on cfg.OperatorAuthRepo determines their role (operator or writer).
func RetrieveFileContents ¶
func RetrieveFileContents(ctx context.Context, config *configs.Config, filePath string) (github.RepositoryContent, error)
RetrieveFileContents fetches the contents of a file from the config repository at the specified path. It returns a github.RepositoryContent object containing the file details.
func RetrieveFileContentsWithConfigAndBranch ¶
func RetrieveFileContentsWithConfigAndBranch(ctx context.Context, config *configs.Config, filePath string, branch string, repoOwner string, repoName string) (*github.RepositoryContent, error)
RetrieveFileContentsWithConfigAndBranch fetches file contents from a specific branch
func SetInstallationTokenForOrg ¶
func SetInstallationTokenForOrg(org, token string)
SetInstallationTokenForOrg sets a cached installation token for an organization. This is primarily used for testing to bypass the GitHub App authentication flow.
func UpdateDeprecationFile ¶
func UpdateDeprecationFile(ctx context.Context, config *configs.Config, filesToDeprecate map[string]types.Configs, sourceRepoOwner, sourceRepoName, sourceBranch string)
UpdateDeprecationFile updates the deprecation file in the source repo with the provided data map. The deprecation file tracks which files have been deleted from the source repo.
Types ¶
type AuditEvent ¶
type AuditEvent struct {
ID string `bson:"_id,omitempty" json:"id,omitempty"`
Timestamp time.Time `bson:"timestamp" json:"timestamp"`
EventType AuditEventType `bson:"event_type" json:"event_type"`
RuleName string `bson:"rule_name,omitempty" json:"rule_name,omitempty"`
SourceRepo string `bson:"source_repo" json:"source_repo"`
SourcePath string `bson:"source_path" json:"source_path"`
TargetRepo string `bson:"target_repo,omitempty" json:"target_repo,omitempty"`
TargetPath string `bson:"target_path,omitempty" json:"target_path,omitempty"`
CommitSHA string `bson:"commit_sha,omitempty" json:"commit_sha,omitempty"`
PRNumber int `bson:"pr_number,omitempty" json:"pr_number,omitempty"`
Success bool `bson:"success" json:"success"`
ErrorMessage string `bson:"error_message,omitempty" json:"error_message,omitempty"`
DurationMs int64 `bson:"duration_ms,omitempty" json:"duration_ms,omitempty"`
FileSize int64 `bson:"file_size,omitempty" json:"file_size,omitempty"`
// Actor identifies the GitHub login responsible for an operator-initiated
// event (e.g. an LLM settings change). Empty for webhook-driven copies.
Actor string `bson:"actor,omitempty" json:"actor,omitempty"`
AdditionalData map[string]any `bson:"additional_data,omitempty" json:"additional_data,omitempty"`
}
AuditEvent represents an audit log entry
type AuditEventType ¶
type AuditEventType string
AuditEventType represents the type of audit event
const ( AuditEventCopy AuditEventType = "copy" AuditEventDeprecation AuditEventType = "deprecation" AuditEventError AuditEventType = "error" AuditEventConfigChange AuditEventType = "config_change" )
type AuditListQuery ¶ added in v0.4.0
type AuditListQuery struct {
Limit int
EventType string // empty = any; otherwise copy | deprecation | error
Success *bool // nil = any
RuleName string // exact match when non-empty
PRNumber *int // nil = any; exact match when set
PathSearch string // substring match on source_path OR target_path when non-empty
Since *time.Time // inclusive lower bound on timestamp when set
}
AuditListQuery filters audit rows for operator dashboards and APIs.
type AuditLogger ¶
type AuditLogger interface {
LogCopyEvent(ctx context.Context, event *AuditEvent) error
LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
LogErrorEvent(ctx context.Context, event *AuditEvent) error
// LogConfigChangeEvent records an operator-initiated configuration change
// (e.g. LLM base URL or active model). Used for after-the-fact detection
// of suspicious changes — the event captures who, what, and old→new value.
LogConfigChangeEvent(ctx context.Context, event *AuditEvent) error
GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
GetStatsByRule(ctx context.Context) (map[string]RuleStats, error)
GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
QueryAuditEvents(ctx context.Context, q AuditListQuery) ([]AuditEvent, error)
Ping(ctx context.Context) error
Close(ctx context.Context) error
}
AuditLogger handles audit logging to MongoDB
func NewMongoAuditLogger ¶
func NewMongoAuditLogger(ctx context.Context, mongoURI, database, collection string, enabled bool) (AuditLogger, error)
NewMongoAuditLogger creates a new MongoDB audit logger
type AuditLoggerHealthStatus ¶
type AuditLoggerHealthStatus struct {
Status string `json:"status"`
Connected bool `json:"connected"`
}
AuditLoggerHealthStatus represents audit logger health
type CachedConfigLoader ¶
type CachedConfigLoader struct {
// contains filtered or unexported fields
}
CachedConfigLoader wraps a ConfigLoader and caches the resolved *YAMLConfig for a configurable TTL. Subsequent calls within the TTL window return the cached config without making any GitHub API calls.
The cache is safe for concurrent access. It is keyed on the effective config file path, so different configs don't collide.
func (*CachedConfigLoader) InvalidateCache ¶
func (c *CachedConfigLoader) InvalidateCache()
InvalidateCache clears all cached entries. Useful after a config-repo push event.
func (*CachedConfigLoader) LoadConfig ¶
func (c *CachedConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfig returns a cached config if fresh, otherwise delegates to the inner loader.
func (*CachedConfigLoader) LoadConfigFromContent ¶
func (c *CachedConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
LoadConfigFromContent delegates directly — content-based loads are not cached since the caller already has the content in hand.
type ConfigDiagnosticResponse ¶
type ConfigDiagnosticResponse struct {
// Version is the build version (set via -ldflags at build time).
Version string `json:"version"`
// Environment summarizes non-secret runtime configuration.
Environment ConfigEnvironment `json:"environment"`
// Workflows contains the resolved workflow definitions (if loadable).
// Nil when the config could not be loaded (see LoadError).
Workflows []ConfigDiagnosticWorkflow `json:"workflows,omitempty"`
// LoadError is set when the effective config file cannot be loaded or parsed.
LoadError string `json:"load_error,omitempty"`
}
ConfigDiagnosticResponse is the JSON structure returned by the /config endpoint.
type ConfigDiagnosticWorkflow ¶
type ConfigDiagnosticWorkflow struct {
Name string `json:"name"`
SourceRepo string `json:"source_repo"`
SourceBranch string `json:"source_branch"`
DestRepo string `json:"dest_repo"`
DestBranch string `json:"dest_branch"`
CommitStrategy string `json:"commit_strategy"`
Transforms int `json:"transforms"`
Exclude []string `json:"exclude,omitempty"`
}
ConfigDiagnosticWorkflow is a compact summary of a resolved workflow.
type ConfigEnvironment ¶
type ConfigEnvironment struct {
Port string `json:"port"`
DryRun bool `json:"dry_run"`
UseMainConfig bool `json:"use_main_config"`
EffectiveConfig string `json:"effective_config_file"`
ConfigRepoOwner string `json:"config_repo_owner"`
ConfigRepoName string `json:"config_repo_name"`
ConfigRepoBranch string `json:"config_repo_branch"`
WebserverPath string `json:"webserver_path"`
// Feature flags
AuditEnabled bool `json:"audit_enabled"`
MetricsEnabled bool `json:"metrics_enabled"`
SlackEnabled bool `json:"slack_enabled"`
// Tuning
ConfigCacheTTLSeconds int `json:"config_cache_ttl_seconds"`
WebhookProcessingTimeoutSeconds int `json:"webhook_processing_timeout_seconds"`
WebhookMaxRetries int `json:"webhook_max_retries"`
GitHubAPIMaxRetries int `json:"github_api_max_retries"`
// Secrets (presence only)
PEMKey string `json:"pem_key"`
WebhookSecret string `json:"webhook_secret"`
MongoURI string `json:"mongo_uri"`
SlackWebhook string `json:"slack_webhook_url"`
}
ConfigEnvironment is a sanitised view of configs.Config. Secret fields are replaced with a presence indicator (e.g. "[SET]" / "[NOT SET]").
type ConfigLoader ¶
type ConfigLoader interface {
LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
}
ConfigLoader handles loading and parsing configuration files
func NewCachedConfigLoader ¶
func NewCachedConfigLoader(inner ConfigLoader, ttl time.Duration) ConfigLoader
NewCachedConfigLoader wraps inner with a TTL cache. A TTL of 0 disables caching (every call delegates directly).
func NewConfigLoader ¶
func NewConfigLoader() ConfigLoader
NewConfigLoader creates a new legacy config loader. Deprecated: use NewMainConfigLoader instead.
func NewMainConfigLoader ¶
func NewMainConfigLoader() ConfigLoader
NewMainConfigLoader creates a new main config loader
type DailyStats ¶
type DailyStats struct {
Date string `bson:"_id" json:"date"`
TotalCopies int `bson:"total_copies" json:"total_copies"`
SuccessCount int `bson:"success_count" json:"success_count"`
FailureCount int `bson:"failure_count" json:"failure_count"`
}
DailyStats represents daily copy volume statistics
type DefaultConfigLoader ¶
type DefaultConfigLoader struct{}
DefaultConfigLoader implements the ConfigLoader interface for the legacy single-file config format. Deprecated: migrate to the main config format (USE_MAIN_CONFIG=true) and use DefaultMainConfigLoader instead.
func (*DefaultConfigLoader) LoadConfig ¶
func (cl *DefaultConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfig loads configuration from the repository or local file
func (*DefaultConfigLoader) LoadConfigFromContent ¶
func (cl *DefaultConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
LoadConfigFromContent loads configuration from a string
type DefaultFileStateService ¶
type DefaultFileStateService struct {
// contains filtered or unexported fields
}
DefaultFileStateService implements FileStateService with thread-safe operations
func (*DefaultFileStateService) AddFileToDeprecate ¶
func (fss *DefaultFileStateService) AddFileToDeprecate(deprecationFile string, entry types.DeprecatedFileEntry)
AddFileToDeprecate appends a file entry to the deprecation list for the given deprecation file Multiple entries can be added for the same deprecation file
func (*DefaultFileStateService) AddFileToUpload ¶
func (fss *DefaultFileStateService) AddFileToUpload(key types.UploadKey, content types.UploadFileContent)
AddFileToUpload adds or updates a file to upload
func (*DefaultFileStateService) ClearFilesToDeprecate ¶
func (fss *DefaultFileStateService) ClearFilesToDeprecate()
ClearFilesToDeprecate clears the files to deprecate map
func (*DefaultFileStateService) ClearFilesToUpload ¶
func (fss *DefaultFileStateService) ClearFilesToUpload()
ClearFilesToUpload clears the files to upload map
func (*DefaultFileStateService) GetFilesToDeprecate ¶
func (fss *DefaultFileStateService) GetFilesToDeprecate() map[string][]types.DeprecatedFileEntry
GetFilesToDeprecate returns a copy of the files to deprecate map The map key is the deprecation file name, and the value is a slice of all entries for that file
func (*DefaultFileStateService) GetFilesToUpload ¶
func (fss *DefaultFileStateService) GetFilesToUpload() map[types.UploadKey]types.UploadFileContent
GetFilesToUpload returns a copy of the files to upload map
type DefaultMainConfigLoader ¶
type DefaultMainConfigLoader struct{}
DefaultMainConfigLoader implements the ConfigLoader interface with main config support
func (*DefaultMainConfigLoader) LoadConfig ¶
func (mcl *DefaultMainConfigLoader) LoadConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadConfig implements the ConfigLoader interface It delegates to LoadMainConfig for the main config format
func (*DefaultMainConfigLoader) LoadConfigFromContent ¶
func (mcl *DefaultMainConfigLoader) LoadConfigFromContent(content string, filename string) (*types.YAMLConfig, error)
LoadConfigFromContent implements the ConfigLoader interface It delegates to LoadMainConfigFromContent for the main config format
func (*DefaultMainConfigLoader) LoadMainConfig ¶
func (mcl *DefaultMainConfigLoader) LoadMainConfig(ctx context.Context, config *configs.Config) (*types.YAMLConfig, error)
LoadMainConfig loads the main configuration and resolves all workflow references
func (*DefaultMainConfigLoader) LoadMainConfigFromContent ¶
func (mcl *DefaultMainConfigLoader) LoadMainConfigFromContent(ctx context.Context, content string, config *configs.Config) (*types.YAMLConfig, error)
LoadMainConfigFromContent loads main configuration from a string and resolves references
type DefaultMessageTemplater ¶
type DefaultMessageTemplater struct{}
DefaultMessageTemplater implements the MessageTemplater interface
func (*DefaultMessageTemplater) RenderCommitMessage ¶
func (mt *DefaultMessageTemplater) RenderCommitMessage(template string, ctx *types.MessageContext) string
RenderCommitMessage renders a commit message template
func (*DefaultMessageTemplater) RenderPRBody ¶
func (mt *DefaultMessageTemplater) RenderPRBody(template string, ctx *types.MessageContext) string
RenderPRBody renders a PR body template
func (*DefaultMessageTemplater) RenderPRTitle ¶
func (mt *DefaultMessageTemplater) RenderPRTitle(template string, ctx *types.MessageContext) string
RenderPRTitle renders a PR title template
type DefaultPRTemplateFetcher ¶
type DefaultPRTemplateFetcher struct{}
DefaultPRTemplateFetcher implements PRTemplateFetcher
func (*DefaultPRTemplateFetcher) FetchPRTemplate ¶
func (f *DefaultPRTemplateFetcher) FetchPRTemplate(ctx context.Context, client *github.Client, repoFullName string, branch string) (string, error)
FetchPRTemplate fetches the PR template from a target repository It checks multiple common locations for PR templates: 1. .github/pull_request_template.md 2. .github/PULL_REQUEST_TEMPLATE.md 3. docs/pull_request_template.md 4. PULL_REQUEST_TEMPLATE.md
type DefaultPathTransformer ¶
type DefaultPathTransformer struct{}
DefaultPathTransformer implements the PathTransformer interface
type DefaultPatternMatcher ¶
type DefaultPatternMatcher struct{}
DefaultPatternMatcher implements the PatternMatcher interface
func (*DefaultPatternMatcher) Match ¶
func (pm *DefaultPatternMatcher) Match(filePath string, pattern types.SourcePattern) types.MatchResult
Match matches a file path against a source pattern
type DefaultSlackNotifier ¶
type DefaultSlackNotifier struct {
// contains filtered or unexported fields
}
DefaultSlackNotifier implements SlackNotifier using Slack webhooks
func (*DefaultSlackNotifier) IsEnabled ¶
func (sn *DefaultSlackNotifier) IsEnabled() bool
IsEnabled returns true if Slack notifications are enabled
func (*DefaultSlackNotifier) NotifyDeprecation ¶
func (sn *DefaultSlackNotifier) NotifyDeprecation(ctx context.Context, event *DeprecationEvent) error
NotifyDeprecation sends a notification when files are deprecated
func (*DefaultSlackNotifier) NotifyError ¶
func (sn *DefaultSlackNotifier) NotifyError(ctx context.Context, event *ErrorEvent) error
NotifyError sends a notification when an error occurs
func (*DefaultSlackNotifier) NotifyFilesCopied ¶
func (sn *DefaultSlackNotifier) NotifyFilesCopied(ctx context.Context, event *FilesCopiedEvent) error
NotifyFilesCopied sends a notification when files are copied
func (*DefaultSlackNotifier) NotifyPRProcessed ¶
func (sn *DefaultSlackNotifier) NotifyPRProcessed(ctx context.Context, event *PRProcessedEvent) error
NotifyPRProcessed sends a notification when a PR is successfully processed
type DeliveryLogBuffer ¶ added in v0.4.0
type DeliveryLogBuffer struct {
// contains filtered or unexported fields
}
DeliveryLogBuffer stores recent log entries keyed by delivery ID for the operator UI.
func NewDeliveryLogBuffer ¶ added in v0.4.0
func NewDeliveryLogBuffer() *DeliveryLogBuffer
NewDeliveryLogBuffer creates an empty delivery log buffer.
func (*DeliveryLogBuffer) Append ¶ added in v0.4.0
func (b *DeliveryLogBuffer) Append(deliveryID string, entry LogEntry)
Append adds a log entry for a delivery ID.
func (*DeliveryLogBuffer) Get ¶ added in v0.4.0
func (b *DeliveryLogBuffer) Get(deliveryID string) []LogEntry
Get returns log entries for a delivery ID (nil if not found).
type DeliverySnapshot ¶ added in v0.4.0
type DeliverySnapshot struct {
DeliveryID string `json:"delivery_id"`
SeenAt time.Time `json:"seen_at"`
Duplicate bool `json:"duplicate"`
}
DeliverySnapshot is one observed webhook delivery ID for operator diagnostics.
type DeliveryTracker ¶
type DeliveryTracker struct {
// contains filtered or unexported fields
}
DeliveryTracker tracks processed GitHub webhook delivery IDs to prevent duplicate processing. GitHub retries deliveries on timeout or error, and the X-GitHub-Delivery header uniquely identifies each delivery.
This is an in-memory implementation suitable for single-instance deployments. For multi-instance deployments, replace with a shared store (e.g. MongoDB or Redis).
func NewDeliveryTracker ¶
func NewDeliveryTracker(ttl time.Duration) *DeliveryTracker
NewDeliveryTracker creates a tracker that expires entries after the given TTL. A background goroutine periodically purges expired entries.
func (*DeliveryTracker) HistoryLen ¶ added in v0.4.0
func (dt *DeliveryTracker) HistoryLen() int
HistoryLen returns how many recent delivery observations are buffered for diagnostics.
func (*DeliveryTracker) Len ¶
func (dt *DeliveryTracker) Len() int
Len returns the current number of tracked delivery IDs (for diagnostics).
func (*DeliveryTracker) RecentDeliveries ¶ added in v0.4.0
func (dt *DeliveryTracker) RecentDeliveries(max int) []DeliverySnapshot
RecentDeliveries returns the last up to max observations (newest at end).
func (*DeliveryTracker) Stop ¶
func (dt *DeliveryTracker) Stop()
Stop halts the background cleanup goroutine.
func (*DeliveryTracker) TryRecord ¶
func (dt *DeliveryTracker) TryRecord(deliveryID string) bool
TryRecord attempts to record a delivery ID. Returns true if the ID is new (not a duplicate), false if it was already seen within the TTL window.
type DeprecationEvent ¶
DeprecationEvent contains information about deprecated files
type ErrorEvent ¶
type ErrorEvent struct {
Operation string
Error error
PRNumber int
SourceRepo string
DeliveryID string // GitHub webhook delivery ID for tracing
Attempts int // number of processing attempts (0 = not set)
AdditionalInfo map[string]interface{}
}
ErrorEvent contains information about an error
type FileMetrics ¶
type FileMetrics struct {
Matched int64 `json:"matched"`
Uploaded int64 `json:"uploaded"`
UploadFailed int64 `json:"upload_failed"`
Deprecated int64 `json:"deprecated"`
UploadSuccessRate float64 `json:"upload_success_rate"`
UploadTime ProcessingTimeStats `json:"upload_time"`
}
FileMetrics represents file operation metrics
type FileStateService ¶
type FileStateService interface {
GetFilesToUpload() map[types.UploadKey]types.UploadFileContent
// GetFilesToDeprecate returns all deprecated file entries grouped by deprecation file name
GetFilesToDeprecate() map[string][]types.DeprecatedFileEntry
AddFileToUpload(key types.UploadKey, content types.UploadFileContent)
// AddFileToDeprecate adds a file entry to the deprecation list for the given deprecation file
AddFileToDeprecate(deprecationFile string, entry types.DeprecatedFileEntry)
ClearFilesToUpload()
ClearFilesToDeprecate()
}
FileStateService manages the state of files to upload and deprecate
func NewFileStateService ¶
func NewFileStateService() FileStateService
NewFileStateService creates a new file state service
type FilesCopiedEvent ¶
type FilesCopiedEvent struct {
PRNumber int
SourceRepo string
TargetRepo string
FileCount int
Files []string
RuleName string
}
FilesCopiedEvent contains information about copied files
type GitHubAPIMetrics ¶
type GitHubAPIMetrics struct {
Calls int64 `json:"calls"`
Errors int64 `json:"errors"`
ErrorRate float64 `json:"error_rate"`
RateLimit RateLimitInfo `json:"rate_limit"`
}
GitHubAPIMetrics represents GitHub API usage metrics
type GitHubHealthStatus ¶
type GitHubHealthStatus struct {
Status string `json:"status"`
Authenticated bool `json:"authenticated"`
}
GitHubHealthStatus represents GitHub API health
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status"`
Started bool `json:"started"`
GitHub GitHubHealthStatus `json:"github"`
Queues QueueHealthStatus `json:"queues"`
AuditLogger AuditLoggerHealthStatus `json:"audit_logger,omitempty"`
Uptime string `json:"uptime"`
}
HealthStatus represents the health status of the application
type LLMClient ¶ added in v0.4.0
type LLMClient interface {
// GenerateJSON sends a prompt to the LLM and returns the raw response body.
GenerateJSON(ctx context.Context, systemPrompt, userPrompt string) (string, error)
// ProviderName returns a short identifier for logging.
ProviderName() string
// Ping checks whether the LLM service is reachable.
Ping(ctx context.Context) error
// GetBaseURL returns the current base URL.
GetBaseURL() string
// SetBaseURL updates the base URL at runtime.
SetBaseURL(url string)
// GetActiveModel returns the model that will be used for generations.
GetActiveModel() string
// SetActiveModel updates the active model at runtime.
SetActiveModel(model string)
// ListModels returns the models installed/available on the LLM server.
ListModels(ctx context.Context) ([]LLMModel, error)
// PullModel asks the server to download a model. Progress updates are
// written to progress as they arrive. The function blocks until the pull
// completes or the context is cancelled.
PullModel(ctx context.Context, name string, progress func(LLMPullProgress)) error
// DeleteModel removes a model from the server.
DeleteModel(ctx context.Context, name string) error
}
LLMClient is the minimal interface used by the operator UI. It supports runtime reconfiguration (active model, base URL) and provider management operations (list/pull/delete models).
func NewLLMClient ¶ added in v0.4.0
func NewLLMClient(opts LLMClientOptions) (LLMClient, error)
NewLLMClient returns a client for the configured provider.
type LLMClientOptions ¶ added in v0.4.0
LLMClientOptions carries the per-provider settings NewLLMClient needs. APIKey is required for hosted providers (anthropic); ignored by ollama.
type LLMModel ¶ added in v0.4.0
type LLMModel struct {
Name string `json:"name"`
Size int64 `json:"size,omitempty"`
ModifiedAt string `json:"modified_at,omitempty"`
}
LLMModel describes an installed model returned by the provider.
type LLMPullProgress ¶ added in v0.4.0
type LLMPullProgress struct {
Status string `json:"status"`
Completed int64 `json:"completed,omitempty"`
Total int64 `json:"total,omitempty"`
Digest string `json:"digest,omitempty"`
Error string `json:"error,omitempty"`
}
LLMPullProgress is a single progress event emitted during PullModel.
type LogEntry ¶ added in v0.4.0
type LogEntry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Fields map[string]any `json:"fields,omitempty"`
}
LogEntry is a single captured log line for operator diagnostics.
type MessageTemplater ¶
type MessageTemplater interface {
RenderCommitMessage(template string, ctx *types.MessageContext) string
RenderPRTitle(template string, ctx *types.MessageContext) string
RenderPRBody(template string, ctx *types.MessageContext) string
}
MessageTemplater handles message template rendering
func NewMessageTemplater ¶
func NewMessageTemplater() MessageTemplater
NewMessageTemplater creates a new message templater
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector collects and manages application metrics
func NewMetricsCollector ¶
func NewMetricsCollector() *MetricsCollector
NewMetricsCollector creates a new metrics collector
func (*MetricsCollector) GetFilesMatched ¶
func (mc *MetricsCollector) GetFilesMatched() int
GetFilesMatched returns the current files matched count
func (*MetricsCollector) GetFilesUploadFailed ¶
func (mc *MetricsCollector) GetFilesUploadFailed() int
GetFilesUploadFailed returns the current files upload failed count
func (*MetricsCollector) GetFilesUploaded ¶
func (mc *MetricsCollector) GetFilesUploaded() int
GetFilesUploaded returns the current files uploaded count
func (*MetricsCollector) GetMetrics ¶
func (mc *MetricsCollector) GetMetrics(fileStateService FileStateService) MetricsData
GetMetrics returns current metrics
func (*MetricsCollector) RecordFileDeprecated ¶
func (mc *MetricsCollector) RecordFileDeprecated()
RecordFileDeprecated increments file deprecated counter
func (*MetricsCollector) RecordFileMatched ¶
func (mc *MetricsCollector) RecordFileMatched()
RecordFileMatched increments file matched counter
func (*MetricsCollector) RecordFileUploadFailed ¶
func (mc *MetricsCollector) RecordFileUploadFailed()
RecordFileUploadFailed increments file upload failed counter
func (*MetricsCollector) RecordFileUploaded ¶
func (mc *MetricsCollector) RecordFileUploaded(duration time.Duration)
RecordFileUploaded increments file uploaded counter
func (*MetricsCollector) RecordGitHubAPICall ¶
func (mc *MetricsCollector) RecordGitHubAPICall()
RecordGitHubAPICall increments GitHub API call counter
func (*MetricsCollector) RecordGitHubAPIError ¶
func (mc *MetricsCollector) RecordGitHubAPIError()
RecordGitHubAPIError increments GitHub API error counter
func (*MetricsCollector) RecordWebhookFailed ¶
func (mc *MetricsCollector) RecordWebhookFailed()
RecordWebhookFailed increments webhook failed counter
func (*MetricsCollector) RecordWebhookIgnored ¶
func (mc *MetricsCollector) RecordWebhookIgnored(eventType string)
RecordWebhookIgnored increments webhook ignored counter and tracks event type
func (*MetricsCollector) RecordWebhookProcessed ¶
func (mc *MetricsCollector) RecordWebhookProcessed(duration time.Duration)
RecordWebhookProcessed increments webhook processed counter
func (*MetricsCollector) RecordWebhookReceived ¶
func (mc *MetricsCollector) RecordWebhookReceived()
RecordWebhookReceived increments webhook received counter
type MetricsData ¶
type MetricsData struct {
Webhooks WebhookMetrics `json:"webhooks"`
Files FileMetrics `json:"files"`
GitHubAPI GitHubAPIMetrics `json:"github_api"`
Queues QueueMetrics `json:"queues"`
System SystemMetrics `json:"system"`
}
MetricsData represents application metrics
type MongoAuditLogger ¶
type MongoAuditLogger struct {
// contains filtered or unexported fields
}
MongoAuditLogger implements AuditLogger using MongoDB
func (*MongoAuditLogger) Close ¶
func (mal *MongoAuditLogger) Close(ctx context.Context) error
Close closes the MongoDB connection.
func (*MongoAuditLogger) GetDailyVolume ¶
func (mal *MongoAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
GetDailyVolume retrieves daily copy volume statistics
func (*MongoAuditLogger) GetEventsByRule ¶
func (mal *MongoAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
GetEventsByRule retrieves events for a specific rule
func (*MongoAuditLogger) GetFailedEvents ¶
func (mal *MongoAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
GetFailedEvents retrieves recent failed events
func (*MongoAuditLogger) GetRecentEvents ¶
func (mal *MongoAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
func (*MongoAuditLogger) GetStatsByRule ¶
GetStatsByRule retrieves statistics grouped by rule
func (*MongoAuditLogger) LogConfigChangeEvent ¶ added in v0.4.0
func (mal *MongoAuditLogger) LogConfigChangeEvent(ctx context.Context, event *AuditEvent) error
LogConfigChangeEvent logs an operator-initiated configuration change.
func (*MongoAuditLogger) LogCopyEvent ¶
func (mal *MongoAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
LogCopyEvent logs a file copy event
func (*MongoAuditLogger) LogDeprecationEvent ¶
func (mal *MongoAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
LogDeprecationEvent logs a file deprecation event
func (*MongoAuditLogger) LogErrorEvent ¶
func (mal *MongoAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
LogErrorEvent logs an error event
func (*MongoAuditLogger) Ping ¶
func (mal *MongoAuditLogger) Ping(ctx context.Context) error
Ping checks MongoDB connectivity.
func (*MongoAuditLogger) QueryAuditEvents ¶ added in v0.4.0
func (mal *MongoAuditLogger) QueryAuditEvents(ctx context.Context, q AuditListQuery) ([]AuditEvent, error)
QueryAuditEvents retrieves audit events matching the given filter criteria.
type NoOpAuditLogger ¶
type NoOpAuditLogger struct{}
NoOpAuditLogger is a no-op implementation when audit logging is disabled
func (*NoOpAuditLogger) GetDailyVolume ¶
func (nal *NoOpAuditLogger) GetDailyVolume(ctx context.Context, days int) ([]DailyStats, error)
func (*NoOpAuditLogger) GetEventsByRule ¶
func (nal *NoOpAuditLogger) GetEventsByRule(ctx context.Context, ruleName string, limit int) ([]AuditEvent, error)
func (*NoOpAuditLogger) GetFailedEvents ¶
func (nal *NoOpAuditLogger) GetFailedEvents(ctx context.Context, limit int) ([]AuditEvent, error)
func (*NoOpAuditLogger) GetRecentEvents ¶
func (nal *NoOpAuditLogger) GetRecentEvents(ctx context.Context, limit int) ([]AuditEvent, error)
func (*NoOpAuditLogger) GetStatsByRule ¶
func (*NoOpAuditLogger) LogConfigChangeEvent ¶ added in v0.4.0
func (nal *NoOpAuditLogger) LogConfigChangeEvent(ctx context.Context, event *AuditEvent) error
func (*NoOpAuditLogger) LogCopyEvent ¶
func (nal *NoOpAuditLogger) LogCopyEvent(ctx context.Context, event *AuditEvent) error
func (*NoOpAuditLogger) LogDeprecationEvent ¶
func (nal *NoOpAuditLogger) LogDeprecationEvent(ctx context.Context, event *AuditEvent) error
func (*NoOpAuditLogger) LogErrorEvent ¶
func (nal *NoOpAuditLogger) LogErrorEvent(ctx context.Context, event *AuditEvent) error
func (*NoOpAuditLogger) QueryAuditEvents ¶ added in v0.4.0
func (nal *NoOpAuditLogger) QueryAuditEvents(ctx context.Context, q AuditListQuery) ([]AuditEvent, error)
type OperatorDeploymentInfo ¶ added in v0.4.0
type OperatorDeploymentInfo struct {
Version string `json:"version"`
UptimeSeconds int64 `json:"uptime_seconds"`
MongoHealthy *bool `json:"mongo_healthy,omitempty"`
GoogleCloudRegion string `json:"google_cloud_region,omitempty"`
CloudRunService string `json:"cloud_run_service,omitempty"`
CloudRunRevision string `json:"cloud_run_revision,omitempty"`
CloudRunConfig string `json:"cloud_run_configuration,omitempty"`
GoogleCloudProject string `json:"google_cloud_project,omitempty"`
Port string `json:"port"`
WebhookPath string `json:"webhook_path"`
DryRun bool `json:"dry_run"`
AuditEnabled bool `json:"audit_enabled"`
AuditDatabase string `json:"audit_database,omitempty"`
AuditCollection string `json:"audit_collection,omitempty"`
ConfigRepo string `json:"config_repo,omitempty"`
EffectiveConfig string `json:"effective_config_file,omitempty"`
OperatorRepoSlug string `json:"operator_repo_slug,omitempty"`
ReleaseAPIMode ReleaseAPIMode `json:"release_api_mode"`
Env map[string]string `json:"cloud_env,omitempty"`
}
OperatorDeploymentInfo is non-secret runtime and platform metadata for the operator UI.
type OperatorRole ¶ added in v0.4.0
type OperatorRole string
OperatorRole represents the permission level for the operator UI.
const ( // RoleOperator has full access: view, replay, release. Operators are // trusted with the full repo topology and bypass per-repo scoping in // the read-only views (audit events, webhook traces, delivery logs, // workflow config). RoleOperator OperatorRole = "operator" // RoleWriter has read-only access: view workflows, audit, recent copies. // Read-only views are post-filtered by repoFilter so writers only see // rows that reference repos they can read on GitHub — without this they // could enumerate every source→target pairing and audit row in the // system, regardless of whether they have GitHub access to those repos. RoleWriter OperatorRole = "writer" // RoleDenied means the user has no access. RoleDenied OperatorRole = "denied" )
type OperatorUser ¶ added in v0.4.0
type OperatorUser struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url,omitempty"`
Role OperatorRole `json:"role"`
}
OperatorUser represents an authenticated operator UI user.
type PRProcessedEvent ¶
type PRProcessedEvent struct {
PRNumber int
PRTitle string
PRURL string
SourceRepo string
TargetRepos []string // List of target repositories files were copied to
FilesMatched int
FilesCopied int
FilesFailed int
ProcessingTime time.Duration
}
PRProcessedEvent contains information about a processed PR
type PRTemplateFetcher ¶
type PRTemplateFetcher interface {
// FetchPRTemplate fetches the PR template from a target repository
// Returns the template content, or empty string if not found
FetchPRTemplate(ctx context.Context, client *github.Client, repoFullName string, branch string) (string, error)
}
PRTemplateFetcher defines the interface for fetching PR templates from repositories
func NewPRTemplateFetcher ¶
func NewPRTemplateFetcher() PRTemplateFetcher
NewPRTemplateFetcher creates a new PR template fetcher
type PathTransformer ¶
type PathTransformer interface {
Transform(sourcePath string, template string, variables map[string]string) (string, error)
}
PathTransformer handles path transformations
func NewPathTransformer ¶
func NewPathTransformer() PathTransformer
NewPathTransformer creates a new path transformer
type PatternMatcher ¶
type PatternMatcher interface {
Match(filePath string, pattern types.SourcePattern) types.MatchResult
}
PatternMatcher handles pattern matching for file paths
func NewPatternMatcher ¶
func NewPatternMatcher() PatternMatcher
NewPatternMatcher creates a new pattern matcher
type ProcessingTimeStats ¶
type ProcessingTimeStats struct {
AvgMs float64 `json:"avg_ms"`
MinMs float64 `json:"min_ms"`
MaxMs float64 `json:"max_ms"`
P50Ms float64 `json:"p50_ms"`
P95Ms float64 `json:"p95_ms"`
P99Ms float64 `json:"p99_ms"`
}
ProcessingTimeStats represents timing statistics
type QueueHealthStatus ¶
type QueueHealthStatus struct {
UploadCount int `json:"upload_count"`
DeprecationCount int `json:"deprecation_count"`
}
QueueHealthStatus represents queue health
type QueueMetrics ¶
type QueueMetrics struct {
UploadQueueSize int `json:"upload_queue_size"`
DeprecationQueueSize int `json:"deprecation_queue_size"`
RetryQueueSize int `json:"retry_queue_size"`
}
QueueMetrics represents queue size metrics
type RateLimitInfo ¶
RateLimitInfo represents GitHub API rate limit info
type RateLimitState ¶
type RateLimitState struct {
// contains filtered or unexported fields
}
RateLimitState holds the most recently observed GitHub API rate limit info. Updated atomically by rateLimitTransport on every API response.
type ReleaseAPIMode ¶ added in v0.4.0
type ReleaseAPIMode string
ReleaseAPIMode describes whether the operator UI can cut a release tag. Typed so the set of possible values is discoverable from the type alone and so the frontend can switch on a known enum instead of a free string.
const ( // ReleaseAPIDisabled — neither OPERATOR_RELEASE_GITHUB_TOKEN nor // OPERATOR_REPO_SLUG is configured; the UI hides the release button. ReleaseAPIDisabled ReleaseAPIMode = "disabled" // ReleaseAPITagCreateEnabled — both are configured; the UI shows the // release flow and /api/release will attempt to create a tag ref. ReleaseAPITagCreateEnabled ReleaseAPIMode = "tag_create_enabled" )
type RuleStats ¶
type RuleStats struct {
RuleName string `bson:"_id" json:"rule_name"`
TotalCopies int `bson:"total_copies" json:"total_copies"`
SuccessCount int `bson:"success_count" json:"success_count"`
FailureCount int `bson:"failure_count" json:"failure_count"`
AvgDuration float64 `bson:"avg_duration" json:"avg_duration_ms"`
}
RuleStats represents statistics for a specific rule
type ServiceContainer ¶
type ServiceContainer struct {
Config *configs.Config
FileStateService FileStateService
TokenManager *TokenManager
// New services
ConfigLoader ConfigLoader
PatternMatcher PatternMatcher
PathTransformer PathTransformer
MessageTemplater MessageTemplater
PRTemplateFetcher PRTemplateFetcher
AuditLogger AuditLogger
MetricsCollector *MetricsCollector
SlackNotifier SlackNotifier
// Webhook deduplication
DeliveryTracker *DeliveryTracker
// Recent webhook outcomes for operator troubleshooting (in-memory)
WebhookTraces *WebhookTraceBuffer
// Per-delivery log capture for operator diagnostics (in-memory)
DeliveryLogs *DeliveryLogBuffer
// Server state
StartTime time.Time
// contains filtered or unexported fields
}
ServiceContainer holds all application services with dependency injection
func NewServiceContainer ¶
func NewServiceContainer(config *configs.Config) (*ServiceContainer, error)
NewServiceContainer creates and initializes all services
func (*ServiceContainer) Close ¶
func (sc *ServiceContainer) Close(ctx context.Context) error
Close cleans up resources. Safe to call multiple times.
func (*ServiceContainer) IsClosed ¶
func (sc *ServiceContainer) IsClosed() bool
IsClosed returns true if the container has been closed
func (*ServiceContainer) Wait ¶
func (sc *ServiceContainer) Wait()
Wait blocks until all background goroutines tracked by this container have finished.
type SlackAttachment ¶
type SlackAttachment struct {
Color string `json:"color,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Text string `json:"text,omitempty"`
Fields []SlackField `json:"fields,omitempty"`
Timestamp int64 `json:"ts,omitempty"`
}
SlackAttachment represents a Slack message attachment
type SlackField ¶
type SlackField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
SlackField represents a field in a Slack attachment
type SlackMessage ¶
type SlackMessage struct {
Channel string `json:"channel,omitempty"`
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
Text string `json:"text,omitempty"`
Attachments []SlackAttachment `json:"attachments,omitempty"`
}
SlackMessage represents a Slack message
type SlackNotifier ¶
type SlackNotifier interface {
// NotifyPRProcessed sends a notification when a PR is successfully processed
NotifyPRProcessed(ctx context.Context, event *PRProcessedEvent) error
// NotifyError sends a notification when an error occurs
NotifyError(ctx context.Context, event *ErrorEvent) error
// NotifyFilesCopied sends a notification when files are copied
NotifyFilesCopied(ctx context.Context, event *FilesCopiedEvent) error
// NotifyDeprecation sends a notification when files are deprecated
NotifyDeprecation(ctx context.Context, event *DeprecationEvent) error
// IsEnabled returns true if Slack notifications are enabled
IsEnabled() bool
}
SlackNotifier handles sending notifications to Slack
func NewSlackNotifier ¶
func NewSlackNotifier(webhookURL, channel, username, iconEmoji string) SlackNotifier
NewSlackNotifier creates a new Slack notifier
func NewSlackNotifierWithOptions ¶
func NewSlackNotifierWithOptions(webhookURL, channel, username, iconEmoji string, plainTextOnly bool, messageVariable string) SlackNotifier
NewSlackNotifierWithOptions creates a new Slack notifier with additional options plainTextOnly should be true when using Slack Workflow Builder webhooks, which don't support attachments or blocks messageVariable is the JSON key name for Workflow Builder webhooks (e.g., "text", "data", "message")
type SystemMetrics ¶
type SystemMetrics struct {
UptimeSeconds int64 `json:"uptime_seconds"`
}
SystemMetrics represents system-level metrics
type TokenManager ¶
type TokenManager struct {
// contains filtered or unexported fields
}
TokenManager provides thread-safe management of GitHub App authentication tokens. It caches JWT tokens and per-org installation tokens with expiry tracking, and holds the HTTP client used for GitHub API calls.
func DefaultTokenManager ¶
func DefaultTokenManager() *TokenManager
DefaultTokenManager returns the package-level TokenManager instance.
func NewTokenManager ¶
func NewTokenManager() *TokenManager
NewTokenManager creates a new TokenManager instance.
func (*TokenManager) GetCachedJWT ¶
func (tm *TokenManager) GetCachedJWT() (string, bool)
GetCachedJWT returns the cached JWT if it's still valid.
func (*TokenManager) GetHTTPClient ¶
func (tm *TokenManager) GetHTTPClient() *http.Client
GetHTTPClient returns the HTTP client used for GitHub API calls.
func (*TokenManager) GetInstallationAccessToken ¶
func (tm *TokenManager) GetInstallationAccessToken() string
GetInstallationAccessToken returns the default installation access token.
func (*TokenManager) GetTokenForOrg ¶
func (tm *TokenManager) GetTokenForOrg(org string) (string, bool)
GetTokenForOrg returns a cached token for the given org if it exists and is still valid. Returns empty string and false if no valid token exists.
func (*TokenManager) SetCachedJWT ¶
func (tm *TokenManager) SetCachedJWT(token string, expiry time.Time)
SetCachedJWT caches a JWT with its expiry time.
func (*TokenManager) SetHTTPClient ¶
func (tm *TokenManager) SetHTTPClient(client *http.Client)
SetHTTPClient sets the HTTP client used for GitHub API calls.
func (*TokenManager) SetInstallationAccessToken ¶
func (tm *TokenManager) SetInstallationAccessToken(token string)
SetInstallationAccessToken sets the default installation access token.
func (*TokenManager) SetTokenForOrg ¶
func (tm *TokenManager) SetTokenForOrg(org, token string, expiresAt time.Time)
SetTokenForOrg caches an installation token for an org with expiry.
func (*TokenManager) SetTokenForOrgNoExpiry ¶
func (tm *TokenManager) SetTokenForOrgNoExpiry(org, token string)
SetTokenForOrgNoExpiry caches an installation token for an org without expiry tracking. Primarily used in tests where token expiry is not relevant.
type WebhookMetrics ¶
type WebhookMetrics struct {
Received int64 `json:"received"`
Processed int64 `json:"processed"`
Failed int64 `json:"failed"`
Ignored int64 `json:"ignored"` // Non-PR events
EventTypes map[string]int64 `json:"event_types"` // Count by event type
SuccessRate float64 `json:"success_rate"`
ProcessingTime ProcessingTimeStats `json:"processing_time"`
}
WebhookMetrics represents webhook processing metrics
type WebhookTraceBuffer ¶ added in v0.4.0
type WebhookTraceBuffer struct {
// contains filtered or unexported fields
}
WebhookTraceBuffer stores the last N webhook outcomes for the operator UI.
func NewWebhookTraceBuffer ¶ added in v0.4.0
func NewWebhookTraceBuffer() *WebhookTraceBuffer
NewWebhookTraceBuffer creates an empty trace buffer.
func (*WebhookTraceBuffer) Append ¶ added in v0.4.0
func (b *WebhookTraceBuffer) Append(e WebhookTraceEntry)
Append adds an entry (timestamps default to UTC now; detail is truncated).
func (*WebhookTraceBuffer) Len ¶ added in v0.4.0
func (b *WebhookTraceBuffer) Len() int
Len returns how many trace entries are buffered.
func (*WebhookTraceBuffer) Recent ¶ added in v0.4.0
func (b *WebhookTraceBuffer) Recent(max int) []WebhookTraceEntry
Recent returns the last up to max entries (oldest first within the slice).
func (*WebhookTraceBuffer) RepoForDelivery ¶ added in v0.4.0
func (b *WebhookTraceBuffer) RepoForDelivery(deliveryID string) string
RepoForDelivery returns the most recent recorded repo for a delivery ID, or "" if no trace with that ID is buffered. The operator UI uses this to scope per-delivery log access by the caller's GitHub repo permissions — without a repo we can't safely show the logs to a writer, so callers that fail to resolve here should treat the delivery as not visible.
type WebhookTraceEntry ¶ added in v0.4.0
type WebhookTraceEntry struct {
At time.Time `json:"at"`
DeliveryID string `json:"delivery_id,omitempty"`
EventType string `json:"event_type,omitempty"`
Action string `json:"action,omitempty"`
Repo string `json:"repo,omitempty"`
BaseBranch string `json:"base_branch,omitempty"`
CommitSHA string `json:"commit_sha,omitempty"`
PRNumber int `json:"pr_number,omitempty"`
Outcome string `json:"outcome"`
Detail string `json:"detail,omitempty"`
}
WebhookTraceEntry is one observed webhook for operator troubleshooting (in-memory only).
type WorkflowProcessor ¶
type WorkflowProcessor interface {
ProcessWorkflow(ctx context.Context, workflow types.Workflow, changedFiles []types.ChangedFile, prNumber int, sourceCommitSHA string) error
}
WorkflowProcessor processes workflows and applies transformations
func NewWorkflowProcessor ¶
func NewWorkflowProcessor( patternMatcher PatternMatcher, pathTransformer PathTransformer, fileStateService FileStateService, metricsCollector *MetricsCollector, messageTemplater MessageTemplater, config *configs.Config, ) WorkflowProcessor
NewWorkflowProcessor creates a new workflow processor
Source Files
¶
- audit_logger.go
- config_cache.go
- config_loader.go
- delivery_tracker.go
- errors.go
- file_state_service.go
- github_auth.go
- github_read.go
- github_write_to_source.go
- github_write_to_target.go
- health_metrics.go
- llm_anthropic.go
- llm_client.go
- log_buffer.go
- logger.go
- main_config_loader.go
- operator_auth.go
- operator_llm_admin.go
- operator_ratelimit.go
- operator_repo_filter.go
- operator_suggest_rule.go
- operator_ui.go
- pattern_matcher.go
- pr_template_fetcher.go
- rate_limit.go
- service_container.go
- slack_notifier.go
- token_manager.go
- webhook_handler_new.go
- webhook_trace_buffer.go
- workflow_processor.go