Help us shape the future of Go! Take the 2026 Go Developer Survey

templates

package
v0.5.13 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package templates provides AMI configuration validation for the Universal AMI System

Package templates provides template application capabilities for running instances.

This module implements the ability to apply templates to already running Prism instances, enabling incremental environment evolution without requiring instance recreation.

Package templates provides template dependency management for version resolution.

Package templates provides template diff calculation capabilities.

Package templates provides remote execution capabilities for template application.

Package templates provides incremental template application capabilities.

Package templates provides instance state inspection capabilities.

Package templates provides marketplace validation and security scanning for Prism templates.

The marketplace validator performs comprehensive security analysis, dependency checking, and quality validation to ensure templates meet community and institutional standards.

Package templates provides template parameterization and variable substitution.

Package templates provides marketplace registry functionality for Prism templates.

The template marketplace enables centralized discovery, validation, and sharing of research environments through community, institutional, and commercial registries.

Package templates provides template rollback capabilities.

Package templates provides Prism's unified template system.

Package templates provides Prism's unified template system.

This package replaces the fragmented template definitions across the codebase with a single, simplified system that leverages existing package managers (apt, conda, spack) instead of custom bash scripts.

Package templates provides Prism's unified template system.

Package templates provides Prism's unified template system.

This package implements a simplified, deterministic template architecture that leverages existing package managers (apt, conda, spack) instead of custom scripts. Templates are declarative YAML definitions that specify packages and services.

Package templates provides Prism's unified template system.

Package templates provides Prism's unified template system.

Index

Constants

View Source
const (
	ComplexitySimple                      = types.TemplateComplexitySimple
	ComplexityModerate                    = types.TemplateComplexityModerate
	ComplexityAdvanced TemplateComplexity = "advanced" // Keep local (not in types package)
	ComplexityComplex                     = types.TemplateComplexityComplex
)

Alias constants for backward compatibility

Variables

View Source
var VariablePattern = regexp.MustCompile(`\{\{\.?(\w+)\}\}`)

VariablePattern regex for finding template variables

Functions

func CreateExampleTemplate

func CreateExampleTemplate(filename string) error

CreateExampleTemplate creates an example template file

func DefaultTemplateDirs

func DefaultTemplateDirs() []string

DefaultTemplateDirs returns the default template directories to scan

func EstimateFileProvisioningTime added in v0.5.7

func EstimateFileProvisioningTime(files []FileConfig) int

EstimateFileProvisioningTime estimates the time required to provision files

func FindVariables

func FindVariables(input string) []string

FindVariables finds all variable references in a string

func GenerateFileProvisioningScript added in v0.5.7

func GenerateFileProvisioningScript(files []FileConfig, instanceRegion string) string

GenerateFileProvisioningScript generates a bash script to download and provision files from S3

func GenerateScript

func GenerateScript(templateName, packageManager string) (string, error)

GenerateScript generates an installation script for a template

func GetCategories

func GetCategories(templates map[string]*Template) []string

GetCategories returns all unique categories from templates

func GetDomains

func GetDomains(templates map[string]*Template) []string

GetDomains returns all unique domains from templates

func GetTags

func GetTags(templates map[string]*Template) []string

GetTags returns all unique tags from templates

func GetTemplate

func GetTemplate(name, region, architecture string) (*types.RuntimeTemplate, error)

GetTemplate returns a single template for the legacy API

func GetTemplateWithPackageManager

func GetTemplateWithPackageManager(name, region, architecture, packageManager, size string) (*types.RuntimeTemplate, error)

GetTemplateWithPackageManager returns a single template with package manager override and size scaling

func GetTemplateWithParameters

func GetTemplateWithParameters(name, region, architecture, packageManager, size string, parameters map[string]interface{}) (*types.RuntimeTemplate, error)

GetTemplateWithParameters returns a template with parameter processing applied

func GetTemplatesForDaemonHandler

func GetTemplatesForDaemonHandler(region, architecture string) (map[string]types.RuntimeTemplate, error)

Integration with daemon handlers

func GetTemplatesForRegion

func GetTemplatesForRegion(region, architecture string) (map[string]types.RuntimeTemplate, error)

GetTemplatesForRegion returns all templates for the specified region and architecture

func ListAvailableTemplates

func ListAvailableTemplates() ([]string, error)

ListAvailableTemplates lists all available templates

func MigrateFromLegacy

func MigrateFromLegacy(outputDir string) error

MigrateFromLegacy migrates existing hardcoded templates to YAML format

func ReplaceAWSTemplatesFunction

func ReplaceAWSTemplatesFunction() func() map[string]types.RuntimeTemplate

ReplaceAWSTemplatesFunction replaces the existing aws.getTemplates() function

func ValidateAllTemplates

func ValidateAllTemplates(templateDirs []string) error

ValidateAllTemplates validates all templates in the given directories

func ValidateFileConfig added in v0.5.7

func ValidateFileConfig(file FileConfig) error

ValidateFileConfig validates a file configuration

func ValidateTemplate

func ValidateTemplate(filename string) error

ValidateTemplate validates a template file

func ValidateTemplateFiles added in v0.5.7

func ValidateTemplateFiles(template *Template) error

ValidateTemplateFiles validates all file configurations in a template

func ValidateTemplateWithRegistry

func ValidateTemplateWithRegistry(templateDirs []string, templateName string) error

ValidateTemplateWithRegistry validates a template with inheritance resolution

Types

type AMIConfig

type AMIConfig struct {
	// AMI deployment strategy
	Strategy AMIStrategy `yaml:"strategy,omitempty" json:"strategy,omitempty"` // ami_preferred, ami_required, ami_fallback

	// Direct AMI mappings (highest priority resolution)
	AMIMappings map[string]string `yaml:"ami_mappings,omitempty" json:"ami_mappings,omitempty"` // region -> AMI ID

	// Dynamic AMI search configuration (second priority)
	AMISearch *AMISearchConfig `yaml:"ami_search,omitempty" json:"ami_search,omitempty"`

	// AWS Marketplace search configuration (third priority)
	MarketplaceSearch *MarketplaceSearchConfig `yaml:"marketplace_search,omitempty" json:"marketplace_search,omitempty"`

	// Fallback behavior when no AMI available
	FallbackStrategy string `yaml:"fallback_strategy,omitempty" json:"fallback_strategy,omitempty"` // script_provisioning, error, cross_region
	FallbackTimeout  string `yaml:"fallback_timeout,omitempty" json:"fallback_timeout,omitempty"`   // Max time for AMI resolution (e.g. "10m")

	// Cost and performance optimization
	PreferredArchitecture    string   `yaml:"preferred_architecture,omitempty" json:"preferred_architecture,omitempty"`         // arm64, x86_64
	InstanceFamilyPreference []string `yaml:"instance_family_preference,omitempty" json:"instance_family_preference,omitempty"` // ["t4g", "m6i", "c6i"]

	// Legacy compatibility (maintains backwards compatibility)
	AMIs           map[string]map[string]string `yaml:"amis,omitempty" json:"amis,omitempty"`                         // region -> arch -> AMI ID (legacy)
	InstanceTypes  map[string]string            `yaml:"instance_types,omitempty" json:"instance_types,omitempty"`     // arch -> instance type (legacy)
	UserDataScript string                       `yaml:"user_data_script,omitempty" json:"user_data_script,omitempty"` // Optional customization script
	SSHUser        string                       `yaml:"ssh_user,omitempty" json:"ssh_user,omitempty"`                 // SSH username for AMI
}

AMIConfig defines AMI-based template configuration for Universal AMI System

type AMIConfigValidator

type AMIConfigValidator struct {
	// Known AWS regions for validation
	ValidRegions map[string]bool

	// Known AWS account IDs for trusted sources
	TrustedAccounts map[string]string // account_id -> description

	// AMI ID pattern validation
	AMIPattern *regexp.Regexp
}

AMIConfigValidator validates AMI configuration in templates

func NewAMIConfigValidator

func NewAMIConfigValidator() *AMIConfigValidator

NewAMIConfigValidator creates a new AMI configuration validator

func (*AMIConfigValidator) GetAMIConfigSummary

func (v *AMIConfigValidator) GetAMIConfigSummary(config *AMIConfig) string

GetAMIConfigSummary returns a human-readable summary of AMI configuration

func (*AMIConfigValidator) ValidateAMIConfig

func (v *AMIConfigValidator) ValidateAMIConfig(config *AMIConfig) []TemplateValidationError

ValidateAMIConfig validates an AMI configuration and returns validation errors

func (*AMIConfigValidator) ValidateTemplateAMIConfig

func (v *AMIConfigValidator) ValidateTemplateAMIConfig(template *Template) []TemplateValidationError

ValidateTemplateAMIConfig validates AMI configuration in the context of a complete template

type AMISearchConfig

type AMISearchConfig struct {
	Owner           string            `yaml:"owner,omitempty" json:"owner,omitempty"`                         // AWS account ID or alias
	NamePattern     string            `yaml:"name_pattern,omitempty" json:"name_pattern,omitempty"`           // AMI name pattern (e.g. "cws-python-ml-*")
	VersionTag      string            `yaml:"version_tag,omitempty" json:"version_tag,omitempty"`             // Specific version tag
	Architecture    []string          `yaml:"architecture,omitempty" json:"architecture,omitempty"`           // ["x86_64", "arm64"]
	MinCreationDate string            `yaml:"min_creation_date,omitempty" json:"min_creation_date,omitempty"` // ISO date string
	RequiredTags    map[string]string `yaml:"required_tags,omitempty" json:"required_tags,omitempty"`         // Tags that must be present
}

AMISearchConfig defines dynamic AMI discovery parameters

type AMIStrategy

type AMIStrategy string

AMIStrategy defines how templates handle AMI resolution

const (
	AMIStrategyPreferred AMIStrategy = "ami_preferred" // Try AMI first, fallback to script (recommended)
	AMIStrategyRequired  AMIStrategy = "ami_required"  // AMI only, fail if unavailable
	AMIStrategyFallback  AMIStrategy = "ami_fallback"  // Script first, AMI if script fails
)

type AppliedTemplate

type AppliedTemplate struct {
	Name               string    `json:"name"`
	AppliedAt          time.Time `json:"applied_at"`
	PackageManager     string    `json:"package_manager"`
	PackagesInstalled  []string  `json:"packages_installed"`
	ServicesConfigured []string  `json:"services_configured"`
	UsersCreated       []string  `json:"users_created"`
	RollbackCheckpoint string    `json:"rollback_checkpoint"`
}

