models

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultPaginationLimit = 10

DefaultPaginationLimit is the default page size for discovery endpoints

View Source
const MaxPaginationLimit = 100

MaxPaginationLimit is the maximum page size for discovery endpoints

Variables

View Source
var APIVersionToSchemaVersion = map[string]string{
	"kubernaut.ai/v1alpha1": "1.0",
}

apiVersionToSchemaVersion maps CRD apiVersion to the DB schema_version value. kubernaut.ai/v1alpha1 is the pre-GA version established by #292.

View Source
var ValidDetectedLabelFields = []string{
	"gitOpsManaged",
	"gitOpsTool",
	"pdbProtected",
	"hpaEnabled",
	"stateful",
	"helmManaged",
	"networkIsolated",
	"serviceMesh",
	"resourceQuotaConstrained",
}

ValidDetectedLabelFields is the authoritative list of valid detected label field names Used for validation of FailedDetections array (DD-WORKFLOW-001 v2.1)

Functions

func IsValidFailedDetectionField

func IsValidFailedDetectionField(fieldName string) bool

IsValidFailedDetectionField returns true if the given field name is a valid DetectedLabels field that can be included in failedDetections. DD-WORKFLOW-001 v2.1: Validation for failedDetections field names V1.0: Uses ValidDetectedLabelFields from workflow_labels.go

func ParseEngineConfig

func ParseEngineConfig(engine string, raw json.RawMessage) (any, error)

ParseEngineConfig deserializes raw engineConfig JSON based on the engine discriminator. BR-WE-016: Two-phase unmarshal — read engine first, then unmarshal config. Returns (nil, nil) when raw is empty, regardless of engine. Returns error for unknown engines or invalid/incomplete ansible config.

func ShouldSkipDetectedLabel

func ShouldSkipDetectedLabel(fieldName string, failedDetections []string) bool

ShouldSkipDetectedLabel returns true if the given field name should be skipped because it's in the failedDetections list. DD-WORKFLOW-001 v2.1: When matching incident DetectedLabels against workflow catalog detected_labels, skip fields that are in failedDetections.

func ValidateDescription

func ValidateDescription(d *WorkflowDescription) error

ValidateDescription checks if the structured description has required fields. BR-WORKFLOW-004: what and whenToUse are required.

func ValidateParameterValue

func ValidateParameterValue(param WorkflowParameter, value string) error

ValidateParameterValue checks a string parameter value against the schema's type and bounds. Returns nil if the value is valid; error with descriptive message otherwise.

Types

type AIAnalysisAudit

type AIAnalysisAudit struct {
	ID                   int64     `json:"id" db:"id"`
	RemediationRequestID string    `json:"remediation_request_id" db:"remediation_request_id"`
	AnalysisID           string    `json:"analysis_id" db:"analysis_id"`
	Provider             string    `json:"provider" db:"provider"` // holmesgpt, openai, claude
	Model                string    `json:"model" db:"model"`
	ConfidenceScore      float64   `json:"confidence_score" db:"confidence_score"`
	TokensUsed           int       `json:"tokens_used" db:"tokens_used"`
	AnalysisDuration     int64     `json:"analysis_duration" db:"analysis_duration"` // milliseconds
	Metadata             string    `json:"metadata" db:"metadata"`                   // JSON string
	CreatedAt            time.Time `json:"created_at" db:"created_at"`
}

AIAnalysisAudit represents AI analysis audit data BR-STORAGE-002: Audit trail for AI analysis

type AIExecutionModeStats

type AIExecutionModeStats struct {
	// CatalogSelected is the count of single-workflow catalog selections
	CatalogSelected int `json:"catalog_selected"`

	// Chained is the count of multi-workflow compositions
	Chained int `json:"chained"`

	// ManualEscalation is the count of escalations to human operators
	ManualEscalation int `json:"manual_escalation"`
}

AIExecutionModeStats tracks AI execution mode distribution (ADR-033 Hybrid Model) Shows how AI selected remediation approaches: - 90-95% catalog selection (single workflow from catalog) - 4-9% workflow chaining (multiple workflows composed) - <1% manual escalation (human intervention required)

type ActionBreakdownItem

type ActionBreakdownItem struct {
	// ActionType is the specific action (e.g., "restart_pod", "scale_deployment")
	ActionType string `json:"action_type"`

	// Executions is the number of times this action was executed
	Executions int `json:"executions"`

	// SuccessRate is the percentage of successful executions for this action
	SuccessRate float64 `json:"success_rate"`
}

ActionBreakdownItem represents action-type-specific statistics Used in MultiDimensionalSuccessRateResponse to show action-level performance

type ActionTrace

type ActionTrace struct {

	// ID is the unique identifier for the audit record (auto-generated by database)
	ID int64 `json:"id" db:"id"`

	// ActionID is the unique identifier for this action execution
	ActionID string `json:"action_id" db:"action_id" validate:"required,max=255"`

	// ActionType is the type of action executed (e.g., "restart_pod", "scale_deployment")
	// NOTE: This is the TERTIARY dimension for success tracking (ADR-033)
	ActionType string `json:"action_type" db:"action_type" validate:"required,max=100"`

	// ActionTimestamp is when the action was executed
	ActionTimestamp time.Time `json:"action_timestamp" db:"action_timestamp" validate:"required"`

	// Status is the execution status (e.g., "completed", "failed", "pending")
	Status string `json:"status" db:"status" validate:"required,oneof=completed failed pending in_progress cancelled"`

	// ResourceType is the Kubernetes resource type (e.g., "Pod", "Deployment")
	ResourceType string `json:"resource_type,omitempty" db:"resource_type" validate:"max=100"`

	// ResourceName is the name of the Kubernetes resource
	ResourceName string `json:"resource_name,omitempty" db:"resource_name" validate:"max=255"`

	// ResourceNamespace is the namespace of the Kubernetes resource
	ResourceNamespace string `json:"resource_namespace,omitempty" db:"resource_namespace" validate:"max=255"`

	// CreatedAt is the timestamp when the audit record was created
	CreatedAt time.Time `json:"created_at" db:"created_at"`

	// UpdatedAt is the timestamp when the audit record was last updated
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`

	// IncidentType is the PRIMARY dimension for success tracking
	// Examples: "pod-oom-killer", "high-cpu-usage", "disk-pressure", "network-timeout"
	// BR-STORAGE-031-01: Used for incident-type success rate aggregation
	// BR-REMEDIATION-015: Populated by RemediationExecutor during execution
	IncidentType string `json:"incident_type" db:"incident_type" validate:"max=100"`

	// AlertName is the original Prometheus alert name (can serve as incident_type proxy)
	// Examples: "PodOOMKilled", "HighCPUUsage", "DiskPressure"
	// BR-STORAGE-031-01: Alternative grouping dimension if incident_type not populated
	AlertName string `json:"alert_name,omitempty" db:"alert_name" validate:"max=255"`

	// IncidentSeverity is the severity level of the incident
	// Values: "critical", "warning", "info"
	// BR-STORAGE-031-01: Used for severity-based filtering in aggregations
	IncidentSeverity string `json:"incident_severity" db:"incident_severity" validate:"oneof=critical warning info ''"`

	// WorkflowID is the SECONDARY dimension for success tracking
	// Examples: "pod-oom-recovery", "disk-cleanup", "network-retry"
	// BR-STORAGE-031-02: Used for workflow success rate aggregation
	// BR-REMEDIATION-016: Populated by RemediationExecutor during execution
	WorkflowID string `json:"workflow_id" db:"workflow_id" validate:"max=64"`

	// WorkflowVersion is the semantic version of the workflow
	// Examples: "v1.0", "v1.2", "v2.0"
	// BR-STORAGE-031-02: Used for version-specific success rate tracking
	// BR-REMEDIATION-016: Populated by Workflow Catalog during selection
	WorkflowVersion string `json:"workflow_version" db:"workflow_version" validate:"max=20"`

	// WorkflowStepNumber is the step position within a multi-step workflow
	// Values: 1, 2, 3, ... (NULL for single-step workflows)
	// BR-REMEDIATION-016: Used to group all steps in a single workflow execution
	WorkflowStepNumber *int `json:"workflow_step_number,omitempty" db:"workflow_step_number" validate:"omitempty,min=1"`

	// WorkflowExecutionID groups all actions in a single workflow run
	// Same ID is used across all steps in a multi-step workflow
	// BR-REMEDIATION-016: Enables workflow-level success tracking (not step-level)
	WorkflowExecutionID string `json:"workflow_execution_id" db:"workflow_execution_id" validate:"max=64"`

	// AISelectedWorkflow indicates AI selected a single workflow from the catalog
	// TRUE for 90-95% of cases (standard catalog-based remediation)
	// BR-STORAGE-031-04: Used to track AI execution mode distribution
	// BR-REMEDIATION-017: Populated by RemediationExecutor based on AI decision
	AISelectedWorkflow bool `json:"ai_selected_workflow" db:"ai_selected_workflow"`

	// AIChainedWorkflows indicates AI chained multiple catalog workflows
	// TRUE for 4-9% of cases (complex problems requiring multiple remediation steps)
	// BR-STORAGE-031-04: Used to identify advanced AI composition scenarios
	// BR-REMEDIATION-017: Populated when AI composes multi-workflow solution
	AIChainedWorkflows bool `json:"ai_chained_workflows" db:"ai_chained_workflows"`

	// AIManualEscalation indicates AI escalated to human operator
	// TRUE for <1% of cases (novel problems requiring human expertise)
	// BR-STORAGE-031-04: Used to identify cases where AI couldn't remediate
	// BR-REMEDIATION-017: Populated when AI determines manual intervention needed
	AIManualEscalation bool `json:"ai_manual_escalation" db:"ai_manual_escalation"`

	// AIWorkflowCustomization stores parameters customized by AI for this specific incident
	// Format: JSON object with parameter overrides
	// Example: {"timeout": "300s", "retry_count": 5, "resource_limits": {"memory": "2Gi"}}
	// BR-STORAGE-031-04: Used to analyze AI parameter tuning effectiveness
	// BR-REMEDIATION-017: Populated when AI customizes workflow parameters
	AIWorkflowCustomization json.RawMessage `json:"ai_workflow_customization,omitempty" db:"ai_workflow_customization"`
}

ActionTrace represents a remediation action execution audit record

func (*ActionTrace) GetAIExecutionMode

func (a *ActionTrace) GetAIExecutionMode() string

GetAIExecutionMode returns a human-readable AI execution mode BR-STORAGE-031-04: Used for reporting and analytics dashboards

func (*ActionTrace) GetEffectiveIncidentType

func (a *ActionTrace) GetEffectiveIncidentType() string

GetEffectiveIncidentType returns the incident type, falling back to alert name BR-STORAGE-031-01: Provides backward compatibility for records without incident_type

func (*ActionTrace) HasIncidentContext

func (a *ActionTrace) HasIncidentContext() bool

HasIncidentContext returns true if incident-type tracking fields are populated BR-STORAGE-031-01: Determines if record can be used for incident-type aggregation

func (*ActionTrace) HasWorkflowContext

func (a *ActionTrace) HasWorkflowContext() bool

HasWorkflowContext returns true if workflow tracking fields are populated BR-STORAGE-031-02: Determines if record can be used for workflow aggregation

func (*ActionTrace) IsFailed

func (a *ActionTrace) IsFailed() bool

IsFailed returns true if the action failed Used for failure rate calculations and error analysis

func (*ActionTrace) IsSuccessful

func (a *ActionTrace) IsSuccessful() bool

IsSuccessful returns true if the action completed successfully Used for success rate calculations (BR-STORAGE-031-01, BR-STORAGE-031-02)

func (*ActionTrace) TableName

func (a *ActionTrace) TableName() string

TableName returns the PostgreSQL table name for this model

func (*ActionTrace) Validate

func (a *ActionTrace) Validate() error

Validate performs business logic validation on the ActionTrace struct

type ActionTypeDescription

type ActionTypeDescription = sharedtypes.StructuredDescription

ActionTypeDescription is an alias for the shared StructuredDescription type. BR-WORKFLOW-004: camelCase JSON keys (migration 026 updates existing data). DD-WORKFLOW-016: Same format shared between RemediationWorkflow and ActionType.

type ActionTypeEntry

type ActionTypeEntry struct {
	ActionType    string                `json:"actionType"`
	Description   ActionTypeDescription `json:"description"`
	WorkflowCount int                   `json:"workflowCount"`
}

ActionTypeEntry represents a single action type in the discovery response (Step 1) Includes the action type metadata and count of matching workflows

type ActionTypeListResponse

type ActionTypeListResponse struct {
	ActionTypes []ActionTypeEntry  `json:"actionTypes"`
	Pagination  PaginationMetadata `json:"pagination"`
}

ActionTypeListResponse is the response for Step 1: list available action types GET /api/v1/workflows/actions

type ActionTypeTaxonomy

type ActionTypeTaxonomy struct {
	ActionType  string          `json:"actionType" db:"action_type"`
	Description json.RawMessage `json:"description" db:"description"`
	Status      string          `json:"status" db:"status"`
	DisabledAt  *time.Time      `json:"disabledAt,omitempty" db:"disabled_at"`
	DisabledBy  *string         `json:"disabledBy,omitempty" db:"disabled_by"`
	CreatedAt   time.Time       `json:"createdAt" db:"created_at"`
	UpdatedAt   time.Time       `json:"updatedAt" db:"updated_at"`
}

ActionTypeTaxonomy represents an entry in the action_type_taxonomy table. Migration 001: action_type_taxonomy table. Migration 004: Added status, disabled_at, disabled_by columns (BR-WORKFLOW-007).

type AggregationItem

type AggregationItem struct {
	// Key is the grouping dimension (namespace, severity, etc.)
	// JSON field name varies by endpoint:
	// - "namespace" for /by-namespace
	// - "severity" for /by-severity
	Key   string `json:"-"` // Omit from JSON, populated dynamically
	Count int    `json:"count"`
}

AggregationItem represents a single item in a grouped aggregation (namespace, severity, etc.)

type AnsibleEngineConfig

type AnsibleEngineConfig struct {
	PlaybookPath    string `yaml:"playbookPath" json:"playbookPath"`
	JobTemplateName string `yaml:"jobTemplateName,omitempty" json:"jobTemplateName,omitempty"`
	InventoryName   string `yaml:"inventoryName,omitempty" json:"inventoryName,omitempty"`
}

AnsibleEngineConfig holds Ansible/AWX/AAP-specific execution configuration. BR-WE-015, BR-WE-016: Deserialized from WorkflowExecution.EngineConfig when Engine="ansible" via two-phase unmarshal (ParseEngineConfig).

type CustomLabels

type CustomLabels map[string][]string

CustomLabels represents customer-defined labels via Rego policies (DD-WORKFLOW-001 v1.5) Format: map[subdomain][]values Example: {"constraint": ["cost-constrained"], "team": ["name=payments"]}

Validation Limits (DD-WORKFLOW-001 v1.9): - Max 10 subdomains (keys) - Max 5 values per subdomain - Max 63 characters per subdomain key - Max 100 characters per value

Common Subdomains: - "constraint": Workflow constraints (e.g., "cost-constrained", "stateful-safe") - "team": Team ownership (e.g., "name=payments", "name=platform") - "risk_tolerance": Risk tolerance level (e.g., "low", "medium", "high") - "business_category": Business domain (e.g., "payment-service", "analytics") - "region": Geographic region (e.g., "us-west-2", "eu-central-1")

func NewCustomLabels

func NewCustomLabels() CustomLabels

NewCustomLabels creates a new CustomLabels instance

func (CustomLabels) IsEmpty

func (c CustomLabels) IsEmpty() bool

IsEmpty checks if CustomLabels has no subdomains

func (*CustomLabels) Scan

func (c *CustomLabels) Scan(value interface{}) error

Scan implements the sql.Scanner interface for database retrieval

func (CustomLabels) Value

func (c CustomLabels) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database storage Returns '{}' for empty map instead of NULL to satisfy NOT NULL constraint

type DeprecatedWorkflowSuccessRateResponse

type DeprecatedWorkflowSuccessRateResponse struct {
	// WorkflowID is the deprecated workflow identifier (mapped to workflow_execution_id)
	// DEPRECATED: Use workflow_id + workflow_execution_id instead
	WorkflowID string `json:"workflow_id"`

	// TotalExecutions is the total count (same as other response types)
	TotalExecutions int `json:"total_executions"`

	// SuccessfulExecutions is the success count (same as other response types)
	SuccessfulExecutions int `json:"successful_executions"`

	// FailedExecutions is the failure count (same as other response types)
	FailedExecutions int `json:"failed_executions"`

	// SuccessRate is the percentage (same as other response types)
	SuccessRate float64 `json:"success_rate"`

	// DeprecationWarning is included in every response to alert clients
	DeprecationWarning string `json:"deprecation_warning"`

	// MigrationGuide provides URL to migration documentation
	MigrationGuide string `json:"migration_guide"`
}

DeprecatedWorkflowSuccessRateResponse represents the deprecated workflow-based success rate BR-STORAGE-031-06: Deprecated Endpoint Warning This response type is maintained for backward compatibility but will be removed in V2.0 DEPRECATED: Use IncidentTypeSuccessRateResponse or WorkflowSuccessRateResponse instead

type DetectedLabels

type DetectedLabels struct {
	// FailedDetections lists fields where detection failed (RBAC, timeout, etc.)
	// If a field name is in this array, its value should be ignored
	// If empty/nil, all detections succeeded
	// Validated: only accepts values from ValidDetectedLabelFields
	// Authority: DD-WORKFLOW-001 v2.1 (Detection Failure Handling)
	FailedDetections []string `` /* 188-byte string literal not displayed */

	// GitOpsManaged indicates if resource is managed by GitOps (ArgoCD/Flux)
	// Detection: Check annotations:
	//   - ArgoCD: "argocd.argoproj.io/instance" exists
	//   - Flux: "kustomize.toolkit.fluxcd.io/name" exists
	// API Call: kubectl get <resource> -o jsonpath='{.metadata.annotations}'
	GitOpsManaged bool `json:"gitOpsManaged,omitempty"`

	// GitOpsTool is the specific GitOps tool if detected
	// Values: "argocd", "flux", "*" (wildcard = any tool)
	// Detection: Based on annotation prefix:
	//   - ArgoCD: "argocd.argoproj.io/" prefix
	//   - Flux: "kustomize.toolkit.fluxcd.io/" or "helm.toolkit.fluxcd.io/" prefix
	// API Call: Same as GitOpsManaged (annotation-based)
	GitOpsTool string `json:"gitOpsTool,omitempty" validate:"omitempty,oneof=argocd flux *"`

	// PDBProtected indicates if a PodDisruptionBudget protects this workload
	// Detection: Check for PDB in namespace matching workload selector
	// API Call: kubectl get pdb -n <namespace> -o json
	// Match: PDB .spec.selector matches workload .spec.selector
	PDBProtected bool `json:"pdbProtected,omitempty"`

	// HPAEnabled indicates if a HorizontalPodAutoscaler is configured
	// Detection: Check for HPA in namespace targeting this workload
	// API Call: kubectl get hpa -n <namespace> -o json
	// Match: HPA .spec.scaleTargetRef matches workload name/kind
	HPAEnabled bool `json:"hpaEnabled,omitempty"`

	// Stateful indicates if workload uses persistent storage or is StatefulSet
	// Detection: Check owner chain for StatefulSet OR check for PVC mounts
	// Method: Owner chain traversal (NO K8s API call)
	//   - If owner_chain contains StatefulSet → stateful = true
	//   - Else if Pod has volumeMounts referencing PVCs → stateful = true
	// Clarification: Uses owner chain, not direct StatefulSet lookup
	Stateful bool `json:"stateful,omitempty"`

	// HelmManaged indicates if resource is managed by Helm
	// Detection: Check annotations:
	//   - "meta.helm.sh/release-name" exists
	//   - "meta.helm.sh/release-namespace" exists
	// API Call: kubectl get <resource> -o jsonpath='{.metadata.annotations}'
	HelmManaged bool `json:"helmManaged,omitempty"`

	// NetworkIsolated indicates if NetworkPolicy restricts traffic
	// Detection: Check for NetworkPolicy in namespace selecting this Pod
	// API Call: kubectl get networkpolicy -n <namespace> -o json
	// Match: NetworkPolicy .spec.podSelector matches Pod labels
	NetworkIsolated bool `json:"networkIsolated,omitempty"`

	// ServiceMesh is the service mesh type if detected
	// Values: "istio", "linkerd", "*" (wildcard = any mesh)
	// Detection: Check pod annotations for sidecar injection:
	//   - Istio: "sidecar.istio.io/status" exists (present after injection)
	//   - Linkerd: "linkerd.io/proxy-version" exists (present after injection)
	// API Call: kubectl get pod -o jsonpath='{.metadata.annotations}'
	// Clarification: Uses annotations, not direct mesh API checks
	ServiceMesh string `json:"serviceMesh,omitempty" validate:"omitempty,oneof=istio linkerd *"`

	// ResourceQuotaConstrained indicates if any ResourceQuota exists in namespace
	// Detection: List ResourceQuotas in namespace
	// API Call: kubectl get resourcequota -n <namespace> -o json
	ResourceQuotaConstrained bool `json:"resourceQuotaConstrained,omitempty"`
}

DetectedLabels represents auto-detected labels from Kubernetes resources (DD-WORKFLOW-001 v1.6) V2.3: 8 auto-detected fields with detection failure handling Detection is performed by SignalProcessing at incident time (NOT by Data Storage)

Boolean Normalization Rule (DD-WORKFLOW-001 v1.5): - Booleans only included when true - False values are omitted from JSON

Wildcard Support (DD-WORKFLOW-001 v1.6): - String fields (GitOpsTool, ServiceMesh) support "*" wildcard - "*" means "requires SOME value" (not specific) - Absent field means "no requirement"

func NewDetectedLabels

func NewDetectedLabels() *DetectedLabels

NewDetectedLabels creates a new DetectedLabels instance

func (*DetectedLabels) IsEmpty

func (d *DetectedLabels) IsEmpty() bool

IsEmpty checks if DetectedLabels has no detected fields

func (*DetectedLabels) Scan

func (d *DetectedLabels) Scan(value interface{}) error

Scan implements sql.Scanner for DetectedLabels Allows scanning JSONB column data into structured DetectedLabels type

func (*DetectedLabels) Value

func (d *DetectedLabels) Value() (driver.Value, error)

Value implements driver.Valuer for DetectedLabels Allows writing structured DetectedLabels type to JSONB column

type DetectedLabelsSchema

type DetectedLabelsSchema struct {
	GitOpsManaged   string `yaml:"-" json:"gitOpsManaged,omitempty"`
	GitOpsTool      string `yaml:"-" json:"gitOpsTool,omitempty"`
	PDBProtected    string `yaml:"-" json:"pdbProtected,omitempty"`
	HPAEnabled      string `yaml:"-" json:"hpaEnabled,omitempty"`
	Stateful        string `yaml:"-" json:"stateful,omitempty"`
	HelmManaged     string `yaml:"-" json:"helmManaged,omitempty"`
	NetworkIsolated string `yaml:"-" json:"networkIsolated,omitempty"`
	ServiceMesh     string `yaml:"-" json:"serviceMesh,omitempty"`

	// PopulatedFields records which fields the author explicitly declared.
	// Mirrors the Signal Processing pattern for distinguishing "empty" from
	// "not defined" at the field level.
	PopulatedFields []string `yaml:"-" json:"-"`
}

DetectedLabelsSchema represents the raw YAML detectedLabels section. Fields are strings matching YAML values; converted to models.DetectedLabels via Parser.ExtractDetectedLabels().

func (DetectedLabelsSchema) MarshalYAML

func (d DetectedLabelsSchema) MarshalYAML() (interface{}, error)

MarshalYAML implements custom YAML marshaling for DetectedLabelsSchema. Symmetric with UnmarshalYAML: emits only the fields listed in PopulatedFields, preserving the distinction between "field absent" and "field present with value". Issue #330: Enables round-trip marshal/unmarshal for test fixture builders.

func (*DetectedLabelsSchema) UnmarshalYAML

func (d *DetectedLabelsSchema) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements custom YAML unmarshaling for DetectedLabelsSchema. Iterates over the raw YAML map to track which fields were explicitly declared (PopulatedFields) while assigning values to typed struct fields.

func (*DetectedLabelsSchema) ValidateDetectedLabels

func (d *DetectedLabelsSchema) ValidateDetectedLabels() error

ValidateDetectedLabels validates the detectedLabels section per BR-WORKFLOW-004. Boolean fields accept only "true"; string fields accept specific values or "*". Uses detectedLabelsFieldSpecs as the single source of truth for field classification.

type DimensionsFilter

type DimensionsFilter struct {
	// IncidentType filters to specific incident type (NULL = all incident types)
	IncidentType *string `json:"incident_type,omitempty"`

	// WorkflowID filters to specific workflow (NULL = all workflows)
	WorkflowID *string `json:"workflow_id,omitempty"`

	// WorkflowVersion filters to specific workflow version (NULL = all versions)
	WorkflowVersion *string `json:"workflow_version,omitempty"`

	// ActionType filters to specific action type (NULL = all action types)
	ActionType *string `json:"action_type,omitempty"`
}

DimensionsFilter specifies which dimensions are included in the aggregation All fields are optional - NULL means "aggregate across all values of this dimension" DEPRECATED: Use QueryDimensions instead for new code

type ExecutionAudit

type ExecutionAudit struct {
	ID             int64      `json:"id" db:"id"`
	WorkflowID     string     `json:"workflow_id" db:"workflow_id"`
	ExecutionID    string     `json:"execution_id" db:"execution_id"`
	ActionType     string     `json:"action_type" db:"action_type"`
	TargetResource string     `json:"target_resource" db:"target_resource"`
	ClusterName    string     `json:"cluster_name" db:"cluster_name"`
	Success        bool       `json:"success" db:"success"`
	StartTime      time.Time  `json:"start_time" db:"start_time"`
	EndTime        *time.Time `json:"end_time,omitempty" db:"end_time"`
	ExecutionTime  int64      `json:"execution_time" db:"execution_time"` // milliseconds
	ErrorMessage   *string    `json:"error_message,omitempty" db:"error_message"`
	Metadata       string     `json:"metadata" db:"metadata"` // JSON string
	CreatedAt      time.Time  `json:"created_at" db:"created_at"`
}

ExecutionAudit represents action execution audit data BR-STORAGE-004: Audit trail for action execution

type ExecutionEngine

type ExecutionEngine string

ExecutionEngine represents the workflow execution engine type Authority: ADR-043 (Workflow Execution Standards)

const (
	// ExecutionEngineTekton represents Tekton Pipelines execution engine
	ExecutionEngineTekton ExecutionEngine = "tekton"
	// ExecutionEngineJob represents Kubernetes Job execution engine
	ExecutionEngineJob ExecutionEngine = "job"
	// ExecutionEngineAnsible represents Ansible/AWX/AAP execution engine (BR-WE-015)
	ExecutionEngineAnsible ExecutionEngine = "ansible"
)

type HealthResponse

type HealthResponse struct {
	Status   string `json:"status"`             // "healthy", "unhealthy"
	Database string `json:"database,omitempty"` // "connected", "disconnected"
	Error    string `json:"error,omitempty"`    // Error message if unhealthy
}

HealthResponse represents the response from GET /health Basic health check endpoint

type IncidentTypeBreakdownItem

type IncidentTypeBreakdownItem struct {
	// IncidentType is the problem category (e.g., "pod-oom-killer", "disk-pressure")
	IncidentType string `json:"incident_type"`

	// Executions is the number of times this workflow was used for this incident type
	Executions int `json:"executions"`

	// SuccessRate is the percentage of successful executions for this specific incident type
	SuccessRate float64 `json:"success_rate"`
}

IncidentTypeBreakdownItem represents incident-type-specific statistics for a workflow Used in WorkflowSuccessRateResponse to show which problems the workflow solves

type IncidentTypeSuccessRateResponse

type IncidentTypeSuccessRateResponse struct {
	// IncidentType is the problem being solved (e.g., "pod-oom-killer", "high-cpu-usage")
	IncidentType string `json:"incident_type"`

	// TimeRange is the analysis period (e.g., "7d", "30d", "90d")
	TimeRange string `json:"time_range"`

	// TotalExecutions is the total number of remediation attempts for this incident type
	TotalExecutions int `json:"total_executions"`

	// SuccessfulExecutions is the number of successful remediations
	SuccessfulExecutions int `json:"successful_executions"`

	// FailedExecutions is the number of failed remediations
	FailedExecutions int `json:"failed_executions"`

	// SuccessRate is the percentage of successful remediations (0.0 to 100.0)
	SuccessRate float64 `json:"success_rate"`

	// Confidence indicates statistical confidence in the success rate
	// Values: "high" (>100 samples), "medium" (20-100 samples), "low" (5-20 samples), "insufficient_data" (<5 samples)
	Confidence string `json:"confidence"`

	// MinSamplesMet indicates if minimum sample size threshold was reached
	MinSamplesMet bool `json:"min_samples_met"`

	// BreakdownByWorkflow shows which workflows were used for this incident type
	// Sorted by execution count (descending) to highlight most popular workflows
	BreakdownByWorkflow []WorkflowBreakdownItem `json:"breakdown_by_workflow,omitempty"`

	// AIExecutionMode shows distribution of AI execution modes (catalog/chained/manual)
	// NULL if no AI mode data available (backward compatibility with pre-ADR-033 data)
	AIExecutionMode *AIExecutionModeStats `json:"ai_execution_mode,omitempty"`
}

IncidentTypeSuccessRateResponse represents success rate aggregation by incident type BR-STORAGE-031-01: Incident-Type Success Rate API This is the PRIMARY dimension for AI learning - tracks which workflows work for specific problems

type LivenessResponse

type LivenessResponse struct {
	Status string `json:"status"` // "alive"
}

LivenessResponse represents the response from GET /health/live Kubernetes liveness probe endpoint

type MandatoryLabels

type MandatoryLabels struct {
	// Severity is the severity level(s) this workflow is designed for (REQUIRED)
	// Values: "critical", "high", "medium", "low", "*" (wildcard for all)
	// Source: Alert/Event (auto-populated by Signal Processing)
	// DD-WORKFLOW-001 v2.8: Always stored as JSONB array. Supports "*" wildcard (like environment).
	Severity []string `json:"severity" validate:"required,min=1"`

	// Component is the Kubernetes resource type(s) this workflow remediates (REQUIRED)
	// Examples: ["pod"], ["deployment", "statefulset"], ["*"] (wildcard for all)
	// Source: K8s Resource (auto-populated by Signal Processing)
	// Issue #790: Changed from string to []string to match severity/environment pattern
	Component []string `json:"component" validate:"required,min=1"`

	// Environment is the deployment environment(s) this workflow targets (REQUIRED)
	// Values: ["production"], ["staging", "production"], ["*"] (wildcard for all)
	// Source: Workflow author declares target environments
	// DD-WORKFLOW-001 v2.5: Array allows workflows to work in multiple environments
	Environment []string `json:"environment" validate:"required,min=1"`

	// Priority is the business priority level (REQUIRED)
	// Values: "P0", "P1", "P2", "P3", "*" (wildcard)
	// Source: Derived from severity + environment (Signal Processing via Rego)
	Priority string `json:"priority" validate:"required"`
}

MandatoryLabels represents the workflow labels stored in the catalog JSONB column. 4 required fields: severity, component, environment, priority. Authority: DD-WORKFLOW-001 v1.4, DD-WORKFLOW-016 Issue #274: signalName removed — LLM selects by actionType, not signalName.

func NewMandatoryLabels

func NewMandatoryLabels(severity []string, component []string, environment []string, priority string) *MandatoryLabels

NewMandatoryLabels creates a new MandatoryLabels instance DD-WORKFLOW-001 v2.5: environment is []string (workflow declares target environments) DD-WORKFLOW-001 v2.8: severity is []string (always array, supports "*" wildcard like environment) Issue #274: signalName parameter removed — LLM selects by actionType. Issue #790: component is now []string (matches severity/environment pattern)

func (*MandatoryLabels) Scan

func (m *MandatoryLabels) Scan(value interface{}) error

Scan implements sql.Scanner for MandatoryLabels Allows scanning JSONB column data into structured MandatoryLabels type

func (MandatoryLabels) Value

func (m MandatoryLabels) Value() (driver.Value, error)

Value implements driver.Valuer for MandatoryLabels Allows writing structured MandatoryLabels type to JSONB column

type MultiDimensionalQuery

type MultiDimensionalQuery struct {
	// IncidentType filters to specific incident type (empty = all incident types)
	IncidentType string

	// WorkflowID filters to specific workflow (empty = all workflows)
	WorkflowID string

	// WorkflowVersion filters to specific workflow version (empty = all versions)
	// Requires WorkflowID to be specified
	WorkflowVersion string

	// ActionType filters to specific action type (empty = all action types)
	ActionType string

	// TimeRange is the time window for aggregation (e.g., "7d", "30d")
	TimeRange string

	// MinSamples is the minimum sample size for confidence calculation (default: 5)
	MinSamples int
}

MultiDimensionalQuery represents the input parameters for multi-dimensional queries BR-STORAGE-031-05: Multi-Dimensional Success Rate API Used by repository layer to construct dynamic WHERE clauses

type MultiDimensionalSuccessRateResponse

type MultiDimensionalSuccessRateResponse struct {
	// Dimensions specifies which dimensions are being aggregated
	Dimensions QueryDimensions `json:"dimensions"`

	// TimeRange is the analysis period (e.g., "7d", "30d", "90d")
	TimeRange string `json:"time_range"`

	// TotalExecutions is the total matching executions across all dimensions
	TotalExecutions int `json:"total_executions"`

	// SuccessfulExecutions is the number of successful executions
	SuccessfulExecutions int `json:"successful_executions"`

	// FailedExecutions is the number of failed executions
	FailedExecutions int `json:"failed_executions"`

	// SuccessRate is the overall success rate (0.0 to 100.0)
	SuccessRate float64 `json:"success_rate"`

	// Confidence indicates statistical confidence in the success rate
	Confidence string `json:"confidence"`

	// MinSamplesMet indicates if minimum sample size threshold was reached
	MinSamplesMet bool `json:"min_samples_met"`

	// BreakdownByIncidentType groups by incident type (if workflow/action specified)
	BreakdownByIncidentType []IncidentTypeBreakdownItem `json:"breakdown_by_incident_type,omitempty"`

	// BreakdownByWorkflow groups by workflow (if incident_type/action specified)
	BreakdownByWorkflow []WorkflowBreakdownItem `json:"breakdown_by_workflow,omitempty"`

	// BreakdownByAction groups by action type (if incident_type/workflow specified)
	BreakdownByAction []ActionBreakdownItem `json:"breakdown_by_action,omitempty"`

	// AIExecutionMode shows AI execution mode distribution
	AIExecutionMode *AIExecutionModeStats `json:"ai_execution_mode,omitempty"`
}

MultiDimensionalSuccessRateResponse represents cross-dimensional success rate aggregation BR-STORAGE-031-05: Multi-Dimensional Success Rate API Combines all 3 dimensions: incident type + workflow + action type

type NamespaceAggregationItem

type NamespaceAggregationItem struct {
	Namespace string `json:"namespace"`
	Count     int    `json:"count"`
}

NamespaceAggregationItem represents a namespace aggregation item BR-STORAGE-032: Namespace Grouping Aggregation

type NamespaceAggregationResponse

type NamespaceAggregationResponse struct {
	Aggregations []NamespaceAggregationItem `json:"aggregations"`
}

NamespaceAggregationResponse represents the namespace aggregation endpoint response BR-STORAGE-032: Namespace Grouping Aggregation

type NotificationAudit

type NotificationAudit struct {
	// ID is the unique identifier for the audit record (auto-generated by database)
	ID int64 `json:"id" db:"id"`

	// RemediationID links this notification to the parent RemediationRequest CRD
	// Maps to: notification_audit.remediation_id (VARCHAR(255) NOT NULL)
	RemediationID string `json:"remediation_id" db:"remediation_id" validate:"required,max=255"`

	// NotificationID is the unique identifier for the NotificationRequest CRD
	// Maps to: notification_audit.notification_id (VARCHAR(255) NOT NULL UNIQUE)
	NotificationID string `json:"notification_id" db:"notification_id" validate:"required,max=255"`

	// Recipient is the target recipient (e.g., email address, Slack user ID, PagerDuty service)
	// Maps to: notification_audit.recipient (VARCHAR(255) NOT NULL)
	Recipient string `json:"recipient" db:"recipient" validate:"required,max=255"`

	// Channel is the communication channel (e.g., "email", "slack", "pagerduty", "sms")
	// Maps to: notification_audit.channel (VARCHAR(50) NOT NULL)
	Channel string `json:"channel" db:"channel" validate:"required,oneof=email slack pagerduty sms"`

	// MessageSummary is a short summary of the notification content
	// Maps to: notification_audit.message_summary (TEXT NOT NULL)
	MessageSummary string `json:"message_summary" db:"message_summary" validate:"required"`

	// Status is the notification status (sent, failed, acknowledged, escalated)
	// Maps to: notification_audit.status (VARCHAR(50) NOT NULL CHECK (status IN ('sent', 'failed', 'acknowledged', 'escalated')))
	Status string `json:"status" db:"status" validate:"required,oneof=sent failed acknowledged escalated"`

	// SentAt is the timestamp when the notification was sent
	// Maps to: notification_audit.sent_at (TIMESTAMP WITH TIME ZONE NOT NULL)
	SentAt time.Time `json:"sent_at" db:"sent_at" validate:"required"`

	// DeliveryStatus is the detailed delivery status from the provider (e.g., "200 OK", "rate_limited")
	// Maps to: notification_audit.delivery_status (TEXT)
	DeliveryStatus string `json:"delivery_status,omitempty" db:"delivery_status"`

	// ErrorMessage contains error details if the notification failed
	// Maps to: notification_audit.error_message (TEXT)
	ErrorMessage string `json:"error_message,omitempty" db:"error_message"`

	// EscalationLevel is the escalation count (0 = initial, 1 = first escalation, etc.)
	// Maps to: notification_audit.escalation_level (INTEGER DEFAULT 0)
	EscalationLevel int `json:"escalation_level" db:"escalation_level" validate:"min=0"`

	// CreatedAt is the timestamp when the audit record was created
	// Maps to: notification_audit.created_at (TIMESTAMP WITH TIME ZONE DEFAULT NOW())
	CreatedAt time.Time `json:"created_at" db:"created_at"`

	// UpdatedAt is the timestamp when the audit record was last updated
	// Maps to: notification_audit.updated_at (TIMESTAMP WITH TIME ZONE DEFAULT NOW())
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}

NotificationAudit represents a notification audit record Authority: migrations/010_audit_write_api_phase1.sql Schema: docs/services/crd-controllers/06-notification/database-integration.md Specification: docs/services/crd-controllers/06-notification/audit-trace-specification.md

This model maps directly to the notification_audit PostgreSQL table. All fields match the database schema for accurate persistence and retrieval.

Business Requirements: - BR-NOTIFICATION-001: Track all notification delivery attempts for compliance - BR-NOTIFICATION-002: Record notification failures for debugging and retry logic - BR-NOTIFICATION-003: Capture escalation events for SLA tracking - BR-NOTIFICATION-004: Enable V2.0 Remediation Analysis Report (RAR) timeline reconstruction

func (*NotificationAudit) TableName

func (n *NotificationAudit) TableName() string

TableName returns the PostgreSQL table name for this model This is used by the database layer for query generation

func (*NotificationAudit) Validate

func (n *NotificationAudit) Validate() error

Validate performs business logic validation on the NotificationAudit struct This is called before persisting to the database to ensure data integrity

type PaginationMetadata

type PaginationMetadata struct {
	TotalCount int  `json:"totalCount"`
	Offset     int  `json:"offset"`
	Limit      int  `json:"limit"`
	HasMore    bool `json:"hasMore"`
}

PaginationMetadata represents pagination information for discovery responses DD-WORKFLOW-016: Default page size 10, offset-based pagination

type QueryDimensions

type QueryDimensions struct {
	// IncidentType is the incident type filter (empty if not specified)
	IncidentType string `json:"incident_type"`

	// WorkflowID is the workflow ID filter (empty if not specified)
	WorkflowID string `json:"workflow_id"`

	// WorkflowVersion is the workflow version filter (empty if not specified)
	WorkflowVersion string `json:"workflow_version"`

	// ActionType is the action type filter (empty if not specified)
	ActionType string `json:"action_type"`
}

QueryDimensions represents the dimensions used in a multi-dimensional query BR-STORAGE-031-05: Multi-Dimensional Success Rate API Used in MultiDimensionalSuccessRateResponse to echo back query parameters

type ReadinessResponse

type ReadinessResponse struct {
	Status string `json:"status"`           // "ready", "not_ready"
	Reason string `json:"reason,omitempty"` // "shutting_down", "database_unreachable"
	Error  string `json:"error,omitempty"`  // Error message if database unreachable
}

ReadinessResponse represents the response from GET /health/ready DD-007: Kubernetes readiness probe coordination during graceful shutdown

type RemediationAudit

type RemediationAudit struct {
	ID                   int64      `json:"id" db:"id"`
	Name                 string     `json:"name" db:"name"`
	Namespace            string     `json:"namespace" db:"namespace"`
	Phase                string     `json:"phase" db:"phase"` // pending, processing, completed, failed
	ActionType           string     `json:"action_type" db:"action_type"`
	Status               string     `json:"status" db:"status"`
	StartTime            time.Time  `json:"start_time" db:"start_time"`
	EndTime              *time.Time `json:"end_time,omitempty" db:"end_time"`
	Duration             *int64     `json:"duration,omitempty" db:"duration"` // milliseconds
	RemediationRequestID string     `json:"remediation_request_id" db:"remediation_request_id"`
	SignalFingerprint    string     `json:"signal_fingerprint" db:"signal_fingerprint"`
	Severity             string     `json:"severity" db:"severity"`
	Environment          string     `json:"environment" db:"environment"`
	ClusterName          string     `json:"cluster_name" db:"cluster_name"`
	TargetResource       string     `json:"target_resource" db:"target_resource"`
	ErrorMessage         *string    `json:"error_message,omitempty" db:"error_message"`
	Metadata             string     `json:"metadata" db:"metadata"` // JSON string
	CreatedAt            time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt            time.Time  `json:"updated_at" db:"updated_at"`
}

RemediationAudit represents a complete remediation workflow audit BR-STORAGE-001: Audit trail for remediation workflows

type RemediationWorkflow

type RemediationWorkflow struct {
	// ========================================
	// IDENTITY (DD-WORKFLOW-002 v3.0, DD-WORKFLOW-012 v2.0)
	// ========================================
	// WorkflowID is UUID primary key (auto-generated by database)
	WorkflowID string `json:"workflowId" db:"workflow_id"`
	// WorkflowName is the human-readable identifier (e.g., "pod-oom-recovery")
	WorkflowName string `json:"workflowName" db:"workflow_name" validate:"required,max=255"`
	// Version is semantic version (e.g., "v1.0.0")
	Version string `json:"version" db:"version" validate:"required,max=50"`
	// SchemaVersion is the workflow-schema.yaml format version (e.g., "1.0", "1.1")
	// BR-WORKFLOW-004 v1.1, #255: Distinguishes schema generations for feature gating.
	SchemaVersion string `json:"schemaVersion" db:"schema_version" validate:"required,max=10"`

	// ========================================
	// METADATA
	// ========================================
	Name string `json:"name" db:"name" validate:"required,max=255"`
	// Description is a structured JSONB description (BR-WORKFLOW-004, migration 026)
	// Format: {"what": "...", "whenToUse": "...", "whenNotToUse": "...", "preconditions": "..."}
	Description StructuredDescription `json:"description" db:"description" validate:"required"`
	Owner       *string               `json:"owner,omitempty" db:"owner" validate:"omitempty,max=255"`
	Maintainer  *string               `json:"maintainer,omitempty" db:"maintainer" validate:"omitempty,max=255,email"`

	// ========================================
	// CONTENT
	// ========================================
	Content     string `json:"content" db:"content" validate:"required"`
	ContentHash string `json:"contentHash" db:"content_hash" validate:"required,len=64"`

	// ========================================
	// ACTION TYPE (DD-WORKFLOW-016, DD-HAPI-017)
	// ========================================
	// ActionType links to action_type_taxonomy table (seeded via DataStorage API)
	// Required for three-step discovery protocol (list actions -> list workflows -> get workflow)
	ActionType string `json:"actionType" db:"action_type" validate:"required"`

	// ========================================
	// EXECUTION (ADR-043, DD-WORKFLOW-002 v2.4, Issue #89)
	// ========================================
	// Parameters is nullable JSONB - use pointer to handle NULL values from database
	Parameters      *json.RawMessage `json:"parameters,omitempty" db:"parameters"`
	ExecutionEngine ExecutionEngine  `json:"executionEngine" db:"execution_engine"`

	// SchemaImage is the OCI image containing /workflow-schema.yaml (pulled at registration)
	SchemaImage *string `json:"schemaImage,omitempty" db:"schema_image"`
	// SchemaDigest is the sha256 digest of the schema OCI image
	SchemaDigest *string `json:"schemaDigest,omitempty" db:"schema_digest"`

	// ExecutionBundle is the operator's Tekton bundle / Job image reference (digest-only)
	// Extracted from execution.bundle in workflow-schema.yaml during registration
	ExecutionBundle *string `json:"executionBundle,omitempty" db:"execution_bundle"`
	// ExecutionBundleDigest is the sha256 digest portion of execution_bundle
	ExecutionBundleDigest *string `json:"executionBundleDigest,omitempty" db:"execution_bundle_digest"`

	// EngineConfig holds engine-specific configuration as JSONB (BR-WE-016).
	// For ansible: {"playbookPath": "...", "jobTemplateName": "...", "inventoryName": "..."}.
	// For tekton/job: NULL.
	EngineConfig *json.RawMessage `json:"engineConfig,omitempty" db:"engine_config"`

	// ServiceAccountName is the pre-existing ServiceAccount for Job/PipelineRun.
	// DD-WE-005 v2.0: Operators create SAs in execution namespace. NULL when absent.
	ServiceAccountName *string `json:"serviceAccountName,omitempty" db:"service_account_name"`

	// Labels contains the 5 mandatory workflow labels
	// Required: YES (signalType, severity, component, environment, priority)
	// Authority: DD-WORKFLOW-001 v1.4
	Labels MandatoryLabels `json:"labels" db:"labels" validate:"required"`

	// CustomLabels contains customer-defined labels for hard filtering
	// DD-WORKFLOW-001 v1.5: Subdomain-based extraction design
	// Format: map[subdomain][]string
	// Example: {"constraint": ["cost-constrained"], "team": ["name=payments"]}
	// V1.0: Structured map for type safety
	CustomLabels CustomLabels `json:"customLabels,omitempty" db:"custom_labels"`

	// DetectedLabels contains auto-detected labels from Kubernetes resources
	// DD-WORKFLOW-001 v2.2: 8 auto-detected fields with wildcard support
	// V1.0: Structured type for compile-time validation
	// Note: Not a pointer - FailedDetections field tracks detection failures
	DetectedLabels DetectedLabels `json:"detectedLabels,omitempty" db:"detected_labels"`

	// ========================================
	// LIFECYCLE MANAGEMENT
	// ========================================
	Status         string     `json:"status" db:"status" validate:"required,oneof=Active Disabled Deprecated Archived"`
	StatusReason   *string    `json:"statusReason,omitempty" db:"status_reason"` // Migration 022: Reason for status change
	DisabledAt     *time.Time `json:"disabledAt,omitempty" db:"disabled_at"`
	DisabledBy     *string    `json:"disabledBy,omitempty" db:"disabled_by" validate:"omitempty,max=255"`
	DisabledReason *string    `json:"disabledReason,omitempty" db:"disabled_reason"`

	// ========================================
	// VERSION MANAGEMENT
	// ========================================
	IsLatestVersion   bool    `json:"isLatestVersion" db:"is_latest_version"`
	PreviousVersion   *string `json:"previousVersion,omitempty" db:"previous_version" validate:"omitempty,max=50"`
	DeprecationNotice *string `json:"deprecationNotice,omitempty" db:"deprecation_notice"`

	// ========================================
	// VERSION CHANGE METADATA
	// ========================================
	VersionNotes  *string    `json:"versionNotes,omitempty" db:"version_notes"`
	ChangeSummary *string    `json:"changeSummary,omitempty" db:"change_summary"`
	ApprovedBy    *string    `json:"approvedBy,omitempty" db:"approved_by" validate:"omitempty,max=255"`
	ApprovedAt    *time.Time `json:"approvedAt,omitempty" db:"approved_at"`

	// ========================================
	// SUCCESS METRICS (ADR-033)
	// ========================================
	ExpectedSuccessRate     *float64 `json:"expectedSuccessRate,omitempty" db:"expected_success_rate" validate:"omitempty,min=0,max=1"`
	ExpectedDurationSeconds *int     `json:"expectedDurationSeconds,omitempty" db:"expected_duration_seconds" validate:"omitempty,min=0"`
	ActualSuccessRate       *float64 `json:"actualSuccessRate,omitempty" db:"actual_success_rate" validate:"omitempty,min=0,max=1"`
	TotalExecutions         int      `json:"totalExecutions" db:"total_executions" validate:"min=0"`
	SuccessfulExecutions    int      `json:"successfulExecutions" db:"successful_executions" validate:"min=0"`

	// ========================================
	// AUDIT TRAIL
	// ========================================
	CreatedAt time.Time `json:"createdAt" db:"created_at"`
	UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
	CreatedBy *string   `json:"createdBy,omitempty" db:"created_by" validate:"omitempty,max=255"`
	UpdatedBy *string   `json:"updatedBy,omitempty" db:"updated_by" validate:"omitempty,max=255"`
}

RemediationWorkflow represents a workflow in the catalog Maps to remediation_workflow_catalog table (migration 015)

func (*RemediationWorkflow) IsActive

func (w *RemediationWorkflow) IsActive() bool

IsActive returns true if the workflow is active (case-insensitive)

func (*RemediationWorkflow) IsArchived

func (w *RemediationWorkflow) IsArchived() bool

IsArchived returns true if the workflow is archived (case-insensitive)

func (*RemediationWorkflow) IsDeprecated

func (w *RemediationWorkflow) IsDeprecated() bool

IsDeprecated returns true if the workflow is deprecated (case-insensitive)

func (*RemediationWorkflow) IsDisabled

func (w *RemediationWorkflow) IsDisabled() bool

IsDisabled returns true if the workflow is disabled (case-insensitive)

type ResourceDependency

type ResourceDependency struct {
	Name string `yaml:"name" json:"name" validate:"required"`
}

ResourceDependency identifies a Kubernetes resource (Secret or ConfigMap) by name in the execution namespace (kubernaut-workflows).

type SchemaValidationError

type SchemaValidationError struct {
	Field   string
	Message string
}

SchemaValidationError represents a workflow schema validation error

func NewSchemaValidationError

func NewSchemaValidationError(field, message string) *SchemaValidationError

NewSchemaValidationError creates a new schema validation error

func (*SchemaValidationError) Error

func (e *SchemaValidationError) Error() string

type SeverityAggregationItem

type SeverityAggregationItem struct {
	Severity string `json:"severity"`
	Count    int    `json:"count"`
}

SeverityAggregationItem represents a severity aggregation item BR-STORAGE-033: Severity Distribution Aggregation

type SeverityAggregationResponse

type SeverityAggregationResponse struct {
	Aggregations []SeverityAggregationItem `json:"aggregations"`
}

SeverityAggregationResponse represents the severity aggregation endpoint response BR-STORAGE-033: Severity Distribution Aggregation

type StructuredDescription

type StructuredDescription struct {
	What          string `json:"what" validate:"required"`
	WhenToUse     string `json:"whenToUse" validate:"required"`
	WhenNotToUse  string `json:"whenNotToUse,omitempty"`
	Preconditions string `json:"preconditions,omitempty"`
}

StructuredDescription provides structured workflow information for LLM and operators. This is stored as JSONB in the description column of remediation_workflow_catalog.

This is a DB-scannable variant of sharedtypes.StructuredDescription that adds custom UnmarshalJSON (backward-compat with plain strings), sql.Scanner, and driver.Valuer implementations. Use ToShared() / FromSharedDescription() to convert.

func FromSharedDescription

FromSharedDescription creates a DB-scannable StructuredDescription from the shared type.

func (*StructuredDescription) Scan

func (d *StructuredDescription) Scan(value interface{}) error

Scan implements sql.Scanner for StructuredDescription Allows scanning JSONB column data into structured StructuredDescription type

func (StructuredDescription) String

func (d StructuredDescription) String() string

String returns a human-readable flat text representation of the description

func (StructuredDescription) ToShared

ToShared converts to the canonical shared StructuredDescription type.

func (*StructuredDescription) UnmarshalJSON

func (d *StructuredDescription) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for StructuredDescription Handles both formats: - string: {"description": "some text"} -> StructuredDescription{What: "some text"} - object: {"description": {"what": "...", "whenToUse": "..."}} -> StructuredDescription{...} This enables backward compatibility with API clients that send plain string descriptions

func (StructuredDescription) Value

func (d StructuredDescription) Value() (driver.Value, error)

Value implements driver.Valuer for StructuredDescription Allows writing structured StructuredDescription type to JSONB column

type SuccessRateAggregationResponse

type SuccessRateAggregationResponse struct {
	WorkflowID   string  `json:"workflow_id"`
	TotalCount   int     `json:"total_count"`
	SuccessCount int     `json:"success_count"`
	FailureCount int     `json:"failure_count"`
	SuccessRate  float64 `json:"success_rate"`
}

SuccessRateAggregationResponse represents the success rate aggregation for a workflow BR-STORAGE-030: Workflow Success Rate Aggregation

type TrendAggregationResponse

type TrendAggregationResponse struct {
	Period     string           `json:"period"` // e.g., "7d", "30d"
	DataPoints []TrendDataPoint `json:"data_points"`
}

TrendAggregationResponse represents the trend aggregation response BR-STORAGE-034: Incident Trend Aggregation

type TrendAnalysisData

type TrendAnalysisData struct {
	// Direction indicates the trend direction ("improving", "stable", "degrading")
	Direction string `json:"direction"`

	// Slope is the rate of change in success rate per day (positive = improving)
	Slope float64 `json:"slope"`

	// DataPoints are the individual trend measurements
	DataPoints []TrendDataPoint `json:"data_points"`
}

TrendAnalysisData represents success rate trend over time Used to identify if workflow effectiveness is improving or degrading

type TrendDataPoint

type TrendDataPoint struct {
	Date  string `json:"date"` // Format: "YYYY-MM-DD"
	Count int    `json:"count"`
}

TrendDataPoint represents a single point in a time-series trend

type WorkflowAudit

type WorkflowAudit struct {
	ID                   int64      `json:"id" db:"id"`
	RemediationRequestID string     `json:"remediation_request_id" db:"remediation_request_id"`
	WorkflowID           string     `json:"workflow_id" db:"workflow_id"`
	Phase                string     `json:"phase" db:"phase"` // planning, executing, completed, failed
	TotalSteps           int        `json:"total_steps" db:"total_steps"`
	CompletedSteps       int        `json:"completed_steps" db:"completed_steps"`
	StartTime            time.Time  `json:"start_time" db:"start_time"`
	EndTime              *time.Time `json:"end_time,omitempty" db:"end_time"`
	Metadata             string     `json:"metadata" db:"metadata"` // JSON string
	CreatedAt            time.Time  `json:"created_at" db:"created_at"`
}

WorkflowAudit represents workflow execution audit data BR-STORAGE-003: Audit trail for workflow execution

type WorkflowBreakdownItem

type WorkflowBreakdownItem struct {
	// WorkflowID is the remediation workflow identifier (e.g., "pod-oom-recovery")
	WorkflowID string `json:"workflow_id"`

	// WorkflowVersion is the semantic version (e.g., "v1.2", "v2.0")
	WorkflowVersion string `json:"workflow_version"`

	// Executions is the number of times this workflow was used
	Executions int `json:"executions"`

	// SuccessRate is the percentage of successful executions for this specific workflow
	SuccessRate float64 `json:"success_rate"`
}

WorkflowBreakdownItem represents workflow-specific statistics within an incident type Used in IncidentTypeSuccessRateResponse to show which workflows were tried

type WorkflowCRDMetadata

type WorkflowCRDMetadata struct {
	Name      string `yaml:"name" json:"name"`
	Namespace string `yaml:"namespace,omitempty" json:"namespace,omitempty"`
}

WorkflowCRDMetadata is the CRD-level metadata (name, namespace). metadata.name provides the workflow name (issue #329).

type WorkflowDependencies

type WorkflowDependencies struct {
	Secrets    []ResourceDependency `yaml:"secrets,omitempty" json:"secrets,omitempty"`
	ConfigMaps []ResourceDependency `yaml:"configMaps,omitempty" json:"configMaps,omitempty"`
}

WorkflowDependencies declares infrastructure resources (Secrets, ConfigMaps) that must exist in the execution namespace for the workflow to function. DD-WE-006: These are operator-provisioned resources, NOT LLM-provided parameters.

func (*WorkflowDependencies) ValidateDependencies

func (d *WorkflowDependencies) ValidateDependencies() error

ValidateDependencies checks the dependencies section for structural correctness: non-empty names and unique names within each category.

type WorkflowDescription

type WorkflowDescription = sharedtypes.StructuredDescription

WorkflowDescription is an alias for the shared StructuredDescription type. DD-WORKFLOW-016: Same format shared between RemediationWorkflow and ActionType.

type WorkflowDisableRequest

type WorkflowDisableRequest struct {
	Reason    *string `json:"reason,omitempty"`    // Why the workflow is being disabled
	UpdatedBy *string `json:"updatedBy,omitempty"` // Who is disabling the workflow
}

WorkflowDisableRequest represents a request to disable a workflow DD-WORKFLOW-012: Convenience endpoint for soft-delete (status = disabled)

type WorkflowDiscoveryEntry

type WorkflowDiscoveryEntry struct {
	WorkflowID         string                `json:"workflowId"`
	WorkflowName       string                `json:"workflowName"`
	Name               string                `json:"name"`
	Description        StructuredDescription `json:"description"`
	Version            string                `json:"version"`
	SchemaImage        string                `json:"schemaImage,omitempty"`
	ExecutionBundle    string                `json:"executionBundle,omitempty"`
	ExecutionEngine    string                `json:"executionEngine,omitempty"`
	ServiceAccountName string                `json:"serviceAccountName,omitempty"`
}

WorkflowDiscoveryEntry represents a workflow summary in the discovery response (Step 2) Contains enough information for the LLM to compare workflows without the full parameter schema.

DD-HAPI-017 v1.1: ActualSuccessRate and TotalExecutions REMOVED from this LLM-facing struct. Global aggregate metrics are misleading for per-incident workflow selection — the conditions under which they were collected (different signals, targets, environments) are not applicable to the current case. The LLM should rely on contextual remediation history via spec-hash matching (DD-HAPI-016) and the StructuredDescription for workflow comparison. These fields remain on the full RemediationWorkflow model for operator dashboards.

type WorkflowDiscoveryFilters

type WorkflowDiscoveryFilters struct {
	// Mandatory context filters (required for all discovery calls)
	Severity    string `json:"severity"`
	Component   string `json:"component"`
	Environment string `json:"environment"`
	Priority    string `json:"priority"`

	// Optional context filters
	CustomLabels   map[string][]string `json:"customLabels,omitempty"`
	DetectedLabels *DetectedLabels     `json:"detectedLabels,omitempty"`

	// Audit correlation
	RemediationID string `json:"remediationId,omitempty"`
}

WorkflowDiscoveryFilters represents the signal context filters used across all three steps of the discovery protocol. These filters are passed as query parameters on GET endpoints. Authority: DD-WORKFLOW-016, DD-HAPI-017

func (*WorkflowDiscoveryFilters) HasContextFilters

func (f *WorkflowDiscoveryFilters) HasContextFilters() bool

HasContextFilters returns true if any of the mandatory context filters are set. Used to determine whether the security gate should be applied for GET /workflows/{id}.

type WorkflowDiscoveryResponse

type WorkflowDiscoveryResponse struct {
	ActionType string                   `json:"actionType"`
	Workflows  []WorkflowDiscoveryEntry `json:"workflows"`
	Pagination PaginationMetadata       `json:"pagination"`
}

WorkflowDiscoveryResponse is the response for Step 2: list workflows for action type GET /api/v1/workflows/actions/{action_type}

type WorkflowExecution

type WorkflowExecution struct {
	// Engine is the execution engine type
	// Values: "tekton", "job", "ansible"
	// Defaults to "tekton" if not specified.
	Engine string `yaml:"engine,omitempty" json:"engine,omitempty" validate:"omitempty,oneof=tekton job ansible"`

	// Bundle is the execution bundle or container image reference
	Bundle string `yaml:"bundle,omitempty" json:"bundle,omitempty" validate:"omitempty"`

	// BundleDigest is the digest of the execution bundle (OPTIONAL).
	// For tekton/job: OCI image SHA. For ansible: Git commit SHA.
	BundleDigest string `yaml:"bundleDigest,omitempty" json:"bundleDigest,omitempty" validate:"omitempty"`

	// ServiceAccountName is the pre-existing ServiceAccount for the Job/PipelineRun.
	// DD-WE-005 v2.0: Operators pre-create SAs with appropriate RBAC in the
	// execution namespace. If absent, K8s assigns the namespace's default SA.
	// Ignored for ansible engine (AWX uses its own credential system).
	// +optional
	ServiceAccountName string `yaml:"serviceAccountName,omitempty" json:"serviceAccountName,omitempty"`

	// EngineConfig holds engine-specific configuration as parsed YAML/JSON.
	// BR-WE-016: Discriminator pattern — the Engine field determines the shape.
	// Stored as interface{} for YAML compatibility; converted to json.RawMessage by the parser.
	EngineConfig interface{} `yaml:"engineConfig,omitempty" json:"engineConfig,omitempty"`
}

WorkflowExecution contains execution engine configuration

type WorkflowListResponse

type WorkflowListResponse struct {
	Workflows []*RemediationWorkflow `json:"workflows"`
	Limit     int                    `json:"limit"`
	Offset    int                    `json:"offset"`
	Total     int                    `json:"total"`
}

WorkflowListResponse represents paginated workflow list results

type WorkflowMaintainer

type WorkflowMaintainer struct {
	// Name is the maintainer's name
	Name string `yaml:"name" json:"name" validate:"required"`

	// Email is the maintainer's email address
	Email string `yaml:"email" json:"email" validate:"required,email"`
}

WorkflowMaintainer contains maintainer contact information

type WorkflowParameter

type WorkflowParameter struct {
	// Name is the parameter name (REQUIRED)
	// Format: UPPER_SNAKE_CASE per DD-WORKFLOW-003
	Name string `yaml:"name" json:"name" validate:"required"`

	// Type is the parameter type (REQUIRED)
	// Values: "string", "integer", "boolean", "array", "float"
	// BR-WORKFLOW-005: "float" added for AWX survey compatibility.
	Type string `yaml:"type" json:"type" validate:"required,oneof=string integer boolean array float"`

	// Required indicates whether the parameter must be provided
	Required bool `yaml:"required" json:"required"`

	// Description is a human-readable description for LLM (REQUIRED)
	Description string `yaml:"description" json:"description" validate:"required"`

	// Enum contains allowed values for string type (OPTIONAL)
	Enum []string `yaml:"enum,omitempty" json:"enum,omitempty" validate:"omitempty"`

	// Pattern is a regex pattern for string validation (OPTIONAL)
	Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty" validate:"omitempty"`

	// Minimum is the minimum value for integer/float types (OPTIONAL)
	// BR-WORKFLOW-005: Changed from *int to *float64 for float support. Backward compatible.
	Minimum *float64 `yaml:"minimum,omitempty" json:"minimum,omitempty" validate:"omitempty"`

	// Maximum is the maximum value for integer/float types (OPTIONAL)
	// BR-WORKFLOW-005: Changed from *int to *float64 for float support. Backward compatible.
	Maximum *float64 `yaml:"maximum,omitempty" json:"maximum,omitempty" validate:"omitempty"`

	// Default is the default value if not provided (OPTIONAL)
	Default interface{} `yaml:"default,omitempty" json:"default,omitempty" validate:"omitempty"`

	// DependsOn references other parameter names that must be set first (OPTIONAL)
	DependsOn []string `yaml:"dependsOn,omitempty" json:"dependsOn,omitempty" validate:"omitempty"`
}