AppliedTemplate represents a template that has been applied to an instance

type ApplyRequest

type ApplyRequest struct {
	InstanceName   string    `json:"instance_name"`
	Template       *Template `json:"template"`
	PackageManager string    `json:"package_manager,omitempty"` // Override template default
	DryRun         bool      `json:"dry_run"`
	Force          bool      `json:"force"` // Override conflicts
}

ApplyRequest represents a request to apply a template to a running instance

type ApplyResponse

type ApplyResponse struct {
	Success            bool          `json:"success"`
	Message            string        `json:"message"`
	PackagesInstalled  int           `json:"packages_installed"`
	ServicesConfigured int           `json:"services_configured"`
	UsersCreated       int           `json:"users_created"`
	RollbackCheckpoint string        `json:"rollback_checkpoint"`
	Warnings           []string      `json:"warnings"`
	ExecutionTime      time.Duration `json:"execution_time"`
}

ApplyResponse represents the result of applying a template

type ApplyResult

type ApplyResult struct {
	PackagesInstalled  int      `json:"packages_installed"`
	ServicesConfigured int      `json:"services_configured"`
	UsersCreated       int      `json:"users_created"`
	Warnings           []string `json:"warnings"`
}

ApplyResult represents the result of applying template changes

type BackupFile

type BackupFile struct {
	OriginalPath string `json:"original_path"`
	BackupPath   string `json:"backup_path"`
	Checksum     string `json:"checksum"`
}

BackupFile represents a backed up configuration file

type BestPracticeViolation

type BestPracticeViolation struct {
	Practice   string `json:"practice"`
	Violation  string `json:"violation"`
	Impact     string `json:"impact"`
	Suggestion string `json:"suggestion"`
}

type BestPracticesRule

type BestPracticesRule struct{}

BestPracticesRule checks for general best practices

func (*BestPracticesRule) Name

func (r *BestPracticesRule) Name() string

func (*BestPracticesRule) Validate

func (r *BestPracticesRule) Validate(template *Template) []ValidationResult

type CVEDatabase

type CVEDatabase interface {
	QueryVulnerabilities(ctx context.Context, packages []string) ([]VulnerabilityInfo, error)
}

type CachedAMIMapping

type CachedAMIMapping struct {
	Mapping  map[string]map[string]string // region -> arch -> AMI ID
	CachedAt time.Time
	Region   string
	Arch     string
}

CachedAMIMapping represents a cached AMI mapping

type CachedTemplate

type CachedTemplate struct {
	Template *Template
	CachedAt time.Time
	Hash     string
}

CachedTemplate represents a cached template with metadata

type ComprehensiveValidator

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

ComprehensiveValidator performs comprehensive template validation

func NewComprehensiveValidator

func NewComprehensiveValidator(registry *TemplateRegistry) *ComprehensiveValidator

NewComprehensiveValidator creates a new validator with all rules

func (*ComprehensiveValidator) ValidateAll

func (v *ComprehensiveValidator) ValidateAll() map[string]*ValidationReport

ValidateAll validates all templates in the registry

func (*ComprehensiveValidator) ValidateTemplate

func (v *ComprehensiveValidator) ValidateTemplate(template *Template) *ValidationReport

ValidateTemplate validates a single template

type ConfigurationAnalysis

type ConfigurationAnalysis struct {
	SecurityMisconfigurations []SecurityMisconfiguration `json:"security_misconfigurations,omitempty"`
	BestPracticeViolations    []BestPracticeViolation    `json:"best_practice_violations,omitempty"`
	NetworkSecurityIssues     []NetworkSecurityIssue     `json:"network_security_issues,omitempty"`
	PrivilegeEscalations      []PrivilegeEscalation      `json:"privilege_escalations,omitempty"`
}

ConfigurationAnalysis analyzes template configuration security

type ConfigurationScanner

type ConfigurationScanner interface {
	ScanConfiguration(ctx context.Context, template *Template) (*ConfigurationAnalysis, error)
}

type ConflictDiff

type ConflictDiff struct {
	Type        string `json:"type"` // "package", "service", "user", "port"
	Description string `json:"description"`
	Resolution  string `json:"resolution"` // "skip", "force", "merge"
}

ConflictDiff represents a conflict that needs resolution

type ConnectionType

type ConnectionType = types.ConnectionType

ConnectionType is an alias to types.ConnectionType (canonical definition)

const (
	ConnectionTypeAuto ConnectionType = "auto" // Keep local (not in types package)
	ConnectionTypeDCV  ConnectionType = "dcv"  // Keep local (not in types package)
	ConnectionTypeSSH                 = types.ConnectionTypeSSH
	ConnectionTypeWeb                 = types.ConnectionTypeWeb
	ConnectionTypeAll  ConnectionType = "all" // Keep local (not in types package)
)

Alias constants for backward compatibility

type ContentAnalysis

type ContentAnalysis struct {
	// Template structure
	TemplateSize     int64   `json:"template_size_bytes"`
	ComplexityScore  float64 `json:"complexity_score"`
	MaintenanceScore float64 `json:"maintenance_score"`

	// Content quality
	DocumentationScore   float64 `json:"documentation_score"`
	DescriptionQuality   string  `json:"description_quality"` // excellent, good, adequate, poor
	MetadataCompleteness float64 `json:"metadata_completeness"`

	// Technical analysis
	PackageAnalysis       PackageAnalysis       `json:"package_analysis"`
	ConfigurationAnalysis ConfigurationAnalysis `json:"configuration_analysis"`

	// Security content analysis
	SecretsFound       []SecretFinding `json:"secrets_found,omitempty"`
	SuspiciousPatterns []PatternMatch  `json:"suspicious_patterns,omitempty"`
}

ContentAnalysis provides analysis of template content and metadata

type CostOptimizationRule

type CostOptimizationRule struct{}

CostOptimizationRule checks for cost optimization opportunities

func (*CostOptimizationRule) Name

func (r *CostOptimizationRule) Name() string

func (*CostOptimizationRule) Validate

func (r *CostOptimizationRule) Validate(template *Template) []ValidationResult

type DependencyAnalysis

type DependencyAnalysis struct {
	Name             string            `json:"name"`
	Version          string            `json:"version,omitempty"`
	Type             string            `json:"type"` // package, template, system
	Source           string            `json:"source,omitempty"`
	SecurityFindings []SecurityFinding `json:"security_findings,omitempty"`
	LicenseInfo      LicenseInfo       `json:"license_info,omitempty"`
	Status           string            `json:"status"` // safe, vulnerable, unknown
}

DependencyAnalysis contains analysis of template dependencies

type DependencyChecker

type DependencyChecker interface {
	CheckDependencies(ctx context.Context, dependencies []TemplateDependency) ([]DependencyAnalysis, error)
}

type DependencyResolver

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

DependencyResolver handles template dependency resolution and version constraints

func NewDependencyResolver

func NewDependencyResolver(versionResolver *VersionResolver) *DependencyResolver

NewDependencyResolver creates a new dependency resolver

func (*DependencyResolver) GetDependencyInfo

func (dr *DependencyResolver) GetDependencyInfo(template *Template) string

GetDependencyInfo returns human-readable dependency information for a template

func (*DependencyResolver) ResolveDependencies

func (dr *DependencyResolver) ResolveDependencies(
	template *Template,
	userVersion, region, architecture string,
) (*ResolvedDependencies, error)

ResolveDependencies resolves template dependencies with user overrides

Parameters:

  • template: The template to resolve dependencies for
  • userVersion: User-provided version override via --version flag
  • region: AWS region for AMI resolution
  • architecture: Instance architecture (x86_64, arm64)

Returns resolved dependencies or an error if resolution fails

func (*DependencyResolver) ValidateVersionConstraint

func (dr *DependencyResolver) ValidateVersionConstraint(resolvedVersion, constraint string) (bool, error)

ValidateVersionConstraint validates if a resolved version satisfies a constraint

This is used for future validation of complex version requirements

type DiffRequest

type DiffRequest struct {
	InstanceName string    `json:"instance_name"`
	Template     *Template `json:"template"`
}

DiffRequest represents a request to calculate template differences

type ExecutionResult

type ExecutionResult struct {
	ExitCode int           `json:"exit_code"`
	Stdout   string        `json:"stdout"`
	Stderr   string        `json:"stderr"`
	Duration time.Duration `json:"duration"`
}

ExecutionResult represents the result of remote command execution

type ExistingUser

type ExistingUser struct {
	Name   string   `json:"name"`
	Groups []string `json:"groups"`
	Shell  string   `json:"shell"`
	Source string   `json:"source"` // "template" or "manual"
}

ExistingUser represents a user account on the instance

type FileConfig added in v0.5.7

type FileConfig struct {
	// Source S3 location
	S3Bucket string `yaml:"s3_bucket" json:"s3_bucket"` // S3 bucket name
	S3Key    string `yaml:"s3_key" json:"s3_key"`       // S3 object key

	// Destination on instance
	DestinationPath string `yaml:"destination_path" json:"destination_path"` // Target path on instance

	// File properties
	Owner       string `yaml:"owner,omitempty" json:"owner,omitempty"`             // File owner (default: current user)
	Group       string `yaml:"group,omitempty" json:"group,omitempty"`             // File group (default: current user's group)
	Permissions string `yaml:"permissions,omitempty" json:"permissions,omitempty"` // File permissions (e.g., "0644")

	// Transfer options
	Checksum    bool `yaml:"checksum,omitempty" json:"checksum,omitempty"`         // Enable MD5 checksum verification (default: true)
	AutoCleanup bool `yaml:"auto_cleanup,omitempty" json:"auto_cleanup,omitempty"` // Delete from S3 after successful download (default: false)

	// Conditional provisioning
	Required bool   `yaml:"required,omitempty" json:"required,omitempty"` // Fail template launch if file transfer fails (default: true)
	OnlyIf   string `yaml:"only_if,omitempty" json:"only_if,omitempty"`   // Conditional expression (e.g., "arch == 'x86_64'")

	// Description for documentation
	Description string `yaml:"description,omitempty" json:"description,omitempty"` // Human-readable description
}

FileConfig defines a file to provision via S3 transfer (v0.5.7)

type IdleDetectionConfig

type IdleDetectionConfig = types.IdleDetectionConfig