WorkflowParameter defines a workflow input parameter Format: JSON Schema compatible subset per BR-WORKFLOW-004

type WorkflowSchema

type WorkflowSchema struct {
	// SchemaVersion is derived from apiVersion by the parser (not present in YAML).
	// Stored in DB column schema_version for format compatibility tracking.
	SchemaVersion string `yaml:"-" json:"schemaVersion"`

	// WorkflowName is derived from the CRD metadata.name by the parser.
	// Not present in the spec YAML; populated by Parse() from crd.Metadata.Name.
	WorkflowName string `yaml:"-" json:"workflowName" validate:"required,max=255"`

	// Version is the semantic version (e.g., "1.0.0", "2.1.3")
	Version string `yaml:"version" json:"version" validate:"required,max=50"`

	// Description is a structured description for LLM and operator consumption
	// BR-WORKFLOW-004: Uses same format as action_type_taxonomy.description (DD-WORKFLOW-016)
	Description WorkflowDescription `yaml:"description" json:"description" validate:"required"`

	// ActionType is the action type from the taxonomy (PascalCase).
	// Must match a valid entry in action_type_taxonomy.
	// DD-WORKFLOW-016: Used as FK for three-step discovery indexing.
	// Examples: "RestartPod", "ScaleReplicas", "DrainNode"
	ActionType string `yaml:"actionType" json:"actionType" validate:"required"`

	// Labels contains mandatory matching/filtering criteria for discovery
	Labels WorkflowSchemaLabels `yaml:"labels" json:"labels" validate:"required"`

	// CustomLabels contains operator-defined key-value labels for additional filtering
	CustomLabels map[string]string `yaml:"customLabels,omitempty" json:"customLabels,omitempty"`

	// DetectedLabels contains author-declared infrastructure requirements (OPTIONAL)
	// ADR-043 v1.3: Matched against incident DetectedLabels from KA LabelDetector
	// DD-WORKFLOW-001 v2.0: Boolean fields accept only "true"; string fields accept
	// specific values or "*" wildcard.
	// nil = section absent from YAML; non-nil empty = explicit empty section
	DetectedLabels *DetectedLabelsSchema `yaml:"detectedLabels,omitempty" json:"detectedLabels,omitempty"`

	// Execution contains execution engine configuration (optional)
	Execution *WorkflowExecution `yaml:"execution,omitempty" json:"execution,omitempty"`

	// Dependencies declares infrastructure resources (Secrets, ConfigMaps) required
	// by the workflow, provisioned by operators in the execution namespace.
	// DD-WE-006: Validated at registration (DS) and execution (WFE) time.
	Dependencies *WorkflowDependencies `yaml:"dependencies,omitempty" json:"dependencies,omitempty"`

	// Maintainers is optional maintainer information
	Maintainers []WorkflowMaintainer `yaml:"maintainers,omitempty" json:"maintainers,omitempty" validate:"omitempty,dive"`

	// Parameters defines the workflow input parameters (at least one required)
	// These are returned to the LLM for parameter population
	Parameters []WorkflowParameter `yaml:"parameters" json:"parameters" validate:"required,min=1,dive"`

	// RollbackParameters defines parameters needed for rollback (optional)
	RollbackParameters []WorkflowParameter `yaml:"rollbackParameters,omitempty" json:"rollbackParameters,omitempty" validate:"omitempty,dive"`
}

WorkflowSchema represents the spec content of a RemediationWorkflow CRD. This is the authoritative schema format for all Kubernaut remediation workflows. Issue #329: WorkflowName is derived from CRD metadata.name (not duplicated in spec).

type WorkflowSchemaCRD

type WorkflowSchemaCRD struct {
	APIVersion string              `yaml:"apiVersion" json:"apiVersion"`
	Kind       string              `yaml:"kind" json:"kind"`
	Metadata   WorkflowCRDMetadata `yaml:"metadata" json:"metadata"`
	Spec       WorkflowSchema      `yaml:"spec" json:"spec"`
}

WorkflowSchemaCRD is the top-level CRD envelope for workflow-schema.yaml. The parser unmarshals into this structure and extracts the Spec for downstream use.

type WorkflowSchemaLabels

type WorkflowSchemaLabels struct {
	// Severity is the severity level(s) this workflow is designed for (REQUIRED)
	// Values: "critical", "high", "medium", "low", "*" (wildcard for all)
	// DD-WORKFLOW-001 v2.8: Always an array in workflow-schema.yaml. Supports "*" wildcard.
	// Examples: severity: [critical] or severity: [low, medium, high] or severity: ["*"]
	Severity []string `yaml:"severity" json:"severity" validate:"required,min=1"`

	// Environment is the target environment(s) (REQUIRED)
	// DD-WORKFLOW-016: Stored as JSONB array in remediation_workflow_catalog
	// Examples: ["production"], ["staging", "production"], ["*"] (wildcard for all)
	Environment []string `yaml:"environment" json:"environment" validate:"required,min=1"`

	// Component is the Kubernetes resource type(s) this workflow remediates (REQUIRED)
	// Examples: ["pod"], ["deployment", "statefulset"], ["*"] (wildcard for all)
	// Issue #790: Changed from string to []string to match severity/environment pattern
	Component []string `yaml:"component" json:"component" validate:"required,min=1"`

	// Priority is the business priority level (REQUIRED)
	// Values: "P0", "P1", "P2", "P3", "*" (wildcard for all)
	// Note: ExtractLabels normalizes to uppercase per OpenAPI enum [P0, P1, P2, P3, "*"]
	Priority string `yaml:"priority" json:"priority" validate:"required"`
}