IdleDetectionConfig is an alias to types.IdleDetectionConfig (canonical definition)

type IncrementalApplyEngine

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

IncrementalApplyEngine applies template changes incrementally to running instances

func NewIncrementalApplyEngine

func NewIncrementalApplyEngine(executor RemoteExecutor) *IncrementalApplyEngine

NewIncrementalApplyEngine creates a new incremental apply engine

func (*IncrementalApplyEngine) ApplyChanges

func (e *IncrementalApplyEngine) ApplyChanges(ctx context.Context, instanceName string, diff *TemplateDiff, template *Template) (*ApplyResult, error)

ApplyChanges applies the calculated template differences to a running instance

type InheritanceRule

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

InheritanceRule validates template inheritance

func (*InheritanceRule) Name

func (r *InheritanceRule) Name() string

func (*InheritanceRule) Validate

func (r *InheritanceRule) Validate(template *Template) []ValidationResult

type InheritanceValidator

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

InheritanceValidator validates inheritance configuration

func (*InheritanceValidator) Validate

func (v *InheritanceValidator) Validate(template *Template) error

type InstalledPackage

type InstalledPackage struct {
	Name           string `json:"name"`
	Version        string `json:"version"`
	PackageManager string `json:"package_manager"`
	Source         string `json:"source"` // "template" or "manual"
}

InstalledPackage represents a package installed on the instance

type InstanceDefaults

type InstanceDefaults struct {
	Type                 string             `yaml:"type,omitempty" json:"type,omitempty"` // Default instance type
	Ports                []int              `yaml:"ports,omitempty" json:"ports,omitempty"`
	RootVolumeGB         int                `yaml:"root_volume_gb,omitempty" json:"root_volume_gb,omitempty"`                   // Root volume size in GB (default: 20)
	EstimatedCostPerHour map[string]float64 `yaml:"estimated_cost_per_hour,omitempty" json:"estimated_cost_per_hour,omitempty"` // arch -> cost
}

InstanceDefaults defines default instance configuration

type InstanceState

type InstanceState struct {
	Packages         []InstalledPackage `json:"packages"`
	Services         []RunningService   `json:"services"`
	Users            []ExistingUser     `json:"users"`
	Ports            []int              `json:"ports"`
	PackageManager   string             `json:"package_manager"`
	AppliedTemplates []AppliedTemplate  `json:"applied_templates"`
	LastInspected    time.Time          `json:"last_inspected"`
}

InstanceState represents the current state of a running instance

func (*InstanceState) GetPackage

func (state *InstanceState) GetPackage(packageName string) *InstalledPackage

GetPackage returns a package by name if it exists

func (*InstanceState) GetService

func (state *InstanceState) GetService(serviceName string) *RunningService

GetService returns a service by name if it exists

func (*InstanceState) GetUser

func (state *InstanceState) GetUser(username string) *ExistingUser

GetUser returns a user by name if it exists

func (*InstanceState) HasPackage

func (state *InstanceState) HasPackage(packageName string) bool

HasPackage checks if a package is installed

func (*InstanceState) HasService

func (state *InstanceState) HasService(serviceName string) bool

HasService checks if a service exists

func (*InstanceState) HasUser

func (state *InstanceState) HasUser(username string) bool

HasUser checks if a user exists

type InstanceStateInspector

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

InstanceStateInspector inspects the current state of running instances

func NewInstanceStateInspector

func NewInstanceStateInspector(executor RemoteExecutor) *InstanceStateInspector

NewInstanceStateInspector creates a new instance state inspector

func (*InstanceStateInspector) InspectInstance

func (i *InstanceStateInspector) InspectInstance(ctx context.Context, instanceName string) (*InstanceState, error)

InspectInstance inspects the current state of a running instance

type LicenseChecker

type LicenseChecker interface {
	ValidateLicenses(ctx context.Context, template *Template) ([]LicenseConflict, error)
}

type LicenseConflict

type LicenseConflict struct {
	Package1 string `json:"package1"`
	License1 string `json:"license1"`
	Package2 string `json:"package2"`
	License2 string `json:"license2"`
	Conflict string `json:"conflict_reason"`
}

type LicenseInfo

type LicenseInfo struct {
	License      string   `json:"license"`
	Compatible   bool     `json:"compatible"`
	Restrictions []string `json:"restrictions,omitempty"`
}

type LicenseRegistry

type LicenseRegistry interface {
	GetLicenseInfo(ctx context.Context, license string) (*LicenseInfo, error)
}

type MarketplaceBadge

type MarketplaceBadge struct {
	Type        string     `yaml:"type" json:"type"`   // verified, trending, editor_choice, community_favorite
	Label       string     `yaml:"label" json:"label"` // Display text
	Description string     `yaml:"description,omitempty" json:"description,omitempty"`
	EarnedAt    *time.Time `yaml:"earned_at,omitempty" json:"earned_at,omitempty"`
}

MarketplaceBadge represents quality or feature badges

type MarketplaceConfig

type MarketplaceConfig struct {
	// Registry information
	Registry     string `yaml:"registry,omitempty" json:"registry,omitempty"`           // Registry URL or identifier (community, institutional, private)
	RegistryType string `yaml:"registry_type,omitempty" json:"registry_type,omitempty"` // community, institutional, private, official

	// Publication metadata
	PublishedAt      *time.Time `yaml:"published_at,omitempty" json:"published_at,omitempty"`
	Publisher        string     `yaml:"publisher,omitempty" json:"publisher,omitempty"`   // Organization or user who published
	License          string     `yaml:"license,omitempty" json:"license,omitempty"`       // Template license (MIT, Apache-2.0, etc.)
	SourceURL        string     `yaml:"source_url,omitempty" json:"source_url,omitempty"` // Git repository or source location
	DocumentationURL string     `yaml:"documentation_url,omitempty" json:"documentation_url,omitempty"`

	// Community metrics
	Downloads   int64   `yaml:"downloads,omitempty" json:"downloads,omitempty"`       // Download/usage count
	Rating      float64 `yaml:"rating,omitempty" json:"rating,omitempty"`             // Average user rating (0-5)
	RatingCount int     `yaml:"rating_count,omitempty" json:"rating_count,omitempty"` // Number of ratings

	// Security and validation
	SecurityScan    *SecurityScanResult `yaml:"security_scan,omitempty" json:"security_scan,omitempty"`
	ValidationTests []ValidationTest    `yaml:"validation_tests,omitempty" json:"validation_tests,omitempty"`

	// Marketplace categories and discoverability
	Keywords   []string           `yaml:"keywords,omitempty" json:"keywords,omitempty"`     // Search keywords
	Categories []string           `yaml:"categories,omitempty" json:"categories,omitempty"` // Marketplace categories
	Badges     []MarketplaceBadge `yaml:"badges,omitempty" json:"badges,omitempty"`         // Quality badges
	Verified   bool               `yaml:"verified,omitempty" json:"verified,omitempty"`     // Official verification status

	// Dependency information
	Dependencies  []TemplateDependency `yaml:"dependencies,omitempty" json:"dependencies,omitempty"`   // Other templates this depends on
	Dependents    []string             `yaml:"dependents,omitempty" json:"dependents,omitempty"`       // Templates that depend on this
	Compatibility []string             `yaml:"compatibility,omitempty" json:"compatibility,omitempty"` // Compatible Prism versions
}

MarketplaceConfig defines template marketplace integration settings (Phase 5B+)

type MarketplaceSearchConfig

type MarketplaceSearchConfig struct {
	ProductCode       string `yaml:"product_code,omitempty" json:"product_code,omitempty"`             // Marketplace product code
	VersionConstraint string `yaml:"version_constraint,omitempty" json:"version_constraint,omitempty"` // Version constraint (e.g. ">=2.0.0")
	Publisher         string `yaml:"publisher,omitempty" json:"publisher,omitempty"`                   // Publisher filter
}

MarketplaceSearchConfig defines AWS Marketplace AMI discovery

type MarketplaceSearchResult

type MarketplaceSearchResult struct {
	Templates     []MarketplaceTemplateRegistryEntry `json:"templates"`
	TotalCount    int                                `json:"total_count"`
	FilteredCount int                                `json:"filtered_count"`
	Query         SearchFilter                       `json:"query"`
	ExecutionTime time.Duration                      `json:"execution_time"`
}

SearchResult contains paginated search results

type MarketplaceTemplateRegistry

type MarketplaceTemplateRegistry struct {
	Name        string
	URL         string
	Type        RegistryType
	Credentials *RegistryCredentials
	Client      *http.Client
}

MarketplaceTemplateRegistry provides centralized template discovery and management

func NewMarketplaceRegistry

func NewMarketplaceRegistry(name, url string, registryType RegistryType) *MarketplaceTemplateRegistry

NewMarketplaceTemplateRegistry creates a new registry client

func (*MarketplaceTemplateRegistry) GetTemplate

GetTemplate retrieves a specific template from the registry

func (*MarketplaceTemplateRegistry) ListCategories

func (r *MarketplaceTemplateRegistry) ListCategories(ctx context.Context) ([]string, error)

ListCategories returns available template categories in the registry

func (*MarketplaceTemplateRegistry) PublishTemplate

func (r *MarketplaceTemplateRegistry) PublishTemplate(ctx context.Context, template *Template) error

PublishTemplate uploads a template to the registry (for writable registries)

func (*MarketplaceTemplateRegistry) Search

Search performs a template search across the registry

func (*MarketplaceTemplateRegistry) SetCredentials

func (r *MarketplaceTemplateRegistry) SetCredentials(creds *RegistryCredentials)

SetCredentials configures authentication for private registries

type MarketplaceTemplateRegistryEntry

type MarketplaceTemplateRegistryEntry struct {
	*Template

	// Registry-specific metadata
	RegistryName string    `json:"registry_name"`
	RegistryType string    `json:"registry_type"`
	LastSynced   time.Time `json:"last_synced"`

	// Enhanced search metadata
	SearchTags     []string `json:"search_tags"`     // Computed from template content
	PopularityRank int      `json:"popularity_rank"` // Registry-specific ranking
}

MarketplaceTemplateRegistryEntry represents a template entry in the registry

type MarketplaceTemplateRegistryManager

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

MarketplaceTemplateRegistryManager manages multiple template registries

func NewMarketplaceTemplateRegistryManager

func NewMarketplaceTemplateRegistryManager() *MarketplaceTemplateRegistryManager

NewMarketplaceTemplateRegistryManager creates a new registry manager

func (*MarketplaceTemplateRegistryManager) AddRegistry

AddRegistry adds a registry to the manager

func (*MarketplaceTemplateRegistryManager) GetRegistry

GetRegistry returns a specific registry by name

func (*MarketplaceTemplateRegistryManager) ListRegistries

ListRegistries returns all configured registries

func (*MarketplaceTemplateRegistryManager) SearchAll

SearchAll searches across all configured registries

type MarketplaceValidationError

type MarketplaceValidationError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Field   string `json:"field,omitempty"`
	Value   any    `json:"value,omitempty"`
}

type MarketplaceValidationResult

type MarketplaceValidationResult struct {
	// Overall validation status
	Status      ValidationStatus `json:"status"`
	Score       float64          `json:"score"` // 0-100 overall quality score
	ValidatedAt time.Time        `json:"validated_at"`
	ValidatorID string           `json:"validator_id"`

	// Security analysis
	SecurityScan SecurityScanResult `json:"security_scan"`

	// Quality analysis
	QualityChecks []QualityCheck `json:"quality_checks"`

	// Dependency analysis
	Dependencies []DependencyAnalysis `json:"dependencies"`

	// Content analysis
	ContentAnalysis ContentAnalysis `json:"content_analysis"`

	// Recommendations
	Recommendations []Recommendation `json:"recommendations"`

	// Errors and warnings
	Errors   []MarketplaceValidationError   `json:"errors,omitempty"`
	Warnings []MarketplaceValidationWarning `json:"warnings,omitempty"`
}

MarketplaceValidationResult contains comprehensive validation results

type MarketplaceValidationWarning

type MarketplaceValidationWarning struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Field   string `json:"field,omitempty"`
	Impact  string `json:"impact"` // low, medium, high
}

type MarketplaceValidator

type MarketplaceValidator struct {
	// Security scanners
	PackageScanner PackageSecurityScanner
	SecretsScanner SecretsScanner
	ConfigScanner  ConfigurationScanner

	// Quality checkers
	DependencyChecker DependencyChecker
	LicenseChecker    LicenseChecker

	// External integrations
	CVEDatabase     CVEDatabase
	LicenseRegistry LicenseRegistry

	// Validation configuration
	Config *ValidationConfig
}

MarketplaceValidator provides comprehensive template validation for marketplace publication

func NewMarketplaceValidator

func NewMarketplaceValidator() *MarketplaceValidator

NewMarketplaceValidator creates a new marketplace validator with default configuration

func (*MarketplaceValidator) ValidateTemplate

func (v *MarketplaceValidator) ValidateTemplate(ctx context.Context, template *Template) (*MarketplaceValidationResult, error)

ValidateTemplate performs comprehensive validation of a template for marketplace publication

type MockRemoteExecutor

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

MockRemoteExecutor implements RemoteExecutor for testing

func NewMockRemoteExecutor

func NewMockRemoteExecutor() *MockRemoteExecutor

NewMockRemoteExecutor creates a new mock executor for testing

func (*MockRemoteExecutor) CopyFile

func (e *MockRemoteExecutor) CopyFile(ctx context.Context, instanceName string, localPath, remotePath string) error

CopyFile records the file copy operation

func (*MockRemoteExecutor) Execute

func (e *MockRemoteExecutor) Execute(ctx context.Context, instanceName string, command string) (*ExecutionResult, error)

Execute records the command and returns a predefined result

func (*MockRemoteExecutor) ExecuteScript

func (e *MockRemoteExecutor) ExecuteScript(ctx context.Context, instanceName string, script string) (*ExecutionResult, error)

ExecuteScript records the script and returns a predefined result

func (*MockRemoteExecutor) GetCommands

func (e *MockRemoteExecutor) GetCommands() []string

GetCommands returns all recorded commands for testing verification

func (*MockRemoteExecutor) GetFile

func (e *MockRemoteExecutor) GetFile(ctx context.Context, instanceName string, remotePath, localPath string) error

GetFile records the file download operation

func (*MockRemoteExecutor) SetResult

func (e *MockRemoteExecutor) SetResult(command string, result *ExecutionResult)

SetResult sets the expected result for a command

type NetworkSecurityIssue

type NetworkSecurityIssue struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Risk        string `json:"risk"`
	Ports       []int  `json:"ports,omitempty"`
}

type OptimizedResolver

type OptimizedResolver struct {
	*TemplateResolver
	// contains filtered or unexported fields
}

OptimizedResolver provides parallel template processing for improved performance

func NewOptimizedResolver

func NewOptimizedResolver() *OptimizedResolver

NewOptimizedResolver creates an optimized template resolver with caching

func (*OptimizedResolver) ClearCache

func (r *OptimizedResolver) ClearCache()

ClearCache clears all cached data

func (*OptimizedResolver) GetCacheStats

func (r *OptimizedResolver) GetCacheStats() map[string]int

GetCacheStats returns cache statistics for monitoring

func (*OptimizedResolver) ResolveTemplateOptimized

func (r *OptimizedResolver) ResolveTemplateOptimized(ctx context.Context, template *Template, region, architecture, packageManagerOverride, size string) (*RuntimeTemplate, error)

ResolveTemplateOptimized resolves template with parallel processing and caching

type OutdatedPackage

type OutdatedPackage struct {
	Package        string `json:"package"`
	CurrentVersion string `json:"current_version"`
	LatestVersion  string `json:"latest_version"`
	SecurityRisk   string `json:"security_risk"` // high, medium, low
}

type PackageAnalysis

type PackageAnalysis struct {
	TotalPackages        int                 `json:"total_packages"`
	KnownVulnerabilities []VulnerabilityInfo `json:"known_vulnerabilities,omitempty"`
	UnknownPackages      []string            `json:"unknown_packages,omitempty"`
	OutdatedPackages     []OutdatedPackage   `json:"outdated_packages,omitempty"`
	LicenseConflicts     []LicenseConflict   `json:"license_conflicts,omitempty"`
}

PackageAnalysis analyzes packages and their security implications

type PackageConsistencyValidator

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

PackageConsistencyValidator validates package consistency

func (*PackageConsistencyValidator) Validate

func (v *PackageConsistencyValidator) Validate(template *Template) error

type PackageDefinitions

type PackageDefinitions struct {
	System []string `yaml:"system,omitempty" json:"system,omitempty"` // apt/dnf packages
	Conda  []string `yaml:"conda,omitempty" json:"conda,omitempty"`   // conda packages
	Spack  []string `yaml:"spack,omitempty" json:"spack,omitempty"`   // spack packages
	Pip    []string `yaml:"pip,omitempty" json:"pip,omitempty"`       // pip packages (when conda used)
}

PackageDefinitions defines packages for different package managers

type PackageDiff

type PackageDiff struct {
	Name           string `json:"name"`
	CurrentVersion string `json:"current_version,omitempty"`
	TargetVersion  string `json:"target_version"`
	Action         string `json:"action"` // "install", "upgrade", "remove"
	PackageManager string `json:"package_manager"`
}

PackageDiff represents a package change

type PackageManagerRule

type PackageManagerRule struct{}

PackageManagerRule validates package manager configuration

func (*PackageManagerRule) Name

func (r *PackageManagerRule) Name() string

func (*PackageManagerRule) Validate

func (r *PackageManagerRule) Validate(template *Template) []ValidationResult

type PackageManagerRules

type PackageManagerRules struct {
	// If template has HPC/scientific computing packages -> spack
	HPCIndicators []string

	// If template has Python data science packages -> conda
	PythonDataScienceIndicators []string

	// If template has R packages -> conda (better R ecosystem)
	RIndicators []string

	// Default fallback -> apt (system packages)
	DefaultManager PackageManagerType
}

PackageManagerRules defines rules for automatic package manager selection

type PackageManagerStrategy

type PackageManagerStrategy struct {
	Template *Template

	// Selection rules for "auto" mode
	Rules PackageManagerRules
}

PackageManagerStrategy handles package manager selection logic

func NewPackageManagerStrategy

func NewPackageManagerStrategy() *PackageManagerStrategy

NewPackageManagerStrategy creates a new package manager strategy

func (*PackageManagerStrategy) SelectPackageManager

func (s *PackageManagerStrategy) SelectPackageManager(template *Template) PackageManagerType

SelectPackageManager returns the template's specified package manager

type PackageManagerType

type PackageManagerType string

PackageManagerType represents supported package managers

const (
	PackageManagerApt   PackageManagerType = "apt"
	PackageManagerDnf   PackageManagerType = "dnf"
	PackageManagerConda PackageManagerType = "conda"
	PackageManagerSpack PackageManagerType = "spack"
	PackageManagerAMI   PackageManagerType = "ami"
	PackageManagerPip   PackageManagerType = "pip"
)

type PackageManagerValidator

type PackageManagerValidator struct{}

PackageManagerValidator validates package manager configuration

func (*PackageManagerValidator) Validate

func (v *PackageManagerValidator) Validate(template *Template) error

type PackageSecurityScanner

type PackageSecurityScanner interface {
	ScanPackages(ctx context.Context, packages PackageDefinitions) (*PackageAnalysis, error)
}

Interface definitions for pluggable scanners

type ParameterHelper

type ParameterHelper struct{}

ParameterHelper provides utilities for working with template parameters

func NewParameterHelper

func NewParameterHelper() *ParameterHelper

NewParameterHelper creates a new parameter helper

func (*ParameterHelper) GetParametersFromTemplate

func (ph *ParameterHelper) GetParametersFromTemplate(tmpl *Template) []string

GetParametersFromTemplate extracts parameters from a template for CLI help

func (*ParameterHelper) ParseParameterFlag

func (ph *ParameterHelper) ParseParameterFlag(flag string) (string, interface{}, error)

ParseParameterFlag parses parameter flags in the format --param name=value

type ParameterProcessor

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

ParameterProcessor handles template parameter substitution

func NewParameterProcessor

func NewParameterProcessor(tmpl *Template, userParams TemplateParameterValues) *ParameterProcessor

NewParameterProcessor creates a parameter processor for a template

func (*ParameterProcessor) ExpandTemplateVariables

func (pp *ParameterProcessor) ExpandTemplateVariables(input string) string

ExpandTemplateVariables expands variables in any string using the current parameter context

func (*ParameterProcessor) GetParameterValue

func (pp *ParameterProcessor) GetParameterValue(name string) (interface{}, bool)