WorkflowSchemaLabels contains mandatory matching/filtering criteria for discovery. These fields are used by the three-step discovery protocol (DD-HAPI-017) to filter workflows for a given incident context. Stored in the labels JSONB column.

BR-WORKFLOW-004: severity, environment, component, priority are required. Issue #274: signalName removed — LLM selects by actionType + structured descriptions.

func (*WorkflowSchemaLabels) ValidateMandatoryLabels

func (l *WorkflowSchemaLabels) ValidateMandatoryLabels() error

ValidateMandatoryLabels checks if all mandatory labels are present BR-WORKFLOW-004: severity, environment, component, priority are required. Issue #274: signalName removed from schema — not validated or stored.

type WorkflowSearchFilters

type WorkflowSearchFilters struct {

	// Severity filters by severity level (MANDATORY)
	// Values: "critical", "high", "medium", "low"
	// DD-WORKFLOW-001 v1.6: camelCase JSON tag
	Severity string `json:"severity" validate:"required,oneof=critical high medium low"`

	// Component filters by Kubernetes resource type (MANDATORY)
	// Example: "pod", "deployment", "node", "service"
	// DD-WORKFLOW-001 v1.4: Added as mandatory label
	Component string `json:"component" validate:"required"`

	// Environment filters by deployment environment (MANDATORY)
	// Source: Single value from Signal Processing
	// DD-WORKFLOW-001 v2.5: Single string (searches workflows with array containing this value)
	Environment string `json:"environment" validate:"required"`

	// Priority filters by priority level (MANDATORY)
	// Values: "P0", "P1", "P2", "P3"
	// DD-WORKFLOW-001 v1.4: Moved from optional to mandatory
	Priority string `json:"priority" validate:"required,oneof=P0 P1 P2 P3"`

	// DetectedLabels contains auto-detected labels from Kubernetes resources
	// DD-WORKFLOW-001 v2.2: 8 auto-detected fields with wildcard support
	// V1.0: Not a pointer - FailedDetections field tracks detection failures
	DetectedLabels DetectedLabels `json:"detectedLabels,omitempty"`

	// CustomLabels contains customer-defined labels for hard filtering
	// DD-WORKFLOW-001 v1.5: Subdomain-based extraction design
	// Format: map[subdomain][]string
	// Example: {"constraint": ["cost-constrained"], "team": ["name=payments"]}
	CustomLabels map[string][]string `json:"customLabels,omitempty"`

	// WorkflowName filters by exact workflow name match (metadata field)
	// Used for test idempotency and workflow lookup by human-readable name
	// Authority: DD-API-001 (OpenAPI client mandatory - added in Jan 2026)
	// Example: "oomkill-increase-memory-v1"
	WorkflowName string `json:"workflowName,omitempty"`

	// Status filters by workflow lifecycle status
	// Default: ["active"] if not specified
	Status []string `json:"status,omitempty"`
}