GetParameterValue returns the processed value for a parameter

func (*ParameterProcessor) GetVariable

func (pp *ParameterProcessor) GetVariable(name string) (string, bool)

GetVariable returns the processed variable value

func (*ParameterProcessor) ProcessTemplate

func (pp *ParameterProcessor) ProcessTemplate() (*Template, error)

ProcessTemplate applies parameter substitution to the entire template

func (*ParameterProcessor) ValidateParameters

func (pp *ParameterProcessor) ValidateParameters() []TemplateValidationError

ValidateParameters validates that all parameters meet their constraints

type ParameterRule

type ParameterRule struct{}

ParameterRule validates template parameters

func (*ParameterRule) Name

func (r *ParameterRule) Name() string

func (*ParameterRule) Validate

func (r *ParameterRule) Validate(template *Template) []ValidationResult

type PatternMatch

type PatternMatch struct {
	Pattern     string `json:"pattern"`
	Location    string `json:"location"`
	Match       string `json:"match"`
	Risk        string `json:"risk"` // high, medium, low
	Description string `json:"description"`
}

type PerformanceRule

type PerformanceRule struct{}

PerformanceRule checks for performance issues

func (*PerformanceRule) Name

func (r *PerformanceRule) Name() string

func (*PerformanceRule) Validate

func (r *PerformanceRule) Validate(template *Template) []ValidationResult

type PortValidator

type PortValidator struct{}

PortValidator validates port configurations

func (*PortValidator) Validate

func (v *PortValidator) Validate(template *Template) error

type PrivilegeEscalation

type PrivilegeEscalation struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Severity    string `json:"severity"`
	Vector      string `json:"vector"`
}

type QualityCheck

type QualityCheck struct {
	Name       string         `json:"name"`
	Status     string         `json:"status"` // passed, failed, warning
	Score      float64        `json:"score"`  // 0-100
	Message    string         `json:"message"`
	Details    map[string]any `json:"details,omitempty"`
	Impact     string         `json:"impact"` // critical, high, medium, low
	ExecutedAt time.Time      `json:"executed_at"`
}

QualityCheck represents a specific quality validation check

type Recommendation

type Recommendation struct {
	Type        string `json:"type"`     // security, quality, performance, maintenance
	Priority    string `json:"priority"` // critical, high, medium, low
	Title       string `json:"title"`
	Description string `json:"description"`
	Action      string `json:"action"`
	Effort      string `json:"effort"` // low, medium, high
}

type RegistryCredentials

type RegistryCredentials struct {
	Type     string `json:"type"` // token, basic, ssh_key
	Token    string `json:"token,omitempty"`
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	SSHKey   string `json:"ssh_key,omitempty"`
}

RegistryCredentials holds authentication information for private registries

type RegistryType

type RegistryType string

RegistryType defines the type of template registry

const (
	RegistryTypeCommunity     RegistryType = "community"
	RegistryTypeInstitutional RegistryType = "institutional"
	RegistryTypePrivate       RegistryType = "private"
	RegistryTypeOfficial      RegistryType = "official"
)

type RemoteExecutor

type RemoteExecutor interface {
	Execute(ctx context.Context, instanceName string, command string) (*ExecutionResult, error)
	ExecuteScript(ctx context.Context, instanceName string, script string) (*ExecutionResult, error)
	CopyFile(ctx context.Context, instanceName string, localPath, remotePath string) error
	GetFile(ctx context.Context, instanceName string, remotePath, localPath string) error
}

RemoteExecutor interface for executing commands on remote instances

type RequiredFieldValidator

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

RequiredFieldValidator validates required template fields

func (*RequiredFieldValidator) Validate

func (v *RequiredFieldValidator) Validate(template *Template) error

type RequiredFieldsRule

type RequiredFieldsRule struct{}

RequiredFieldsRule validates required template fields

func (*RequiredFieldsRule) Name

func (r *RequiredFieldsRule) Name() string

func (*RequiredFieldsRule) Validate

func (r *RequiredFieldsRule) Validate(template *Template) []ValidationResult

type ResolvedDependencies

type ResolvedDependencies struct {
	BaseOS           string // Resolved base OS (e.g., "ubuntu")
	Version          string // Resolved version (e.g., "24.04")
	ResolvedAMI      string // Resolved AMI ID
	VersionSource    string // How version was determined (user_override, template_requirement, default)
	SatisfiesRequest bool   // Whether resolution satisfied user's request
}

ResolvedDependencies contains resolved dependency information

type RollbackCheckpoint

type RollbackCheckpoint struct {
	ID              string             `json:"id"`
	CreatedAt       time.Time          `json:"created_at"`
	InstanceName    string             `json:"instance_name"`
	Description     string             `json:"description"`
	PackageSnapshot []InstalledPackage `json:"package_snapshot"`
	ServiceSnapshot []RunningService   `json:"service_snapshot"`
	UserSnapshot    []ExistingUser     `json:"user_snapshot"`
	FilesBackedUp   []BackupFile       `json:"files_backed_up"`
	EnvironmentVars map[string]string  `json:"environment_vars"`
}

RollbackCheckpoint represents a point-in-time snapshot of instance state

type RunningService

type RunningService struct {
	Name    string `json:"name"`
	Status  string `json:"status"` // "running", "stopped", "error"
	Port    int    `json:"port"`
	Enabled bool   `json:"enabled"`
	Source  string `json:"source"` // "template" or "manual"
}

RunningService represents a service running on the instance

type RuntimeTemplate

type RuntimeTemplate = types.RuntimeTemplate

RuntimeTemplate represents a resolved template ready for instance launch This maintains compatibility with existing types.RuntimeTemplate RuntimeTemplate is an alias to types.RuntimeTemplate (canonical definition)

type S3ClientInterface

type S3ClientInterface interface {
	PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
	GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
	DeleteObject(ctx context.Context, params *s3.DeleteObjectInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)
}

S3ClientInterface defines the interface for S3 client operations needed by executor

type SSHRemoteExecutor

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

SSHRemoteExecutor implements RemoteExecutor using SSH connections

func NewSSHRemoteExecutor

func NewSSHRemoteExecutor(keyPath, user string) *SSHRemoteExecutor

NewSSHRemoteExecutor creates a new SSH-based remote executor

func (*SSHRemoteExecutor) CopyFile

func (e *SSHRemoteExecutor) CopyFile(ctx context.Context, instanceName string, localPath, remotePath string) error

CopyFile copies a file from local to remote instance via SCP

func (*SSHRemoteExecutor) Execute

func (e *SSHRemoteExecutor) Execute(ctx context.Context, instanceName string, command string) (*ExecutionResult, error)

Execute executes a single command on the remote instance via SSH

func (*SSHRemoteExecutor) ExecuteScript

func (e *SSHRemoteExecutor) ExecuteScript(ctx context.Context, instanceName string, script string) (*ExecutionResult, error)

ExecuteScript executes a script on the remote instance via SSH

func (*SSHRemoteExecutor) GetFile

func (e *SSHRemoteExecutor) GetFile(ctx context.Context, instanceName string, remotePath, localPath string) error

GetFile copies a file from remote instance to local via SCP

type SSMClientInterface

type SSMClientInterface interface {
	SendCommand(ctx context.Context, params *ssm.SendCommandInput, optFns ...func(*ssm.Options)) (*ssm.SendCommandOutput, error)
	GetCommandInvocation(ctx context.Context, params *ssm.GetCommandInvocationInput, optFns ...func(*ssm.Options)) (*ssm.GetCommandInvocationOutput, error)
}

SSMClientInterface defines the interface for SSM client operations needed by executor

type ScriptData

type ScriptData struct {
	Template           *Template
	PackageManager     string
	Packages           []string
	Users              []UserData
	Services           []ServiceConfig
	WebInterfaceBindIP string // Dynamic IP binding for web interfaces (0.0.0.0 or 127.0.0.1)
}

ScriptData contains data for script template execution

type ScriptGenerator

type ScriptGenerator struct {
	// Script templates for each package manager
	AptTemplate   string
	DnfTemplate   string
	CondaTemplate string
	SpackTemplate string
	AMITemplate   string
	PipTemplate   string
}

ScriptGenerator generates installation scripts for different package managers

func NewScriptGenerator

func NewScriptGenerator() *ScriptGenerator

NewScriptGenerator creates a new script generator

func (*ScriptGenerator) GenerateScript

func (sg *ScriptGenerator) GenerateScript(tmpl *Template, packageManager PackageManagerType) (string, error)

GenerateScript generates an installation script for a template

type SearchFilter

type SearchFilter struct {
	// Text search
	Query    string   `json:"query,omitempty"`
	Keywords []string `json:"keywords,omitempty"`

	// Classification filters
	Categories []string             `json:"categories,omitempty"`
	Domains    []string             `json:"domains,omitempty"`
	Complexity []TemplateComplexity `json:"complexity,omitempty"`

	// Quality filters
	MinRating     float64 `json:"min_rating,omitempty"`
	VerifiedOnly  bool    `json:"verified_only,omitempty"`
	ValidatedOnly bool    `json:"validated_only,omitempty"`

	// Registry filters
	Registries    []string       `json:"registries,omitempty"`
	RegistryTypes []RegistryType `json:"registry_types,omitempty"`

	// Feature filters
	ResearchUserSupport bool     `json:"research_user_support,omitempty"`
	ConnectionTypes     []string `json:"connection_types,omitempty"`
	PackageManagers     []string `json:"package_managers,omitempty"`

	// Sorting and pagination
	SortBy    string `json:"sort_by,omitempty"`    // popularity, rating, updated, name
	SortOrder string `json:"sort_order,omitempty"` // asc, desc
	Limit     int    `json:"limit,omitempty"`
	Offset    int    `json:"offset,omitempty"`
}

SearchFilter defines criteria for template marketplace searches

type SearchOptions

type SearchOptions struct {
	Query         string   // Text search query
	Category      string   // Filter by category
	Domain        string   // Filter by domain
	Complexity    string   // Filter by complexity
	Tags          []string // Filter by tags
	Popular       *bool    // Filter by popular status
	Featured      *bool    // Filter by featured status
	HasGPU        *bool    // Filter by GPU support
	MaxLaunchTime int      // Maximum launch time in minutes
}

SearchOptions defines search and filter criteria for templates

type SearchResult

type SearchResult struct {
	Template *Template
	Score    float64  // Relevance score for ranking
	Matches  []string // What matched in the search
}

SearchResult represents a template search result with relevance scoring

func SearchTemplates

func SearchTemplates(templates map[string]*Template, options SearchOptions) []SearchResult

SearchTemplates searches and filters templates based on criteria

type SecretFinding

type SecretFinding struct {
	Type     string  `json:"type"`     // api_key, password, private_key, etc.
	Location string  `json:"location"` // field or section where found
	Severity string  `json:"severity"` // critical, high, medium
	Masked   string  `json:"masked"`   // partially masked secret for identification
	Entropy  float64 `json:"entropy"`  // randomness score
}

type SecretsScanner

type SecretsScanner interface {
	ScanForSecrets(ctx context.Context, content string) ([]SecretFinding, error)
}

type SecurityFinding

type SecurityFinding struct {
	Severity    string `yaml:"severity" json:"severity"` // critical, high, medium, low, info
	Category    string `yaml:"category" json:"category"` // vulnerability, misconfiguration, secret, etc.
	Description string `yaml:"description" json:"description"`
	Remediation string `yaml:"remediation,omitempty" json:"remediation,omitempty"`
	CVEID       string `yaml:"cve_id,omitempty" json:"cve_id,omitempty"`
}

SecurityFinding represents a security issue found during scanning

type SecurityMisconfiguration

type SecurityMisconfiguration struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Severity    string `json:"severity"`
	Remediation string `json:"remediation"`
}

type SecurityRule

type SecurityRule struct{}

SecurityRule checks for security best practices

func (*SecurityRule) Name

func (r *SecurityRule) Name() string

func (*SecurityRule) Validate

func (r *SecurityRule) Validate(template *Template) []ValidationResult

type SecurityScanResult

type SecurityScanResult struct {
	Status    string            `yaml:"status" json:"status"` // passed, failed, warning, pending
	ScanDate  time.Time         `yaml:"scan_date" json:"scan_date"`
	Scanner   string            `yaml:"scanner" json:"scanner"` // Tool used for scanning
	Findings  []SecurityFinding `yaml:"findings,omitempty" json:"findings,omitempty"`
	Score     float64           `yaml:"score,omitempty" json:"score,omitempty"`           // Security score (0-100)
	ReportURL string            `yaml:"report_url,omitempty" json:"report_url,omitempty"` // Detailed report link
}

SecurityScanResult contains security scanning information

type ServiceConfig

type ServiceConfig struct {
	Name   string   `yaml:"name" json:"name"`
	Port   int      `yaml:"port,omitempty" json:"port,omitempty"`
	Config []string `yaml:"config,omitempty" json:"config,omitempty"` // Config file lines
	Enable bool     `yaml:"enable,omitempty" json:"enable,omitempty"` // Default: true
}

ServiceConfig defines a service to configure and enable

type ServiceDiff

type ServiceDiff struct {
	Name          string `json:"name"`
	CurrentStatus string `json:"current_status,omitempty"`
	TargetStatus  string `json:"target_status"`
	Action        string `json:"action"` // "configure", "start", "stop", "restart"
	Port          int    `json:"port"`
}

ServiceDiff represents a service change

type ServicePortRule

type ServicePortRule struct{}

ServicePortRule validates service configurations

func (*ServicePortRule) Name

func (r *ServicePortRule) Name() string

func (*ServicePortRule) Validate

func (r *ServicePortRule) Validate(template *Template) []ValidationResult

type ServiceValidator

type ServiceValidator struct{}

ServiceValidator validates service configurations

func (*ServiceValidator) Validate

func (v *ServiceValidator) Validate(template *Template) error

type StateManager

type StateManager interface {
	LoadState() (*types.State, error)
}

StateManager defines the interface for state management operations needed by executor

type SystemsManagerExecutor

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

SystemsManagerExecutor implements RemoteExecutor using AWS Systems Manager

func NewSystemsManagerExecutor

func NewSystemsManagerExecutor(region string, ssmClient SSMClientInterface, s3Client S3ClientInterface, s3Bucket string, stateManager StateManager) *SystemsManagerExecutor

NewSystemsManagerExecutor creates a new Systems Manager-based remote executor

func (*SystemsManagerExecutor) CopyFile

func (e *SystemsManagerExecutor) CopyFile(ctx context.Context, instanceName string, localPath, remotePath string) error

CopyFile copies a file using S3 as intermediate storage for Systems Manager

func (*SystemsManagerExecutor) Execute

func (e *SystemsManagerExecutor) Execute(ctx context.Context, instanceName string, command string) (*ExecutionResult, error)

Execute executes a command via AWS Systems Manager Run Command

func (*SystemsManagerExecutor) ExecuteScript

func (e *SystemsManagerExecutor) ExecuteScript(ctx context.Context, instanceName string, script string) (*ExecutionResult, error)

ExecuteScript executes a script via AWS Systems Manager

func (*SystemsManagerExecutor) GetFile

func (e *SystemsManagerExecutor) GetFile(ctx context.Context, instanceName string, remotePath, localPath string) error

GetFile gets a file using S3 as intermediate storage for Systems Manager

type Template

type Template struct {
	// Basic metadata
	Name            string `yaml:"name" json:"name"`
	Slug            string `yaml:"slug,omitempty" json:"slug,omitempty"` // Short dash-separated name for CLI
	Description     string `yaml:"description" json:"description"`
	LongDescription string `yaml:"long_description,omitempty" json:"long_description,omitempty"` // Detailed description for GUI
	Base            string `yaml:"base" json:"base"`                                             // Base OS (ubuntu-22.04, etc.) or parent template

	// Template inheritance
	Inherits []string `yaml:"inherits,omitempty" json:"inherits,omitempty"` // Parent templates to inherit from

	// Complexity and categorization
	Complexity TemplateComplexity `yaml:"complexity,omitempty" json:"complexity,omitempty"` // simple, moderate, advanced, complex
	Category   string             `yaml:"category,omitempty" json:"category,omitempty"`     // "Machine Learning", "Data Science", etc.
	Domain     string             `yaml:"domain,omitempty" json:"domain,omitempty"`         // "ml", "datascience", "bio", "web", "base"

	// Visual presentation
	Icon     string `yaml:"icon,omitempty" json:"icon,omitempty"`         // Unicode emoji or icon identifier
	Color    string `yaml:"color,omitempty" json:"color,omitempty"`       // Hex color for category theming
	Popular  bool   `yaml:"popular,omitempty" json:"popular,omitempty"`   // Popular badge display
	Featured bool   `yaml:"featured,omitempty" json:"featured,omitempty"` // Featured template (always visible)

	// Connection configuration
	ConnectionType ConnectionType `yaml:"connection_type,omitempty" json:"connection_type,omitempty"` // Explicit connection type (dcv, ssh, auto)

	// Package management strategy
	PackageManager string             `yaml:"package_manager,omitempty" json:"package_manager,omitempty"` // "auto", "apt", "dnf", "conda", "spack", "ami"
	Packages       PackageDefinitions `yaml:"packages,omitempty" json:"packages,omitempty"`

	// AMI configuration (for pre-built images)
	AMIConfig AMIConfig `yaml:"ami_config,omitempty" json:"ami_config,omitempty"`

	// Service configuration
	Services []ServiceConfig `yaml:"services,omitempty" json:"services,omitempty"`

	// User setup
	Users []UserConfig `yaml:"users,omitempty" json:"users,omitempty"`

	// Post-install script
	PostInstall string `yaml:"post_install,omitempty" json:"post_install,omitempty"`

	// File provisioning (S3-backed transfers) (v0.5.7)
	Files []FileConfig `yaml:"files,omitempty" json:"files,omitempty"`

	// User data script for instance initialization
	UserData string `yaml:"user_data,omitempty" json:"user_data,omitempty"`

	// Idle detection configuration
	IdleDetection *IdleDetectionConfig `yaml:"idle_detection,omitempty" json:"idle_detection,omitempty"`

	// Instance defaults
	InstanceDefaults InstanceDefaults `yaml:"instance_defaults,omitempty" json:"instance_defaults,omitempty"`

	// User guidance
	EstimatedLaunchTime int      `yaml:"estimated_launch_time,omitempty" json:"estimated_launch_time,omitempty"` // Launch time in minutes
	Prerequisites       []string `yaml:"prerequisites,omitempty" json:"prerequisites,omitempty"`                 // Required knowledge/skills
	LearningResources   []string `yaml:"learning_resources,omitempty" json:"learning_resources,omitempty"`       // Documentation links

	// Template parameterization
	Parameters map[string]TemplateParameter `yaml:"parameters,omitempty" json:"parameters,omitempty"` // User-configurable parameters
	Variables  map[string]string            `yaml:"variables,omitempty" json:"variables,omitempty"`   // Template-level variables

	// Research user integration (Phase 5A+)
	ResearchUser *research.ResearchUserTemplate `yaml:"research_user,omitempty" json:"research_user,omitempty"`

	// Template metadata
	Version          string            `yaml:"version,omitempty" json:"version,omitempty"`
	ValidationStatus ValidationStatus  `yaml:"validation_status,omitempty" json:"validation_status,omitempty"` // validated, testing, experimental
	Tags             map[string]string `yaml:"tags,omitempty" json:"tags,omitempty"`
	Maintainer       string            `yaml:"maintainer,omitempty" json:"maintainer,omitempty"`
	LastUpdated      time.Time         `yaml:"last_updated,omitempty" json:"last_updated,omitempty"`

	// Marketplace integration (Phase 5B+)
	Marketplace *MarketplaceConfig `yaml:"marketplace,omitempty" json:"marketplace,omitempty"`
}

Template represents a unified Prism template

func GetTemplateInfo

func GetTemplateInfo(name string) (*Template, error)

GetTemplateInfo returns detailed information about a template

func RecommendTemplates

func RecommendTemplates(templates map[string]*Template, userDomain string, maxResults int) []*Template

RecommendTemplates suggests templates based on user history and preferences

type TemplateApplicationEngine

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

TemplateApplicationEngine handles applying templates to running instances

func NewTemplateApplicationEngine

func NewTemplateApplicationEngine(executor RemoteExecutor) *TemplateApplicationEngine

NewTemplateApplicationEngine creates a new template application engine

func (*TemplateApplicationEngine) ApplyTemplate

ApplyTemplate applies a template to a running instance

type TemplateApplicationRecord