WorkflowSearchFilters represents label-based filters DD-CONTEXT-005: Filter Before LLM pattern DD-LLM-001: MCP Workflow Search Parameter Taxonomy DD-WORKFLOW-004: Hybrid Weighted Label Scoring DD-WORKFLOW-001 v1.6: All API fields use camelCase

type WorkflowSearchRequest

type WorkflowSearchRequest struct {
	// RemediationID is the parent remediation request ID for audit correlation
	// BR-AUDIT-023: Used as correlation_id in audit events
	RemediationID string `json:"remediationId,omitempty"`

	// Filters for label-based matching (REQUIRED)
	// Must include at minimum: signalType, severity, component, environment, priority
	// Authority: DD-CONTEXT-005 (Filter Before LLM pattern)
	Filters *WorkflowSearchFilters `json:"filters" validate:"required"`

	// TopK is the number of results to return (default: 10, max: 100)
	TopK int `json:"topK,omitempty" validate:"omitempty,min=1,max=100"`

	// MinScore is the minimum normalized score threshold (0.0-1.0)
	// Default: 0.0 (no threshold)
	// Workflows with score < MinScore are excluded from results
	MinScore float64 `json:"minScore,omitempty" validate:"omitempty,min=0,max=1"`

	// IncludeDisabled includes disabled workflows in results (default: false)
	IncludeDisabled bool `json:"includeDisabled,omitempty"`
}