type TemplateApplicationRecord struct {
	InstanceName       string    `json:"instance_name"`
	TemplateName       string    `json:"template_name"`
	TemplateVersion    string    `json:"template_version"`
	AppliedAt          time.Time `json:"applied_at"`
	Checkpoint         string    `json:"checkpoint"`
	PackagesInstalled  int       `json:"packages_installed"`
	ServicesConfigured int       `json:"services_configured"`
	UsersCreated       int       `json:"users_created"`
	Warnings           []string  `json:"warnings,omitempty"`
}

TemplateApplicationRecord tracks template application history

type TemplateComplexity

type TemplateComplexity = types.TemplateComplexity

TemplateComplexity is an alias to types.TemplateComplexity (canonical definition)

type TemplateConfig

type TemplateConfig struct {
	// Template directories to scan
	TemplateDirs []string `json:"template_dirs"`

	// Default package manager preference
	DefaultPackageManager string `json:"default_package_manager"`

	// Cache settings
	CacheEnabled    bool `json:"cache_enabled"`
	CacheTTLMinutes int  `json:"cache_ttl_minutes"`

	// Package manager paths
	PackageManagerPaths map[string]string `json:"package_manager_paths"`
}

TemplateConfig represents global template system configuration

func DefaultTemplateConfig

func DefaultTemplateConfig() *TemplateConfig

DefaultTemplateConfig returns the default template configuration

type TemplateDependency

type TemplateDependency struct {
	Name    string `yaml:"name" json:"name"`                           // Template name or slug
	Version string `yaml:"version,omitempty" json:"version,omitempty"` // Version requirement (semver)
	Source  string `yaml:"source,omitempty" json:"source,omitempty"`   // Registry or source location
	Type    string `yaml:"type,omitempty" json:"type,omitempty"`       // inherits, runtime, build
}

TemplateDependency represents a dependency on another template

type TemplateDiff

type TemplateDiff struct {
	PackagesToInstall   []PackageDiff  `json:"packages_to_install"`
	PackagesToRemove    []PackageDiff  `json:"packages_to_remove"`
	ServicesToConfigure []ServiceDiff  `json:"services_to_configure"`
	ServicesToStop      []ServiceDiff  `json:"services_to_stop"`
	UsersToCreate       []UserDiff     `json:"users_to_create"`
	UsersToModify       []UserDiff     `json:"users_to_modify"`
	PortsToOpen         []int          `json:"ports_to_open"`
	ConflictsFound      []ConflictDiff `json:"conflicts_found"`
}

TemplateDiff represents the difference between current state and desired template

func (*TemplateDiff) HasChanges

func (diff *TemplateDiff) HasChanges() bool

HasChanges returns true if the diff contains any changes to apply

func (*TemplateDiff) Summary

func (diff *TemplateDiff) Summary() string

Summary returns a human-readable summary of the diff

type TemplateDiffCalculator

type TemplateDiffCalculator struct{}

TemplateDiffCalculator calculates differences between current state and desired template

func NewTemplateDiffCalculator

func NewTemplateDiffCalculator() *TemplateDiffCalculator

NewTemplateDiffCalculator creates a new template diff calculator

func (*TemplateDiffCalculator) CalculateDiff

func (d *TemplateDiffCalculator) CalculateDiff(currentState *InstanceState, template *Template) (*TemplateDiff, error)

CalculateDiff calculates the differences between current instance state and desired template

type TemplateParameter

type TemplateParameter struct {
	// Basic parameter information
	Name        string `yaml:"name" json:"name"`
	Description string `yaml:"description" json:"description"`
	Type        string `yaml:"type" json:"type"` // string, int, bool, choice

	// Value constraints
	Default  interface{}   `yaml:"default,omitempty" json:"default,omitempty"`
	Choices  []interface{} `yaml:"choices,omitempty" json:"choices,omitempty"`   // For choice type
	Min      interface{}   `yaml:"min,omitempty" json:"min,omitempty"`           // For int type
	Max      interface{}   `yaml:"max,omitempty" json:"max,omitempty"`           // For int type
	Pattern  string        `yaml:"pattern,omitempty" json:"pattern,omitempty"`   // For string type (regex)
	Required bool          `yaml:"required,omitempty" json:"required,omitempty"` // Parameter is required

	// UI presentation
	DisplayName string `yaml:"display_name,omitempty" json:"display_name,omitempty"` // Human-readable name
	Group       string `yaml:"group,omitempty" json:"group,omitempty"`               // Parameter group for UI organization
	Order       int    `yaml:"order,omitempty" json:"order,omitempty"`               // Display order within group
	Hidden      bool   `yaml:"hidden,omitempty" json:"hidden,omitempty"`             // Hide from UI (internal use)

	// Advanced features
	Conditional string `yaml:"conditional,omitempty" json:"conditional,omitempty"` // Show only if condition is met
	Impact      string `yaml:"impact,omitempty" json:"impact,omitempty"`           // cost, performance, security
}

TemplateParameter defines a configurable parameter for templates

type TemplateParameterType

type TemplateParameterType string

TemplateParameterType defines the supported parameter types

const (
	ParameterTypeString TemplateParameterType = "string"
	ParameterTypeInt    TemplateParameterType = "int"
	ParameterTypeBool   TemplateParameterType = "bool"
	ParameterTypeChoice TemplateParameterType = "choice"
	ParameterTypeList   TemplateParameterType = "list"
)

type TemplateParameterValues

type TemplateParameterValues map[string]interface{}

TemplateParameterValues holds user-provided parameter values

func (TemplateParameterValues) Validate

func (values TemplateParameterValues) Validate(parameters map[string]TemplateParameter) []TemplateValidationError

Validate checks if parameter values meet the template parameter constraints

type TemplateParser

type TemplateParser struct {
	// Base AMI mappings for validation (hierarchical structure for version support)
	// Structure: distro -> version -> region -> arch -> AMI
	BaseAMIs map[string]map[string]map[string]map[string]string

	// Package manager strategy
	Strategy *PackageManagerStrategy
}

TemplateParser handles parsing and validation of template YAML files

func NewTemplateParser

func NewTemplateParser() *TemplateParser

NewTemplateParser creates a new template parser

func (*TemplateParser) ParseTemplate

func (p *TemplateParser) ParseTemplate(content []byte) (*Template, error)

ParseTemplate parses a template from YAML content

func (*TemplateParser) ParseTemplateFile

func (p *TemplateParser) ParseTemplateFile(filename string) (*Template, error)

ParseTemplateFile parses a template from a YAML file

func (*TemplateParser) ValidateTemplate

func (p *TemplateParser) ValidateTemplate(template *Template) error

ValidateTemplate validates a template for correctness using Strategy Pattern (SOLID: Single Responsibility)

type TemplateRegistry

type TemplateRegistry struct {
	// Template directories to scan
	TemplateDirs []string

	// Cached templates (indexed by name)
	Templates map[string]*Template

	// Slug index for fast lookup (slug -> template name)
	SlugIndex map[string]string

	// Last scan time
	LastScan time.Time
}

TemplateRegistry manages template discovery and caching

func NewTemplateRegistry

func NewTemplateRegistry(templateDirs []string) *TemplateRegistry

TemplateRegistry implementation

func (*TemplateRegistry) GetTemplate

func (r *TemplateRegistry) GetTemplate(nameOrSlug string) (*Template, error)

GetTemplate retrieves a template by name or slug

func (*TemplateRegistry) ListTemplates

func (r *TemplateRegistry) ListTemplates() map[string]*Template

ListTemplates returns all available templates

func (*TemplateRegistry) ResolveInheritance

func (r *TemplateRegistry) ResolveInheritance() error

ResolveInheritance resolves template inheritance by merging parent templates

func (*TemplateRegistry) ScanTemplates

func (r *TemplateRegistry) ScanTemplates() error

ScanTemplates scans template directories and loads templates

type TemplateResolver

type TemplateResolver struct {
	Parser      *TemplateParser
	ScriptGen   *ScriptGenerator
	AMIRegistry map[string]map[string]map[string]string // template -> region -> arch -> AMI
}

TemplateResolver converts unified templates to runtime templates

func NewTemplateResolver

func NewTemplateResolver() *TemplateResolver

NewTemplateResolver creates a new template resolver

func (*TemplateResolver) CheckAMIAvailability

func (r *TemplateResolver) CheckAMIAvailability(templateName, region, architecture string) string

CheckAMIAvailability checks if a pre-built AMI exists for a template Returns the AMI ID if available, empty string if not

func (*TemplateResolver) ResolveAllTemplates

func (r *TemplateResolver) ResolveAllTemplates(registry *TemplateRegistry, region, architecture string) (map[string]*RuntimeTemplate, error)

ResolveAllTemplates resolves all templates in a registry to runtime templates

func (*TemplateResolver) ResolveTemplate

func (r *TemplateResolver) ResolveTemplate(template *Template, region, architecture string) (*RuntimeTemplate, error)

ResolveTemplate converts a unified template to a runtime template

func (*TemplateResolver) ResolveTemplateWithOptions

func (r *TemplateResolver) ResolveTemplateWithOptions(template *Template, region, architecture, packageManagerOverride, size string) (*RuntimeTemplate, error)

ResolveTemplateWithOptions converts a unified template to a runtime template with package manager override and size scaling

func (*TemplateResolver) UpdateAMIRegistry

func (r *TemplateResolver) UpdateAMIRegistry(ctx context.Context, ssmClient interface{}) error

UpdateAMIRegistry queries AWS SSM Parameter Store and updates the resolver's AMI registry This enables automatic discovery of pre-built AMIs for templates

type TemplateRollbackManager

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

TemplateRollbackManager manages rollback checkpoints and restoration

func NewTemplateRollbackManager

func NewTemplateRollbackManager(executor RemoteExecutor) *TemplateRollbackManager

NewTemplateRollbackManager creates a new template rollback manager

func (*TemplateRollbackManager) CreateCheckpoint

func (r *TemplateRollbackManager) CreateCheckpoint(ctx context.Context, instanceName string) (string, error)

CreateCheckpoint creates a rollback checkpoint before applying template changes

func (*TemplateRollbackManager) ListCheckpoints

func (r *TemplateRollbackManager) ListCheckpoints(ctx context.Context, instanceName string) ([]RollbackCheckpoint, error)

ListCheckpoints lists available rollback checkpoints for an instance

func (*TemplateRollbackManager) RollbackToCheckpoint

func (r *TemplateRollbackManager) RollbackToCheckpoint(ctx context.Context, instanceName, checkpointID string) error