WorkflowSearchRequest represents a label-only workflow search request V1.0: Pure label matching with wildcard weighting (no embeddings) Rationale: Indeterministic LLM-generated keywords decrease correctness (81% → 95%)

type WorkflowSearchResponse

type WorkflowSearchResponse struct {
	// Workflows is the list of matching workflows, ranked by label score
	Workflows []WorkflowSearchResult `json:"workflows"`

	// TotalResults is the total number of matching workflows
	TotalResults int `json:"totalResults"`

	// Filters are the applied filters (now required for all searches)
	Filters *WorkflowSearchFilters `json:"filters"`
}

WorkflowSearchResponse represents label-only search results V1.0: No query field (label-only search)

type WorkflowSearchResult

type WorkflowSearchResult struct {

	// WorkflowID is the UUID primary key (DD-WORKFLOW-002 v3.0)
	WorkflowID string `json:"workflowId"`

	// Title is the human-readable workflow name (DD-WORKFLOW-002 v3.0: renamed from "name")
	Title string `json:"title"`

	// Description is the structured workflow description (BR-WORKFLOW-004)
	Description StructuredDescription `json:"description"`

	// SchemaVersion is the workflow-schema.yaml format version (e.g., "1.0", "1.1")
	// BR-WORKFLOW-004 v1.1, #255
	SchemaVersion string `json:"schemaVersion,omitempty"`

	// SchemaImage is the OCI image reference used for registration
	SchemaImage string `json:"schemaImage,omitempty"`

	// ExecutionBundle is the operator's execution bundle reference (digest-only)
	ExecutionBundle string `json:"executionBundle,omitempty"`

	// ExecutionBundleDigest is the sha256 digest of the execution bundle
	ExecutionBundleDigest string `json:"executionBundleDigest,omitempty"`

	// ExecutionEngine is the workflow's execution engine (tekton, job, ansible)
	ExecutionEngine ExecutionEngine `json:"executionEngine,omitempty"`

	// EngineConfig holds engine-specific configuration as raw JSON (BR-WE-016)
	EngineConfig *json.RawMessage `json:"engineConfig,omitempty"`

	// ServiceAccountName is the per-workflow SA (DD-WE-005 v2.0). Omitted if not set.
	ServiceAccountName string `json:"serviceAccountName,omitempty"`

	// Confidence is the normalized label score (0.0-1.0) - DD-WORKFLOW-002 v3.0 name
	// Formula: (mandatory_match_score + label_boost - label_penalty) / 10.0
	// Range: 0.0-1.0 (normalized from raw score range 0.0-10.0)
	Confidence float64 `json:"confidence" validate:"min=0,max=1"`

	// LabelBoost is the boost from matching DetectedLabels (0.0-0.39)
	// Sum of all matching DetectedLabel weights (with wildcard weighting)
	// Max: 0.10 (gitOpsManaged) + 0.10 (gitOpsTool) + 0.05 (pdbProtected) + ... = 0.39
	// Wildcard matches get 50% of boost (e.g., gitOpsTool='*' → 0.05 instead of 0.10)
	LabelBoost float64 `json:"labelBoost" validate:"min=0,max=0.39"`

	// LabelPenalty is the penalty from conflicting DetectedLabels (0.0-0.20)
	// Sum of all conflicting high-impact DetectedLabel weights
	// High-impact conflicts: gitOpsManaged, pdbProtected
	LabelPenalty float64 `json:"labelPenalty" validate:"min=0,max=0.20"`

	// FinalScore is the normalized label score (0.0-1.0)
	// Same as Confidence (provided for consistency with DD-WORKFLOW-004)
	FinalScore float64 `json:"finalScore" validate:"min=0,max=1"`

	// Rank is the position in the result set (1-based)
	Rank int `json:"rank" validate:"min=1"`

	// CustomLabels contains customer-defined labels for hard filtering
	// DD-WORKFLOW-001 v1.5: Subdomain-based extraction design
	// Format: map[subdomain][]string
	// Example: {"constraint": ["cost-constrained"], "team": ["name=payments"]}
	// V1.0: Structured type for compile-time validation
	CustomLabels CustomLabels `json:"customLabels,omitempty"`

	// DetectedLabels contains auto-detected labels from Kubernetes resources
	// DD-WORKFLOW-001 v2.2: 8 auto-detected fields with wildcard support
	// V1.0: Structured type for compile-time validation
	// Note: Not a pointer - FailedDetections field tracks detection failures
	DetectedLabels DetectedLabels `json:"detectedLabels,omitempty"`

	// ========================================
	// PARAMETER SCHEMA (BR-HAPI-191)
	// ========================================
	// Parameters contains the workflow parameter schema (JSONB)
	// Used by KA for parameter validation and by LLM for correct parameter names
	// Format: {"schema": {"parameters": [{"name": "PARAM_NAME", "type": "string", ...}]}}
	Parameters *json.RawMessage `json:"parameters,omitempty"`

	// ========================================
	// INTERNAL: Full workflow data (not serialized to JSON)
	// ========================================
	// Workflow contains the full workflow data for internal processing
	// This is not included in the JSON response per DD-WORKFLOW-002 v3.0
	Workflow RemediationWorkflow `json:"-"`
}