RollbackToCheckpoint rolls back the instance to a previous checkpoint

type TemplateTest

type TemplateTest struct {
	Name        string
	Description string
	Template    string
	TestFunc    TestFunction
}

TemplateTest represents a single test case for a template

type TemplateTester

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

TemplateTester runs tests against templates

func NewTemplateTester

func NewTemplateTester(registry *TemplateRegistry) *TemplateTester

NewTemplateTester creates a new tester with default test suites

func (*TemplateTester) RunAllTests

func (t *TemplateTester) RunAllTests(ctx context.Context) map[string]*TestReport

RunAllTests runs all test suites against all templates

func (*TemplateTester) RunSuite

func (t *TemplateTester) RunSuite(ctx context.Context, suite TestSuite) *TestReport

RunSuite runs a single test suite

type TemplateUsage

type TemplateUsage struct {
	TemplateName      string    `json:"template_name"`
	LaunchCount       int       `json:"launch_count"`
	LastUsed          time.Time `json:"last_used"`
	TotalLaunchTime   int       `json:"total_launch_time_seconds"`
	AverageLaunchTime int       `json:"average_launch_time_seconds"`
	SuccessRate       float64   `json:"success_rate"`
	SuccessCount      int       `json:"success_count"`
	FailureCount      int       `json:"failure_count"`
}

TemplateUsage represents usage data for a single template

type TemplateValidationError

type TemplateValidationError struct {
	Field   string
	Message string
}

TemplateValidationError represents template validation errors

func (*TemplateValidationError) Error

func (e *TemplateValidationError) Error() string

type TemplateValidationOrchestrator

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

TemplateValidationOrchestrator coordinates validation using Strategy Pattern (SOLID: Single Responsibility)

func NewTemplateValidationOrchestrator

func NewTemplateValidationOrchestrator(parser *TemplateParser) *TemplateValidationOrchestrator

NewTemplateValidationOrchestrator creates template validation orchestrator

func (*TemplateValidationOrchestrator) ValidateAll

func (o *TemplateValidationOrchestrator) ValidateAll(template *Template) error

ValidateAll runs all validation strategies

type TemplateValidator

type TemplateValidator interface {
	Validate(template *Template) error
}

TemplateValidator interface for different validation strategies (Strategy Pattern - SOLID)

type TestFunction

type TestFunction func(ctx context.Context, template *Template) TestResult

TestFunction defines a test implementation

type TestReport

type TestReport struct {
	SuiteName   string
	StartTime   time.Time
	EndTime     time.Time
	TotalTests  int
	PassedTests int
	FailedTests int
	TestResults map[string]TestResult
}

TestReport contains results for all tests in a suite

type TestResult

type TestResult struct {
	Passed   bool
	Duration time.Duration
	Message  string
	Details  []string
}

TestResult represents the outcome of a test

type TestSuite

type TestSuite struct {
	Name        string
	Description string
	Tests       []TemplateTest
}

TestSuite represents a collection of template tests

type UsageStats

type UsageStats struct {
	Stats map[string]*TemplateUsage `json:"stats"`
	// contains filtered or unexported fields
}

UsageStats tracks template usage statistics

func GetUsageStats

func GetUsageStats() *UsageStats

GetUsageStats returns the singleton usage stats instance

func (*UsageStats) GetPopularTemplates

func (u *UsageStats) GetPopularTemplates(limit int) []*TemplateUsage

GetPopularTemplates returns the most frequently used templates

func (*UsageStats) GetRecentlyUsedTemplates

func (u *UsageStats) GetRecentlyUsedTemplates(limit int) []*TemplateUsage

GetRecentlyUsedTemplates returns templates used recently

func (*UsageStats) GetTemplateUsage

func (u *UsageStats) GetTemplateUsage(templateName string) *TemplateUsage

GetTemplateUsage returns usage stats for a specific template

func (*UsageStats) RecordLaunch

func (u *UsageStats) RecordLaunch(templateName string, success bool, launchTimeSeconds int)

RecordLaunch records a template launch attempt

type UserConfig

type UserConfig struct {
	Name   string   `yaml:"name" json:"name"`
	Groups []string `yaml:"groups,omitempty" json:"groups,omitempty"`
	Shell  string   `yaml:"shell,omitempty" json:"shell,omitempty"` // Default: /bin/bash
}

UserConfig defines a user to create

type UserConfigRule

type UserConfigRule struct{}

UserConfigRule validates user configuration

func (*UserConfigRule) Name

func (r *UserConfigRule) Name() string

func (*UserConfigRule) Validate

func (r *UserConfigRule) Validate(template *Template) []ValidationResult

type UserData

type UserData struct {
	Name   string
	Groups []string
	Shell  string
}

UserData contains processed user data for script generation

type UserDiff

type UserDiff struct {
	Name          string   `json:"name"`
	CurrentGroups []string `json:"current_groups,omitempty"`
	TargetGroups  []string `json:"target_groups"`
	Action        string   `json:"action"` // "create", "modify", "add_to_groups"
}

UserDiff represents a user account change

type UserValidator

type UserValidator struct{}

UserValidator validates user configurations

func (*UserValidator) Validate

func (v *UserValidator) Validate(template *Template) error

type ValidationConfig

type ValidationConfig struct {
	// Security thresholds
	MaxCriticalVulnerabilities int     `json:"max_critical_vulnerabilities"`
	MaxHighVulnerabilities     int     `json:"max_high_vulnerabilities"`
	MinSecurityScore           float64 `json:"min_security_score"`

	// Quality requirements
	RequireDescription   bool `json:"require_description"`
	RequireLicense       bool `json:"require_license"`
	RequireDocumentation bool `json:"require_documentation"`
	MinDescriptionLength int  `json:"min_description_length"`
	MaxLaunchTime        int  `json:"max_launch_time_minutes"`

	// Package validation
	AllowedPackageManagers []string `json:"allowed_package_managers"`
	BlockedPackages        []string `json:"blocked_packages"`
	RequirePackageVersions bool     `json:"require_package_versions"`

	// Content restrictions
	ForbiddenPatterns []string `json:"forbidden_patterns"`
	AllowedDomains    []string `json:"allowed_domains"`
	MaxTemplateSize   int64    `json:"max_template_size_bytes"`

	// Registry-specific rules
	RegistryType  RegistryType `json:"registry_type"`
	EnforcePolicy bool         `json:"enforce_policy"`
}

ValidationConfig defines validation rules and thresholds

type ValidationLevel

type ValidationLevel string

ValidationLevel represents the severity of a validation issue

const (
	ValidationError   ValidationLevel = "error"   // Must fix before template can be used
	ValidationWarning ValidationLevel = "warning" // Should fix but not blocking
	ValidationInfo    ValidationLevel = "info"    // Suggestions for improvement
)

type ValidationReport

type ValidationReport struct {
	TemplateName string
	Valid        bool
	Results      []ValidationResult
	ErrorCount   int
	WarningCount int
	InfoCount    int
}

ValidationReport contains all validation results for a template

type ValidationResult

type ValidationResult struct {
	Level   ValidationLevel
	Field   string
	Message string
	Line    int // Optional line number in template file
}

ValidationResult represents a single validation finding

type ValidationRule

type ValidationRule interface {
	Name() string
	Validate(template *Template) []ValidationResult
}

ValidationRule defines a validation check

type ValidationStatus

type ValidationStatus = types.ValidationStatus

ValidationStatus is an alias to types.ValidationStatus (canonical definition)

const (
	ValidationValidated                     = types.ValidationStatusValid
	ValidationTesting      ValidationStatus = "testing"      // Keep local (not in types package)
	ValidationExperimental ValidationStatus = "experimental" // Keep local (not in types package)
	ValidationFailed       ValidationStatus = "failed"       // Keep local (not in types package)
)

Alias constants for backward compatibility

type ValidationTest

type ValidationTest struct {
	Name       string    `yaml:"name" json:"name"`
	Status     string    `yaml:"status" json:"status"` // passed, failed, skipped
	ExecutedAt time.Time `yaml:"executed_at" json:"executed_at"`
	Duration   string    `yaml:"duration,omitempty" json:"duration,omitempty"`
	Message    string    `yaml:"message,omitempty" json:"message,omitempty"`
	Details    string    `yaml:"details,omitempty" json:"details,omitempty"`
}

ValidationTest represents automated template validation results

type VersionResolver

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

VersionResolver handles dynamic version resolution for templates This enables the universal version system (--version flag) for both OS and software versions

func NewVersionResolver

func NewVersionResolver(parser *TemplateParser) *VersionResolver

NewVersionResolver creates a new version resolver

func (*VersionResolver) GetSupportedVersions

func (vr *VersionResolver) GetSupportedVersions(distro string) ([]string, error)

GetSupportedVersions returns all supported versions for a given distro

func (*VersionResolver) GetVersionAliases

func (vr *VersionResolver) GetVersionAliases(distro string) map[string]string

GetVersionAliases returns available version aliases for a given distro

func (*VersionResolver) ResolveAMI

func (vr *VersionResolver) ResolveAMI(templateBase, version, region, architecture string) (string, error)

ResolveAMI resolves an AMI based on template base OS, version, region, and architecture

Parameters:

  • templateBase: The base OS distro family (e.g., "ubuntu", "rocky", "amazonlinux", "alpine")
  • version: The OS version (e.g., "24.04", "9.5", "latest", "lts") or empty for default
  • region: AWS region (e.g., "us-west-2")
  • architecture: Architecture (e.g., "x86_64", "arm64")

Returns the AMI ID or an error if resolution fails

func (*VersionResolver) ResolveTemplateVersion

func (vr *VersionResolver) ResolveTemplateVersion(template *Template, userOverride string) (string, error)

ResolveTemplateVersion resolves version requirements from a template

func (*VersionResolver) ValidateVersion

func (vr *VersionResolver) ValidateVersion(distro, version string) error

ValidateVersion checks if a version is valid for a given distro

type VulnerabilityInfo

type VulnerabilityInfo struct {
	CVEID       string  `json:"cve_id"`
	Package     string  `json:"package"`
	Version     string  `json:"version"`
	Severity    string  `json:"severity"`
	Description string  `json:"description"`
	FixVersion  string  `json:"fix_version,omitempty"`
	Score       float64 `json:"cvss_score,omitempty"`
}

Supporting types for detailed analysis

Jump to

Keyboard shortcuts

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