WorkflowSearchResult represents a single search result with label-based scoring DD-WORKFLOW-002 v3.0: FLAT response structure (no nested workflow object) DD-WORKFLOW-004 v1.5: Label-Only Scoring with Wildcard Weighting Authority: CONFIDENCE_ASSESSMENT_REMOVE_EMBEDDINGS.md (92% confidence)

type WorkflowSuccessRateResponse

type WorkflowSuccessRateResponse struct {
	// WorkflowID is the remediation workflow identifier (e.g., "disk-cleanup", "network-retry")
	WorkflowID string `json:"workflow_id"`

	// WorkflowVersion is the semantic version (e.g., "v1.0", "v2.0")
	WorkflowVersion string `json:"workflow_version"`

	// TimeRange is the analysis period (e.g., "7d", "30d", "90d")
	TimeRange string `json:"time_range"`

	// TotalExecutions is the total number of times this workflow was executed
	TotalExecutions int `json:"total_executions"`

	// SuccessfulExecutions is the number of successful executions
	SuccessfulExecutions int `json:"successful_executions"`

	// FailedExecutions is the number of failed executions
	FailedExecutions int `json:"failed_executions"`

	// SuccessRate is the percentage of successful executions (0.0 to 100.0)
	SuccessRate float64 `json:"success_rate"`

	// Confidence indicates statistical confidence in the success rate
	// Values: "high" (>100 samples), "medium" (20-100 samples), "low" (5-20 samples), "insufficient_data" (<5 samples)
	Confidence string `json:"confidence"`

	// MinSamplesMet indicates if minimum sample size threshold was reached
	MinSamplesMet bool `json:"min_samples_met"`

	// BreakdownByIncidentType shows which incident types this workflow was used for
	// Sorted by execution count (descending) to highlight primary use cases
	BreakdownByIncidentType []IncidentTypeBreakdownItem `json:"breakdown_by_incident_type,omitempty"`

	// AIExecutionMode shows distribution of AI execution modes for this workflow
	// NULL if no AI mode data available (backward compatibility)
	AIExecutionMode *AIExecutionModeStats `json:"ai_execution_mode,omitempty"`

	// TrendAnalysis shows success rate trend over time (optional)
	TrendAnalysis *TrendAnalysisData `json:"trend_analysis,omitempty"`
}

WorkflowSuccessRateResponse represents success rate aggregation by workflow BR-STORAGE-031-02: Workflow Success Rate API This is the SECONDARY dimension - tracks which workflows are most effective overall

type WorkflowUpdateRequest

type WorkflowUpdateRequest struct {
	// Mutable fields (DD-WORKFLOW-012)
	Status         *string `json:"status,omitempty"`         // active, disabled, deprecated, archived
	DisabledBy     *string `json:"disabledBy,omitempty"`     // Who disabled the workflow
	DisabledReason *string `json:"disabledReason,omitempty"` // Why the workflow was disabled

	// Immutable fields - included for validation (will be rejected if provided)
	Description *StructuredDescription `json:"description,omitempty"` // IMMUTABLE - rejected if provided
	Content     *string                `json:"content,omitempty"`     // IMMUTABLE - rejected if provided
	Labels      *json.RawMessage       `json:"labels,omitempty"`      // IMMUTABLE - rejected if provided
}

WorkflowUpdateRequest represents a request to update mutable workflow fields DD-WORKFLOW-012: Only mutable fields can be updated (status, metrics) Immutable fields (description, content, labels) require creating a new version

type WorkflowVersionsResponse

type WorkflowVersionsResponse struct {
	WorkflowName string                `json:"workflowName"`
	Versions     []RemediationWorkflow `json:"versions"`
	Total        int                   `json:"total"`
}

WorkflowVersionsResponse represents all versions of a workflow by workflow_name DD-WORKFLOW-002 v3.0: List all versions by workflow_name

Jump to

Keyboard shortcuts

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