models

package
v0.0.0-...-b8e807e Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: MIT Imports: 11 Imported by: 0

README

Models Package

Overview

The models package contains all domain models for the Developer Mesh AI Agent Orchestration Platform. It provides type-safe data structures for multi-agent coordination and distributed task processing.

Core Domain Models

Agent Models

The agent models represent AI agents in the system:

// Agent represents an AI agent in the system
type Agent struct {
    ID           string                 `json:"id" db:"id"`
    TenantID     uuid.UUID              `json:"tenant_id" db:"tenant_id"`
    Name         string                 `json:"name" db:"name"`
    ModelID      string                 `json:"model_id" db:"model_id"`
    Type         string                 `json:"type" db:"type"`
    Status       string                 `json:"status" db:"status"` // available, busy, offline
    Capabilities []string               `json:"capabilities" db:"capabilities"`
    Metadata     map[string]interface{} `json:"metadata" db:"metadata"`
    CreatedAt    time.Time              `json:"created_at" db:"created_at"`
    UpdatedAt    time.Time              `json:"updated_at" db:"updated_at"`
    LastSeenAt   *time.Time             `json:"last_seen_at" db:"last_seen_at"`
}

// Agent States with validation (in agent_status.go)
- AgentStatusOffline   → Starting
- AgentStatusStarting  → Active/Error
- AgentStatusActive    → Draining/Maintenance/Error/Stopping
- AgentStatusDraining  → Inactive/Error
- AgentStatusInactive  → Active/Maintenance/Stopping
- AgentStatusMaintenance → Active/Inactive/Stopping
- AgentStatusError     → Stopping/Maintenance
- AgentStatusStopping  → Offline

Key Features:

  • State machine with transition validation
  • Agent capabilities tracking
  • Workload metrics tracking (CPU, memory, tasks, etc.)
  • Health check results
  • Metrics collection integration
Task Models

Tasks represent units of work that can be assigned to agents:

// Task represents a unit of work in the multi-agent system
type Task struct {
    ID             uuid.UUID    `json:"id" db:"id"`
    TenantID       uuid.UUID    `json:"tenant_id" db:"tenant_id"`
    Type           string       `json:"type" db:"type"`
    Status         TaskStatus   `json:"status" db:"status"`
    Priority       TaskPriority `json:"priority" db:"priority"`
    
    // Agent relationships
    CreatedBy  string  `json:"created_by" db:"created_by"`
    AssignedTo *string `json:"assigned_to,omitempty" db:"assigned_to"`
    
    // Task hierarchy
    ParentTaskID *uuid.UUID `json:"parent_task_id,omitempty" db:"parent_task_id"`
    
    // Task data
    Title       string  `json:"title" db:"title"`
    Description string  `json:"description,omitempty" db:"description"`
    Parameters  JSONMap `json:"parameters" db:"parameters"`
    Result      JSONMap `json:"result,omitempty" db:"result"`
    Error       string  `json:"error,omitempty" db:"error"`
    
    // Execution control
    MaxRetries     int `json:"max_retries" db:"max_retries"`
    RetryCount     int `json:"retry_count" db:"retry_count"`
    TimeoutSeconds int `json:"timeout_seconds" db:"timeout_seconds"`
    
    // Timestamps
    CreatedAt   time.Time  `json:"created_at" db:"created_at"`
    AssignedAt  *time.Time `json:"assigned_at,omitempty" db:"assigned_at"`
    StartedAt   *time.Time `json:"started_at,omitempty" db:"started_at"`
    CompletedAt *time.Time `json:"completed_at,omitempty" db:"completed_at"`
    
    // Optimistic locking
    Version int `json:"version" db:"version"`
}

// Task States (no state machine validation in implementation)
- TaskStatusPending
- TaskStatusAssigned
- TaskStatusAccepted
- TaskStatusRejected
- TaskStatusInProgress
- TaskStatusCompleted
- TaskStatusFailed
- TaskStatusCancelled
- TaskStatusTimeout

Features:

  • Task delegation tracking
  • Parent-child task relationships
  • Retry logic based on retry count
  • Priority levels (low, normal, high, critical)
  • Timeout enforcement
  • Version-based optimistic locking
Workflow Models

Workflows coordinate multi-agent task execution:

// Workflow represents a multi-agent workflow definition
type Workflow struct {
    ID          uuid.UUID      `json:"id" db:"id"`
    TenantID    uuid.UUID      `json:"tenant_id" db:"tenant_id"`
    Name        string         `json:"name" db:"name"`
    Type        WorkflowType   `json:"type" db:"type"`
    Version     int            `json:"version" db:"version"`
    CreatedBy   string         `json:"created_by" db:"created_by"`
    Agents      JSONMap        `json:"agents" db:"agents"`
    Steps       WorkflowSteps  `json:"steps" db:"steps"`
    Config      JSONMap        `json:"config" db:"config"`
    Description string         `json:"description,omitempty" db:"description"`
    Tags        pq.StringArray `json:"tags,omitempty" db:"tags"`
    IsActive    bool           `json:"is_active" db:"is_active"`
    CreatedAt   time.Time      `json:"created_at" db:"created_at"`
    UpdatedAt   time.Time      `json:"updated_at" db:"updated_at"`
}

// WorkflowExecution represents a running or completed workflow instance
type WorkflowExecution struct {
    ID          uuid.UUID      `json:"id" db:"id"`
    WorkflowID  uuid.UUID      `json:"workflow_id" db:"workflow_id"`
    TenantID    uuid.UUID      `json:"tenant_id" db:"tenant_id"`
    Status      WorkflowStatus `json:"status" db:"status"`
    Context     JSONMap        `json:"context" db:"context"`
    State       JSONMap        `json:"state" db:"state"`
    InitiatedBy string         `json:"initiated_by" db:"initiated_by"`
    Error       string         `json:"error,omitempty" db:"error"`
    StartedAt   time.Time      `json:"started_at" db:"started_at"`
    CompletedAt *time.Time     `json:"completed_at,omitempty" db:"completed_at"`
}

// Workflow Types (implemented)
- WorkflowTypeSequential    // Steps run one after another
- WorkflowTypeParallel      // Steps run simultaneously
- WorkflowTypeConditional   // Conditional execution
- WorkflowTypeCollaborative // Multi-agent collaboration

Workflow Execution States:

  • WorkflowStatusPending
  • WorkflowStatusRunning
  • WorkflowStatusPaused
  • WorkflowStatusCompleted
  • WorkflowStatusFailed
  • WorkflowStatusCancelled
  • WorkflowStatusTimeout
Document Models

Documents support collaborative editing:

// SharedDocument represents a collaborative document
type SharedDocument struct {
    ID            uuid.UUID  `json:"id" db:"id"`
    WorkspaceID   uuid.UUID  `json:"workspace_id" db:"workspace_id"`
    TenantID      uuid.UUID  `json:"tenant_id" db:"tenant_id"`
    Type          string     `json:"type" db:"type"`
    Title         string     `json:"title" db:"title"`
    Content       string     `json:"content" db:"content"`
    ContentType   string     `json:"content_type" db:"content_type"`
    Version       int64      `json:"version" db:"version"`
    CreatedBy     string     `json:"created_by" db:"created_by"`
    Metadata      JSONMap    `json:"metadata" db:"metadata"`
    LockedBy      *string    `json:"locked_by,omitempty" db:"locked_by"`
    LockedAt      *time.Time `json:"locked_at,omitempty" db:"locked_at"`
    LockExpiresAt *time.Time `json:"lock_expires_at,omitempty" db:"lock_expires_at"`
    CreatedAt     time.Time  `json:"created_at" db:"created_at"`
    UpdatedAt     time.Time  `json:"updated_at" db:"updated_at"`
}

// DocumentOperation represents a CRDT operation on a document
type DocumentOperation struct {
    ID                uuid.UUID  `json:"id" db:"id"`
    DocumentID        uuid.UUID  `json:"document_id" db:"document_id"`
    TenantID          uuid.UUID  `json:"tenant_id" db:"tenant_id"`
    AgentID           string     `json:"agent_id" db:"agent_id"`
    OperationType     string     `json:"operation_type" db:"operation_type"`
    OperationData     JSONMap    `json:"operation_data" db:"operation_data"`
    VectorClock       JSONMap    `json:"vector_clock" db:"vector_clock"`
    SequenceNumber    int64      `json:"sequence_number" db:"sequence_number"`
    Timestamp         time.Time  `json:"timestamp" db:"timestamp"`
    ParentOperationID *uuid.UUID `json:"parent_operation_id,omitempty" db:"parent_operation_id"`
    IsApplied         bool       `json:"is_applied" db:"is_applied"`
}

Features:

  • Document locking mechanism
  • CRDT operations for conflict-free editing
  • Vector clocks for operation ordering
  • Document snapshots for version history
  • Conflict resolution tracking

Binary WebSocket Protocol

High-performance binary protocol for agent communication:

// BinaryHeader represents the binary protocol header (24 bytes)
type BinaryHeader struct {
    Magic      uint32 // 0x4D435057 "MCPW"
    Version    uint8  // Protocol version (1)
    Type       uint8  // Message type
    Flags      uint16 // Compression, encryption flags
    SequenceID uint64 // Message sequence ID
    Method     uint16 // Method enum (not string)
    Reserved   uint16 // Padding for alignment
    DataSize   uint32 // Payload size
}

// Method enums for binary protocol
const (
    MethodInitialize       uint16 = 1
    MethodToolList         uint16 = 2
    MethodToolExecute      uint16 = 3
    MethodContextGet       uint16 = 4
    MethodContextUpdate    uint16 = 5
    MethodEventSubscribe   uint16 = 6
    MethodEventUnsubscribe uint16 = 7
    MethodPing             uint16 = 8
    MethodPong             uint16 = 9
)

// Flag bits
const (
    FlagCompressed uint16 = 1 << 0
    FlagEncrypted  uint16 = 1 << 1
    FlagBatch      uint16 = 1 << 2
)

Implementation Features:

  • Magic number "MCPW" (0x4D435057) for protocol identification
  • Binary encoding with BigEndian byte order
  • Optional compression flag
  • Method enums for fast routing
  • 1MB maximum payload size
  • Sequence ID for message tracking

Additional Features

Task Delegation
// TaskDelegation represents a task being delegated between agents
type TaskDelegation struct {
    ID             uuid.UUID      `json:"id" db:"id"`
    TaskID         uuid.UUID      `json:"task_id" db:"task_id"`
    FromAgentID    string         `json:"from_agent_id" db:"from_agent_id"`
    ToAgentID      string         `json:"to_agent_id" db:"to_agent_id"`
    Reason         string         `json:"reason,omitempty" db:"reason"`
    DelegationType DelegationType `json:"delegation_type" db:"delegation_type"`
    Metadata       JSONMap        `json:"metadata" db:"metadata"`
    DelegatedAt    time.Time      `json:"delegated_at" db:"delegated_at"`
}

// Delegation Types
- DelegationManual      // Manual delegation
- DelegationAutomatic   // Automatic delegation
- DelegationFailover    // Failover delegation
- DelegationLoadBalance // Load balance delegation
Workflow Steps
// WorkflowStep represents a step in a workflow
type WorkflowStep struct {
    ID              string                 `json:"id"`
    Name            string                 `json:"name"`
    Description     string                 `json:"description,omitempty"`
    Type            string                 `json:"type"`
    Action          string                 `json:"action"`
    AgentID         string                 `json:"agent_id"`
    Input           map[string]interface{} `json:"input"`
    Config          map[string]interface{} `json:"config"`
    TimeoutSeconds  int                    `json:"timeout_seconds,omitempty"`
    Retries         int                    `json:"retries"`
    RetryPolicy     WorkflowRetryPolicy    `json:"retry_policy,omitempty"`
    ContinueOnError bool                   `json:"continue_on_error"`
    Dependencies    []string               `json:"dependencies"`
    OnFailure       string                 `json:"on_failure,omitempty"`
}
State Machine Features

The agent status model includes state machine validation:

// Valid state transitions
var validAgentTransitions = map[AgentStatus][]AgentStatus{
    AgentStatusOffline:     {AgentStatusStarting},
    AgentStatusStarting:    {AgentStatusActive, AgentStatusError},
    AgentStatusActive:      {AgentStatusDraining, AgentStatusMaintenance, AgentStatusError, AgentStatusStopping},
    // ... etc
}

// CanTransitionTo checks if a status transition is valid
func (s AgentStatus) CanTransitionTo(target AgentStatus) bool

// TransitionTo performs a validated state transition with metrics
func (s AgentStatus) TransitionTo(target AgentStatus, metrics MetricsClient) (AgentStatus, error)

JSONMap Utility

Flexible map type for dynamic data with database serialization:

type JSONMap map[string]interface{}

// Implements driver.Valuer for database serialization
func (m JSONMap) Value() (driver.Value, error)

// Implements sql.Scanner for database deserialization
func (m *JSONMap) Scan(value interface{}) error

Extended Models

Workflow Templates
// WorkflowTemplate represents a reusable workflow template
type WorkflowTemplate struct {
    ID          uuid.UUID              `json:"id" db:"id"`
    Name        string                 `json:"name" db:"name"`
    Description string                 `json:"description" db:"description"`
    Category    string                 `json:"category" db:"category"`
    Definition  map[string]interface{} `json:"definition" db:"definition"`
    Parameters  []TemplateParameter    `json:"parameters" db:"parameters"`
    CreatedBy   string                 `json:"created_by" db:"created_by"`
    CreatedAt   time.Time              `json:"created_at" db:"created_at"`
    UpdatedAt   time.Time              `json:"updated_at" db:"updated_at"`
}
Execution Tracking
// ExecutionStatus represents detailed workflow execution status
type ExecutionStatus struct {
    ExecutionID    uuid.UUID              `json:"execution_id"`
    WorkflowID     uuid.UUID              `json:"workflow_id"`
    Status         string                 `json:"status"`
    Progress       int                    `json:"progress"`
    CurrentSteps   []string               `json:"current_steps"`
    CompletedSteps int                    `json:"completed_steps"`
    TotalSteps     int                    `json:"total_steps"`
    StartedAt      time.Time              `json:"started_at"`
    UpdatedAt      time.Time              `json:"updated_at"`
    EstimatedEnd   *time.Time             `json:"estimated_end,omitempty"`
    Metrics        map[string]interface{} `json:"metrics,omitempty"`
}

Best Practices

1. State Management

For agent status transitions, use the validation methods:

// Good
if status.CanTransitionTo(newStatus) {
    status, err = status.TransitionTo(newStatus, metrics)
}

// Note: Most models don't have built-in state validation
2. Version Control

Use version fields for optimistic locking (where available):

// Task has version field
task.Version++
// Workflow has version field  
workflow.Version++
3. Binary Protocol

Use the provided header parsing/writing functions:

// Parse binary header
header, err := ParseBinaryHeader(reader)

// Write binary header
err := WriteBinaryHeader(writer, header)
4. Type Safety

Use the defined constants for statuses and types:

// Use constants
task.Status = TaskStatusInProgress
workflow.Status = WorkflowStatusRunning

// Not strings
task.Status = "in_progress" // Avoid

Testing

The models package is designed for testing:

# Run tests
go test ./pkg/models/...

# With coverage
go test -cover ./pkg/models/...

Implementation Status

Implemented:

  • Basic domain models (Agent, Task, Workflow, Document)
  • Binary WebSocket protocol with MCPW magic
  • State machine for agent status transitions
  • Task delegation tracking
  • Workflow execution tracking
  • Document collaboration with CRDT operations
  • JSONMap utility with DB serialization

Not Implemented:

  • State validation for tasks and workflows
  • Advanced coordination patterns (MapReduce, etc.)
  • Protocol buffer support
  • GraphQL schema generation
  • Comprehensive helper methods on JSONMap

References

Documentation

Overview

This file contains legacy entity methods for backward compatibility. The primary entity type definitions are now in relationships.go

Package models provides common data models used across the developer-mesh workspace. It contains definitions for entity relationships and connection models that represent relationships between various GitHub entities.

This package is part of the Go workspace migration and provides a standardized location for all shared model definitions.

Index

Constants

View Source
const (
	HarnessQueryTypePipeline          = "pipeline"
	HarnessQueryTypeCIBuild           = "ci_build"
	HarnessQueryTypeCDDeployment      = "cd_deployment"
	HarnessQueryTypeSTOExperiment     = "sto_experiment"
	HarnessQueryTypeFeatureFlag       = "feature_flag"
	HarnessQueryTypeCCMCost           = "ccm_cost"
	HarnessQueryTypeCCMRecommendation = "ccm_recommendation"
	HarnessQueryTypeCCMBudget         = "ccm_budget"
	HarnessQueryTypeCCMAnomaly        = "ccm_anomaly"
)

Harness query types

View Source
const (
	SonarQubeQueryTypeProject     = "project"
	SonarQubeQueryTypeQualityGate = "quality_gate"
	SonarQubeQueryTypeIssues      = "issues"
	SonarQubeQueryTypeMetrics     = "metrics"
)

SonarQube query types

View Source
const (
	ArtifactoryQueryTypeRepository = "repository"
	ArtifactoryQueryTypeArtifact   = "artifact"
	ArtifactoryQueryTypeBuild      = "build"
	ArtifactoryQueryTypeStorage    = "storage"
)

Artifactory query types

View Source
const (
	XrayQueryTypeSummary         = "summary"
	XrayQueryTypeVulnerabilities = "vulnerabilities"
	XrayQueryTypeLicenses        = "licenses"
	XrayQueryTypeScans           = "scans"
)

Xray query types

View Source
const (
	AgentTypeIDE        = "ide"
	AgentTypeSlack      = "slack"
	AgentTypeMonitoring = "monitoring"
	AgentTypeCI         = "ci"
	AgentTypeCustom     = "custom"
	AgentTypeWebhook    = "webhook"
	AgentTypeAPI        = "api"
)

Agent Type constants

View Source
const (
	ManifestStatusActive    = "active"
	ManifestStatusInactive  = "inactive"
	ManifestStatusPending   = "pending"
	ManifestStatusSuspended = "suspended"
	ManifestStatusArchived  = "archived"
)

Manifest Status constants

View Source
const (
	RegistrationStatusPending = "pending"
	RegistrationStatusActive  = "active"
	RegistrationStatusExpired = "expired"
	RegistrationStatusRevoked = "revoked"
	RegistrationStatusFailed  = "failed"
)

Registration Status constants

View Source
const (
	RegistrationHealthHealthy   = "healthy"
	RegistrationHealthUnhealthy = "unhealthy"
	RegistrationHealthDegraded  = "degraded"
	RegistrationHealthUnknown   = "unknown"
)

Registration Health Status constants

View Source
const (
	ChannelTypeWebSocket = "websocket"
	ChannelTypeHTTP      = "http"
	ChannelTypeGRPC      = "grpc"
	ChannelTypeRedis     = "redis"
	ChannelTypeKafka     = "kafka"
	ChannelTypeSQS       = "sqs"
)

Channel Type constants

View Source
const (
	CapabilityTypeCommand      = "command"
	CapabilityTypeQuery        = "query"
	CapabilityTypeNotification = "notification"
	CapabilityTypeIntegration  = "integration"
	CapabilityTypeAutomation   = "automation"
	CapabilityTypeMonitoring   = "monitoring"
)

Capability Type constants

View Source
const (
	IsolationModeStrict  = "strict"  // No cross-tenant access
	IsolationModeRelaxed = "relaxed" // Allow configured cross-tenant access
	IsolationModeOpen    = "open"    // Allow all cross-tenant access within org
)

IsolationMode constants

View Source
const (
	TenantTypeStandard    = "standard"
	TenantTypeAdmin       = "admin"
	TenantTypeIntegration = "integration"
)

TenantType constants

View Source
const (
	IsolationLevelNormal     = "normal"
	IsolationLevelRestricted = "restricted"
	IsolationLevelElevated   = "elevated"
)

IsolationLevel constants

View Source
const (
	AccessTypeRead     = "read"
	AccessTypeWrite    = "write"
	AccessTypeAdmin    = "admin"
	AccessTypeDelegate = "delegate"
)

AccessType constants

View Source
const (
	// DirectionOutgoing represents a relationship from source to target
	DirectionOutgoing = "outgoing"
	// DirectionIncoming represents a relationship from target to source
	DirectionIncoming = "incoming"
	// DirectionBidirectional represents a bidirectional relationship
	DirectionBidirectional = "bidirectional"
)

Relationship directions

View Source
const (
	StepStatusPending          = "pending"
	StepStatusQueued           = "queued"
	StepStatusRunning          = "running"
	StepStatusCompleted        = "completed"
	StepStatusFailed           = "failed"
	StepStatusSkipped          = "skipped"
	StepStatusRetrying         = "retrying"
	StepStatusCancelling       = "cancelling"
	StepStatusCancelled        = "cancelled"
	StepStatusTimeout          = "timeout"
	StepStatusAwaitingApproval = "awaiting_approval"
)

Step status constants

View Source
const (
	WorkflowExecutionStatusPending   = WorkflowStatusPending
	WorkflowExecutionStatusRunning   = WorkflowStatusRunning
	WorkflowExecutionStatusPaused    = WorkflowStatusPaused
	WorkflowExecutionStatusCompleted = WorkflowStatusCompleted
	WorkflowExecutionStatusFailed    = WorkflowStatusFailed
	WorkflowExecutionStatusCancelled = WorkflowStatusCancelled
	WorkflowExecutionStatusTimeout   = WorkflowStatusTimeout
)

Alias the existing WorkflowStatus constants for compatibility

Variables

View Source
var RolePermissions = map[WorkspaceMemberRole][]string{
	WorkspaceMemberRoleOwner:     {"*"},
	WorkspaceMemberRoleAdmin:     {"read", "write", "delete", "invite", "settings"},
	WorkspaceMemberRoleEditor:    {"read", "write", "comment"},
	WorkspaceMemberRoleCommenter: {"read", "comment"},
	WorkspaceMemberRoleViewer:    {"read"},
	WorkspaceMemberRoleGuest:     {"read:public"},
}

RolePermissions defines what each role can do

StepTransitions defines valid step state transitions

View Source
var WorkflowTransitions = map[WorkflowStatus][]WorkflowStatus{
	WorkflowStatusPending:   {WorkflowStatusRunning, WorkflowStatusCancelled},
	WorkflowStatusRunning:   {WorkflowStatusPaused, WorkflowStatusCompleted, WorkflowStatusFailed, WorkflowStatusCancelled, WorkflowStatusTimeout},
	WorkflowStatusPaused:    {WorkflowStatusRunning, WorkflowStatusCancelled, WorkflowStatusTimeout},
	WorkflowStatusCompleted: {},
	WorkflowStatusFailed:    {},
	WorkflowStatusCancelled: {},
	WorkflowStatusTimeout:   {},
}

WorkflowTransitions defines valid state transitions

Functions

func GenerateRelationshipID

func GenerateRelationshipID(
	relType RelationshipType,
	source EntityID,
	target EntityID,
	direction string,
) string

GenerateRelationshipID creates a deterministic ID for a relationship

func LegacyGenerateRelationshipID

func LegacyGenerateRelationshipID(arg1 any, arg2 any, arg3 any, arg4 ...any) string

LegacyGenerateRelationshipID generates a unique ID for a relationship Takes either (source, target, relType) or (relType, source, target, direction) - the latter ignores direction This is a legacy implementation for backward compatibility with existing code

Types

type APIChangeType

type APIChangeType string

APIChangeType represents the type of API change

const (
	APIChangeAdded      APIChangeType = "added"
	APIChangeModified   APIChangeType = "modified"
	APIChangeDeprecated APIChangeType = "deprecated"
	APIChangeRemoved    APIChangeType = "removed"
)

type ActionParameter

type ActionParameter struct {
	Name        string      `json:"name"`
	In          string      `json:"in"` // query, path, header, body
	Required    bool        `json:"required"`
	Description string      `json:"description,omitempty"`
	Type        string      `json:"type"`
	Default     interface{} `json:"default,omitempty"`
}

ActionParameter represents a parameter for a tool action

type Agent

type Agent struct {
	ID           string                 `json:"id" db:"id"`
	TenantID     uuid.UUID              `json:"tenant_id" db:"tenant_id"`
	Name         string                 `json:"name" db:"name"`
	ModelID      string                 `json:"model_id" db:"model_id"`
	Type         string                 `json:"type" db:"type"`
	Status       string                 `json:"status" db:"status"` // available, busy, offline
	Capabilities []string               `json:"capabilities" db:"capabilities"`
	Metadata     map[string]interface{} `json:"metadata" db:"metadata"`
	CreatedAt    time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at" db:"updated_at"`
	LastSeenAt   *time.Time             `json:"last_seen_at" db:"last_seen_at"`

	// Attribution for virtual/session agents (not stored in DB, computed)
	Attribution *AgentAttribution `json:"attribution,omitempty" db:"-"`
}

Agent represents an AI agent in the system

type AgentAttribution

type AgentAttribution struct {
	Level        AttributionLevel `json:"level"`                  // Attribution level
	PrimaryID    string           `json:"primary_id"`             // Primary identifier for attribution
	SecondaryID  *string          `json:"secondary_id,omitempty"` // Secondary identifier (e.g., edge_mcp_id when user is primary)
	CostCenter   string           `json:"cost_center"`            // Who accumulates the costs
	BillableUnit string           `json:"billable_unit"`          // Who gets charged (usually tenant_id)
	UserID       *uuid.UUID       `json:"user_id,omitempty"`      // User ID if available
	EdgeMCPID    *string          `json:"edge_mcp_id,omitempty"`  // Edge MCP machine identity
	SessionID    *string          `json:"session_id,omitempty"`   // Session identifier
}

AgentAttribution provides hierarchical cost and audit attribution

func ResolveAttribution

func ResolveAttribution(session *EdgeMCPSession) AgentAttribution

ResolveAttribution creates attribution metadata from session information Implements hierarchical attribution following 2025 best practices

type AgentCapability

type AgentCapability string

AgentCapability defines what an agent can do

const (
	AgentCapabilityCompute     AgentCapability = "compute"
	AgentCapabilityStorage     AgentCapability = "storage"
	AgentCapabilityNetwork     AgentCapability = "network"
	AgentCapabilityOrchestrate AgentCapability = "orchestrate"
	AgentCapabilityAnalyze     AgentCapability = "analyze"
	AgentCapabilitySecure      AgentCapability = "secure"
	AgentCapabilitySpecialized AgentCapability = "specialized"
)

type AgentChannel

type AgentChannel struct {
	ID             uuid.UUID  `json:"id" db:"id"`
	RegistrationID uuid.UUID  `json:"registration_id" db:"registration_id"`
	ChannelType    string     `json:"channel_type" db:"channel_type"`
	ChannelConfig  JSONMap    `json:"channel_config" db:"channel_config"`
	Priority       int        `json:"priority" db:"priority"`
	Active         bool       `json:"active" db:"active"`
	LastMessageAt  *time.Time `json:"last_message_at" db:"last_message_at"`
	CreatedAt      time.Time  `json:"created_at" db:"created_at"`
}

AgentChannel represents a communication channel for an agent

func (*AgentChannel) IsHighPriority

func (ac *AgentChannel) IsHighPriority() bool

IsHighPriority checks if the channel is high priority

type AgentContext

type AgentContext struct {
	AgentType   string `json:"agent_type"` // ide, cli, ci, browser, slack, etc.
	AgentID     string `json:"agent_id"`
	UserID      string `json:"user_id"`
	SessionID   string `json:"session_id"`
	Environment string `json:"environment"` // development, staging, production
}

AgentContext provides context about the agent making the request

type AgentFilter

type AgentFilter struct {
	ID       string `json:"id,omitempty"`
	TenantID string `json:"tenant_id,omitempty"`
	Name     string `json:"name,omitempty"`
	ModelID  string `json:"model_id,omitempty"`
}

AgentFilter defines filter criteria for agent operations

type AgentHealth

type AgentHealth struct {
	Status    HealthStatus           `json:"status"`
	LastCheck time.Time              `json:"last_check"`
	NextCheck time.Time              `json:"next_check"`
	Checks    map[string]CheckResult `json:"checks"`
	Message   string                 `json:"message,omitempty"`
}

AgentHealth represents health check results

type AgentManifest

type AgentManifest struct {
	ID               uuid.UUID  `json:"id" db:"id"`
	OrganizationID   uuid.UUID  `json:"organization_id" db:"organization_id"`
	AgentID          string     `json:"agent_id" db:"agent_id"`
	AgentType        string     `json:"agent_type" db:"agent_type"`
	Name             string     `json:"name" db:"name"`
	Version          string     `json:"version" db:"version"`
	Description      string     `json:"description" db:"description"`
	Capabilities     JSONMap    `json:"capabilities" db:"capabilities"`
	Requirements     JSONMap    `json:"requirements" db:"requirements"`
	ConnectionConfig JSONMap    `json:"connection_config" db:"connection_config"`
	AuthConfig       JSONMap    `json:"auth_config" db:"auth_config"`
	Metadata         JSONMap    `json:"metadata" db:"metadata"`
	Status           string     `json:"status" db:"status"`
	LastHeartbeat    *time.Time `json:"last_heartbeat" db:"last_heartbeat"`
	CreatedBy        *uuid.UUID `json:"created_by" db:"created_by"`
	UpdatedBy        *uuid.UUID `json:"updated_by" db:"updated_by"`
	CreatedAt        time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt        time.Time  `json:"updated_at" db:"updated_at"`
}

AgentManifest represents a registered agent type with its capabilities

func (*AgentManifest) GetAuthParam

func (am *AgentManifest) GetAuthParam(key string) (interface{}, bool)

GetAuthParam retrieves an authentication parameter

func (*AgentManifest) GetConnectionParam

func (am *AgentManifest) GetConnectionParam(key string) (interface{}, bool)

GetConnectionParam retrieves a connection parameter

func (*AgentManifest) GetRequirement

func (am *AgentManifest) GetRequirement(key string) (interface{}, bool)

GetRequirement retrieves a specific requirement value

func (*AgentManifest) HasCapability

func (am *AgentManifest) HasCapability(capabilityType, capabilityName string) bool

HasCapability checks if the manifest has a specific capability

func (*AgentManifest) IsActive

func (am *AgentManifest) IsActive() bool

IsActive checks if the agent manifest is active

type AgentMetrics

type AgentMetrics struct {
	CPUUsage      float64   `json:"cpu_usage"`    // 0-100
	MemoryUsage   float64   `json:"memory_usage"` // 0-100
	DiskUsage     float64   `json:"disk_usage"`   // 0-100
	NetworkIO     float64   `json:"network_io"`   // bytes/sec
	TasksActive   int       `json:"tasks_active"`
	TasksQueued   int       `json:"tasks_queued"`
	TasksComplete int64     `json:"tasks_complete"`
	ErrorRate     float64   `json:"error_rate"`    // errors per minute
	ResponseTime  float64   `json:"response_time"` // milliseconds
	LastUpdated   time.Time `json:"last_updated"`
}

AgentMetrics tracks real-time agent performance

type AgentPerformance

type AgentPerformance struct {
	AgentID               string                 `json:"agent_id"`
	TasksCompleted        int64                  `json:"tasks_completed"`
	TasksFailed           int64                  `json:"tasks_failed"`
	AverageCompletionTime float64                `json:"average_completion_time"`
	SuccessRate           float64                `json:"success_rate"`
	LoadFactor            float64                `json:"load_factor"`
	SpeedScore            float64                `json:"speed_score"`
	TaskTypeMetrics       map[string]TaskMetrics `json:"task_type_metrics"`
}

AgentPerformance represents agent performance metrics

type AgentRegistration

type AgentRegistration struct {
	ID                 uuid.UUID  `json:"id" db:"id"`
	ManifestID         uuid.UUID  `json:"manifest_id" db:"manifest_id"`
	TenantID           uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	InstanceID         string     `json:"instance_id" db:"instance_id"`
	RegistrationToken  string     `json:"registration_token" db:"registration_token"`
	RegistrationStatus string     `json:"registration_status" db:"registration_status"`
	ActivationDate     *time.Time `json:"activation_date" db:"activation_date"`
	ExpirationDate     *time.Time `json:"expiration_date" db:"expiration_date"`
	RuntimeConfig      JSONMap    `json:"runtime_config" db:"runtime_config"`
	ConnectionDetails  JSONMap    `json:"connection_details" db:"connection_details"`
	HealthStatus       string     `json:"health_status" db:"health_status"`
	HealthCheckURL     string     `json:"health_check_url" db:"health_check_url"`
	LastHealthCheck    *time.Time `json:"last_health_check" db:"last_health_check"`
	Metrics            JSONMap    `json:"metrics" db:"metrics"`
	CreatedAt          time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt          time.Time  `json:"updated_at" db:"updated_at"`
}

AgentRegistration represents an active instance of an agent

func (*AgentRegistration) GetMetric

func (ar *AgentRegistration) GetMetric(key string) (interface{}, bool)

GetMetric retrieves a specific metric value

func (*AgentRegistration) GetRuntimeParam

func (ar *AgentRegistration) GetRuntimeParam(key string) (interface{}, bool)

GetRuntimeParam retrieves a runtime configuration parameter

func (*AgentRegistration) IsExpired

func (ar *AgentRegistration) IsExpired() bool

IsExpired checks if the registration has expired

func (*AgentRegistration) IsHealthy

func (ar *AgentRegistration) IsHealthy() bool

IsHealthy checks if the agent registration is healthy

func (*AgentRegistration) NeedsHealthCheck

func (ar *AgentRegistration) NeedsHealthCheck(interval time.Duration) bool

NeedsHealthCheck checks if a health check is due

type AgentStatus

type AgentStatus string

AgentStatus represents the operational state of an agent

const (
	AgentStatusActive      AgentStatus = "active"
	AgentStatusInactive    AgentStatus = "inactive"
	AgentStatusMaintenance AgentStatus = "maintenance"
	AgentStatusDraining    AgentStatus = "draining"
	AgentStatusError       AgentStatus = "error"
	AgentStatusOffline     AgentStatus = "offline"
	AgentStatusStarting    AgentStatus = "starting"
	AgentStatusStopping    AgentStatus = "stopping"
)

func (AgentStatus) CanTransitionTo

func (s AgentStatus) CanTransitionTo(target AgentStatus) bool

CanTransitionTo checks if a status transition is valid

func (AgentStatus) TransitionTo

func (s AgentStatus) TransitionTo(target AgentStatus, metrics MetricsClient) (AgentStatus, error)

TransitionTo performs a validated state transition with metrics

func (AgentStatus) Validate

func (s AgentStatus) Validate() error

Validate ensures the status is valid

type AgentWorkload

type AgentWorkload struct {
	AgentID       string         `json:"agent_id"`
	ActiveTasks   int            `json:"active_tasks"`
	QueuedTasks   int            `json:"queued_tasks"`
	TasksByType   map[string]int `json:"tasks_by_type"`
	LoadScore     float64        `json:"load_score"`     // 0.0 (idle) to 1.0 (overloaded)
	EstimatedTime int            `json:"estimated_time"` // Estimated time to complete all tasks in seconds
}

AgentWorkload represents current workload for an agent

type AggregationConfig

type AggregationConfig struct {
	Method     string `json:"method"`       // combine_results, first_complete, majority_vote
	WaitForAll bool   `json:"wait_for_all"` // Whether to wait for all subtasks
	Timeout    int    `json:"timeout"`      // Timeout in seconds
}

AggregationConfig defines how results should be aggregated

type ApprovalDecision

type ApprovalDecision struct {
	ID         uuid.UUID              `json:"id"`
	Approved   bool                   `json:"approved"`
	ApprovedBy string                 `json:"approved_by"`
	Comments   string                 `json:"comments,omitempty"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	Timestamp  time.Time              `json:"timestamp"`
}

ApprovalDecision represents an approval decision for a workflow step

func (*ApprovalDecision) GetID

func (a *ApprovalDecision) GetID() uuid.UUID

Add methods to make ApprovalDecision implement AggregateRoot

func (*ApprovalDecision) GetType

func (a *ApprovalDecision) GetType() string

func (*ApprovalDecision) GetVersion

func (a *ApprovalDecision) GetVersion() int

type Artifact

type Artifact struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	SHA1   string `json:"sha1"`
	MD5    string `json:"md5"`
	SHA256 string `json:"sha256"`
}

Artifact represents an artifact in an Artifactory build module

type ArtifactoryArtifact

type ArtifactoryArtifact struct {
	Repo        string               `json:"repo"`
	Path        string               `json:"path"`
	Name        string               `json:"name"`
	Type        string               `json:"type"`
	Size        int64                `json:"size"`
	Created     string               `json:"created"`
	CreatedBy   string               `json:"createdBy"`
	Modified    string               `json:"modified"`
	ModifiedBy  string               `json:"modifiedBy"`
	LastUpdated string               `json:"lastUpdated"`
	DownloadUri string               `json:"downloadUri"`
	MimeType    string               `json:"mimeType"`
	Checksums   ArtifactoryChecksums `json:"checksums"`
	Properties  map[string][]string  `json:"properties"`
}

ArtifactoryArtifact represents an artifact in Artifactory

type ArtifactoryBuild

type ArtifactoryBuild struct {
	BuildInfo struct {
		Name       string            `json:"name"`
		Number     string            `json:"number"`
		Started    time.Time         `json:"started"`
		BuildAgent BuildAgent        `json:"buildAgent"`
		Modules    []Module          `json:"modules"`
		Properties map[string]string `json:"properties"`
	} `json:"buildInfo"`
}

ArtifactoryBuild represents a build in Artifactory

type ArtifactoryChecksums

type ArtifactoryChecksums struct {
	SHA1   string `json:"sha1"`
	MD5    string `json:"md5"`
	SHA256 string `json:"sha256"`
}

ArtifactoryChecksums represents checksums for an artifact

type ArtifactoryQuery

type ArtifactoryQuery struct {
	Type        string `json:"type"`
	RepoKey     string `json:"repoKey"`
	Path        string `json:"path"`
	RepoType    string `json:"repoType"`
	PackageType string `json:"packageType"`
	BuildName   string `json:"buildName"`
	BuildNumber string `json:"buildNumber"`
}

ArtifactoryQuery defines parameters for querying Artifactory

type ArtifactoryRepositories

type ArtifactoryRepositories struct {
	Repositories []ArtifactoryRepository `json:"repositories"`
}

ArtifactoryRepositories represents repositories in Artifactory

type ArtifactoryRepository

type ArtifactoryRepository struct {
	Key         string `json:"key"`
	Type        string `json:"type"`
	Description string `json:"description"`
	URL         string `json:"url"`
	PackageType string `json:"packageType"`
}

ArtifactoryRepository represents a single repository in Artifactory

type ArtifactoryStorage

type ArtifactoryStorage struct {
	BinariesSummary struct {
		BinariesCount int64 `json:"binariesCount"`
		BinariesSize  int64 `json:"binariesSize"`
		ArtifactsSize int64 `json:"artifactsSize"`
		Optimization  int64 `json:"optimization"`
		ItemsCount    int64 `json:"itemsCount"`
	} `json:"binariesSummary"`
	FileStoreSummary struct {
		StorageType      string `json:"storageType"`
		StorageDirectory string `json:"storageDirectory"`
		TotalSpace       int64  `json:"totalSpace"`
		UsedSpace        int64  `json:"usedSpace"`
		FreeSpace        int64  `json:"freeSpace"`
	} `json:"fileStoreSummary"`
	RepositoriesSummary struct {
		RepoCount    int           `json:"repoCount"`
		Repositories []RepoSummary `json:"repositories"`
	} `json:"repositoriesSummary"`
}

ArtifactoryStorage represents storage info in Artifactory

type ArtifactoryWebhookData

type ArtifactoryWebhookData struct {
	RepoKey    string `json:"repo_key"`
	Path       string `json:"path"`
	Name       string `json:"name"`
	SHA1       string `json:"sha1"`
	SHA256     string `json:"sha256"`
	Size       int64  `json:"size"`
	Created    string `json:"created"`
	CreatedBy  string `json:"created_by"`
	Modified   string `json:"modified"`
	ModifiedBy string `json:"modified_by"`
}

ArtifactoryWebhookData represents the data in an Artifactory webhook event

type ArtifactoryWebhookEvent

type ArtifactoryWebhookEvent struct {
	Domain    string                 `json:"domain"`
	EventType string                 `json:"event_type"`
	Data      ArtifactoryWebhookData `json:"data"`
}

ArtifactoryWebhookEvent represents an Artifactory webhook event

type AttributionLevel

type AttributionLevel string

AttributionLevel represents the level of cost attribution

const (
	AttributionLevelUser    AttributionLevel = "user"     // User-level attribution (strongest)
	AttributionLevelEdgeMCP AttributionLevel = "edge_mcp" // Machine identity attribution
	AttributionLevelTenant  AttributionLevel = "tenant"   // Tenant-level attribution (weakest)
	AttributionLevelSystem  AttributionLevel = "system"   // System-level (rare)
)

type AuthMappingConfig

type AuthMappingConfig struct {
	SourceType string            `json:"source_type"` // What we receive
	TargetType string            `json:"target_type"` // What tool expects
	HeaderName string            `json:"header_name,omitempty"`
	QueryParam string            `json:"query_param,omitempty"`
	Transform  string            `json:"transform,omitempty"` // base64, hex, url_encode, etc.
	Prefix     string            `json:"prefix,omitempty"`    // e.g., "Bearer ", "token "
	Properties map[string]string `json:"properties,omitempty"`
}

AuthMappingConfig defines how to map incoming auth to tool-specific auth

type AutomationRule

type AutomationRule struct {
	ID         string                 `json:"id"`
	Name       string                 `json:"name"`
	Enabled    bool                   `json:"enabled"`
	Trigger    string                 `json:"trigger"` // event type
	Conditions []RuleCondition        `json:"conditions,omitempty"`
	Actions    []RuleAction           `json:"actions"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
}

AutomationRule defines an automation rule for the workspace

type BuildAgent

type BuildAgent struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

BuildAgent represents a build agent in Artifactory

type Change

type Change struct {
	Type     string `json:"type"` // "add", "remove", "modify"
	Path     string `json:"path"`
	OldValue string `json:"old_value,omitempty"`
	NewValue string `json:"new_value,omitempty"`
	Line     int    `json:"line,omitempty"`
}

Change represents a single change in a document

type CheckResult

type CheckResult struct {
	Status      HealthStatus  `json:"status"`
	Message     string        `json:"message"`
	LastSuccess time.Time     `json:"last_success"`
	Duration    time.Duration `json:"duration"`
	Error       string        `json:"error,omitempty"`
}

type ClientType

type ClientType string

ClientType represents the type of client

const (
	ClientTypeClaudeCode ClientType = "claude-code"
	ClientTypeIDE        ClientType = "ide"
	ClientTypeAgent      ClientType = "agent"
	ClientTypeCLI        ClientType = "cli"
)

func (ClientType) Validate

func (c ClientType) Validate() error

Validate checks if the client type is valid

type CollaborationMetrics

type CollaborationMetrics struct {
	DocumentID          uuid.UUID        `json:"document_id"`
	Period              time.Duration    `json:"period"`
	UniqueCollaborators int              `json:"unique_collaborators"`
	TotalOperations     int64            `json:"total_operations"`
	OperationsByType    map[string]int64 `json:"operations_by_type"`
	ConflictCount       int64            `json:"conflict_count"`
	AverageResponseTime time.Duration    `json:"average_response_time"`
	PeakConcurrency     int              `json:"peak_concurrency"`
}

CollaborationMetrics represents metrics for document collaboration

type CollaborationSettings

type CollaborationSettings struct {
	AllowGuestAccess   bool     `json:"allow_guest_access"`
	RequireApproval    bool     `json:"require_approval"`
	DefaultMemberRole  string   `json:"default_member_role"`
	AllowedDomains     []string `json:"allowed_domains,omitempty"`
	MaxMembers         int      `json:"max_members,omitempty"`
	EnablePresence     bool     `json:"enable_presence"`
	EnableTypingStatus bool     `json:"enable_typing_status"`
	ConflictResolution string   `json:"conflict_resolution"` // manual, auto_merge, last_write_wins
}

CollaborationSettings defines collaboration preferences

type CollaborativeWorkflow

type CollaborativeWorkflow struct {
	*Workflow
	RequiredAgents   []string          `json:"required_agents"`
	AgentRoles       map[string]string `json:"agent_roles"`
	CoordinationMode string            `json:"coordination_mode"` // parallel, sequential, consensus
	VotingStrategy   string            `json:"voting_strategy"`   // majority, unanimous, weighted
	SyncPoints       []string          `json:"sync_points"`       // Step IDs where agents must synchronize
}

CollaborativeWorkflow represents a workflow designed for multi-agent collaboration

type CompensationAction

type CompensationAction struct {
	ID          uuid.UUID              `json:"id"`
	ExecutionID uuid.UUID              `json:"execution_id"`
	StepID      string                 `json:"step_id"`
	Type        string                 `json:"type"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
	Status      string                 `json:"status"`
	CreatedAt   time.Time              `json:"created_at"`
	ExecutedAt  *time.Time             `json:"executed_at,omitempty"`
	Result      map[string]interface{} `json:"result,omitempty"`
}

CompensationAction represents a compensation action for failed workflows

type CompletionMode

type CompletionMode string

CompletionMode defines when a distributed task is considered complete

const (
	CompletionModeAll       CompletionMode = "all"       // All subtasks must complete
	CompletionModeAny       CompletionMode = "any"       // Any subtask completion completes the task
	CompletionModeMajority  CompletionMode = "majority"  // Majority of subtasks must complete
	CompletionModeThreshold CompletionMode = "threshold" // Configurable threshold of completions
	CompletionModeBestOf    CompletionMode = "best_of"   // Best result from N attempts
)

func (CompletionMode) IsValid

func (m CompletionMode) IsValid() bool

IsCompletionValid checks if the completion mode is valid

type ConflictInfo

type ConflictInfo struct {
	ID            uuid.UUID              `json:"id"`
	DocumentID    uuid.UUID              `json:"document_id"`
	Type          string                 `json:"type"` // concurrent_edit, schema_mismatch, etc.
	LocalVersion  interface{}            `json:"local_version"`
	RemoteVersion interface{}            `json:"remote_version"`
	AffectedPath  string                 `json:"affected_path"`
	DetectedAt    time.Time              `json:"detected_at"`
	Metadata      map[string]interface{} `json:"metadata"`
}

ConflictInfo represents information about a detected conflict

type ConflictResolution

type ConflictResolution struct {
	ID                 uuid.UUID  `json:"id" db:"id"`
	TenantID           uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	ResourceType       string     `json:"resource_type" db:"resource_type"`
	ResourceID         uuid.UUID  `json:"resource_id" db:"resource_id"`
	ConflictType       string     `json:"conflict_type" db:"conflict_type"`
	Description        string     `json:"description,omitempty" db:"description"`
	ResolutionStrategy string     `json:"resolution_strategy,omitempty" db:"resolution_strategy"`
	Details            JSONMap    `json:"details" db:"details"`
	ResolvedBy         *string    `json:"resolved_by,omitempty" db:"resolved_by"`
	ResolvedAt         *time.Time `json:"resolved_at,omitempty" db:"resolved_at"`
	CreatedAt          time.Time  `json:"created_at" db:"created_at"`
}

ConflictResolution represents a resolved conflict in document operations

type ConflictStrategy

type ConflictStrategy string
const (
	ConflictStrategyLatestWins ConflictStrategy = "latest_wins"
	ConflictStrategyMerge      ConflictStrategy = "merge"
	ConflictStrategyManual     ConflictStrategy = "manual"
	ConflictStrategyCustom     ConflictStrategy = "custom"
)

func (ConflictStrategy) Validate

func (c ConflictStrategy) Validate() error

Validate ensures the conflict strategy is valid

type ConnectionMetadata

type ConnectionMetadata struct {
	IPAddress  string                 `json:"ip_address,omitempty"`
	UserAgent  string                 `json:"user_agent,omitempty"`
	Protocol   string                 `json:"protocol,omitempty"`
	TLSVersion string                 `json:"tls_version,omitempty"`
	Headers    map[string]string      `json:"headers,omitempty"`
	Extra      map[string]interface{} `json:"extra,omitempty"`
}

ConnectionMetadata contains client connection information

func (*ConnectionMetadata) Scan

func (cm *ConnectionMetadata) Scan(value interface{}) error

Scan implements sql.Scanner for ConnectionMetadata

func (ConnectionMetadata) Value

func (cm ConnectionMetadata) Value() (driver.Value, error)

Value implements driver.Valuer for ConnectionMetadata

type Context

type Context struct {
	// ID is the unique identifier for this context
	ID string `json:"id" db:"id"`

	// Type is the type of context (e.g., conversation, task, etc.)
	Type string `json:"type" db:"type"`

	// Name is the display name of this context (not persisted to database - metadata field instead)
	Name string `json:"name,omitempty" db:"-"`

	// Description is a human-readable description of the context (not persisted to database - metadata field instead)
	Description string `json:"description,omitempty" db:"-"`

	// AgentID is the identifier for the AI agent that owns this context
	AgentID string `json:"agent_id,omitempty" db:"agent_id"`

	// TenantID is the tenant this context belongs to
	TenantID string `json:"tenant_id" db:"tenant_id"`

	// ModelID identifies which AI model this context is for
	ModelID string `json:"model_id,omitempty" db:"model_id"`

	// SessionID is the identifier for the user session
	SessionID string `json:"session_id,omitempty" db:"session_id"`

	// Content contains the actual context data
	Content []ContextItem `json:"content,omitempty" db:"-"`

	// Metadata contains additional information about the context
	Metadata map[string]any `json:"metadata,omitempty" db:"metadata"`

	// CreatedAt is when this context was created
	CreatedAt time.Time `json:"created_at" db:"created_at"`

	// UpdatedAt is when this context was last updated
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`

	// ExpiresAt is when this context expires (if applicable)
	ExpiresAt time.Time `json:"expires_at,omitempty" db:"expires_at"`

	// MaxTokens is the maximum number of tokens this context can contain
	MaxTokens int `json:"max_tokens,omitempty" db:"max_tokens"`

	// CurrentTokens is the current token count for this context (maps to token_count in DB)
	CurrentTokens int `json:"current_tokens,omitempty" db:"token_count"`
}

Context represents an AI model context

type ContextFilter

type ContextFilter struct {
	ID          string    `json:"id,omitempty"`
	TenantID    string    `json:"tenant_id,omitempty"`
	Name        string    `json:"name,omitempty"`
	ContentType string    `json:"content_type,omitempty"`
	CreatedAt   time.Time `json:"created_at,omitempty"`
	UpdatedAt   time.Time `json:"updated_at,omitempty"`
}

ContextFilter defines filter criteria for context operations

type ContextItem

type ContextItem struct {
	// ID is the unique identifier for this context item
	ID string `json:"id,omitempty" db:"id"`

	// ContextID is the ID of the context this item belongs to
	ContextID string `json:"context_id,omitempty" db:"context_id"`

	// Role is the role of this context item (e.g., user, assistant, system)
	Role string `json:"role" db:"role"`

	// Content is the text content of this context item
	Content string `json:"content" db:"content"`

	// Timestamp is when this context item was created
	Timestamp time.Time `json:"timestamp" db:"created_at"`

	// Tokens is the token count for this context item
	Tokens int `json:"tokens,omitempty" db:"token_count"`

	// Metadata contains additional information about this context item
	Metadata map[string]any `json:"metadata,omitempty" db:"metadata"`
}

ContextItem represents a single item in a context

type ContextUpdateOptions

type ContextUpdateOptions struct {
	// ReplaceContent indicates whether to replace the entire content or append to it
	ReplaceContent bool `json:"replace_content,omitempty"`

	// Truncate indicates whether to truncate the context if it exceeds the maximum tokens
	Truncate bool `json:"truncate,omitempty"`

	// TruncateStrategy defines the strategy for truncating the context
	TruncateStrategy string `json:"truncate_strategy,omitempty"`
}

ContextUpdateOptions provides options for updating a context

type CoordinationMode

type CoordinationMode string

CoordinationMode defines how subtasks are coordinated

const (
	CoordinationModeParallel    CoordinationMode = "parallel"     // All subtasks run in parallel
	CoordinationModeSequential  CoordinationMode = "sequential"   // Subtasks run one after another
	CoordinationModePipeline    CoordinationMode = "pipeline"     // Output of one feeds into next
	CoordinationModeMapReduce   CoordinationMode = "map_reduce"   // Map phase then reduce phase
	CoordinationModeLeaderElect CoordinationMode = "leader_elect" // One agent elected as coordinator
)

func (CoordinationMode) IsValid

func (m CoordinationMode) IsValid() bool

IsCoordinationValid checks if the coordination mode is valid

type CreateSessionRequest

type CreateSessionRequest struct {
	SessionID       string                 `json:"session_id,omitempty"`
	EdgeMCPID       string                 `json:"edge_mcp_id" validate:"required"`
	TenantID        uuid.UUID              `json:"tenant_id" validate:"required"`
	UserID          *uuid.UUID             `json:"user_id,omitempty"`
	ClientName      string                 `json:"client_name,omitempty"`
	ClientType      ClientType             `json:"client_type,omitempty"`
	ClientVersion   string                 `json:"client_version,omitempty"`
	PassthroughAuth *PassthroughAuthBundle `json:"passthrough_auth,omitempty"`
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
	TTL             int                    `json:"ttl,omitempty"` // Session TTL in seconds
}

CreateSessionRequest represents a request to create a new session

type CredentialPayload

type CredentialPayload struct {
	ServiceType ServiceType            `json:"service_type" binding:"required"`
	Credentials map[string]string      `json:"credentials" binding:"required"` // Will be encrypted before storage
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	ExpiresAt   *time.Time             `json:"expires_at,omitempty"`
}

CredentialPayload is the incoming request for storing credentials

type CredentialRequest

type CredentialRequest struct {
	Action      string           `json:"action"`
	Parameters  interface{}      `json:"parameters"`
	Credentials *ToolCredentials `json:"credentials,omitempty"`
}

CredentialRequest wraps tool requests with optional credentials

type CredentialResponse

type CredentialResponse struct {
	ID             string                 `json:"id"`
	ServiceType    ServiceType            `json:"service_type"`
	IsActive       bool                   `json:"is_active"`
	HasCredentials bool                   `json:"has_credentials"` // Indicates if credentials are configured
	Metadata       map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt      time.Time              `json:"created_at"`
	UpdatedAt      time.Time              `json:"updated_at"`
	LastUsedAt     *time.Time             `json:"last_used_at,omitempty"`
	ExpiresAt      *time.Time             `json:"expires_at,omitempty"`
}

CredentialResponse is returned to the client (without sensitive data)

type DecryptedCredentials

type DecryptedCredentials struct {
	ServiceType ServiceType            `json:"service_type"`
	Credentials map[string]string      `json:"credentials"` // e.g., {"token": "ghp_...", "region": "us-east-1"}
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

DecryptedCredentials represents the structure after decryption This should never be serialized to JSON or logged

func (*DecryptedCredentials) ToPassthroughCredential

func (dc *DecryptedCredentials) ToPassthroughCredential() *PassthroughCredential

PassthroughCredential converts DecryptedCredentials to PassthroughCredential format used by edge-mcp for passing credentials to tool executions

type DelegationNode

type DelegationNode struct {
	Delegation *TaskDelegation
	Next       *DelegationNode
}

DelegationNode represents a node in the delegation chain

type DelegationType

type DelegationType string

DelegationType represents how a task was delegated

const (
	DelegationManual      DelegationType = "manual"
	DelegationAutomatic   DelegationType = "automatic"
	DelegationFailover    DelegationType = "failover"
	DelegationLoadBalance DelegationType = "load_balance"
)

type Dependency

type Dependency struct {
	ID     string `json:"id"`
	Type   string `json:"type"`
	SHA1   string `json:"sha1"`
	MD5    string `json:"md5"`
	SHA256 string `json:"sha256"`
}

Dependency represents a dependency in an Artifactory build module

type DependencyType

type DependencyType string

DependencyType represents the type of dependency

const (
	DependencyTypeRuntime  DependencyType = "runtime"
	DependencyTypeDev      DependencyType = "dev"
	DependencyTypePeer     DependencyType = "peer"
	DependencyTypeOptional DependencyType = "optional"
	DependencyTypeBuild    DependencyType = "build"
)

type DiscoveryHint

type DiscoveryHint struct {
	OpenAPIURL       string            `json:"openapi_url,omitempty"`
	AuthHeaders      map[string]string `json:"auth_headers,omitempty"`
	CustomPaths      []string          `json:"custom_paths,omitempty"`
	APIFormat        string            `json:"api_format,omitempty"`
	ExampleEndpoint  string            `json:"example_endpoint,omitempty"`
	DocumentationURL string            `json:"documentation_url,omitempty"`
}

DiscoveryHint provides user-supplied hints for API discovery

type DiscoveryResult

type DiscoveryResult struct {
	Status           string                 `json:"status"`
	OpenAPISpec      interface{}            `json:"openapi_spec,omitempty"`
	SpecURL          string                 `json:"spec_url,omitempty"`
	DiscoveredURLs   []string               `json:"discovered_urls"`
	RequiresManual   bool                   `json:"requires_manual"`
	SuggestedActions []string               `json:"suggested_actions,omitempty"`
	Capabilities     []string               `json:"capabilities,omitempty"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

DiscoveryResult contains the results of API discovery

type DiscoverySession

type DiscoverySession struct {
	ID                string                 `json:"id" db:"id"`
	SessionID         string                 `json:"session_id" db:"session_id"`
	TenantID          string                 `json:"tenant_id" db:"tenant_id"`
	BaseURL           string                 `json:"base_url" db:"base_url"`
	Status            string                 `json:"status" db:"status"`
	DiscoveryResult   *DiscoveryResult       `json:"discovery_result,omitempty" db:"discovery_result"`
	DiscoveryMetadata map[string]interface{} `json:"discovery_metadata" db:"discovery_metadata"`
	CreatedAt         time.Time              `json:"created_at" db:"created_at"`
	ExpiresAt         time.Time              `json:"expires_at" db:"expires_at"`
}

DiscoverySession represents an active discovery session

type DistributedTask

type DistributedTask struct {
	ID          uuid.UUID         `json:"id"`
	Type        string            `json:"type"`
	Title       string            `json:"title"`
	Description string            `json:"description"`
	Priority    TaskPriority      `json:"priority"`
	Subtasks    []Subtask         `json:"subtasks"`
	Aggregation AggregationConfig `json:"aggregation"`
	SubtaskIDs  []uuid.UUID       `json:"subtask_ids,omitempty"`

	// Phase 3 additions
	Task                *Task            `json:"task,omitempty" db:"-"`
	CoordinationMode    CoordinationMode `json:"coordination_mode" db:"coordination_mode"`
	CompletionMode      CompletionMode   `json:"completion_mode" db:"completion_mode"`
	CompletionThreshold int              `json:"completion_threshold,omitempty" db:"completion_threshold"`

	// Execution tracking fields
	ExecutionPlan *ExecutionPlan  `json:"execution_plan,omitempty" db:"execution_plan"`
	Partitions    []TaskPartition `json:"partitions,omitempty" db:"-"`
	Progress      *TaskProgress   `json:"progress,omitempty" db:"-"`
	ResourceUsage *ResourceUsage  `json:"resource_usage,omitempty" db:"-"`

	// Timing fields
	StartedAt         *time.Time    `json:"started_at,omitempty" db:"started_at"`
	CompletedAt       *time.Time    `json:"completed_at,omitempty" db:"completed_at"`
	EstimatedDuration time.Duration `json:"estimated_duration,omitempty" db:"estimated_duration"`

	// Results aggregation
	ResultsCollected    int           `json:"results_collected" db:"results_collected"`
	FinalResult         interface{}   `json:"final_result,omitempty" db:"final_result"`
	IntermediateResults []interface{} `json:"intermediate_results,omitempty" db:"-"`
}

DistributedTask represents a task that can be split into subtasks

func (*DistributedTask) CalculateProgress

func (dt *DistributedTask) CalculateProgress() float64

CalculateProgress calculates the overall progress of the distributed task

func (*DistributedTask) GetEstimatedCompletion

func (dt *DistributedTask) GetEstimatedCompletion() *time.Time

GetEstimatedCompletion returns the estimated completion time

func (*DistributedTask) IsComplete

func (dt *DistributedTask) IsComplete() bool

IsComplete checks if the distributed task is complete based on completion mode

func (*DistributedTask) SetDefaults

func (dt *DistributedTask) SetDefaults()

SetDefaults sets default values for a distributed task

func (*DistributedTask) Validate

func (dt *DistributedTask) Validate() error

Validate validates the distributed task

type Document

type Document struct {
	ID          uuid.UUID  `json:"id" db:"id"`
	TenantID    uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	WorkspaceID *uuid.UUID `json:"workspace_id,omitempty" db:"workspace_id"`
	Title       string     `json:"title" db:"title"`
	Type        string     `json:"type" db:"type"`
	Content     string     `json:"content" db:"content"`
	ContentType string     `json:"content_type" db:"content_type"`
	CreatedBy   string     `json:"created_by" db:"created_by"`
	Version     int        `json:"version" db:"version"`
	Permissions JSONMap    `json:"permissions" db:"permissions"`
	Metadata    JSONMap    `json:"metadata" db:"metadata"`
	CreatedAt   time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at" db:"updated_at"`
	DeletedAt   *time.Time `json:"deleted_at,omitempty" db:"deleted_at"`
}

Document represents a shared document for collaboration

type DocumentChange

type DocumentChange struct {
	ID         uuid.UUID `json:"id" db:"id"`
	DocumentID uuid.UUID `json:"document_id" db:"document_id"`
	AgentID    string    `json:"agent_id" db:"agent_id"`
	ChangeType string    `json:"change_type" db:"change_type"`
	Position   int       `json:"position" db:"position"`
	Content    string    `json:"content" db:"content"`
	Length     int       `json:"length" db:"length"`
	Metadata   JSONMap   `json:"metadata" db:"metadata"`
	Timestamp  time.Time `json:"timestamp" db:"timestamp"`
}

DocumentChange represents a change to a document (for CRDT)

type DocumentConflictResolution

type DocumentConflictResolution struct {
	Strategy      ConflictStrategy `json:"strategy"`
	ResolvedBy    string           `json:"resolved_by"`
	ResolvedAt    time.Time        `json:"resolved_at"`
	OriginalValue interface{}      `json:"original_value,omitempty"`
}

type DocumentDiff

type DocumentDiff struct {
	FromVersion int       `json:"from_version"`
	ToVersion   int       `json:"to_version"`
	Changes     []Change  `json:"changes"`
	CreatedAt   time.Time `json:"created_at"`
}

DocumentDiff represents the difference between two document versions

type DocumentLock

type DocumentLock struct {
	DocumentID    uuid.UUID `json:"document_id"`
	LockedBy      string    `json:"locked_by"`
	LockedAt      time.Time `json:"locked_at"`
	LockExpiresAt time.Time `json:"lock_expires_at"`
	LockType      string    `json:"lock_type"` // "exclusive" or "shared"
}

DocumentLock represents lock information for a document

type DocumentOperation

type DocumentOperation struct {
	ID                uuid.UUID  `json:"id" db:"id"`
	DocumentID        uuid.UUID  `json:"document_id" db:"document_id"`
	TenantID          uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	AgentID           string     `json:"agent_id" db:"agent_id"`
	OperationType     string     `json:"operation_type" db:"operation_type"`
	OperationData     JSONMap    `json:"operation_data" db:"operation_data"`
	VectorClock       JSONMap    `json:"vector_clock" db:"vector_clock"`
	SequenceNumber    int64      `json:"sequence_number" db:"sequence_number"`
	Timestamp         time.Time  `json:"timestamp" db:"timestamp"`
	ParentOperationID *uuid.UUID `json:"parent_operation_id,omitempty" db:"parent_operation_id"`
	IsApplied         bool       `json:"is_applied" db:"is_applied"`
}

DocumentOperation represents a CRDT operation on a document

func (*DocumentOperation) IsConflict

func (op *DocumentOperation) IsConflict(other *DocumentOperation) bool

IsConflict checks if this operation conflicts with another

type DocumentSnapshot

type DocumentSnapshot struct {
	ID          uuid.UUID `json:"id" db:"id"`
	DocumentID  uuid.UUID `json:"document_id" db:"document_id"`
	Version     int64     `json:"version" db:"version"`
	Content     string    `json:"content" db:"content"`
	VectorClock JSONMap   `json:"vector_clock" db:"vector_clock"`
	CreatedAt   time.Time `json:"created_at" db:"created_at"`
	CreatedBy   string    `json:"created_by" db:"created_by"`
}

DocumentSnapshot represents a point-in-time snapshot of a document

type DocumentStats

type DocumentStats struct {
	DocumentID    uuid.UUID `json:"document_id"`
	TotalVersions int       `json:"total_versions"`
	TotalEdits    int       `json:"total_edits"`
	UniqueEditors int       `json:"unique_editors"`
	LastEditedAt  time.Time `json:"last_edited_at"`
	LastEditedBy  string    `json:"last_edited_by"`
	ContentLength int       `json:"content_length"`
	CreatedAt     time.Time `json:"created_at"`
}

DocumentStats represents statistics about a document

type DocumentType

type DocumentType string

DocumentType represents the type of document

const (
	DocumentTypeMarkdown DocumentType = "markdown"
	DocumentTypeJSON     DocumentType = "json"
	DocumentTypeYAML     DocumentType = "yaml"
	DocumentTypeCode     DocumentType = "code"
	DocumentTypeDiagram  DocumentType = "diagram"
	DocumentTypeRunbook  DocumentType = "runbook"
	DocumentTypePlaybook DocumentType = "playbook"
	DocumentTypeTemplate DocumentType = "template"
	DocumentTypeConfig   DocumentType = "config"
)

func (DocumentType) Validate

func (d DocumentType) Validate() error

Validate ensures the document type is valid

type DocumentUpdate

type DocumentUpdate struct {
	ID                 uuid.UUID                  `json:"id" db:"id"`
	DocumentID         uuid.UUID                  `json:"document_id" db:"document_id"`
	Version            int                        `json:"version" db:"version"`
	UpdateType         UpdateType                 `json:"update_type" db:"update_type"`
	Path               string                     `json:"path" db:"path"`
	OldValue           interface{}                `json:"old_value" db:"old_value"`
	NewValue           interface{}                `json:"new_value" db:"new_value"`
	UpdatedBy          string                     `json:"updated_by" db:"updated_by"`
	UpdatedAt          time.Time                  `json:"updated_at" db:"updated_at"`
	Metadata           map[string]interface{}     `json:"metadata" db:"metadata"`
	Checksum           string                     `json:"checksum" db:"checksum"`
	ConflictResolution DocumentConflictResolution `json:"conflict_resolution,omitempty" db:"conflict_resolution"`
}

DocumentUpdate represents a document update operation

type DocumentVersion

type DocumentVersion struct {
	ID         uuid.UUID `json:"id" db:"id"`
	DocumentID uuid.UUID `json:"document_id" db:"document_id"`
	Version    int       `json:"version" db:"version"`
	Content    string    `json:"content" db:"content"`
	CreatedBy  string    `json:"created_by" db:"created_by"`
	CreatedAt  time.Time `json:"created_at" db:"created_at"`
	Metadata   JSONMap   `json:"metadata" db:"metadata"`
}

DocumentVersion represents a specific version of a document

type DynamicTool

type DynamicTool struct {
	ID                   string                 `json:"id" db:"id"`
	TenantID             string                 `json:"tenant_id" db:"tenant_id"`
	ToolName             string                 `json:"tool_name" db:"tool_name"`
	ToolType             string                 `json:"tool_type" db:"tool_type"`
	DisplayName          string                 `json:"display_name" db:"display_name"`
	BaseURL              string                 `json:"base_url" db:"base_url"`
	InputSchema          map[string]interface{} `json:"input_schema,omitempty" db:"-"`
	DocumentationURL     *string                `json:"documentation_url,omitempty" db:"documentation_url"`
	OpenAPIURL           *string                `json:"openapi_url,omitempty" db:"openapi_url"`
	OpenAPISpecURL       *string                `json:"openapi_spec_url,omitempty" db:"openapi_spec_url"`
	OpenAPISpec          *json.RawMessage       `json:"openapi_spec,omitempty" db:"openapi_spec"`
	Config               map[string]interface{} `json:"config" db:"config"`
	AuthType             string                 `json:"auth_type" db:"auth_type"`
	AuthConfig           map[string]interface{} `json:"auth_config,omitempty" db:"auth_config"`
	CredentialConfig     *json.RawMessage       `json:"credential_config,omitempty" db:"credential_config"`
	CredentialsEncrypted []byte                 `json:"-" db:"credentials_encrypted"`
	EncryptedCredentials string                 `json:"-" db:"encrypted_credentials"`
	Headers              *json.RawMessage       `json:"headers,omitempty" db:"headers"`
	APISpec              *json.RawMessage       `json:"api_spec,omitempty" db:"api_spec"`
	DiscoveredEndpoints  *json.RawMessage       `json:"discovered_endpoints,omitempty" db:"discovered_endpoints"`
	HealthCheckConfig    *json.RawMessage       `json:"health_check_config,omitempty" db:"health_check_config"`
	RetryPolicy          *json.RawMessage       `json:"retry_policy,omitempty" db:"retry_policy"`
	HealthConfig         *json.RawMessage       `json:"health_config,omitempty" db:"health_config"`
	Status               string                 `json:"status" db:"status"`
	IsActive             bool                   `json:"is_active" db:"is_active"`
	LastHealthCheck      *time.Time             `json:"last_health_check,omitempty" db:"last_health_check"`
	HealthStatus         *json.RawMessage       `json:"health_status,omitempty" db:"health_status"`
	HealthMessage        *string                `json:"health_message,omitempty" db:"health_message"`
	Description          *string                `json:"description,omitempty" db:"description"`
	Tags                 []string               `json:"tags,omitempty" db:"tags"`
	Metadata             *json.RawMessage       `json:"metadata,omitempty" db:"metadata"`
	Provider             string                 `json:"provider,omitempty" db:"provider"`
	PassthroughConfig    *json.RawMessage       `json:"passthrough_config,omitempty" db:"passthrough_config"`
	WebhookConfig        *json.RawMessage       `json:"webhook_config,omitempty" db:"webhook_config"`
	CreatedAt            time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt            time.Time              `json:"updated_at" db:"updated_at"`
	CreatedBy            *string                `json:"created_by,omitempty" db:"created_by"`
	UpdatedBy            *string                `json:"updated_by,omitempty" db:"updated_by"`
}

DynamicTool represents a dynamically configured tool

type EdgeMCPSession

type EdgeMCPSession struct {
	// Primary identification
	ID        uuid.UUID `json:"id" db:"id"`
	SessionID string    `json:"session_id" db:"session_id"`

	// Association
	TenantID  uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	UserID    *uuid.UUID `json:"user_id,omitempty" db:"user_id"`
	EdgeMCPID string     `json:"edge_mcp_id" db:"edge_mcp_id"`

	// Client information
	ClientName    *string     `json:"client_name,omitempty" db:"client_name"`
	ClientType    *ClientType `json:"client_type,omitempty" db:"client_type"`
	ClientVersion *string     `json:"client_version,omitempty" db:"client_version"`

	// Session state
	Status        SessionStatus `json:"status" db:"status"`
	Initialized   bool          `json:"initialized" db:"initialized"`
	CoreSessionID *string       `json:"core_session_id,omitempty" db:"core_session_id"`

	// Passthrough auth (stored encrypted)
	PassthroughAuth          *PassthroughAuthBundle `json:"passthrough_auth,omitempty" db:"-"`
	PassthroughAuthEncrypted *string                `json:"-" db:"passthrough_auth_encrypted"`

	// Metadata
	ConnectionMetadata json.RawMessage `json:"connection_metadata,omitempty" db:"connection_metadata"`
	ContextID          *uuid.UUID      `json:"context_id,omitempty" db:"context_id"`

	// Activity tracking
	LastActivityAt     time.Time `json:"last_activity_at" db:"last_activity_at"`
	ToolExecutionCount int       `json:"tool_execution_count" db:"tool_execution_count"`
	TotalTokensUsed    int       `json:"total_tokens_used" db:"total_tokens_used"`

	// Lifecycle
	CreatedAt         time.Time  `json:"created_at" db:"created_at"`
	ExpiresAt         *time.Time `json:"expires_at,omitempty" db:"expires_at"`
	TerminatedAt      *time.Time `json:"terminated_at,omitempty" db:"terminated_at"`
	TerminationReason *string    `json:"termination_reason,omitempty" db:"termination_reason"`
}

EdgeMCPSession represents an edge MCP client session

func (*EdgeMCPSession) GetIdleTime

func (s *EdgeMCPSession) GetIdleTime() time.Duration

GetIdleTime returns the time since last activity

func (*EdgeMCPSession) GetSessionAge

func (s *EdgeMCPSession) GetSessionAge() time.Duration

GetSessionAge returns the age of the session

func (*EdgeMCPSession) IsActive

func (s *EdgeMCPSession) IsActive() bool

IsActive returns true if the session is active

func (*EdgeMCPSession) IsExpired

func (s *EdgeMCPSession) IsExpired() bool

IsExpired checks if the session has expired

func (*EdgeMCPSession) ShouldRefresh

func (s *EdgeMCPSession) ShouldRefresh() bool

ShouldRefresh checks if the session should be refreshed (80% of lifetime)

func (*EdgeMCPSession) Validate

func (s *EdgeMCPSession) Validate() error

Validate performs validation on the session

type Embedding

type Embedding struct {
	ID           string    `json:"id"`
	ContextID    string    `json:"context_id"`
	ContentIndex int       `json:"content_index"`
	Text         string    `json:"text"`
	Embedding    []float32 `json:"embedding"`
	ModelID      string    `json:"model_id"`
}

Embedding represents a vector embedding with additional metadata

type EmbeddingResponse

type EmbeddingResponse struct {
	EmbeddingID string                 `json:"embedding_id"`
	Vector      []float64              `json:"vector,omitempty"`
	Model       string                 `json:"model"`
	Provider    string                 `json:"provider"`
	Dimensions  int                    `json:"dimensions"`
	TaskType    string                 `json:"task_type"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt   time.Time              `json:"created_at"`
	Success     bool                   `json:"success"`
	Error       string                 `json:"error,omitempty"`
}

EmbeddingResponse represents the response from an embedding generation request

type EndpointRateLimit

type EndpointRateLimit struct {
	RequestsPerMinute int `json:"requests_per_minute"`
	BurstSize         int `json:"burst_size"`
}

EndpointRateLimit represents rate limits for a specific endpoint

type EnhancedPassthroughConfig

type EnhancedPassthroughConfig struct {
	Mode               string                       `json:"mode"` // required, optional, disabled, hybrid
	FallbackToService  bool                         `json:"fallback_to_service"`
	SupportedAuthTypes []string                     `json:"supported_auth_types"`
	Rules              []PassthroughRule            `json:"rules"`
	AuthMapping        map[string]AuthMappingConfig `json:"auth_mapping"`
	SecurityPolicy     *PassthroughSecurityPolicy   `json:"security_policy"`
}

EnhancedPassthroughConfig defines comprehensive passthrough configuration for a tool

type EntityID

type EntityID struct {
	// Type of the entity
	Type EntityType `json:"type"`

	// Owner of the entity (GitHub username or organization)
	Owner string `json:"owner"`

	// Repository name
	Repo string `json:"repo"`

	// Identifier of the entity (issue number, PR number, commit hash, etc.)
	ID string `json:"id"`

	// Additional qualifiers for uniquely identifying the entity
	Qualifiers map[string]string `json:"qualifiers,omitempty"`
}

EntityID represents a unique identifier for an entity

func EntityIDFromContentMetadata

func EntityIDFromContentMetadata(contentType string, owner, repo, contentID string) EntityID

EntityIDFromContentMetadata creates an EntityID from storage content metadata

func NewEntityID

func NewEntityID(entityType EntityType, owner, repo, id string) EntityID

NewEntityID creates a new EntityID

func (EntityID) String

func (e EntityID) String() string

String returns a string representation of the entity ID

func (EntityID) WithQualifiers

func (e EntityID) WithQualifiers(qualifiers map[string]string) EntityID

WithQualifiers adds qualifiers to an EntityID

type EntityRelationship

type EntityRelationship struct {
	// ID is a unique identifier for this relationship
	ID string `json:"id"`

	// Type of relationship
	Type RelationshipType `json:"type"`

	// Direction of the relationship (outgoing, incoming, bidirectional)
	Direction string `json:"direction"`

	// Source entity
	Source EntityID `json:"source"`

	// Target entity
	Target EntityID `json:"target"`

	// Strength of the relationship (0.0 to 1.0)
	Strength float64 `json:"strength"`

	// Context provides additional information about the relationship
	Context string `json:"context,omitempty"`

	// Metadata contains additional structured data about the relationship
	Metadata map[string]any `json:"metadata,omitempty"`

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

	// UpdatedAt is the timestamp when the relationship was last updated
	UpdatedAt time.Time `json:"updated_at"`
}

EntityRelationship represents a relationship between two GitHub entities

func NewEntityRelationship

func NewEntityRelationship(
	relType RelationshipType,
	source EntityID,
	target EntityID,
	direction string,
	strength float64,
) *EntityRelationship

NewEntityRelationship creates a new relationship between two entities

func (*EntityRelationship) WithContext

func (r *EntityRelationship) WithContext(context string) *EntityRelationship

WithContext adds context to a relationship

func (*EntityRelationship) WithContextMap

func (r *EntityRelationship) WithContextMap(keyOrMap any, value ...any) *EntityRelationship

WithContext adds context to the relationship with more flexible parameters It can be called with either a key-value pair or a complete map

func (*EntityRelationship) WithMetadata

func (r *EntityRelationship) WithMetadata(metadata map[string]any) *EntityRelationship

WithMetadata adds metadata to a relationship

func (*EntityRelationship) WithMetadataMap

func (r *EntityRelationship) WithMetadataMap(keyOrMap any, value ...any) *EntityRelationship

WithMetadataMap adds metadata to the relationship with more flexible parameters It can be called with either a key-value pair or a complete map

type EntityType

type EntityType string

EntityType represents the type of GitHub entity

const (
	// EntityTypeRepository represents a GitHub repository
	EntityTypeRepository EntityType = "repository"
	// EntityTypeIssue represents a GitHub issue
	EntityTypeIssue EntityType = "issue"
	// EntityTypePullRequest represents a GitHub pull request
	EntityTypePullRequest EntityType = "pull_request"
	// EntityTypeCommit represents a GitHub commit
	EntityTypeCommit EntityType = "commit"
	// EntityTypeFile represents a file in a GitHub repository
	EntityTypeFile EntityType = "file"
	// EntityTypeUser represents a GitHub user
	EntityTypeUser EntityType = "user"
	// EntityTypeOrganization represents a GitHub organization
	EntityTypeOrganization EntityType = "organization"
	// EntityTypeDiscussion represents a GitHub discussion
	EntityTypeDiscussion EntityType = "discussion"
	// EntityTypeComment represents a comment on an issue, PR, or discussion
	EntityTypeComment EntityType = "comment"
	// EntityTypeRelease represents a GitHub release
	EntityTypeRelease EntityType = "release"
	// EntityTypeCodeChunk represents a semantic code chunk
	EntityTypeCodeChunk EntityType = "code_chunk"
)

Entity types

type ErrorCategory

type ErrorCategory string

ErrorCategory groups related error types

const (
	CategoryAuth       ErrorCategory = "AUTHENTICATION"
	CategoryResource   ErrorCategory = "RESOURCE"
	CategoryRateLimit  ErrorCategory = "RATE_LIMIT"
	CategoryValidation ErrorCategory = "VALIDATION"
	CategoryNetwork    ErrorCategory = "NETWORK"
	CategoryExternal   ErrorCategory = "EXTERNAL_SERVICE"
	CategorySystem     ErrorCategory = "SYSTEM"
	CategoryProtocol   ErrorCategory = "PROTOCOL"
	CategoryBusiness   ErrorCategory = "BUSINESS_LOGIC"
)

type ErrorCode

type ErrorCode string

ErrorCode represents standardized error codes for the system

const (
	// Authentication and Authorization errors (1xxx)
	ErrorCodeAuthFailed       ErrorCode = "AUTH_FAILED"       // Authentication failed
	ErrorCodeUnauthorized     ErrorCode = "UNAUTHORIZED"      // Not authorized to perform action
	ErrorCodeTokenExpired     ErrorCode = "TOKEN_EXPIRED"     // Authentication token has expired
	ErrorCodeInvalidAPIKey    ErrorCode = "INVALID_API_KEY"   // API key is invalid or malformed
	ErrorCodePermissionDenied ErrorCode = "PERMISSION_DENIED" // User lacks required permissions
	ErrorCodeAccountSuspended ErrorCode = "ACCOUNT_SUSPENDED" // Account has been suspended
	ErrorCodeMFARequired      ErrorCode = "MFA_REQUIRED"      // Multi-factor authentication required

	// Resource errors (2xxx)
	ErrorCodeNotFound         ErrorCode = "NOT_FOUND"         // Resource not found
	ErrorCodeAlreadyExists    ErrorCode = "ALREADY_EXISTS"    // Resource already exists
	ErrorCodeConflict         ErrorCode = "CONFLICT"          // Resource conflict (e.g., version mismatch)
	ErrorCodeResourceLocked   ErrorCode = "RESOURCE_LOCKED"   // Resource is locked for modification
	ErrorCodeResourceDeleted  ErrorCode = "RESOURCE_DELETED"  // Resource has been deleted
	ErrorCodeResourceExpired  ErrorCode = "RESOURCE_EXPIRED"  // Resource has expired
	ErrorCodeDependencyFailed ErrorCode = "DEPENDENCY_FAILED" // Required dependency is unavailable

	// Rate limiting and quotas (3xxx)
	ErrorCodeRateLimit        ErrorCode = "RATE_LIMIT"        // Rate limit exceeded
	ErrorCodeQuotaExceeded    ErrorCode = "QUOTA_EXCEEDED"    // Quota exceeded
	ErrorCodeConcurrencyLimit ErrorCode = "CONCURRENCY_LIMIT" // Too many concurrent operations
	ErrorCodeBandwidthLimit   ErrorCode = "BANDWIDTH_LIMIT"   // Bandwidth limit exceeded
	ErrorCodeStorageLimit     ErrorCode = "STORAGE_LIMIT"     // Storage limit exceeded

	// Validation errors (4xxx)
	ErrorCodeValidation       ErrorCode = "VALIDATION_ERROR"  // Input validation failed
	ErrorCodeInvalidInput     ErrorCode = "INVALID_INPUT"     // Invalid input provided
	ErrorCodeMissingParameter ErrorCode = "MISSING_PARAMETER" // Required parameter missing
	ErrorCodeInvalidFormat    ErrorCode = "INVALID_FORMAT"    // Invalid format for input
	ErrorCodeOutOfRange       ErrorCode = "OUT_OF_RANGE"      // Value out of acceptable range
	ErrorCodeTypeMismatch     ErrorCode = "TYPE_MISMATCH"     // Type mismatch in input
	ErrorCodeSchemaViolation  ErrorCode = "SCHEMA_VIOLATION"  // Schema validation failed

	// Network and connectivity (5xxx)
	ErrorCodeTimeout          ErrorCode = "TIMEOUT"           // Operation timed out
	ErrorCodeNetworkError     ErrorCode = "NETWORK_ERROR"     // Network error occurred
	ErrorCodeConnectionFailed ErrorCode = "CONNECTION_FAILED" // Failed to establish connection
	ErrorCodeServiceOffline   ErrorCode = "SERVICE_OFFLINE"   // Service is offline
	ErrorCodeDNSResolution    ErrorCode = "DNS_RESOLUTION"    // DNS resolution failed
	ErrorCodeSSLError         ErrorCode = "SSL_ERROR"         // SSL/TLS error
	ErrorCodeProxyError       ErrorCode = "PROXY_ERROR"       // Proxy connection error

	// External service errors (6xxx)
	ErrorCodeUpstreamError    ErrorCode = "UPSTREAM_ERROR"    // Upstream service error
	ErrorCodeProviderError    ErrorCode = "PROVIDER_ERROR"    // External provider error
	ErrorCodeIntegrationError ErrorCode = "INTEGRATION_ERROR" // Integration failure
	ErrorCodeWebhookFailed    ErrorCode = "WEBHOOK_FAILED"    // Webhook delivery failed
	ErrorCodeAPIError         ErrorCode = "API_ERROR"         // External API error

	// System errors (7xxx)
	ErrorCodeInternal      ErrorCode = "INTERNAL_ERROR" // Internal server error
	ErrorCodeDatabaseError ErrorCode = "DATABASE_ERROR" // Database operation failed
	ErrorCodeCacheError    ErrorCode = "CACHE_ERROR"    // Cache operation failed
	ErrorCodeConfigError   ErrorCode = "CONFIG_ERROR"   // Configuration error
	ErrorCodeInitError     ErrorCode = "INIT_ERROR"     // Initialization failed
	ErrorCodeShutdown      ErrorCode = "SHUTDOWN"       // System is shutting down
	ErrorCodeMaintenance   ErrorCode = "MAINTENANCE"    // System under maintenance

	// Protocol and format errors (8xxx)
	ErrorCodeProtocolError    ErrorCode = "PROTOCOL_ERROR"      // Protocol violation
	ErrorCodeVersionMismatch  ErrorCode = "VERSION_MISMATCH"    // Version incompatibility
	ErrorCodeEncodingError    ErrorCode = "ENCODING_ERROR"      // Encoding/decoding failed
	ErrorCodeParsingError     ErrorCode = "PARSING_ERROR"       // Failed to parse data
	ErrorCodeSerializationErr ErrorCode = "SERIALIZATION_ERROR" // Serialization failed

	// Business logic errors (9xxx)
	ErrorCodeInvalidOperation ErrorCode = "INVALID_OPERATION"   // Operation not allowed
	ErrorCodePreconditionFail ErrorCode = "PRECONDITION_FAILED" // Precondition not met
	ErrorCodeStateError       ErrorCode = "STATE_ERROR"         // Invalid state for operation
	ErrorCodeWorkflowError    ErrorCode = "WORKFLOW_ERROR"      // Workflow execution failed
	ErrorCodePolicyViolation  ErrorCode = "POLICY_VIOLATION"    // Policy violation detected
)

type ErrorResponse

type ErrorResponse struct {
	// Core error information
	Code      ErrorCode     `json:"code"`              // Standardized error code
	Message   string        `json:"message"`           // Human-readable error message
	Details   string        `json:"details,omitempty"` // Detailed error description
	Category  ErrorCategory `json:"category"`          // Error category for grouping
	Severity  ErrorSeverity `json:"severity"`          // Error severity level
	Timestamp time.Time     `json:"timestamp"`         // When the error occurred

	// Context information
	RequestID string `json:"request_id,omitempty"` // Request identifier for tracing
	Operation string `json:"operation,omitempty"`  // Operation that failed
	Service   string `json:"service,omitempty"`    // Service that generated error
	Version   string `json:"version,omitempty"`    // API/protocol version

	// Affected resources
	Resource         *ResourceInfo  `json:"resource,omitempty"`          // Primary affected resource
	RelatedResources []ResourceInfo `json:"related_resources,omitempty"` // Related affected resources

	// Recovery information
	Suggestion       string         `json:"suggestion,omitempty"`        // Suggested action to resolve
	Documentation    string         `json:"documentation,omitempty"`     // Link to relevant documentation
	AlternativeTools []string       `json:"alternative_tools,omitempty"` // Alternative tools to try
	RecoverySteps    []RecoveryStep `json:"recovery_steps,omitempty"`    // Steps to recover
	RetryStrategy    *RetryStrategy `json:"retry_strategy,omitempty"`    // Retry guidance

	// Rate limiting information
	RetryAfter    *time.Duration `json:"retry_after,omitempty"`     // When to retry (for rate limits)
	RateLimitInfo *RateLimitInfo `json:"rate_limit_info,omitempty"` // Rate limit details

	// Additional metadata
	Metadata   map[string]interface{} `json:"metadata,omitempty"`    // Additional error metadata
	StackTrace []string               `json:"stack_trace,omitempty"` // Stack trace (debug mode only)
	InnerError *ErrorResponse         `json:"inner_error,omitempty"` // Nested error for error chains
}

ErrorResponse represents a comprehensive error response for AI agents

func NewAuthError

func NewAuthError(message string) *ErrorResponse

NewAuthError creates an authentication error

func NewErrorResponse

func NewErrorResponse(code ErrorCode, message string) *ErrorResponse

NewErrorResponse creates a new error response with defaults

func NewNotFoundError

func NewNotFoundError(resourceType, resourceID string) *ErrorResponse

NewNotFoundError creates a not found error

func NewRateLimitError

func NewRateLimitError(limit, remaining int, reset time.Time) *ErrorResponse

NewRateLimitError creates a rate limit error

func NewTimeoutError

func NewTimeoutError(operation string, timeout time.Duration) *ErrorResponse

NewTimeoutError creates a timeout error

func NewValidationError

func NewValidationError(field, issue string) *ErrorResponse

NewValidationError creates a validation error

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

Error implements the error interface

func (*ErrorResponse) GetSeverityPriority

func (e *ErrorResponse) GetSeverityPriority() int

GetSeverityPriority returns numeric priority for severity (higher = more severe)

func (*ErrorResponse) IsRetryable

func (e *ErrorResponse) IsRetryable() bool

IsRetryable checks if the error is retryable

func (*ErrorResponse) ToJSON

func (e *ErrorResponse) ToJSON() ([]byte, error)

ToJSON converts error response to JSON

func (*ErrorResponse) WithDetails

func (e *ErrorResponse) WithDetails(details string) *ErrorResponse

WithDetails adds details to the error

func (*ErrorResponse) WithDocumentation

func (e *ErrorResponse) WithDocumentation(documentation string) *ErrorResponse

WithDocumentation adds documentation link

func (*ErrorResponse) WithInnerError

func (e *ErrorResponse) WithInnerError(inner *ErrorResponse) *ErrorResponse

WithInnerError adds nested error for error chains

func (*ErrorResponse) WithMetadata

func (e *ErrorResponse) WithMetadata(key string, value interface{}) *ErrorResponse

WithMetadata adds metadata key-value pair

func (*ErrorResponse) WithOperation

func (e *ErrorResponse) WithOperation(operation string) *ErrorResponse

WithOperation adds the operation context

func (*ErrorResponse) WithRateLimitInfo

func (e *ErrorResponse) WithRateLimitInfo(info RateLimitInfo) *ErrorResponse

WithRateLimitInfo adds rate limit information

func (*ErrorResponse) WithRecoverySteps

func (e *ErrorResponse) WithRecoverySteps(steps []RecoveryStep) *ErrorResponse

WithRecoverySteps adds recovery steps

func (*ErrorResponse) WithRequestID

func (e *ErrorResponse) WithRequestID(requestID string) *ErrorResponse

WithRequestID adds request ID for tracing

func (*ErrorResponse) WithResource

func (e *ErrorResponse) WithResource(resource ResourceInfo) *ErrorResponse

WithResource adds affected resource information

func (*ErrorResponse) WithRetryAfter

func (e *ErrorResponse) WithRetryAfter(duration time.Duration) *ErrorResponse

WithRetryAfter sets retry after duration

func (*ErrorResponse) WithRetryStrategy

func (e *ErrorResponse) WithRetryStrategy(strategy RetryStrategy) *ErrorResponse

WithRetryStrategy adds retry strategy

func (*ErrorResponse) WithService

func (e *ErrorResponse) WithService(service string) *ErrorResponse

WithService adds the service context

func (*ErrorResponse) WithSeverity

func (e *ErrorResponse) WithSeverity(severity ErrorSeverity) *ErrorResponse

WithSeverity sets the error severity

func (*ErrorResponse) WithSuggestion

func (e *ErrorResponse) WithSuggestion(suggestion string) *ErrorResponse

WithSuggestion adds a recovery suggestion

func (*ErrorResponse) WithVersion

func (e *ErrorResponse) WithVersion(version string) *ErrorResponse

WithVersion adds the version context

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity indicates the severity level of an error

const (
	SeverityInfo     ErrorSeverity = "INFO"     // Informational, not an actual error
	SeverityWarning  ErrorSeverity = "WARNING"  // Warning, operation succeeded with issues
	SeverityError    ErrorSeverity = "ERROR"    // Error, operation failed but recoverable
	SeverityCritical ErrorSeverity = "CRITICAL" // Critical error, system-level impact
	SeverityFatal    ErrorSeverity = "FATAL"    // Fatal error, requires immediate attention
)

type Event

type Event struct {
	// Source is the source of the event (e.g., openai, anthropic, langchain)
	Source string `json:"source"`

	// Type is the type of the event (e.g., context_update, model_request)
	Type string `json:"type"`

	// Timestamp is when the event occurred
	Timestamp time.Time `json:"timestamp"`

	// Data contains the event data
	Data any `json:"data"`

	// AgentID is the identifier for the AI agent that generated this event
	AgentID string `json:"agent_id"`

	// SessionID is the identifier for the user session
	SessionID string `json:"session_id,omitempty"`
}

Event represents an MCP event

type EventFilter

type EventFilter struct {
	Sources    []string  `json:"sources"`
	Types      []string  `json:"types"`
	AgentIDs   []string  `json:"agent_ids,omitempty"`
	SessionIDs []string  `json:"session_ids,omitempty"`
	After      time.Time `json:"after"`
	Before     time.Time `json:"before"`
}

EventFilter defines criteria for filtering events

func (*EventFilter) MatchEvent

func (f *EventFilter) MatchEvent(event Event) bool

MatchEvent checks if an event matches the filter criteria

type EventHandler

type EventHandler func(Event) error

EventHandler is a function that processes an event

type ExecutionContext

type ExecutionContext struct {
	ExecutionID   uuid.UUID              `json:"execution_id"`
	WorkflowID    uuid.UUID              `json:"workflow_id"`
	Status        string                 `json:"status"`
	CurrentStep   string                 `json:"current_step"`
	TotalSteps    int                    `json:"total_steps"`
	StartedAt     time.Time              `json:"started_at"`
	CompletedAt   *time.Time             `json:"completed_at,omitempty"`
	ExecutionTime time.Duration          `json:"execution_time"`
	StepResults   map[string]interface{} `json:"step_results"`
}

ExecutionContext for workflow executions

type ExecutionEvent

type ExecutionEvent struct {
	Timestamp   time.Time              `json:"timestamp"`
	EventType   string                 `json:"event_type"`
	StepID      string                 `json:"step_id,omitempty"`
	AgentID     string                 `json:"agent_id,omitempty"`
	Description string                 `json:"description"`
	Details     map[string]interface{} `json:"details,omitempty"`
}

ExecutionEvent represents an event in the workflow execution timeline

type ExecutionPhase

type ExecutionPhase struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	TaskIDs  []string `json:"task_ids"`
	Parallel bool     `json:"parallel"`
	MaxRetry int      `json:"max_retry"`
}

ExecutionPhase represents a phase in the execution plan

type ExecutionPlan

type ExecutionPlan struct {
	Phases      []ExecutionPhase       `json:"phases"`
	SyncPoints  []SyncPoint            `json:"sync_points,omitempty"`
	Constraints map[string]interface{} `json:"constraints,omitempty"`
	Timeout     time.Duration          `json:"timeout"`
}

ExecutionPlan represents the execution plan for a distributed task

type ExecutionStatus

type ExecutionStatus struct {
	ExecutionID    uuid.UUID              `json:"execution_id"`
	WorkflowID     uuid.UUID              `json:"workflow_id"`
	Status         string                 `json:"status"`
	Progress       int                    `json:"progress"`
	CurrentSteps   []string               `json:"current_steps"`
	CompletedSteps int                    `json:"completed_steps"`
	TotalSteps     int                    `json:"total_steps"`
	StartedAt      time.Time              `json:"started_at"`
	UpdatedAt      time.Time              `json:"updated_at"`
	EstimatedEnd   *time.Time             `json:"estimated_end,omitempty"`
	Metrics        map[string]interface{} `json:"metrics,omitempty"`
}

ExecutionStatus represents detailed workflow execution status

type ExecutionTrace

type ExecutionTrace struct {
	ExecutionID uuid.UUID              `json:"execution_id"`
	Steps       []StepTrace            `json:"steps"`
	Timeline    []TimelineEvent        `json:"timeline"`
	Metadata    map[string]interface{} `json:"metadata"`
}

ExecutionTrace represents a trace of workflow execution

type ExtendedDistributedTask

type ExtendedDistributedTask struct {
	DistributedTask

	// Embedded task reference
	Task *Task `json:"task,omitempty"`

	// Coordination fields
	CoordinationMode    CoordinationMode `json:"coordination_mode"`
	CompletionMode      CompletionMode   `json:"completion_mode"`
	CompletionThreshold int              `json:"completion_threshold,omitempty"` // For threshold mode

	// Execution tracking
	ExecutionPlan *ExecutionPlan  `json:"execution_plan,omitempty"`
	Partitions    []TaskPartition `json:"partitions,omitempty"`
	Progress      *TaskProgress   `json:"progress,omitempty"`
	ResourceUsage *ResourceUsage  `json:"resource_usage,omitempty"`

	// Timing
	StartedAt         *time.Time    `json:"started_at,omitempty"`
	CompletedAt       *time.Time    `json:"completed_at,omitempty"`
	EstimatedDuration time.Duration `json:"estimated_duration,omitempty"`

	// Results aggregation
	ResultsCollected    int           `json:"results_collected"`
	FinalResult         interface{}   `json:"final_result,omitempty"`
	IntermediateResults []interface{} `json:"intermediate_results,omitempty"`
}

ExtendedDistributedTask extends the DistributedTask with production fields

func (*ExtendedDistributedTask) CalculateProgress

func (dt *ExtendedDistributedTask) CalculateProgress() float64

CalculateProgress calculates the overall progress of the distributed task

func (*ExtendedDistributedTask) GetEstimatedCompletion

func (dt *ExtendedDistributedTask) GetEstimatedCompletion() *time.Time

GetEstimatedCompletion returns the estimated completion time

func (*ExtendedDistributedTask) IsComplete

func (dt *ExtendedDistributedTask) IsComplete() bool

IsComplete checks if the distributed task is complete based on completion mode

type GitHubQuery

type GitHubQuery struct {
	// Type specifies the type of query
	Type GitHubQueryType `json:"type"`

	// Owner is the repository owner (organization or user)
	Owner string `json:"owner"`

	// Repo is the repository name
	Repo string `json:"repo"`

	// State is used for filtering pull requests or issues
	State string `json:"state,omitempty"`

	// Branch is used for filtering commits or other branch-specific queries
	Branch string `json:"branch,omitempty"`

	// ID is used when querying a specific resource by ID
	ID string `json:"id,omitempty"`

	// Number is used when querying a specific pull request or issue by number
	Number int `json:"number,omitempty"`
}

GitHubQuery represents a query to the GitHub API

type GitHubQueryType

type GitHubQueryType string

GitHubQueryType defines the type of GitHub query

const (
	// GitHubQueryTypeRepository represents a repository query
	GitHubQueryTypeRepository GitHubQueryType = "repository"

	// GitHubQueryTypePullRequests represents a pull requests query
	GitHubQueryTypePullRequests GitHubQueryType = "pull_requests"

	// GitHubQueryTypeIssues represents an issues query
	GitHubQueryTypeIssues GitHubQueryType = "issues"

	// GitHubQueryTypeCommits represents a commits query
	GitHubQueryTypeCommits GitHubQueryType = "commits"
)

type HarnessCCMAnomaly

type HarnessCCMAnomaly struct {
	ID            string         `json:"id"`
	Name          string         `json:"name"`
	Status        string         `json:"status"`
	CloudProvider string         `json:"cloudProvider"`
	ResourceID    string         `json:"resourceId"`
	ResourceName  string         `json:"resourceName"`
	Description   string         `json:"description"`
	AnomalyCost   float64        `json:"anomalyCost"`
	ExpectedCost  float64        `json:"expectedCost"`
	Currency      string         `json:"currency"`
	DetectedAt    time.Time      `json:"detectedAt"`
	StartTime     time.Time      `json:"startTime"`
	EndTime       time.Time      `json:"endTime"`
	Details       map[string]any `json:"details"`
}

HarnessCCMAnomaly represents a cost anomaly in CCM

type HarnessCCMAnomalyQuery

type HarnessCCMAnomalyQuery struct {
	StartTime      time.Time `json:"startTime"`
	EndTime        time.Time `json:"endTime"`
	Status         string    `json:"status"`
	CloudProvider  string    `json:"cloudProvider"`
	IncludeDetails bool      `json:"includeDetails"`
}

HarnessCCMAnomalyQuery defines parameters for querying cost anomalies

type HarnessCCMBudget

type HarnessCCMBudget struct {
	ID              string         `json:"id"`
	Name            string         `json:"name"`
	Type            string         `json:"type"`
	Amount          float64        `json:"amount"`
	Currency        string         `json:"currency"`
	Period          string         `json:"period"`
	StartDate       time.Time      `json:"startDate"`
	EndDate         time.Time      `json:"endDate"`
	ActualSpend     float64        `json:"actualSpend"`
	ForecastedSpend float64        `json:"forecastedSpend"`
	Status          string         `json:"status"`
	CreatedAt       time.Time      `json:"createdAt"`
	LastUpdatedAt   time.Time      `json:"lastUpdatedAt"`
	Details         map[string]any `json:"details"`
}

HarnessCCMBudget represents a budget in CCM

type HarnessCCMBudgetQuery

type HarnessCCMBudgetQuery struct {
	BudgetID       string `json:"budgetId"`
	Status         string `json:"status"`
	IncludeDetails bool   `json:"includeDetails"`
}

HarnessCCMBudgetQuery defines parameters for querying budgets

type HarnessCCMCostData

type HarnessCCMCostData struct {
	TotalCost     float64              `json:"totalCost"`
	Currency      string               `json:"currency"`
	TimeGrain     string               `json:"timeGrain"`
	StartTime     time.Time            `json:"startTime"`
	EndTime       time.Time            `json:"endTime"`
	CostBreakdown []HarnessCCMCostItem `json:"costBreakdown"`
	Details       map[string]any       `json:"details"`
}

HarnessCCMCostData represents cost data from CCM

type HarnessCCMCostItem

type HarnessCCMCostItem struct {
	Name       string  `json:"name"`
	Cost       float64 `json:"cost"`
	Percentage float64 `json:"percentage"`
}

HarnessCCMCostItem represents a cost item breakdown

type HarnessCCMCostQuery

type HarnessCCMCostQuery struct {
	StartTime      time.Time `json:"startTime"`
	EndTime        time.Time `json:"endTime"`
	GroupBy        []string  `json:"groupBy"`
	FilterBy       []string  `json:"filterBy"`
	CloudProvider  string    `json:"cloudProvider"`
	PerspectiveID  string    `json:"perspectiveId"`
	IncludeDetails bool      `json:"includeDetails"`
}

HarnessCCMCostQuery defines parameters for querying cloud cost data

type HarnessCCMRecommendation

type HarnessCCMRecommendation struct {
	ID               string         `json:"id"`
	Type             string         `json:"type"`
	Status           string         `json:"status"`
	CloudProvider    string         `json:"cloudProvider"`
	ResourceID       string         `json:"resourceId"`
	ResourceName     string         `json:"resourceName"`
	Description      string         `json:"description"`
	PotentialSavings float64        `json:"potentialSavings"`
	Currency         string         `json:"currency"`
	CreatedAt        time.Time      `json:"createdAt"`
	ExpiresAt        time.Time      `json:"expiresAt"`
	Details          map[string]any `json:"details"`
}

HarnessCCMRecommendation represents a cost optimization recommendation

type HarnessCCMRecommendationQuery

type HarnessCCMRecommendationQuery struct {
	Status             string `json:"status"`
	CloudProvider      string `json:"cloudProvider"`
	RecommendationType string `json:"type"`
	ResourceID         string `json:"resourceId"`
	IncludeDetails     bool   `json:"includeDetails"`
}

HarnessCCMRecommendationQuery defines parameters for querying recommendations

type HarnessCDDeployment

type HarnessCDDeployment struct {
	ID            string    `json:"id"`
	PipelineID    string    `json:"pipelineId"`
	ServiceID     string    `json:"serviceId"`
	EnvironmentID string    `json:"environmentId"`
	Environment   string    `json:"environment"` // Added for test compatibility
	Service       string    `json:"service"`     // Added for test compatibility
	Status        string    `json:"status"`
	StartTime     time.Time `json:"startTime"`
	EndTime       time.Time `json:"endTime"`
	ArtifactID    string    `json:"artifactId"`
	TriggeredBy   string    `json:"triggeredBy"`
}

HarnessCDDeployment represents a Harness CD deployment

type HarnessCDDeploymentEvent

type HarnessCDDeploymentEvent struct {
	EventType  string              `json:"eventType"`
	Deployment HarnessCDDeployment `json:"deployment"`
}

HarnessCDDeploymentEvent represents a Harness CD deployment webhook event

type HarnessCIBuild

type HarnessCIBuild struct {
	ID          string    `json:"id"`
	BuildNumber int       `json:"buildNumber"`
	PipelineID  string    `json:"pipelineId"`
	CommitID    string    `json:"commitId"`
	Branch      string    `json:"branch"`
	Status      string    `json:"status"`
	StartTime   time.Time `json:"startTime"`
	EndTime     time.Time `json:"endTime"`
	Duration    int64     `json:"duration"`
	TriggeredBy string    `json:"triggeredBy"`
}

HarnessCIBuild represents a Harness CI build

type HarnessCIBuildEvent

type HarnessCIBuildEvent struct {
	EventType string         `json:"eventType"`
	Build     HarnessCIBuild `json:"build"`
}

HarnessCIBuildEvent represents a Harness CI build webhook event

type HarnessFeatureFlag

type HarnessFeatureFlag struct {
	ID             string         `json:"id"`
	Name           string         `json:"name"`
	Identifier     string         `json:"identifier"`
	ProjectID      string         `json:"projectId"`
	Description    string         `json:"description"`
	Variations     []any          `json:"variations"`
	DefaultServeOn string         `json:"defaultServeOn"`
	State          string         `json:"state"`
	Kind           string         `json:"kind"`
	Tags           []string       `json:"tags"`
	Targeting      map[string]any `json:"targeting"`
}

HarnessFeatureFlag represents a Harness feature flag

type HarnessFeatureFlagEvent

type HarnessFeatureFlagEvent struct {
	EventType   string             `json:"eventType"`
	FeatureFlag HarnessFeatureFlag `json:"featureFlag"`
}

HarnessFeatureFlagEvent represents a Harness feature flag webhook event

type HarnessPipeline

type HarnessPipeline struct {
	ID             string    `json:"id"`
	Name           string    `json:"name"`
	Identifier     string    `json:"identifier"`
	ProjectID      string    `json:"projectId"`
	OrgID          string    `json:"orgId"`
	Status         string    `json:"status"`
	CreatedAt      time.Time `json:"createdAt"`
	LastRunAt      time.Time `json:"lastRunAt"`
	LastModifiedAt time.Time `json:"lastModifiedAt"`
	Tags           []string  `json:"tags"`
}

HarnessPipeline represents a Harness pipeline

type HarnessQuery

type HarnessQuery struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

HarnessQuery defines parameters for querying Harness

type HarnessSTOExperiment

type HarnessSTOExperiment struct {
	ID            string    `json:"id"`
	Name          string    `json:"name"`
	Status        string    `json:"status"`
	StartTime     time.Time `json:"startTime"`
	EndTime       time.Time `json:"endTime"`
	ServiceID     string    `json:"serviceId"`
	EnvironmentID string    `json:"environmentId"`
	Metrics       []string  `json:"metrics"`
}

HarnessSTOExperiment represents a Harness STO experiment

type HarnessSTOExperimentEvent

type HarnessSTOExperimentEvent struct {
	EventType  string               `json:"eventType"`
	Experiment HarnessSTOExperiment `json:"experiment"`
}

HarnessSTOExperimentEvent represents a Harness STO experiment webhook event

type HealthStatus

type HealthStatus string
const (
	HealthStatusHealthy   HealthStatus = "healthy"
	HealthStatusDegraded  HealthStatus = "degraded"
	HealthStatusUnhealthy HealthStatus = "unhealthy"
	HealthStatusUnknown   HealthStatus = "unknown"
)

type JSONMap

type JSONMap map[string]interface{}

JSONMap is a type alias for map[string]interface{} that implements sql.Scanner and driver.Valuer

func (*JSONMap) Scan

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

Scan implements sql.Scanner for JSONMap

func (JSONMap) Value

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

Value implements driver.Valuer for JSONMap

type KeyTypeRateLimit

type KeyTypeRateLimit struct {
	RequestsPerMinute int `json:"requests_per_minute"`
	RequestsPerHour   int `json:"requests_per_hour"`
	RequestsPerDay    int `json:"requests_per_day"`
}

KeyTypeRateLimit represents rate limits for a specific key type

type ManifestCapability

type ManifestCapability struct {
	ID               uuid.UUID `json:"id" db:"id"`
	ManifestID       uuid.UUID `json:"manifest_id" db:"manifest_id"`
	CapabilityType   string    `json:"capability_type" db:"capability_type"`
	CapabilityName   string    `json:"capability_name" db:"capability_name"`
	CapabilityConfig JSONMap   `json:"capability_config" db:"capability_config"`
	Required         bool      `json:"required" db:"required"`
	CreatedAt        time.Time `json:"created_at" db:"created_at"`
}

ManifestCapability represents a specific capability of an agent manifest

type MemberActivity

type MemberActivity struct {
	WorkspaceID    uuid.UUID              `json:"workspace_id"`
	AgentID        string                 `json:"agent_id"`
	AgentName      string                 `json:"agent_name"`
	LastActivityAt time.Time              `json:"last_activity_at"`
	ActivityType   string                 `json:"activity_type"`
	ActivityCount  int64                  `json:"activity_count"`
	Details        map[string]interface{} `json:"details"`
}

MemberActivity represents activity of a workspace member

type MemberPresence

type MemberPresence struct {
	WorkspaceID uuid.UUID `json:"workspace_id"`
	AgentID     string    `json:"agent_id"`
	AgentName   string    `json:"agent_name"`
	Status      string    `json:"status"` // online, away, busy, offline
	LastSeenAt  time.Time `json:"last_seen_at"`
	Location    string    `json:"location,omitempty"` // Current location in workspace (e.g., document ID)
}

MemberPresence represents the presence status of a workspace member

type MemberRole

type MemberRole string

MemberRole defines the role of a member in a workspace

const (
	MemberRoleOwner  MemberRole = "owner"
	MemberRoleAdmin  MemberRole = "admin"
	MemberRoleMember MemberRole = "member"
	MemberRoleViewer MemberRole = "viewer"
)

type MetricsClient

type MetricsClient interface {
	IncrementCounter(name string, value float64, tags map[string]string)
	RecordGauge(name string, value float64, tags map[string]string)
	RecordHistogram(name string, value float64, tags map[string]string)
	RecordTiming(name string, duration time.Duration, tags map[string]string)
}

MetricsClient interface for metrics collection

type Model

type Model struct {
	ID        string     `json:"id" db:"id"`
	TenantID  string     `json:"tenant_id" db:"tenant_id"`
	Name      string     `json:"name" db:"name"`
	CreatedAt *time.Time `json:"created_at,omitempty" db:"created_at"`
	UpdatedAt *time.Time `json:"updated_at,omitempty" db:"updated_at"`
}

type ModelFilter

type ModelFilter struct {
	ID       string `json:"id,omitempty"`
	TenantID string `json:"tenant_id,omitempty"`
	Name     string `json:"name,omitempty"`
}

ModelFilter defines filter criteria for model operations

type Module

type Module struct {
	ID           string       `json:"id"`
	Artifacts    []Artifact   `json:"artifacts"`
	Dependencies []Dependency `json:"dependencies"`
}

Module represents a module in an Artifactory build

type MultiAgentWorkflowStep

type MultiAgentWorkflowStep struct {
	ID                   uuid.UUID `json:"id" db:"id"`
	WorkflowID           uuid.UUID `json:"workflow_id" db:"workflow_id"`
	Name                 string    `json:"name" db:"name"`
	Type                 string    `json:"type" db:"type"`
	Order                int       `json:"order" db:"order"`
	Config               JSONMap   `json:"config" db:"config"`
	Dependencies         []string  `json:"dependencies" db:"dependencies"`
	AssignedAgents       []string  `json:"assigned_agents" db:"assigned_agents"`
	RequiredCapabilities []string  `json:"required_capabilities" db:"required_capabilities"`
	TimeoutSeconds       int       `json:"timeout_seconds" db:"timeout_seconds"`
	RetryPolicy          JSONMap   `json:"retry_policy" db:"retry_policy"`
	CreatedAt            time.Time `json:"created_at" db:"created_at"`
}

Enhanced WorkflowStep for multi-agent support

type NotificationSettings

type NotificationSettings struct {
	Enabled         bool                   `json:"enabled"`
	EmailEnabled    bool                   `json:"email_enabled"`
	WebhookEnabled  bool                   `json:"webhook_enabled"`
	WebhookURL      string                 `json:"webhook_url,omitempty"`
	EventTypes      []string               `json:"event_types,omitempty"`
	DigestFrequency string                 `json:"digest_frequency,omitempty"` // immediate, hourly, daily, weekly
	Preferences     map[string]interface{} `json:"preferences,omitempty"`
}

NotificationSettings defines notification preferences

type OAuthToken

type OAuthToken struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	TokenType    string    `json:"token_type"`
	ExpiresAt    time.Time `json:"expires_at,omitempty"`
	Scope        string    `json:"scope,omitempty"`
}

OAuthToken represents an OAuth2 token with metadata

func (*OAuthToken) IsExpired

func (o *OAuthToken) IsExpired() bool

IsExpired checks if the OAuth token is expired

func (*OAuthToken) ShouldRefresh

func (o *OAuthToken) ShouldRefresh() bool

ShouldRefresh checks if the token should be refreshed (80% of lifetime)

type OperationGroup

type OperationGroup struct {
	Name        string   `json:"name"`
	DisplayName string   `json:"displayName"`
	Description string   `json:"description"`
	Operations  []string `json:"operations"`
}

OperationGroup groups related operations together

type OptimizationSuggestion

type OptimizationSuggestion struct {
	Type        string  `json:"type"`
	StepID      string  `json:"step_id,omitempty"`
	Description string  `json:"description"`
	Impact      float64 `json:"impact"` // Estimated improvement percentage
}

OptimizationSuggestion represents a suggestion for workflow optimization

type Organization

type Organization struct {
	ID            uuid.UUID `json:"id" db:"id"`
	Name          string    `json:"name" db:"name"`
	Slug          string    `json:"slug" db:"slug"`
	IsolationMode string    `json:"isolation_mode" db:"isolation_mode"`
	Settings      JSONMap   `json:"settings" db:"settings"`
	CreatedAt     time.Time `json:"created_at" db:"created_at"`
	UpdatedAt     time.Time `json:"updated_at" db:"updated_at"`
}

Organization represents a top-level organizational unit

func (*Organization) AllowsCrossTenantAccess

func (o *Organization) AllowsCrossTenantAccess() bool

AllowsCrossTenantAccess checks if the organization allows any cross-tenant access

func (*Organization) IsStrictlyIsolated

func (o *Organization) IsStrictlyIsolated() bool

IsStrictlyIsolated checks if the organization enforces strict tenant isolation

type OrganizationTenant

type OrganizationTenant struct {
	OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"`
	TenantID       uuid.UUID `json:"tenant_id" db:"tenant_id"`
	TenantName     string    `json:"tenant_name" db:"tenant_name"`
	TenantType     string    `json:"tenant_type" db:"tenant_type"`
	IsolationLevel string    `json:"isolation_level" db:"isolation_level"`
	CreatedAt      time.Time `json:"created_at" db:"created_at"`
}

OrganizationTenant represents the mapping between organizations and tenants

func (*OrganizationTenant) IsAdmin

func (ot *OrganizationTenant) IsAdmin() bool

IsAdmin checks if the tenant has admin privileges

func (*OrganizationTenant) IsRestricted

func (ot *OrganizationTenant) IsRestricted() bool

IsRestricted checks if the tenant has restricted access

type OrganizationTool

type OrganizationTool struct {
	ID             string `json:"id" db:"id"`
	OrganizationID string `json:"organization_id" db:"organization_id"`
	TenantID       string `json:"tenant_id" db:"tenant_id"`
	TemplateID     string `json:"template_id" db:"template_id"`

	// Instance configuration
	InstanceName string `json:"instance_name" db:"instance_name"`
	DisplayName  string `json:"display_name,omitempty" db:"display_name"`
	Description  string `json:"description,omitempty" db:"description"`

	// Configuration and credentials
	InstanceConfig       map[string]interface{} `json:"instance_config" db:"instance_config"`
	CredentialsEncrypted []byte                 `json:"-" db:"credentials_encrypted"`
	EncryptionKeyID      *string                `json:"-" db:"encryption_key_id"`

	// Customizations
	CustomMappings     *json.RawMessage `json:"custom_mappings,omitempty" db:"custom_mappings"`
	EnabledFeatures    *json.RawMessage `json:"enabled_features,omitempty" db:"enabled_features"`
	DisabledOperations []string         `json:"disabled_operations,omitempty" db:"disabled_operations"`
	RateLimitOverrides *json.RawMessage `json:"rate_limit_overrides,omitempty" db:"rate_limit_overrides"`
	CustomHeaders      *json.RawMessage `json:"custom_headers,omitempty" db:"custom_headers"`

	// Health and status
	Status          string           `json:"status" db:"status"`
	IsActive        bool             `json:"is_active" db:"is_active"`
	LastHealthCheck *time.Time       `json:"last_health_check,omitempty" db:"last_health_check"`
	HealthStatus    *json.RawMessage `json:"health_status,omitempty" db:"health_status"`
	HealthMessage   string           `json:"health_message,omitempty" db:"health_message"`

	// Usage tracking
	LastUsedAt *time.Time `json:"last_used_at,omitempty" db:"last_used_at"`
	UsageCount int        `json:"usage_count" db:"usage_count"`
	ErrorCount int        `json:"error_count" db:"error_count"`

	// Metadata
	Tags     []string         `json:"tags,omitempty" db:"tags"`
	Metadata *json.RawMessage `json:"metadata,omitempty" db:"metadata"`

	// Audit
	CreatedAt time.Time `json:"created_at" db:"created_at"`
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
	CreatedBy *string   `json:"created_by,omitempty" db:"created_by"`
	UpdatedBy *string   `json:"updated_by,omitempty" db:"updated_by"`
}

OrganizationTool represents an organization-specific tool instance based on a template

type OrganizationToolUsage

type OrganizationToolUsage struct {
	ID                 string          `json:"id" db:"id"`
	OrganizationToolID string          `json:"organization_tool_id" db:"organization_tool_id"`
	OperationName      string          `json:"operation_name" db:"operation_name"`
	ExecutionCount     int             `json:"execution_count" db:"execution_count"`
	SuccessCount       int             `json:"success_count" db:"success_count"`
	ErrorCount         int             `json:"error_count" db:"error_count"`
	AvgResponseTimeMs  int             `json:"avg_response_time_ms,omitempty" db:"avg_response_time_ms"`
	MinResponseTimeMs  int             `json:"min_response_time_ms,omitempty" db:"min_response_time_ms"`
	MaxResponseTimeMs  int             `json:"max_response_time_ms,omitempty" db:"max_response_time_ms"`
	PeriodStart        time.Time       `json:"period_start" db:"period_start"`
	PeriodEnd          time.Time       `json:"period_end" db:"period_end"`
	ErrorTypes         json.RawMessage `json:"error_types,omitempty" db:"error_types"`
}

OrganizationToolUsage tracks usage of organization tools for analytics

type PackageAPIChange

type PackageAPIChange struct {
	ID             uuid.UUID     `json:"id" db:"id"`
	ReleaseID      uuid.UUID     `json:"release_id" db:"release_id"`
	ChangeType     APIChangeType `json:"change_type" db:"change_type"`
	APISignature   string        `json:"api_signature" db:"api_signature"`
	Description    *string       `json:"description,omitempty" db:"description"`
	Breaking       bool          `json:"breaking" db:"breaking"`
	MigrationGuide *string       `json:"migration_guide,omitempty" db:"migration_guide"`
	FilePath       *string       `json:"file_path,omitempty" db:"file_path"`
	LineNumber     *int          `json:"line_number,omitempty" db:"line_number"`
	Metadata       JSONMap       `json:"metadata" db:"metadata"`
	CreatedAt      time.Time     `json:"created_at" db:"created_at"`
}

PackageAPIChange tracks API/interface changes in a release

type PackageAsset

type PackageAsset struct {
	ID             uuid.UUID `json:"id" db:"id"`
	ReleaseID      uuid.UUID `json:"release_id" db:"release_id"`
	Name           string    `json:"name" db:"name"`
	ContentType    *string   `json:"content_type,omitempty" db:"content_type"`
	SizeBytes      *int64    `json:"size_bytes,omitempty" db:"size_bytes"`
	DownloadURL    *string   `json:"download_url,omitempty" db:"download_url"`
	ArtifactoryURL *string   `json:"artifactory_url,omitempty" db:"artifactory_url"`
	SHA256Checksum *string   `json:"sha256_checksum,omitempty" db:"sha256_checksum"`
	SHA1Checksum   *string   `json:"sha1_checksum,omitempty" db:"sha1_checksum"`
	MD5Checksum    *string   `json:"md5_checksum,omitempty" db:"md5_checksum"`
	Metadata       JSONMap   `json:"metadata" db:"metadata"`
	CreatedAt      time.Time `json:"created_at" db:"created_at"`
}

PackageAsset represents an artifact associated with a release

type PackageDependency

type PackageDependency struct {
	ID                uuid.UUID       `json:"id" db:"id"`
	ReleaseID         uuid.UUID       `json:"release_id" db:"release_id"`
	DependencyName    string          `json:"dependency_name" db:"dependency_name"`
	VersionConstraint *string         `json:"version_constraint,omitempty" db:"version_constraint"`
	DependencyType    *DependencyType `json:"dependency_type,omitempty" db:"dependency_type"`
	RepositoryURL     *string         `json:"repository_url,omitempty" db:"repository_url"`
	ResolvedVersion   *string         `json:"resolved_version,omitempty" db:"resolved_version"`
	Metadata          JSONMap         `json:"metadata" db:"metadata"`
	CreatedAt         time.Time       `json:"created_at" db:"created_at"`
}

PackageDependency represents a dependency of a package release

type PackageRelease

type PackageRelease struct {
	ID               uuid.UUID `json:"id" db:"id"`
	TenantID         uuid.UUID `json:"tenant_id" db:"tenant_id"`
	RepositoryName   string    `json:"repository_name" db:"repository_name"`
	PackageName      string    `json:"package_name" db:"package_name"`
	Version          string    `json:"version" db:"version"`
	VersionMajor     *int      `json:"version_major,omitempty" db:"version_major"`
	VersionMinor     *int      `json:"version_minor,omitempty" db:"version_minor"`
	VersionPatch     *int      `json:"version_patch,omitempty" db:"version_patch"`
	Prerelease       *string   `json:"prerelease,omitempty" db:"prerelease"`
	IsBreakingChange bool      `json:"is_breaking_change" db:"is_breaking_change"`
	ReleaseNotes     *string   `json:"release_notes,omitempty" db:"release_notes"`
	Changelog        *string   `json:"changelog,omitempty" db:"changelog"`
	PublishedAt      time.Time `json:"published_at" db:"published_at"`
	AuthorLogin      *string   `json:"author_login,omitempty" db:"author_login"`
	GitHubReleaseID  *int64    `json:"github_release_id,omitempty" db:"github_release_id"`
	ArtifactoryPath  *string   `json:"artifactory_path,omitempty" db:"artifactory_path"`
	PackageType      string    `json:"package_type" db:"package_type"`
	Description      *string   `json:"description,omitempty" db:"description"`
	License          *string   `json:"license,omitempty" db:"license"`
	Homepage         *string   `json:"homepage,omitempty" db:"homepage"`
	DocumentationURL *string   `json:"documentation_url,omitempty" db:"documentation_url"`
	Metadata         JSONMap   `json:"metadata" db:"metadata"`
	CreatedAt        time.Time `json:"created_at" db:"created_at"`
	UpdatedAt        time.Time `json:"updated_at" db:"updated_at"`
}

PackageRelease represents a package release in the system

type PackageReleaseCreate

type PackageReleaseCreate struct {
	TenantID         uuid.UUID `json:"tenant_id" validate:"required"`
	RepositoryName   string    `json:"repository_name" validate:"required"`
	PackageName      string    `json:"package_name" validate:"required"`
	Version          string    `json:"version" validate:"required"`
	VersionMajor     *int      `json:"version_major,omitempty"`
	VersionMinor     *int      `json:"version_minor,omitempty"`
	VersionPatch     *int      `json:"version_patch,omitempty"`
	Prerelease       *string   `json:"prerelease,omitempty"`
	IsBreakingChange bool      `json:"is_breaking_change"`
	ReleaseNotes     *string   `json:"release_notes,omitempty"`
	Changelog        *string   `json:"changelog,omitempty"`
	PublishedAt      time.Time `json:"published_at" validate:"required"`
	AuthorLogin      *string   `json:"author_login,omitempty"`
	GitHubReleaseID  *int64    `json:"github_release_id,omitempty"`
	PackageType      string    `json:"package_type" validate:"required"`
	Description      *string   `json:"description,omitempty"`
	License          *string   `json:"license,omitempty"`
	Homepage         *string   `json:"homepage,omitempty"`
	DocumentationURL *string   `json:"documentation_url,omitempty"`
	Metadata         JSONMap   `json:"metadata,omitempty"`
}

PackageReleaseCreate represents the data needed to create a new package release

type PackageReleaseWithDetails

type PackageReleaseWithDetails struct {
	Release      PackageRelease      `json:"release"`
	Assets       []PackageAsset      `json:"assets,omitempty"`
	APIChanges   []PackageAPIChange  `json:"api_changes,omitempty"`
	Dependencies []PackageDependency `json:"dependencies,omitempty"`
}

PackageReleaseWithDetails includes all related data for a release

type PackageType

type PackageType string

PackageType represents the type of package

const (
	PackageTypeNPM     PackageType = "npm"
	PackageTypeMaven   PackageType = "maven"
	PackageTypePython  PackageType = "python"
	PackageTypeGo      PackageType = "go"
	PackageTypeDocker  PackageType = "docker"
	PackageTypeGeneric PackageType = "generic"
)

type PaginationInfo

type PaginationInfo struct {
	Total      int  `json:"total"`
	Page       int  `json:"page"`
	PageSize   int  `json:"page_size"`
	TotalPages int  `json:"total_pages"`
	HasNext    bool `json:"has_next"`
	HasPrev    bool `json:"has_prev"`
}

PaginationInfo contains pagination metadata

type ParsedReleaseNotes

type ParsedReleaseNotes struct {
	RawNotes          string                 `json:"raw_notes"`
	HasBreakingChange bool                   `json:"has_breaking_changes"`
	BreakingChanges   []string               `json:"breaking_changes,omitempty"`
	NewFeatures       []string               `json:"new_features,omitempty"`
	BugFixes          []string               `json:"bug_fixes,omitempty"`
	MigrationGuide    *string                `json:"migration_guide,omitempty"`
	Sections          []ReleaseNotesSection  `json:"sections,omitempty"`
	Metadata          map[string]interface{} `json:"metadata,omitempty"`
}

ParsedReleaseNotes represents structured release notes

type PassthroughAuthBundle

type PassthroughAuthBundle struct {
	// Support multiple credentials for different services
	Credentials map[string]*PassthroughCredential `json:"credentials,omitempty"`

	// Session tokens for stateful APIs
	SessionTokens map[string]string `json:"session_tokens,omitempty"`

	// OAuth tokens with refresh capability
	OAuthTokens map[string]*OAuthToken `json:"oauth_tokens,omitempty"`

	// Raw headers for custom auth
	CustomHeaders map[string]string `json:"custom_headers,omitempty"`

	// Agent metadata for audit/security
	AgentContext *AgentContext `json:"agent_context,omitempty"`
}

PassthroughAuthBundle contains all authentication credentials for a request

func (*PassthroughAuthBundle) GetCredentialForTool

func (p *PassthroughAuthBundle) GetCredentialForTool(toolName string) *PassthroughCredential

GetCredentialForTool returns the most appropriate credential for a tool

func (*PassthroughAuthBundle) GetOAuthTokenForTool

func (p *PassthroughAuthBundle) GetOAuthTokenForTool(toolName string) *OAuthToken

GetOAuthTokenForTool returns the OAuth token for a specific tool

func (*PassthroughAuthBundle) Validate

func (p *PassthroughAuthBundle) Validate() error

Validate performs validation on the PassthroughAuthBundle

type PassthroughConfig

type PassthroughConfig struct {
	Mode              string `json:"mode"`                // optional, required, disabled
	FallbackToService bool   `json:"fallback_to_service"` // Allow fallback to service account
}

PassthroughConfig defines how user token passthrough should be handled

type PassthroughCredential

type PassthroughCredential struct {
	Type       string            `json:"type"` // bearer, api_key, basic, custom, aws_signature, digest
	Token      string            `json:"token,omitempty"`
	Username   string            `json:"username,omitempty"`
	Password   string            `json:"password,omitempty"`
	KeyName    string            `json:"key_name,omitempty"`
	KeyValue   string            `json:"key_value,omitempty"`
	Properties map[string]string `json:"properties,omitempty"` // Flexible fields for tool-specific needs
}

PassthroughCredential represents a single authentication credential

func (*PassthroughCredential) MaskedPassword

func (p *PassthroughCredential) MaskedPassword() string

MaskedPassword returns a masked version of the password for logging

func (*PassthroughCredential) MaskedToken

func (p *PassthroughCredential) MaskedToken() string

MaskedToken returns a masked version of the token for logging

func (*PassthroughCredential) SafeForLogging

func (p *PassthroughCredential) SafeForLogging() PassthroughCredential

SafeForLogging returns a copy with masked sensitive data for logging

type PassthroughRule

type PassthroughRule struct {
	RuleID        string   `json:"rule_id"`
	AgentTypes    []string `json:"agent_types"`
	Actions       []string `json:"actions"` // Specific actions that allow passthrough
	Environments  []string `json:"environments"`
	AuthRequired  bool     `json:"auth_required"`
	AllowFallback bool     `json:"allow_fallback"`
	Priority      int      `json:"priority"` // Higher priority rules are evaluated first
}

PassthroughRule defines when passthrough auth is allowed

type PassthroughSecurityPolicy

type PassthroughSecurityPolicy struct {
	RequireEncryption   bool     `json:"require_encryption"`
	AllowedDomains      []string `json:"allowed_domains"`
	BlockedDomains      []string `json:"blocked_domains"`
	MaxTokenAge         int      `json:"max_token_age_seconds"`
	RequireUserContext  bool     `json:"require_user_context"`
	RequireAgentContext bool     `json:"require_agent_context"`
	AuditLevel          string   `json:"audit_level"` // none, basic, detailed, verbose
	ValidateTokenFormat bool     `json:"validate_token_format"`
}

PassthroughSecurityPolicy defines security requirements for passthrough auth

type PendingApproval

type PendingApproval struct {
	ExecutionID uuid.UUID              `json:"execution_id"`
	WorkflowID  uuid.UUID              `json:"workflow_id"`
	StepID      string                 `json:"step_id"`
	StepName    string                 `json:"step_name"`
	RequestedAt time.Time              `json:"requested_at"`
	RequiredBy  []string               `json:"required_by"`
	ApprovedBy  []string               `json:"approved_by,omitempty"`
	RejectedBy  []string               `json:"rejected_by,omitempty"`
	DueBy       *time.Time             `json:"due_by,omitempty"`
	Context     map[string]interface{} `json:"context,omitempty"`
}

PendingApproval represents a pending approval request

type Prompt

type Prompt struct {
	ID          string           `json:"id" db:"id"`
	TenantID    string           `json:"tenant_id" db:"tenant_id"`
	Name        string           `json:"name" db:"name"`
	Description string           `json:"description" db:"description"`
	Arguments   []PromptArgument `json:"arguments" db:"arguments"`
	Template    string           `json:"template" db:"template"`
	Category    string           `json:"category,omitempty" db:"category"`
	Tags        []string         `json:"tags,omitempty" db:"tags"`
	Metadata    JSONMap          `json:"metadata,omitempty" db:"metadata"`
	CreatedAt   time.Time        `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time        `json:"updated_at" db:"updated_at"`
}

Prompt represents a reusable prompt template

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required"`
	Default     string `json:"default,omitempty"`
}

PromptArgument represents an argument in a prompt template

type PromptArgumentList

type PromptArgumentList []PromptArgument

PromptArgumentList is a custom type for storing prompt arguments as JSON

func (*PromptArgumentList) Scan

func (p *PromptArgumentList) Scan(value interface{}) error

Scan implements the sql.Scanner interface

func (PromptArgumentList) Value

func (p PromptArgumentList) Value() (driver.Value, error)

Value implements the driver.Valuer interface

type PromptCreateRequest

type PromptCreateRequest struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Arguments   []PromptArgument       `json:"arguments,omitempty"`
	Template    string                 `json:"template"`
	Category    string                 `json:"category,omitempty"`
	Tags        []string               `json:"tags,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

PromptCreateRequest represents a request to create a new prompt

type PromptListRequest

type PromptListRequest struct {
	TenantID string   `json:"tenant_id"`
	Category string   `json:"category,omitempty"`
	Tags     []string `json:"tags,omitempty"`
	Limit    int      `json:"limit,omitempty"`
	Offset   int      `json:"offset,omitempty"`
}

PromptListRequest represents parameters for listing prompts

type PromptMessage

type PromptMessage struct {
	Role    string `json:"role"` // "user", "assistant", "system"
	Content string `json:"content"`
}

PromptMessage represents a message in the rendered prompt

type PromptRenderRequest

type PromptRenderRequest struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments"`
}

PromptRenderRequest represents a request to render a prompt with arguments

type PromptRenderResponse

type PromptRenderResponse struct {
	Messages []PromptMessage `json:"messages"`
}

PromptRenderResponse represents the response from rendering a prompt

type PromptUpdateRequest

type PromptUpdateRequest struct {
	Name        *string                `json:"name,omitempty"`
	Description *string                `json:"description,omitempty"`
	Arguments   []PromptArgument       `json:"arguments,omitempty"`
	Template    *string                `json:"template,omitempty"`
	Category    *string                `json:"category,omitempty"`
	Tags        []string               `json:"tags,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

PromptUpdateRequest represents a request to update a prompt

type QueryOptions

type QueryOptions struct {
	Limit  int    `json:"limit"`
	Offset int    `json:"offset"`
	SortBy string `json:"sortBy"`
	Order  string `json:"order"`
}

Database query options

type RateLimitConfig

type RateLimitConfig struct {
	// Default rate limits
	DefaultRequestsPerMinute int `json:"default_requests_per_minute"`
	DefaultRequestsPerHour   int `json:"default_requests_per_hour"`
	DefaultRequestsPerDay    int `json:"default_requests_per_day"`

	// Key type specific overrides
	KeyTypeOverrides map[string]KeyTypeRateLimit `json:"key_type_overrides,omitempty"`

	// Endpoint specific overrides
	EndpointOverrides map[string]EndpointRateLimit `json:"endpoint_overrides,omitempty"`
}

RateLimitConfig represents rate limiting configuration

func (*RateLimitConfig) Scan

func (r *RateLimitConfig) Scan(value interface{}) error

Scan implements sql.Scanner for RateLimitConfig

func (RateLimitConfig) Value

func (r RateLimitConfig) Value() (driver.Value, error)

Value implements driver.Valuer for RateLimitConfig

type RateLimitInfo

type RateLimitInfo struct {
	Limit     int           `json:"limit"`               // Rate limit
	Remaining int           `json:"remaining"`           // Remaining requests
	Reset     time.Time     `json:"reset"`               // When limit resets
	Window    time.Duration `json:"window"`              // Rate limit window
	Scope     string        `json:"scope,omitempty"`     // Scope of rate limit
	TierInfo  string        `json:"tier_info,omitempty"` // Information about tier/plan
}

RateLimitInfo provides rate limit details

type RecoveryStep

type RecoveryStep struct {
	Order       int                    `json:"order"`                // Step order
	Action      string                 `json:"action"`               // Action to take
	Description string                 `json:"description"`          // Detailed description
	Tool        string                 `json:"tool,omitempty"`       // Tool to use for this step
	Parameters  map[string]interface{} `json:"parameters,omitempty"` // Parameters for the action
	Optional    bool                   `json:"optional,omitempty"`   // Whether step is optional
}

RecoveryStep represents a step in error recovery

type RelationshipType

type RelationshipType string

RelationshipType represents the type of relationship between entities

const (
	// RelationshipTypeReferences indicates an entity references another entity
	RelationshipTypeReferences RelationshipType = "references"
	// RelationshipTypeContains indicates an entity contains another entity
	RelationshipTypeContains RelationshipType = "contains"
	// RelationshipTypeCreates indicates an entity created another entity
	RelationshipTypeCreates RelationshipType = "creates"
	// RelationshipTypeModifies indicates an entity modified another entity
	RelationshipTypeModifies RelationshipType = "modifies"
	// RelationshipTypeAssociates indicates a general association between entities
	RelationshipTypeAssociates RelationshipType = "associates"
	// RelationshipTypeDependsOn indicates an entity depends on another entity
	RelationshipTypeDependsOn RelationshipType = "depends_on"
	// RelationshipTypeImplements indicates an entity implements another entity
	RelationshipTypeImplements RelationshipType = "implements"
	// RelationshipTypeExtends indicates an entity extends another entity
	RelationshipTypeExtends RelationshipType = "extends"
	// RelationshipTypeReplaces indicates an entity replaces another entity
	RelationshipTypeReplaces RelationshipType = "replaces"
	// RelationshipTypeComments indicates an entity is a comment on another entity
	RelationshipTypeComments RelationshipType = "comments"
)

Relationship types

type ReleaseNotesSection

type ReleaseNotesSection struct {
	Title   string   `json:"title"`
	Content []string `json:"content"`
}

ReleaseNotesSection represents a parsed section of release notes

type RepoSummary

type RepoSummary struct {
	RepoKey      string `json:"repoKey"`
	RepoType     string `json:"repoType"`
	FoldersCount int    `json:"foldersCount"`
	FilesCount   int    `json:"filesCount"`
	UsedSpace    string `json:"usedSpace"`
	ItemsCount   int    `json:"itemsCount"`
	PackageType  string `json:"packageType"`
	Percentage   string `json:"percentage"`
}

RepoSummary represents a repository summary in Artifactory

type Resource

type Resource struct {
	ID          string    `json:"id" db:"id"`
	TenantID    string    `json:"tenant_id" db:"tenant_id"`
	URI         string    `json:"uri" db:"uri"`
	Name        string    `json:"name" db:"name"`
	Description string    `json:"description,omitempty" db:"description"`
	MimeType    string    `json:"mimeType" db:"mime_type"`
	Content     string    `json:"content,omitempty" db:"content"`
	Metadata    JSONMap   `json:"metadata,omitempty" db:"metadata"`
	Tags        []string  `json:"tags,omitempty" db:"tags"`
	CreatedAt   time.Time `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" db:"updated_at"`
}

Resource represents a resource that can be accessed by AI agents

type ResourceContent

type ResourceContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType"`
	Content  string `json:"content"`
}

ResourceContent represents the content of a resource

type ResourceCreateRequest

type ResourceCreateRequest struct {
	URI         string                 `json:"uri"`
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	MimeType    string                 `json:"mimeType"`
	Content     string                 `json:"content"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	Tags        []string               `json:"tags,omitempty"`
}

ResourceCreateRequest represents a request to create a new resource

type ResourceInfo

type ResourceInfo struct {
	Type       string                 `json:"type"`                 // Resource type (e.g., "repository", "issue")
	ID         string                 `json:"id,omitempty"`         // Resource identifier
	Name       string                 `json:"name,omitempty"`       // Resource name
	Path       string                 `json:"path,omitempty"`       // Resource path or location
	Owner      string                 `json:"owner,omitempty"`      // Resource owner
	State      string                 `json:"state,omitempty"`      // Current resource state
	Attributes map[string]interface{} `json:"attributes,omitempty"` // Additional attributes
}

ResourceInfo describes an affected resource

type ResourceListRequest

type ResourceListRequest struct {
	TenantID string                 `json:"tenant_id"`
	Filter   map[string]interface{} `json:"filter,omitempty"`
	Limit    int                    `json:"limit,omitempty"`
	Offset   int                    `json:"offset,omitempty"`
}

ResourceListRequest represents parameters for listing resources

type ResourceMetrics

type ResourceMetrics struct {
	CPUSeconds      float64 `json:"cpu_seconds"`
	MemoryMBSeconds float64 `json:"memory_mb_seconds"`
	NetworkMB       float64 `json:"network_mb"`
	StorageMB       float64 `json:"storage_mb"`
}

type ResourceSubscription

type ResourceSubscription struct {
	ID         string    `json:"id" db:"id"`
	TenantID   string    `json:"tenant_id" db:"tenant_id"`
	ResourceID string    `json:"resource_id" db:"resource_id"`
	AgentID    string    `json:"agent_id" db:"agent_id"`
	Events     []string  `json:"events" db:"events"` // "created", "updated", "deleted"
	CreatedAt  time.Time `json:"created_at" db:"created_at"`
}

ResourceSubscription represents a subscription to resource changes

type ResourceUpdateRequest

type ResourceUpdateRequest struct {
	Name        *string                `json:"name,omitempty"`
	Description *string                `json:"description,omitempty"`
	MimeType    *string                `json:"mimeType,omitempty"`
	Content     *string                `json:"content,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	Tags        []string               `json:"tags,omitempty"`
}

ResourceUpdateRequest represents a request to update a resource

type ResourceUsage

type ResourceUsage struct {
	TaskID      uuid.UUID `json:"task_id"`
	CPUPercent  float64   `json:"cpu_percent"`
	MemoryMB    int64     `json:"memory_mb"`
	DiskIOMB    int64     `json:"disk_io_mb"`
	NetworkMB   int64     `json:"network_mb"`
	GPUPercent  float64   `json:"gpu_percent,omitempty"`
	StartTime   time.Time `json:"start_time"`
	LastUpdated time.Time `json:"last_updated"`
}

ResourceUsage represents resource usage for a task

type RetryStrategy

type RetryStrategy struct {
	Retryable      bool          `json:"retryable"`                 // Whether error is retryable
	MaxAttempts    int           `json:"max_attempts,omitempty"`    // Maximum retry attempts
	BackoffType    string        `json:"backoff_type,omitempty"`    // Backoff strategy (exponential, linear)
	InitialDelay   time.Duration `json:"initial_delay,omitempty"`   // Initial retry delay
	MaxDelay       time.Duration `json:"max_delay,omitempty"`       // Maximum retry delay
	RetryCondition string        `json:"retry_condition,omitempty"` // Condition for retry
}

RetryStrategy provides retry guidance

type RuleAction

type RuleAction struct {
	Type       string                 `json:"type"` // webhook, notification, task, etc.
	Parameters map[string]interface{} `json:"parameters"`
}

RuleAction defines an action for an automation rule

type RuleCondition

type RuleCondition struct {
	Field    string      `json:"field"`
	Operator string      `json:"operator"` // eq, ne, gt, lt, contains, etc.
	Value    interface{} `json:"value"`
}

RuleCondition defines a condition for an automation rule

type SecuritySettings

type SecuritySettings struct {
	RequireMFA     bool     `json:"require_mfa"`
	AllowAPIAccess bool     `json:"allow_api_access"`
	IPWhitelist    []string `json:"ip_whitelist,omitempty"`
	SessionTimeout int      `json:"session_timeout"` // minutes
	DataEncryption bool     `json:"data_encryption"`
	AuditLogging   bool     `json:"audit_logging"`
	ComplianceMode string   `json:"compliance_mode,omitempty"` // HIPAA, SOC2, etc.
	RetentionDays  int      `json:"retention_days,omitempty"`
}

SecuritySettings defines security preferences

type ServiceType

type ServiceType string

ServiceType represents the type of third-party service

const (
	ServiceTypeGitHub      ServiceType = "github"
	ServiceTypeHarness     ServiceType = "harness"
	ServiceTypeAWS         ServiceType = "aws"
	ServiceTypeAzure       ServiceType = "azure"
	ServiceTypeGCP         ServiceType = "gcp"
	ServiceTypeSnyk        ServiceType = "snyk"
	ServiceTypeJira        ServiceType = "jira"
	ServiceTypeSlack       ServiceType = "slack"
	ServiceTypeSonarQube   ServiceType = "sonarqube"
	ServiceTypeArtifactory ServiceType = "artifactory"
	ServiceTypeJenkins     ServiceType = "jenkins"
	ServiceTypeGitLab      ServiceType = "gitlab"
	ServiceTypeBitbucket   ServiceType = "bitbucket"
	ServiceTypeConfluence  ServiceType = "confluence"
	ServiceTypeGeneric     ServiceType = "generic"
)

type SessionFilter

type SessionFilter struct {
	TenantID   *uuid.UUID     `json:"tenant_id,omitempty"`
	UserID     *uuid.UUID     `json:"user_id,omitempty"`
	EdgeMCPID  *string        `json:"edge_mcp_id,omitempty"`
	Status     *SessionStatus `json:"status,omitempty"`
	ClientType *ClientType    `json:"client_type,omitempty"`
	ActiveOnly bool           `json:"active_only,omitempty"`
	Since      *time.Time     `json:"since,omitempty"`
	Until      *time.Time     `json:"until,omitempty"`
	Limit      int            `json:"limit,omitempty"`
	Offset     int            `json:"offset,omitempty"`
	OrderBy    string         `json:"order_by,omitempty"`
	OrderDesc  bool           `json:"order_desc,omitempty"`
}

SessionFilter represents filters for querying sessions

func (*SessionFilter) SetDefaults

func (f *SessionFilter) SetDefaults()

SetDefaults sets default values for the filter

type SessionMetrics

type SessionMetrics struct {
	TenantID            uuid.UUID `json:"tenant_id" db:"tenant_id"`
	ActiveSessions      int       `json:"active_sessions" db:"active_sessions"`
	TotalSessions       int       `json:"total_sessions" db:"total_sessions"`
	TotalToolExecutions int       `json:"total_tool_executions" db:"total_tool_executions"`
	TotalTokensUsed     int       `json:"total_tokens_used" db:"total_tokens_used"`
	AvgSessionMinutes   float64   `json:"avg_session_duration_minutes" db:"avg_session_duration_minutes"`
}

SessionMetrics contains aggregated metrics for sessions

type SessionResponse

type SessionResponse struct {
	*EdgeMCPSession
	SessionAge    string `json:"session_age,omitempty"`
	IdleTime      string `json:"idle_time,omitempty"`
	IsExpired     bool   `json:"is_expired"`
	ShouldRefresh bool   `json:"should_refresh"`
}

SessionResponse represents a session response with additional computed fields

func NewSessionResponse

func NewSessionResponse(session *EdgeMCPSession) *SessionResponse

NewSessionResponse creates a new session response from a session

type SessionStatus

type SessionStatus string

SessionStatus represents the state of a session

const (
	SessionStatusActive     SessionStatus = "active"
	SessionStatusIdle       SessionStatus = "idle"
	SessionStatusExpired    SessionStatus = "expired"
	SessionStatusTerminated SessionStatus = "terminated"
)

func (SessionStatus) Validate

func (s SessionStatus) Validate() error

Validate checks if the session status is valid

type SessionToolExecution

type SessionToolExecution struct {
	ID         uuid.UUID       `json:"id" db:"id"`
	SessionID  uuid.UUID       `json:"session_id" db:"session_id"`
	ToolName   string          `json:"tool_name" db:"tool_name"`
	ToolID     *uuid.UUID      `json:"tool_id,omitempty" db:"tool_id"`
	Arguments  json.RawMessage `json:"arguments,omitempty" db:"arguments"`
	Result     json.RawMessage `json:"result,omitempty" db:"result"`
	Error      *string         `json:"error,omitempty" db:"error"`
	DurationMs *int            `json:"duration_ms,omitempty" db:"duration_ms"`
	TokensUsed *int            `json:"tokens_used,omitempty" db:"tokens_used"`
	ExecutedAt time.Time       `json:"executed_at" db:"executed_at"`
}

SessionToolExecution represents a tool execution within a session

func (*SessionToolExecution) GetDuration

func (e *SessionToolExecution) GetDuration() time.Duration

GetDuration returns the duration as a time.Duration

func (*SessionToolExecution) IsSuccess

func (e *SessionToolExecution) IsSuccess() bool

IsSuccess returns true if the execution was successful

func (*SessionToolExecution) Validate

func (e *SessionToolExecution) Validate() error

Validate performs validation on the tool execution

type SessionToolExecutionRequest

type SessionToolExecutionRequest struct {
	ToolName   string          `json:"tool_name" validate:"required"`
	ToolID     *uuid.UUID      `json:"tool_id,omitempty"`
	Arguments  json.RawMessage `json:"arguments,omitempty"`
	Result     json.RawMessage `json:"result,omitempty"`
	Error      *string         `json:"error,omitempty"`
	DurationMs int             `json:"duration_ms,omitempty"`
	TokensUsed int             `json:"tokens_used,omitempty"`
}

SessionToolExecutionRequest represents a request to record a tool execution in a session

type SharedDocument

type SharedDocument struct {
	ID            uuid.UUID  `json:"id" db:"id"`
	WorkspaceID   uuid.UUID  `json:"workspace_id" db:"workspace_id"`
	TenantID      uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	Type          string     `json:"type" db:"type"`
	Title         string     `json:"title" db:"title"`
	Content       string     `json:"content" db:"content"`
	ContentType   string     `json:"content_type" db:"content_type"`
	Version       int64      `json:"version" db:"version"`
	CreatedBy     string     `json:"created_by" db:"created_by"`
	Metadata      JSONMap    `json:"metadata" db:"metadata"`
	LockedBy      *string    `json:"locked_by,omitempty" db:"locked_by"`
	LockedAt      *time.Time `json:"locked_at,omitempty" db:"locked_at"`
	LockExpiresAt *time.Time `json:"lock_expires_at,omitempty" db:"lock_expires_at"`
	CreatedAt     time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt     time.Time  `json:"updated_at" db:"updated_at"`
	DeletedAt     *time.Time `json:"deleted_at,omitempty" db:"deleted_at"`

	// Runtime data
	Operations    []*DocumentOperation `json:"operations,omitempty" db:"-"`
	Collaborators []string             `json:"collaborators,omitempty" db:"-"`
}

SharedDocument represents a collaborative document

func (*SharedDocument) CanEdit

func (d *SharedDocument) CanEdit(agentID string) bool

CanEdit returns true if the agent can edit the document

func (*SharedDocument) IsLocked

func (d *SharedDocument) IsLocked() bool

IsLocked returns true if the document is currently locked

type SimulationResult

type SimulationResult struct {
	Success         bool                       `json:"success"`
	ExecutionPath   []string                   `json:"execution_path"`
	EstimatedTime   time.Duration              `json:"estimated_time"`
	ResourceUsage   map[string]interface{}     `json:"resource_usage"`
	PotentialErrors []string                   `json:"potential_errors,omitempty"`
	Warnings        []string                   `json:"warnings,omitempty"`
	StepDetails     map[string]*StepSimulation `json:"step_details"`
}

SimulationResult represents the result of a workflow simulation

type SonarQubeBranchRef

type SonarQubeBranchRef struct {
	Name string `json:"name"`
	Type string `json:"type"`
	URL  string `json:"url"`
}

SonarQubeBranchRef represents a branch reference in a webhook

type SonarQubeCondition

type SonarQubeCondition struct {
	Status         string `json:"status"`
	MetricKey      string `json:"metricKey"`
	Comparator     string `json:"comparator"`
	ErrorThreshold string `json:"errorThreshold"`
	ActualValue    string `json:"actualValue"`
}

SonarQubeCondition represents a condition in a SonarQube quality gate

type SonarQubeConditionRef

type SonarQubeConditionRef struct {
	Metric         string `json:"metric"`
	Status         string `json:"status"`
	ErrorThreshold string `json:"errorThreshold"`
	ActualValue    string `json:"actualValue"`
}

SonarQubeConditionRef represents a condition reference in a webhook

type SonarQubeIssue

type SonarQubeIssue struct {
	Key          string    `json:"key"`
	Rule         string    `json:"rule"`
	Severity     string    `json:"severity"`
	Component    string    `json:"component"`
	Project      string    `json:"project"`
	Line         int       `json:"line"`
	Status       string    `json:"status"`
	Message      string    `json:"message"`
	Effort       string    `json:"effort"`
	Debt         string    `json:"debt"`
	CreationDate time.Time `json:"creationDate"`
}

SonarQubeIssue represents a single issue in SonarQube

type SonarQubeIssues

type SonarQubeIssues struct {
	Total  int              `json:"total"`
	Issues []SonarQubeIssue `json:"issues"`
}

SonarQubeIssues represents issues in SonarQube

type SonarQubeMeasure

type SonarQubeMeasure struct {
	Metric string `json:"metric"`
	Value  string `json:"value"`
	Period struct {
		Index int    `json:"index"`
		Value string `json:"value"`
	} `json:"period,omitempty"`
}

SonarQubeMeasure represents a measure in SonarQube

type SonarQubeMetrics

type SonarQubeMetrics struct {
	Component struct {
		Key       string             `json:"key"`
		Name      string             `json:"name"`
		Qualifier string             `json:"qualifier"`
		Measures  []SonarQubeMeasure `json:"measures"`
	} `json:"component"`
}

SonarQubeMetrics represents metrics in SonarQube

type SonarQubeProject

type SonarQubeProject struct {
	Key          string    `json:"key"`
	Name         string    `json:"name"`
	Description  string    `json:"description"`
	Qualifier    string    `json:"qualifier"`
	LastAnalysis time.Time `json:"lastAnalysisDate"`
	Visibility   string    `json:"visibility"`
}

SonarQubeProject represents a SonarQube project

type SonarQubeProjectRef

type SonarQubeProjectRef struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	URL  string `json:"url"`
}

SonarQubeProjectRef represents a project reference in a webhook

type SonarQubeQualityGate

type SonarQubeQualityGate struct {
	ProjectStatus struct {
		Status      string               `json:"status"`
		Conditions  []SonarQubeCondition `json:"conditions"`
		PeriodIndex int                  `json:"periodIndex"`
	} `json:"projectStatus"`
}

SonarQubeQualityGate represents a SonarQube quality gate

type SonarQubeQualityGateRef

type SonarQubeQualityGateRef struct {
	Name       string                  `json:"name"`
	Status     string                  `json:"status"`
	Conditions []SonarQubeConditionRef `json:"conditions"`
}

SonarQubeQualityGateRef represents a quality gate reference in a webhook

type SonarQubeQuery

type SonarQubeQuery struct {
	Type         string `json:"type"`
	ProjectKey   string `json:"projectKey"`
	Organization string `json:"organization"`
	Severity     string `json:"severity"`
	Status       string `json:"status"`
	MetricKeys   string `json:"metricKeys"`
}

SonarQubeQuery defines parameters for querying SonarQube

type SonarQubeTaskRef

type SonarQubeTaskRef struct {
	ID              string `json:"id"`
	Type            string `json:"type"`
	Status          string `json:"status"`
	StartedAt       string `json:"startedAt"`
	ExecutionTimeMs int64  `json:"executionTimeMs"`
}

SonarQubeTaskRef represents a task reference in a webhook

type SonarQubeWebhookEvent

type SonarQubeWebhookEvent struct {
	ServerURL   string                   `json:"serverUrl"`
	TaskID      string                   `json:"taskId"`
	Status      string                   `json:"status"`
	AnalysedAt  string                   `json:"analysedAt"`
	Project     *SonarQubeProjectRef     `json:"project,omitempty"`
	QualityGate *SonarQubeQualityGateRef `json:"qualityGate,omitempty"`
	Branch      *SonarQubeBranchRef      `json:"branch,omitempty"`
	Task        *SonarQubeTaskRef        `json:"task,omitempty"`
}

SonarQubeWebhookEvent represents a SonarQube webhook event

type StateOperation

type StateOperation struct {
	Type  string      `json:"type"`  // set, increment, add_to_set, remove_from_set
	Path  string      `json:"path"`  // JSON path to the field
	Value interface{} `json:"value"` // Value to set/add
	Delta int         `json:"delta"` // For increment operations
}

StateOperation represents an operation to modify workspace state

type StateSnapshot

type StateSnapshot struct {
	ID          uuid.UUID              `json:"id"`
	WorkspaceID uuid.UUID              `json:"workspace_id"`
	Version     int64                  `json:"version"`
	State       map[string]interface{} `json:"state"`
	CreatedAt   time.Time              `json:"created_at"`
	CreatedBy   string                 `json:"created_by"`
}

StateSnapshot represents a snapshot of workspace state

type StepExecution

type StepExecution struct {
	ExecutionID uuid.UUID  `json:"execution_id" db:"execution_id"`
	StepName    string     `json:"step_name" db:"step_name"`
	StartedAt   time.Time  `json:"started_at" db:"started_at"`
	CompletedAt *time.Time `json:"completed_at,omitempty" db:"completed_at"`
	Status      string     `json:"status" db:"status"`
	Result      JSONMap    `json:"result,omitempty" db:"result"`
	Error       *string    `json:"error,omitempty" db:"error"`
	RetryCount  int        `json:"retry_count" db:"retry_count"`
}

StepExecution represents the execution of a workflow step

type StepExecutionStatus

type StepExecutionStatus string

StepExecutionStatus for step execution state

Convert step status string constants to StepExecutionStatus

func (StepExecutionStatus) CanTransitionTo

func (s StepExecutionStatus) CanTransitionTo(target StepExecutionStatus) bool

CanTransitionTo checks if step status transition is valid

func (StepExecutionStatus) IsTerminal

func (s StepExecutionStatus) IsTerminal() bool

IsTerminal returns true if the step status is a terminal state

func (StepExecutionStatus) TransitionTo

TransitionTo performs a validated state transition with metrics

func (StepExecutionStatus) Validate

func (s StepExecutionStatus) Validate() error

Validate ensures the step status is valid

type StepMetrics

type StepMetrics struct {
	SuccessRate    float64        `json:"success_rate"`
	AverageTime    time.Duration  `json:"average_time"`
	FailureReasons map[string]int `json:"failure_reasons"`
}

StepMetrics represents metrics for a workflow step

type StepSimulation

type StepSimulation struct {
	StepID        string        `json:"step_id"`
	CanExecute    bool          `json:"can_execute"`
	EstimatedTime time.Duration `json:"estimated_time"`
	Requirements  []string      `json:"requirements,omitempty"`
	Issues        []string      `json:"issues,omitempty"`
}

StepSimulation represents simulation details for a single step

type StepStatus

type StepStatus struct {
	StepID      string                 `json:"step_id"`
	Status      string                 `json:"status"`
	AgentID     string                 `json:"agent_id"`
	Input       map[string]interface{} `json:"input,omitempty"`
	Output      map[string]interface{} `json:"output,omitempty"`
	Error       string                 `json:"error,omitempty"`
	StartedAt   *time.Time             `json:"started_at,omitempty"`
	CompletedAt *time.Time             `json:"completed_at,omitempty"`
	RetryCount  int                    `json:"retry_count"`
}

StepStatus represents the execution state of a workflow step

func (*StepStatus) GetAttempts

func (s *StepStatus) GetAttempts() int

func (*StepStatus) GetCreatedAt

func (s *StepStatus) GetCreatedAt() time.Time

func (*StepStatus) GetName

func (s *StepStatus) GetName() string

StepStatus extended methods

type StepTrace

type StepTrace struct {
	StepID    string                 `json:"step_id"`
	StartTime time.Time              `json:"start_time"`
	EndTime   time.Time              `json:"end_time"`
	Duration  time.Duration          `json:"duration"`
	Status    string                 `json:"status"`
	Input     map[string]interface{} `json:"input"`
	Output    map[string]interface{} `json:"output"`
	Error     string                 `json:"error,omitempty"`
}

StepTrace represents a trace of a step execution

type Subtask

type Subtask struct {
	ID          string                 `json:"id"`
	AgentID     string                 `json:"agent_id"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"parameters"`
}

Subtask represents a subtask definition

type SubtaskCreatedEvent

type SubtaskCreatedEvent struct {
	ParentTask *Task `json:"parent_task"`
	Subtask    *Task `json:"subtask"`
}

SubtaskCreatedEvent represents a subtask creation event

type SyncPoint

type SyncPoint struct {
	ID            string        `json:"id"`
	Name          string        `json:"name"`
	RequiredTasks []string      `json:"required_tasks"`
	Timeout       time.Duration `json:"timeout"`
	OnTimeout     string        `json:"on_timeout"` // continue, fail, retry
}

SyncPoint represents a synchronization point between subtasks

type Task

type Task struct {
	// Core fields
	ID       uuid.UUID    `json:"id" db:"id"`
	TenantID uuid.UUID    `json:"tenant_id" db:"tenant_id"`
	Type     string       `json:"type" db:"type"`
	Status   TaskStatus   `json:"status" db:"status"`
	Priority TaskPriority `json:"priority" db:"priority"`

	// Agent relationships
	CreatedBy  string  `json:"created_by" db:"created_by"`
	AssignedTo *string `json:"assigned_to,omitempty" db:"assigned_to"`

	// Task hierarchy
	ParentTaskID *uuid.UUID `json:"parent_task_id,omitempty" db:"parent_task_id"`

	// Task data
	Title       string  `json:"title" db:"title"`
	Description string  `json:"description,omitempty" db:"description"`
	Parameters  JSONMap `json:"parameters" db:"parameters"`
	Result      JSONMap `json:"result,omitempty" db:"result"`
	Error       string  `json:"error,omitempty" db:"error"`

	// Execution control
	MaxRetries     int `json:"max_retries" db:"max_retries"`
	RetryCount     int `json:"retry_count" db:"retry_count"`
	TimeoutSeconds int `json:"timeout_seconds" db:"timeout_seconds"`

	// Timestamps
	CreatedAt   time.Time  `json:"created_at" db:"created_at"`
	AssignedAt  *time.Time `json:"assigned_at,omitempty" db:"assigned_at"`
	StartedAt   *time.Time `json:"started_at,omitempty" db:"started_at"`
	CompletedAt *time.Time `json:"completed_at,omitempty" db:"completed_at"`
	UpdatedAt   time.Time  `json:"updated_at" db:"updated_at"`
	DeletedAt   *time.Time `json:"deleted_at,omitempty" db:"deleted_at"`

	// Optimistic locking
	Version int `json:"version" db:"version"`

	// Computed fields (not stored)
	Subtasks     []*Task           `json:"subtasks,omitempty" db:"-"`
	Delegations  []*TaskDelegation `json:"delegations,omitempty" db:"-"`
	Tags         []string          `json:"tags,omitempty" db:"-"`
	Capabilities []string          `json:"capabilities,omitempty" db:"-"`
}

Task represents a unit of work in the multi-agent system

func (*Task) CanRetry

func (t *Task) CanRetry() bool

CanRetry returns true if the task can be retried

func (*Task) Duration

func (t *Task) Duration() time.Duration

Duration returns the task execution duration

func (*Task) GetID

func (t *Task) GetID() uuid.UUID

GetID returns the task ID (implements AggregateRoot)

func (*Task) GetType

func (t *Task) GetType() string

GetType returns the aggregate type (implements AggregateRoot)

func (*Task) GetVersion

func (t *Task) GetVersion() int

GetVersion returns the version (implements AggregateRoot)

func (*Task) IsOverdue

func (t *Task) IsOverdue() bool

IsOverdue returns true if the task has exceeded its timeout

func (*Task) IsTerminal

func (t *Task) IsTerminal() bool

IsTerminal returns true if the task is in a terminal state

type TaskConflict

type TaskConflict struct {
	Type   string        `json:"type"`   // status, assignment, priority
	Values []interface{} `json:"values"` // Conflicting values from different agents
}

TaskConflict represents a conflict in task updates

type TaskCreatedEvent

type TaskCreatedEvent struct {
	Task *Task `json:"task"`
}

TaskCreatedEvent represents a task creation event

type TaskDelegatedEvent

type TaskDelegatedEvent struct {
	Task          *Task           `json:"task"`
	Delegation    *TaskDelegation `json:"delegation"`
	PreviousAgent string          `json:"previous_agent"`
}

TaskDelegatedEvent represents a task delegation event

type TaskDelegation

type TaskDelegation struct {
	ID             uuid.UUID      `json:"id" db:"id"`
	TaskID         uuid.UUID      `json:"task_id" db:"task_id"`
	TaskCreatedAt  time.Time      `json:"task_created_at" db:"task_created_at"` // For partitioned table FK
	FromAgentID    string         `json:"from_agent_id" db:"from_agent_id"`
	ToAgentID      string         `json:"to_agent_id" db:"to_agent_id"`
	Reason         string         `json:"reason,omitempty" db:"reason"`
	DelegationType DelegationType `json:"delegation_type" db:"delegation_type"`
	Metadata       JSONMap        `json:"metadata" db:"metadata"`
	DelegatedAt    time.Time      `json:"delegated_at" db:"delegated_at"`
}

TaskDelegation represents a task being delegated between agents

type TaskEvent

type TaskEvent struct {
	ID        uuid.UUID              `json:"id" db:"id"`
	TaskID    uuid.UUID              `json:"task_id" db:"task_id"`
	Type      string                 `json:"type" db:"type"`
	Timestamp time.Time              `json:"timestamp" db:"timestamp"`
	AgentID   string                 `json:"agent_id" db:"agent_id"`
	Data      map[string]interface{} `json:"data" db:"data"`
}

TaskEvent represents an event in task lifecycle

type TaskMetrics

type TaskMetrics struct {
	Count       int64   `json:"count"`
	SuccessRate float64 `json:"success_rate"`
	AverageTime float64 `json:"average_time"`
	MedianTime  float64 `json:"median_time"`
	P95Time     float64 `json:"p95_time"`
}

TaskMetrics represents metrics for a specific task type

type TaskPartition

type TaskPartition struct {
	ID         string                 `json:"id"`
	RangeStart int64                  `json:"range_start,omitempty"`
	RangeEnd   int64                  `json:"range_end,omitempty"`
	DataSet    string                 `json:"data_set,omitempty"`
	Parameters map[string]interface{} `json:"parameters,omitempty"`
	Weight     float64                `json:"weight"` // Relative weight for load balancing
}

TaskPartition represents a partition of work for a subtask

type TaskPriority

type TaskPriority string

TaskPriority represents the urgency of a task

const (
	TaskPriorityLow      TaskPriority = "low"
	TaskPriorityNormal   TaskPriority = "normal"
	TaskPriorityHigh     TaskPriority = "high"
	TaskPriorityCritical TaskPriority = "critical"
)

type TaskProgress

type TaskProgress struct {
	TaskID                 uuid.UUID              `json:"task_id"`
	TotalSteps             int                    `json:"total_steps"`
	CompletedSteps         int                    `json:"completed_steps"`
	CurrentStep            string                 `json:"current_step"`
	PercentComplete        float64                `json:"percent_complete"`
	EstimatedTimeRemaining time.Duration          `json:"estimated_time_remaining,omitempty"`
	LastUpdated            time.Time              `json:"last_updated"`
	Details                map[string]interface{} `json:"details,omitempty"`
}

TaskProgress represents progress information for a task

type TaskStats

type TaskStats struct {
	TotalTasks      int64                  `json:"total_tasks"`
	TasksByStatus   map[TaskStatus]int64   `json:"tasks_by_status"`
	TasksByPriority map[TaskPriority]int64 `json:"tasks_by_priority"`
	TasksByType     map[string]int64       `json:"tasks_by_type"`
	AverageTime     float64                `json:"average_time_seconds"`
	SuccessRate     float64                `json:"success_rate"`
}

TaskStats represents task statistics

type TaskStatus

type TaskStatus string

TaskStatus represents the lifecycle state of a task

const (
	TaskStatusPending    TaskStatus = "pending"
	TaskStatusAssigned   TaskStatus = "assigned"
	TaskStatusAccepted   TaskStatus = "accepted"
	TaskStatusRejected   TaskStatus = "rejected"
	TaskStatusInProgress TaskStatus = "in_progress"
	TaskStatusCompleted  TaskStatus = "completed"
	TaskStatusFailed     TaskStatus = "failed"
	TaskStatusCancelled  TaskStatus = "cancelled"
	TaskStatusTimeout    TaskStatus = "timeout"
)

type TaskTree

type TaskTree struct {
	Root     *Task
	Children map[uuid.UUID][]*Task
	Depth    int
}

TaskTree represents a hierarchical task structure

type TemplateParameter

type TemplateParameter struct {
	Name         string      `json:"name"`
	Type         string      `json:"type"`
	Description  string      `json:"description"`
	Required     bool        `json:"required"`
	DefaultValue interface{} `json:"default_value,omitempty"`
}

TemplateParameter represents a parameter in a workflow template

type TenantAccessMatrix

type TenantAccessMatrix struct {
	ID             uuid.UUID `json:"id" db:"id"`
	SourceTenantID uuid.UUID `json:"source_tenant_id" db:"source_tenant_id"`
	TargetTenantID uuid.UUID `json:"target_tenant_id" db:"target_tenant_id"`
	OrganizationID uuid.UUID `json:"organization_id" db:"organization_id"`
	AccessType     string    `json:"access_type" db:"access_type"`
	Permissions    JSONMap   `json:"permissions" db:"permissions"`
	CreatedAt      time.Time `json:"created_at" db:"created_at"`
}

TenantAccessMatrix represents the access permissions between tenants

func (*TenantAccessMatrix) CanAccess

func (tam *TenantAccessMatrix) CanAccess(accessType string) bool

CanAccess checks if source tenant can access target tenant with specified access type

func (*TenantAccessMatrix) HasPermission

func (tam *TenantAccessMatrix) HasPermission(permission string) bool

HasPermission checks if a specific permission exists in the permissions map

type TenantConfig

type TenantConfig struct {
	ID              string                 `json:"id" db:"id"`
	TenantID        string                 `json:"tenant_id" db:"tenant_id"`
	RateLimitConfig RateLimitConfig        `json:"rate_limit_config" db:"rate_limit_config"`
	ServiceTokens   map[string]string      `json:"-" db:"-"`              // Decrypted in memory only
	EncryptedTokens json.RawMessage        `json:"-" db:"service_tokens"` // Encrypted in database
	AllowedOrigins  pq.StringArray         `json:"allowed_origins" db:"allowed_origins"`
	Features        map[string]interface{} `json:"features" db:"-"` // Parsed from JSONB
	FeaturesJSON    json.RawMessage        `json:"-" db:"features"` // Raw JSONB from database
	CreatedAt       time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt       time.Time              `json:"updated_at" db:"updated_at"`
}

TenantConfig represents per-tenant configuration settings

func DefaultTenantConfig

func DefaultTenantConfig(tenantID string) *TenantConfig

DefaultTenantConfig returns a default configuration for a tenant

func (*TenantConfig) GetRateLimitForEndpoint

func (tc *TenantConfig) GetRateLimitForEndpoint(endpoint string) (EndpointRateLimit, bool)

GetRateLimitForEndpoint returns the rate limit configuration for a specific endpoint

func (*TenantConfig) GetRateLimitForKeyType

func (tc *TenantConfig) GetRateLimitForKeyType(keyType string) KeyTypeRateLimit

GetRateLimitForKeyType returns the rate limit configuration for a specific key type

func (*TenantConfig) GetServiceToken

func (tc *TenantConfig) GetServiceToken(provider string) (string, bool)

GetServiceToken returns the decrypted service token for a provider

func (*TenantConfig) HasServiceToken

func (tc *TenantConfig) HasServiceToken(provider string) bool

HasServiceToken checks if a service token exists for a provider

func (*TenantConfig) IsFeatureEnabled

func (tc *TenantConfig) IsFeatureEnabled(feature string) bool

IsFeatureEnabled checks if a specific feature is enabled for the tenant

type TimelineEvent

type TimelineEvent struct {
	Timestamp   time.Time              `json:"timestamp"`
	Type        string                 `json:"type"`
	StepID      string                 `json:"step_id,omitempty"`
	Description string                 `json:"description"`
	Data        map[string]interface{} `json:"data,omitempty"`
}

TimelineEvent represents an event in the execution timeline

type TokenCredential

type TokenCredential struct {
	Token        string    `json:"token"`
	Type         string    `json:"type,omitempty"`     // "pat", "oauth", "basic", "bearer", "api_key"
	Username     string    `json:"username,omitempty"` // For basic auth
	Password     string    `json:"password,omitempty"` // For basic auth (encrypted in storage)
	BaseURL      string    `json:"base_url,omitempty"` // For self-hosted instances
	ExpiresAt    time.Time `json:"expires_at,omitempty"`
	HeaderName   string    `json:"header_name,omitempty"`   // For API key header name
	HeaderPrefix string    `json:"header_prefix,omitempty"` // For custom header prefix (e.g., "Bearer", "Token")
	QueryParam   string    `json:"query_param,omitempty"`   // For API key as query parameter
}

TokenCredential represents a single credential

func (*TokenCredential) GetToken

func (tc *TokenCredential) GetToken() string

GetToken returns the token if valid, empty string if expired

func (*TokenCredential) IsExpired

func (tc *TokenCredential) IsExpired() bool

IsExpired checks if the credential has expired

func (*TokenCredential) SanitizedForLogging

func (tc *TokenCredential) SanitizedForLogging() map[string]interface{}

SanitizedForLogging returns credential info without sensitive data

type ToolAction

type ToolAction struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Method      string                 `json:"method"`
	Path        string                 `json:"path"`
	Parameters  []ActionParameter      `json:"parameters,omitempty"`
	Responses   map[string]interface{} `json:"responses,omitempty"`
}

ToolAction represents an available action on a tool

type ToolCredentials

type ToolCredentials struct {
	GitHub      *TokenCredential `json:"github,omitempty"`
	Jira        *TokenCredential `json:"jira,omitempty"`
	SonarQube   *TokenCredential `json:"sonarqube,omitempty"`
	Artifactory *TokenCredential `json:"artifactory,omitempty"`
	Jenkins     *TokenCredential `json:"jenkins,omitempty"`
	GitLab      *TokenCredential `json:"gitlab,omitempty"`
	Bitbucket   *TokenCredential `json:"bitbucket,omitempty"`
	// Extensible for more tools
	Custom map[string]*TokenCredential `json:"custom,omitempty"`
}

ToolCredentials represents user-provided credentials for backend tools

func (*ToolCredentials) GetCredentialFor

func (tc *ToolCredentials) GetCredentialFor(tool string) *TokenCredential

GetCredentialFor retrieves the credential for a specific tool

func (*ToolCredentials) HasCredentialFor

func (tc *ToolCredentials) HasCredentialFor(tool string) bool

HasCredentialFor checks if credentials exist for a specific tool

func (*ToolCredentials) SanitizedForLogging

func (tc *ToolCredentials) SanitizedForLogging() map[string]interface{}

SanitizedForLogging returns a version safe for logging

type ToolExecutionRequest

type ToolExecutionRequest struct {
	Action          string                 `json:"action"`
	Parameters      map[string]interface{} `json:"parameters,omitempty"`
	Headers         map[string]string      `json:"headers,omitempty"`
	Timeout         int                    `json:"timeout,omitempty"` // in seconds
	PassthroughAuth *PassthroughAuthBundle `json:"passthrough_auth,omitempty"`
}

ToolExecutionRequest represents a request to execute a tool action

type ToolExecutionResponse

type ToolExecutionResponse struct {
	Success    bool                `json:"success"`
	StatusCode int                 `json:"status_code"`
	Headers    map[string][]string `json:"headers,omitempty"`
	Body       interface{}         `json:"body,omitempty"`
	Error      string              `json:"error,omitempty"`
	Duration   int64               `json:"duration_ms"`
	ExecutedAt time.Time           `json:"executed_at"`

	// Cache metadata fields
	FromCache  bool   `json:"from_cache,omitempty"`
	CacheHit   bool   `json:"cache_hit,omitempty"`
	CacheLevel string `json:"cache_level,omitempty"`
	HitCount   int    `json:"hit_count,omitempty"`
}

ToolExecutionResponse represents the response from executing a tool action

type ToolFilter

type ToolFilter struct {
	ID       string `json:"id,omitempty"`
	TenantID string `json:"tenant_id,omitempty"`
	Name     string `json:"name,omitempty"`
	Type     string `json:"type,omitempty"`
}

ToolFilter defines filter criteria for tool operations

type ToolHealthStatus

type ToolHealthStatus struct {
	IsHealthy    bool                   `json:"is_healthy"`
	LastChecked  time.Time              `json:"last_checked"`
	ResponseTime int                    `json:"response_time_ms"`
	Error        string                 `json:"error,omitempty"`
	Version      string                 `json:"version,omitempty"`
	Details      map[string]interface{} `json:"details,omitempty"`
}

ToolHealthStatus represents the health status of a tool

type ToolRetryPolicy

type ToolRetryPolicy struct {
	MaxRetries       int      `json:"max_retries"`
	InitialDelay     int      `json:"initial_delay_ms"`
	MaxDelay         int      `json:"max_delay_ms"`
	Multiplier       float64  `json:"multiplier"`
	RetryableErrors  []string `json:"retryable_errors"`
	RetryOnTimeout   bool     `json:"retry_on_timeout"`
	RetryOnRateLimit bool     `json:"retry_on_rate_limit"`
}

ToolRetryPolicy defines retry configuration for a tool

type ToolTemplate

type ToolTemplate struct {
	ID              string  `json:"id" db:"id"`
	ProviderName    string  `json:"provider_name" db:"provider_name"`
	ProviderVersion string  `json:"provider_version" db:"provider_version"`
	DisplayName     string  `json:"display_name" db:"display_name"`
	Description     string  `json:"description" db:"description"`
	IconURL         *string `json:"icon_url,omitempty" db:"icon_url"`
	Category        string  `json:"category,omitempty" db:"category"`

	// Configurations
	DefaultConfig     providers.ProviderConfig              `json:"default_config" db:"default_config"`
	OperationGroups   []OperationGroup                      `json:"operation_groups" db:"operation_groups"`
	OperationMappings map[string]providers.OperationMapping `json:"operation_mappings" db:"operation_mappings"`
	AIDefinitions     *json.RawMessage                      `json:"ai_definitions,omitempty" db:"ai_definitions"`

	// Customization
	CustomizationSchema *json.RawMessage `json:"customization_schema,omitempty" db:"customization_schema"`
	RequiredCredentials []string         `json:"required_credentials" db:"required_credentials"`
	OptionalCredentials []string         `json:"optional_credentials,omitempty" db:"optional_credentials"`
	OptionalFeatures    *json.RawMessage `json:"optional_features,omitempty" db:"optional_features"`

	// Features
	Features providers.ProviderFeatures `json:"features" db:"features"`

	// Metadata
	Tags                  []string         `json:"tags,omitempty" db:"tags"`
	DocumentationURL      string           `json:"documentation_url,omitempty" db:"documentation_url"`
	APIDocumentationURL   *string          `json:"api_documentation_url,omitempty" db:"api_documentation_url"`
	ExampleConfigurations *json.RawMessage `json:"example_configurations,omitempty" db:"example_configurations"`

	// Visibility
	IsPublic          bool       `json:"is_public" db:"is_public"`
	IsActive          bool       `json:"is_active" db:"is_active"`
	IsDeprecated      bool       `json:"is_deprecated" db:"is_deprecated"`
	DeprecatedAt      *time.Time `json:"deprecated_at,omitempty" db:"deprecated_at"`
	DeprecatedMessage *string    `json:"deprecated_message,omitempty" db:"deprecated_message"`

	// Audit
	CreatedAt time.Time `json:"created_at" db:"created_at"`
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
	CreatedBy *string   `json:"created_by,omitempty" db:"created_by"`
	UpdatedBy *string   `json:"updated_by,omitempty" db:"updated_by"`
}

ToolTemplate represents a pre-defined tool configuration for standard providers

type ToolTemplateVersion

type ToolTemplateVersion struct {
	ID               string          `json:"id" db:"id"`
	TemplateID       string          `json:"template_id" db:"template_id"`
	VersionNumber    string          `json:"version_number" db:"version_number"`
	TemplateSnapshot json.RawMessage `json:"template_snapshot" db:"template_snapshot"`
	ChangeSummary    string          `json:"change_summary,omitempty" db:"change_summary"`
	BreakingChanges  bool            `json:"breaking_changes" db:"breaking_changes"`
	MigrationGuide   string          `json:"migration_guide,omitempty" db:"migration_guide"`
	CreatedAt        time.Time       `json:"created_at" db:"created_at"`
	CreatedBy        *string         `json:"created_by,omitempty" db:"created_by"`
}

ToolTemplateVersion tracks version history of tool templates

type ToolWebhookConfig

type ToolWebhookConfig struct {
	Enabled               bool                   `json:"enabled"`
	EndpointPath          string                 `json:"endpoint_path,omitempty"`           // e.g., /api/webhooks/tools/{toolId}
	AuthType              string                 `json:"auth_type"`                         // hmac, bearer, basic, signature, none
	AuthConfig            map[string]interface{} `json:"auth_config,omitempty"`             // Auth-specific config (e.g., secret, header names)
	Events                []WebhookEventConfig   `json:"events,omitempty"`                  // Supported events
	Headers               map[string]string      `json:"headers,omitempty"`                 // Expected headers
	PayloadFormat         string                 `json:"payload_format,omitempty"`          // json, form, xml
	SignatureHeader       string                 `json:"signature_header,omitempty"`        // Header containing signature
	SignatureAlgorithm    string                 `json:"signature_algorithm,omitempty"`     // hmac-sha256, hmac-sha1, etc.
	IPWhitelist           []string               `json:"ip_whitelist,omitempty"`            // Allowed source IPs
	DefaultProcessingMode string                 `json:"default_processing_mode,omitempty"` // Default processing mode for events
}

ToolWebhookConfig defines webhook configuration for a dynamic tool

type TrendData

type TrendData struct {
	Current  float64 `json:"current"`
	Previous float64 `json:"previous"`
	Change   float64 `json:"change_percentage"`
	Trend    string  `json:"trend"` // increasing, decreasing, stable
}

TrendData represents trend information

type UpdateType

type UpdateType string
const (
	UpdateTypeInsert  UpdateType = "insert"
	UpdateTypeDelete  UpdateType = "delete"
	UpdateTypeReplace UpdateType = "replace"
	UpdateTypeMove    UpdateType = "move"
	UpdateTypeMerge   UpdateType = "merge"
)

func (UpdateType) Validate

func (u UpdateType) Validate() error

Validate ensures the update type is valid

type UserCredential

type UserCredential struct {
	ID                   string                 `json:"id" db:"id"`
	TenantID             string                 `json:"tenant_id" db:"tenant_id"`
	UserID               string                 `json:"user_id" db:"user_id"`
	ServiceType          ServiceType            `json:"service_type" db:"service_type"`
	EncryptedCredentials []byte                 `json:"-" db:"encrypted_credentials"` // Never expose in JSON
	EncryptionKeyVersion int                    `json:"encryption_key_version" db:"encryption_key_version"`
	IsActive             bool                   `json:"is_active" db:"is_active"`
	Metadata             map[string]interface{} `json:"metadata" db:"metadata"`
	CreatedAt            time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt            time.Time              `json:"updated_at" db:"updated_at"`
	LastUsedAt           *time.Time             `json:"last_used_at,omitempty" db:"last_used_at"`
	ExpiresAt            *time.Time             `json:"expires_at,omitempty" db:"expires_at"`
}

UserCredential represents stored credentials for a third-party service

func (*UserCredential) ToResponse

func (uc *UserCredential) ToResponse() *CredentialResponse

ToResponse converts UserCredential to CredentialResponse (safe for API)

type UserCredentialAudit

type UserCredentialAudit struct {
	ID           string                 `json:"id" db:"id"`
	CredentialID string                 `json:"credential_id" db:"credential_id"`
	TenantID     string                 `json:"tenant_id" db:"tenant_id"`
	UserID       string                 `json:"user_id" db:"user_id"`
	ServiceType  ServiceType            `json:"service_type" db:"service_type"`
	Operation    string                 `json:"operation" db:"operation"` // created, updated, deleted, used, validated
	Success      bool                   `json:"success" db:"success"`
	ErrorMessage sql.NullString         `json:"error_message,omitempty" db:"error_message"`
	IPAddress    sql.NullString         `json:"ip_address,omitempty" db:"ip_address"`
	UserAgent    sql.NullString         `json:"user_agent,omitempty" db:"user_agent"`
	Metadata     map[string]interface{} `json:"metadata,omitempty" db:"metadata"`
	CreatedAt    time.Time              `json:"created_at" db:"created_at"`
}

UserCredentialAudit represents an audit log entry for credential operations

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError represents a validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Vector

type Vector struct {
	ID        string         `json:"id" db:"id"`
	TenantID  string         `json:"tenant_id" db:"tenant_id"`
	Content   string         `json:"content" db:"content"`
	Embedding []float32      `json:"embedding" db:"embedding"`
	Metadata  map[string]any `json:"metadata" db:"metadata"`
	CreatedAt time.Time      `json:"created_at" db:"created_at"`
	UpdatedAt time.Time      `json:"updated_at" db:"updated_at"`
}

Vector represents a vector embedding stored in the database

func NewVector

func NewVector(tenantID, content string, embedding []float32, metadata map[string]any) *Vector

NewVector creates a new vector embedding

type VectorFilter

type VectorFilter struct {
	ID        string `json:"id,omitempty"`
	TenantID  string `json:"tenant_id,omitempty"`
	ContextID string `json:"context_id,omitempty"`
	ModelID   string `json:"model_id,omitempty"`
}

VectorFilter defines filter criteria for vector operations

type VersionInfo

type VersionInfo struct {
	Raw        string  `json:"raw"`
	Major      int     `json:"major"`
	Minor      int     `json:"minor"`
	Patch      int     `json:"patch"`
	Prerelease *string `json:"prerelease,omitempty"`
}

VersionInfo represents parsed semantic version information

type WebhookConfig

type WebhookConfig struct {
	ID               uuid.UUID      `json:"id" db:"id"`
	OrganizationName string         `json:"organization_name" db:"organization_name"`
	WebhookSecret    string         `json:"-" db:"webhook_secret"` // Never expose in JSON
	Enabled          bool           `json:"enabled" db:"enabled"`
	AllowedEvents    pq.StringArray `json:"allowed_events" db:"allowed_events"`
	Metadata         JSONMap        `json:"metadata" db:"metadata"`
	CreatedAt        time.Time      `json:"created_at" db:"created_at"`
	UpdatedAt        time.Time      `json:"updated_at" db:"updated_at"`
}

WebhookConfig represents a webhook configuration for an organization

func (*WebhookConfig) IsEventAllowed

func (w *WebhookConfig) IsEventAllowed(eventType string) bool

IsEventAllowed checks if a given event type is allowed for this organization

func (*WebhookConfig) Validate

func (w *WebhookConfig) Validate() error

Validate checks if the webhook configuration is valid

type WebhookConfigCreate

type WebhookConfigCreate struct {
	OrganizationName string         `json:"organization_name" validate:"required,min=1,max=255"`
	WebhookSecret    string         `json:"webhook_secret" validate:"required,min=32"` // Require strong secrets
	AllowedEvents    []string       `json:"allowed_events,omitempty"`
	Metadata         map[string]any `json:"metadata,omitempty"`
}

WebhookConfigCreate represents the data needed to create a new webhook configuration

type WebhookConfigList

type WebhookConfigList struct {
	Items      []*WebhookConfig `json:"items"`
	TotalCount int              `json:"total_count"`
}

WebhookConfigList represents a list of webhook configurations

type WebhookConfigUpdate

type WebhookConfigUpdate struct {
	Enabled       *bool          `json:"enabled,omitempty"`
	WebhookSecret *string        `json:"webhook_secret,omitempty" validate:"omitempty,min=32"`
	AllowedEvents []string       `json:"allowed_events,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
}

WebhookConfigUpdate represents the data needed to update a webhook configuration

type WebhookEvent

type WebhookEvent struct {
	ID          string                 `json:"id" db:"id"`
	ToolID      string                 `json:"tool_id" db:"tool_id"`
	TenantID    string                 `json:"tenant_id" db:"tenant_id"`
	EventType   string                 `json:"event_type" db:"event_type"`
	Payload     json.RawMessage        `json:"payload" db:"payload"`
	Headers     map[string][]string    `json:"headers" db:"headers"`
	SourceIP    string                 `json:"source_ip" db:"source_ip"`
	ReceivedAt  time.Time              `json:"received_at" db:"received_at"`
	ProcessedAt *time.Time             `json:"processed_at,omitempty" db:"processed_at"`
	Status      string                 `json:"status" db:"status"` // pending, processed, failed
	Error       string                 `json:"error,omitempty" db:"error"`
	Metadata    map[string]interface{} `json:"metadata,omitempty" db:"metadata"`
}

WebhookEvent represents a received webhook event

type WebhookEventConfig

type WebhookEventConfig struct {
	EventType      string                 `json:"event_type"`   // e.g., "push", "pull_request", "issue"
	PayloadPath    string                 `json:"payload_path"` // JSON path to event type in payload
	SchemaURL      string                 `json:"schema_url,omitempty"`
	TransformRules map[string]interface{} `json:"transform_rules,omitempty"` // Rules to transform payload
	RequiredFields []string               `json:"required_fields,omitempty"` // Required fields in payload
	ProcessingMode string                 `json:"processing_mode,omitempty"` // Processing mode for this event type
}

WebhookEventConfig defines configuration for a specific webhook event type

type Workflow

type Workflow struct {
	ID          uuid.UUID      `json:"id" db:"id"`
	TenantID    uuid.UUID      `json:"tenant_id" db:"tenant_id"`
	Name        string         `json:"name" db:"name"`
	Type        WorkflowType   `json:"type" db:"type"`
	Version     int            `json:"version" db:"version"`
	CreatedBy   string         `json:"created_by" db:"created_by"`
	Agents      JSONMap        `json:"agents" db:"agents"`
	Steps       WorkflowSteps  `json:"steps" db:"steps"`
	Config      JSONMap        `json:"config" db:"config"`
	Description string         `json:"description,omitempty" db:"description"`
	Tags        pq.StringArray `json:"tags,omitempty" db:"tags"`
	IsActive    bool           `json:"is_active" db:"is_active"`
	CreatedAt   time.Time      `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at" db:"updated_at"`
	DeletedAt   *time.Time     `json:"deleted_at,omitempty" db:"deleted_at"`
}

Workflow represents a multi-agent workflow definition

func (*Workflow) GetID

func (w *Workflow) GetID() uuid.UUID

Add methods to make Workflow implement AggregateRoot

func (*Workflow) GetLastExecutedAt

func (w *Workflow) GetLastExecutedAt() *time.Time

Extend Workflow with additional fields

func (*Workflow) GetSteps

func (w *Workflow) GetSteps() []WorkflowStep

Helper function to get workflow steps as structured objects

func (*Workflow) GetType

func (w *Workflow) GetType() string

func (*Workflow) GetVersion

func (w *Workflow) GetVersion() int

func (*Workflow) SetLastExecutedAt

func (w *Workflow) SetLastExecutedAt(t time.Time)

type WorkflowExecution

type WorkflowExecution struct {
	ID          uuid.UUID      `json:"id" db:"id"`
	WorkflowID  uuid.UUID      `json:"workflow_id" db:"workflow_id"`
	TenantID    uuid.UUID      `json:"tenant_id" db:"tenant_id"`
	Status      WorkflowStatus `json:"status" db:"status"`
	Context     JSONMap        `json:"context" db:"context"`
	State       JSONMap        `json:"state" db:"state"`
	InitiatedBy string         `json:"initiated_by" db:"initiated_by"`
	Error       string         `json:"error,omitempty" db:"error"`
	StartedAt   time.Time      `json:"started_at" db:"started_at"`
	CompletedAt *time.Time     `json:"completed_at,omitempty" db:"completed_at"`
	UpdatedAt   time.Time      `json:"updated_at" db:"updated_at"`

	// Runtime data
	Workflow      *Workflow              `json:"workflow,omitempty" db:"-"`
	StepStatuses  map[string]*StepStatus `json:"step_statuses,omitempty" db:"-"`
	CurrentStepID string                 `json:"current_step_id,omitempty" db:"-"`
}

WorkflowExecution represents a running or completed workflow instance

func (*WorkflowExecution) Duration

func (e *WorkflowExecution) Duration() time.Duration

Duration returns the execution duration

func (*WorkflowExecution) GetCreatedAt

func (e *WorkflowExecution) GetCreatedAt() time.Time

func (*WorkflowExecution) GetID

func (e *WorkflowExecution) GetID() uuid.UUID

Add methods to make WorkflowExecution implement AggregateRoot

func (*WorkflowExecution) GetInput

func (e *WorkflowExecution) GetInput() map[string]interface{}

func (*WorkflowExecution) GetSteps

func (e *WorkflowExecution) GetSteps() map[string]*StepStatus

func (*WorkflowExecution) GetTriggeredBy

func (e *WorkflowExecution) GetTriggeredBy() string

Extend WorkflowExecution with additional fields through helper methods

func (*WorkflowExecution) GetType

func (e *WorkflowExecution) GetType() string

func (*WorkflowExecution) GetVersion

func (e *WorkflowExecution) GetVersion() int

func (*WorkflowExecution) IsTerminal

func (e *WorkflowExecution) IsTerminal() bool

IsTerminal returns true if the workflow is in a terminal state

func (*WorkflowExecution) SetInput

func (e *WorkflowExecution) SetInput(input map[string]interface{})

type WorkflowExecutionMetrics

type WorkflowExecutionMetrics struct {
	ExecutionID   uuid.UUID                `json:"execution_id"`
	TotalDuration time.Duration            `json:"total_duration"`
	StepDurations map[string]time.Duration `json:"step_durations"`
	QueueTime     time.Duration            `json:"queue_time"`
	RetryCount    int                      `json:"retry_count"`
	ResourceUsage ResourceMetrics          `json:"resource_usage"`
	CostEstimate  float64                  `json:"cost_estimate"`
}

WorkflowExecutionMetrics tracks workflow performance

type WorkflowExecutionRequest

type WorkflowExecutionRequest struct {
	WorkflowID  uuid.UUID              `json:"workflow_id"`
	Input       map[string]interface{} `json:"input"`
	Context     map[string]interface{} `json:"context"`
	TriggeredBy string                 `json:"triggered_by"`
	Priority    string                 `json:"priority"`
}

WorkflowExecutionRequest represents a request to execute a workflow

type WorkflowInsights

type WorkflowInsights struct {
	WorkflowID              uuid.UUID                `json:"workflow_id"`
	Period                  time.Duration            `json:"period"`
	BottleneckSteps         []string                 `json:"bottleneck_steps"`
	FailurePredictors       map[string]float64       `json:"failure_predictors"`
	OptimizationSuggestions []OptimizationSuggestion `json:"optimization_suggestions"`
	TrendAnalysis           map[string]TrendData     `json:"trend_analysis"`
}

WorkflowInsights represents insights about workflow performance

type WorkflowMetrics

type WorkflowMetrics struct {
	WorkflowID      uuid.UUID              `json:"workflow_id"`
	TotalExecutions int64                  `json:"total_executions"`
	SuccessfulRuns  int64                  `json:"successful_runs"`
	FailedRuns      int64                  `json:"failed_runs"`
	AverageRunTime  time.Duration          `json:"average_run_time"`
	MedianRunTime   time.Duration          `json:"median_run_time"`
	P95RunTime      time.Duration          `json:"p95_run_time"`
	StepMetrics     map[string]StepMetrics `json:"step_metrics"`
}

WorkflowMetrics represents metrics for a workflow

type WorkflowRetryPolicy

type WorkflowRetryPolicy struct {
	MaxAttempts int           `json:"max_attempts"`
	BackoffType string        `json:"backoff_type"` // linear, exponential
	InitialWait time.Duration `json:"initial_wait"`
	MaxWait     time.Duration `json:"max_wait"`
}

WorkflowRetryPolicy defines retry behavior for workflow steps

type WorkflowStatus

type WorkflowStatus string

WorkflowStatus represents the state of a workflow execution

const (
	WorkflowStatusPending   WorkflowStatus = "pending"
	WorkflowStatusRunning   WorkflowStatus = "running"
	WorkflowStatusPaused    WorkflowStatus = "paused"
	WorkflowStatusCompleted WorkflowStatus = "completed"
	WorkflowStatusFailed    WorkflowStatus = "failed"
	WorkflowStatusCancelled WorkflowStatus = "cancelled"
	WorkflowStatusTimeout   WorkflowStatus = "timeout"
)
const (
	WorkflowStatusActive   WorkflowStatus = "active"
	WorkflowStatusInactive WorkflowStatus = "inactive"
	WorkflowStatusDraft    WorkflowStatus = "draft"
	WorkflowStatusArchived WorkflowStatus = "archived"
)

WorkflowStatus constants for workflow definitions

func (WorkflowStatus) CanTransitionTo

func (s WorkflowStatus) CanTransitionTo(target WorkflowStatus) bool

CanTransitionTo checks if workflow status transition is valid

func (WorkflowStatus) IsTerminal

func (s WorkflowStatus) IsTerminal() bool

IsTerminal returns true if the status is a terminal state

type WorkflowStep

type WorkflowStep struct {
	ID              string                 `json:"id"`
	Name            string                 `json:"name"`
	Description     string                 `json:"description,omitempty"`
	Type            string                 `json:"type"`
	Action          string                 `json:"action"`
	AgentID         string                 `json:"agent_id"`
	Input           map[string]interface{} `json:"input"`
	Config          map[string]interface{} `json:"config"`
	Timeout         time.Duration          `json:"timeout"`
	TimeoutSeconds  int                    `json:"timeout_seconds,omitempty"`
	Retries         int                    `json:"retries"`
	RetryPolicy     WorkflowRetryPolicy    `json:"retry_policy,omitempty"`
	ContinueOnError bool                   `json:"continue_on_error"`
	Dependencies    []string               `json:"dependencies"`
	OnFailure       string                 `json:"on_failure,omitempty"` // fail_workflow, continue, compensate
}

WorkflowStep represents a step in a workflow

type WorkflowSteps

type WorkflowSteps []WorkflowStep

WorkflowSteps represents an array of workflow steps with proper database serialization

func (WorkflowSteps) GetByID

func (s WorkflowSteps) GetByID(id string) (*WorkflowStep, bool)

GetByID returns a step by its ID

func (WorkflowSteps) GetInExecutionOrder

func (s WorkflowSteps) GetInExecutionOrder() []WorkflowStep

GetInExecutionOrder returns steps in execution order based on dependencies

func (WorkflowSteps) MarshalJSON

func (s WorkflowSteps) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (*WorkflowSteps) Scan

func (s *WorkflowSteps) Scan(value interface{}) error

Scan implements sql.Scanner for database deserialization

func (*WorkflowSteps) UnmarshalJSON

func (s *WorkflowSteps) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

func (WorkflowSteps) Validate

func (s WorkflowSteps) Validate() error

Validate ensures all steps are valid

func (WorkflowSteps) Value

func (s WorkflowSteps) Value() (driver.Value, error)

Value implements driver.Valuer for database serialization

type WorkflowTemplate

type WorkflowTemplate struct {
	ID          uuid.UUID              `json:"id" db:"id"`
	Name        string                 `json:"name" db:"name"`
	Description string                 `json:"description" db:"description"`
	Category    string                 `json:"category" db:"category"`
	Definition  map[string]interface{} `json:"definition" db:"definition"`
	Parameters  []TemplateParameter    `json:"parameters" db:"parameters"`
	CreatedBy   string                 `json:"created_by" db:"created_by"`
	CreatedAt   time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at" db:"updated_at"`
}

WorkflowTemplate represents a reusable workflow template

func (*WorkflowTemplate) GetID

func (t *WorkflowTemplate) GetID() uuid.UUID

Add methods to make WorkflowTemplate implement AggregateRoot

func (*WorkflowTemplate) GetType

func (t *WorkflowTemplate) GetType() string

func (*WorkflowTemplate) GetVersion

func (t *WorkflowTemplate) GetVersion() int

type WorkflowType

type WorkflowType string

WorkflowType represents the execution strategy of a workflow

const (
	WorkflowTypeSequential    WorkflowType = "sequential"
	WorkflowTypeParallel      WorkflowType = "parallel"
	WorkflowTypeConditional   WorkflowType = "conditional"
	WorkflowTypeCollaborative WorkflowType = "collaborative"
)
const (
	WorkflowTypeStandard     WorkflowType = "standard"
	WorkflowTypeDAG          WorkflowType = "dag"
	WorkflowTypeSaga         WorkflowType = "saga"
	WorkflowTypeStateMachine WorkflowType = "state_machine"
	WorkflowTypeEvent        WorkflowType = "event_driven"
)

Add WorkflowTypeStandard to existing types

type WorkflowVersion

type WorkflowVersion struct {
	ID         uuid.UUID              `json:"id" db:"id"`
	WorkflowID uuid.UUID              `json:"workflow_id" db:"workflow_id"`
	Version    int                    `json:"version" db:"version"`
	Changes    string                 `json:"changes" db:"changes"`
	Definition map[string]interface{} `json:"definition" db:"definition"`
	CreatedBy  string                 `json:"created_by" db:"created_by"`
	CreatedAt  time.Time              `json:"created_at" db:"created_at"`
}

WorkflowVersion represents a version of a workflow

type WorkloadInfo

type WorkloadInfo struct {
	AgentID       string    `json:"agent_id"`
	ActiveTasks   int       `json:"active_tasks"`
	QueuedTasks   int       `json:"queued_tasks"`
	CPUUsage      float64   `json:"cpu_usage"`
	MemoryUsage   float64   `json:"memory_usage"`
	WorkloadScore float64   `json:"workload_score"` // Calculated score 0-100
	LastUpdated   time.Time `json:"last_updated"`
}

WorkloadInfo contains agent workload information

func (*WorkloadInfo) Calculate

func (w *WorkloadInfo) Calculate()

Calculate computes the overall workload score

type Workspace

type Workspace struct {
	ID             uuid.UUID           `json:"id" db:"id"`
	TenantID       uuid.UUID           `json:"tenant_id" db:"tenant_id"`
	Name           string              `json:"name" db:"name"`
	Type           string              `json:"type" db:"type"`
	OwnerID        string              `json:"owner_id" db:"owner_id"`
	Description    string              `json:"description,omitempty" db:"description"`
	Configuration  JSONMap             `json:"configuration" db:"configuration"`
	Visibility     WorkspaceVisibility `json:"visibility" db:"visibility"`
	State          JSONMap             `json:"state" db:"state"`
	StateVersion   int64               `json:"state_version" db:"state_version"`
	LastActivityAt time.Time           `json:"last_activity_at" db:"last_activity_at"`
	LockedBy       *string             `json:"locked_by,omitempty" db:"locked_by"`
	LockedAt       *time.Time          `json:"locked_at,omitempty" db:"locked_at"`
	LockExpiresAt  *time.Time          `json:"lock_expires_at,omitempty" db:"lock_expires_at"`
	CreatedAt      time.Time           `json:"created_at" db:"created_at"`
	UpdatedAt      time.Time           `json:"updated_at" db:"updated_at"`
	DeletedAt      *time.Time          `json:"deleted_at,omitempty" db:"deleted_at"`

	// New production fields for Phase 3
	IsPublic bool              `json:"is_public" db:"is_public"`
	Settings WorkspaceSettings `json:"settings" db:"settings"`
	Tags     pq.StringArray    `json:"tags" db:"tags"`
	Metadata JSONMap           `json:"metadata" db:"metadata"`

	// Additional fields for production
	Owner    string          `json:"owner" db:"owner"`
	Status   WorkspaceStatus `json:"status" db:"status"`
	Features pq.StringArray  `json:"features" db:"features"`
	Limits   WorkspaceLimits `json:"limits" db:"limits"`
	Stats    *WorkspaceStats `json:"stats,omitempty" db:"-"` // Computed field

	// Runtime data
	Members   []*WorkspaceMember `json:"members,omitempty" db:"-"`
	Documents []*SharedDocument  `json:"documents,omitempty" db:"-"`
}

Workspace represents a collaborative space for agents

func (*Workspace) HasFeature

func (w *Workspace) HasFeature(feature string) bool

HasFeature checks if the workspace has a specific feature enabled

func (*Workspace) HasTag

func (w *Workspace) HasTag(tag string) bool

HasTag checks if the workspace has a specific tag

func (*Workspace) IsActive

func (w *Workspace) IsActive() bool

IsActive returns true if the workspace is active

func (*Workspace) IsLocked

func (w *Workspace) IsLocked() bool

IsLocked returns true if the workspace is currently locked

func (*Workspace) SetDefaultValues

func (w *Workspace) SetDefaultValues()

SetDefaultValues sets default values for a new workspace

func (*Workspace) Validate

func (w *Workspace) Validate() error

Validate validates the workspace fields

type WorkspaceActivity

type WorkspaceActivity struct {
	ID           uuid.UUID              `json:"id" db:"id"`
	WorkspaceID  uuid.UUID              `json:"workspace_id" db:"workspace_id"`
	AgentID      string                 `json:"agent_id" db:"agent_id"`
	ActivityType string                 `json:"activity_type" db:"activity_type"`
	Description  string                 `json:"description" db:"description"`
	Details      map[string]interface{} `json:"details,omitempty" db:"details"`
	Timestamp    time.Time              `json:"timestamp" db:"timestamp"`
}

WorkspaceActivity represents an activity event in a workspace

type WorkspaceCollaborator

type WorkspaceCollaborator struct {
	ID          uuid.UUID `json:"id" db:"id"`
	WorkspaceID uuid.UUID `json:"workspace_id" db:"workspace_id"`
	AgentID     string    `json:"agent_id" db:"agent_id"`
	Role        string    `json:"role" db:"role"` // "owner", "editor", "viewer"
	Permissions []string  `json:"permissions" db:"permissions"`
	AddedAt     time.Time `json:"added_at" db:"added_at"`
	AddedBy     string    `json:"added_by" db:"added_by"`
}

WorkspaceCollaborator represents a collaborator in a workspace

type WorkspaceLimits

type WorkspaceLimits struct {
	MaxMembers       int   `json:"max_members"`
	MaxDocuments     int   `json:"max_documents"`
	MaxStorageBytes  int64 `json:"max_storage_bytes"`
	MaxOperationsDay int   `json:"max_operations_day"`
	MaxAgents        int   `json:"max_agents"`
	MaxConcurrent    int   `json:"max_concurrent"`
}

WorkspaceLimits defines resource limits for a workspace

func GetDefaultWorkspaceLimits

func GetDefaultWorkspaceLimits() WorkspaceLimits

GetDefaultWorkspaceLimits returns default workspace limits

func (WorkspaceLimits) IsWithinLimits

func (wl WorkspaceLimits) IsWithinLimits(members, documents int, storageBytes int64) bool

IsWithinLimits checks if the given values are within the workspace limits

func (*WorkspaceLimits) Scan

func (wl *WorkspaceLimits) Scan(value interface{}) error

Scan implements the sql.Scanner interface for database retrieval

func (WorkspaceLimits) Value

func (wl WorkspaceLimits) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database storage

type WorkspaceMember

type WorkspaceMember struct {
	WorkspaceID uuid.UUID  `json:"workspace_id" db:"workspace_id"`
	AgentID     string     `json:"agent_id" db:"agent_id"`
	TenantID    uuid.UUID  `json:"tenant_id" db:"tenant_id"`
	Role        MemberRole `json:"role" db:"role"`
	Permissions JSONMap    `json:"permissions" db:"permissions"`
	JoinedAt    time.Time  `json:"joined_at" db:"joined_at"`
	LastSeenAt  *time.Time `json:"last_seen_at,omitempty" db:"last_seen_at"`

	// Runtime data
	Agent interface{} `json:"agent,omitempty" db:"-"` // Agent details if loaded
}

WorkspaceMember represents an agent's membership in a workspace

func (*WorkspaceMember) CanEdit

func (m *WorkspaceMember) CanEdit() bool

CanEdit returns true if the member has edit permissions

func (*WorkspaceMember) CanManage

func (m *WorkspaceMember) CanManage() bool

CanManage returns true if the member has management permissions

type WorkspaceMemberRole

type WorkspaceMemberRole string

WorkspaceMemberRole defines access levels

const (
	WorkspaceMemberRoleOwner     WorkspaceMemberRole = "owner"
	WorkspaceMemberRoleAdmin     WorkspaceMemberRole = "admin"
	WorkspaceMemberRoleEditor    WorkspaceMemberRole = "editor"
	WorkspaceMemberRoleCommenter WorkspaceMemberRole = "commenter"
	WorkspaceMemberRoleViewer    WorkspaceMemberRole = "viewer"
	WorkspaceMemberRoleGuest     WorkspaceMemberRole = "guest"
)

func (WorkspaceMemberRole) CanTransitionTo

func (r WorkspaceMemberRole) CanTransitionTo(target WorkspaceMemberRole) bool

CanTransitionTo checks if a role can be changed to another role

func (WorkspaceMemberRole) HasPermission

func (r WorkspaceMemberRole) HasPermission(permission string) bool

HasPermission checks if a role has a specific permission

func (WorkspaceMemberRole) IsHigherThan

func (r WorkspaceMemberRole) IsHigherThan(other WorkspaceMemberRole) bool

IsHigherThan checks if this role has more privileges than another

func (WorkspaceMemberRole) Validate

func (w WorkspaceMemberRole) Validate() error

Validate ensures the workspace member role is valid

type WorkspaceSettings

type WorkspaceSettings struct {
	Notifications   NotificationSettings   `json:"notifications"`
	Collaboration   CollaborationSettings  `json:"collaboration"`
	Security        SecuritySettings       `json:"security"`
	AutomationRules []AutomationRule       `json:"automation_rules,omitempty"`
	Preferences     map[string]interface{} `json:"preferences,omitempty"`
}

WorkspaceSettings represents the settings for a workspace

func GetDefaultWorkspaceSettings

func GetDefaultWorkspaceSettings() WorkspaceSettings

GetDefaultWorkspaceSettings returns default workspace settings

func (*WorkspaceSettings) Scan

func (ws *WorkspaceSettings) Scan(value interface{}) error

Scan implements the sql.Scanner interface for database retrieval

func (WorkspaceSettings) Value

func (ws WorkspaceSettings) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database storage

type WorkspaceState

type WorkspaceState struct {
	WorkspaceID    uuid.UUID              `json:"workspace_id"`
	Version        int64                  `json:"version"`
	Data           map[string]interface{} `json:"data"`
	VectorClock    map[string]int         `json:"vector_clock"`
	LastModifiedBy string                 `json:"last_modified_by"`
	LastModifiedAt time.Time              `json:"last_modified_at"`
}

WorkspaceState represents the distributed state of a workspace

type WorkspaceStats

type WorkspaceStats struct {
	WorkspaceID      uuid.UUID `json:"workspace_id"`
	TotalMembers     int64     `json:"total_members"`
	ActiveMembers    int64     `json:"active_members"`
	TotalDocuments   int64     `json:"total_documents"`
	TotalOperations  int64     `json:"total_operations"`
	StorageUsedBytes int64     `json:"storage_used_bytes"`
	LastActivityAt   time.Time `json:"last_activity_at"`
}

WorkspaceStats represents statistics for a workspace

type WorkspaceStatus

type WorkspaceStatus string

WorkspaceStatus represents the status of a workspace

const (
	WorkspaceStatusActive   WorkspaceStatus = "active"
	WorkspaceStatusInactive WorkspaceStatus = "inactive"
	WorkspaceStatusArchived WorkspaceStatus = "archived"
	WorkspaceStatusDeleted  WorkspaceStatus = "deleted"
)

func (WorkspaceStatus) IsValid

func (s WorkspaceStatus) IsValid() bool

IsValid checks if the workspace status is valid

type WorkspaceVisibility

type WorkspaceVisibility string

WorkspaceVisibility defines who can access a workspace

const (
	WorkspaceVisibilityPrivate WorkspaceVisibility = "private"
	WorkspaceVisibilityTeam    WorkspaceVisibility = "team"
	WorkspaceVisibilityPublic  WorkspaceVisibility = "public"
)

type XrayIssue

type XrayIssue struct {
	ID        string             `json:"id"`
	Type      string             `json:"type"`
	Severity  string             `json:"severity"`
	Summary   string             `json:"summary"`
	Component XrayIssueComponent `json:"component"`
}

XrayIssue represents an issue in a JFrog Xray webhook event

type XrayIssueComponent

type XrayIssueComponent struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Path    string `json:"path"`
}

XrayIssueComponent represents a component in a JFrog Xray issue

type XrayLicense

type XrayLicense struct {
	Name        string   `json:"name"`
	FullName    string   `json:"full_name"`
	MoreInfoURL string   `json:"more_info_url"`
	Components  []string `json:"components"`
}

XrayLicense represents a license in Xray

type XrayLicenseComponent

type XrayLicenseComponent struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Path    string `json:"path"`
}

XrayLicenseComponent represents a component with a license in Xray

type XrayLicenseDetail

type XrayLicenseDetail struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	FullName    string                 `json:"full_name"`
	URL         string                 `json:"url"`
	Type        string                 `json:"type"`
	Description string                 `json:"description"`
	Components  []XrayLicenseComponent `json:"components"`
}

XrayLicenseDetail represents a detailed license in Xray

type XrayLicenses

type XrayLicenses struct {
	Licenses   []XrayLicenseDetail `json:"licenses"`
	TotalCount int                 `json:"total_count"`
}

XrayLicenses represents licenses in Xray

type XrayQuery

type XrayQuery struct {
	Type         string `json:"type"`
	ArtifactPath string `json:"artifactPath"`
	CVE          string `json:"cve"`
	LicenseID    string `json:"licenseId"`
	BuildName    string `json:"buildName"`
	BuildNumber  string `json:"buildNumber"`
}

XrayQuery defines parameters for querying JFrog Xray

type XrayScan

type XrayScan struct {
	ID                 string    `json:"id"`
	ResourceType       string    `json:"resource_type"`
	ResourceName       string    `json:"resource_name"`
	Status             string    `json:"status"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
	VulnerabilityCount int       `json:"vulnerability_count"`
	LicenseCount       int       `json:"license_count"`
}

XrayScan represents a scan in Xray

type XrayScans

type XrayScans struct {
	Scans []XrayScan `json:"scans"`
}

XrayScans represents scans in Xray

type XraySummary

type XraySummary struct {
	Vulnerabilities    []XrayVulnerability `json:"vulnerabilities"`
	Licenses           []XrayLicense       `json:"licenses"`
	SecurityViolations []XrayViolation     `json:"security_violations"`
	LicenseViolations  []XrayViolation     `json:"license_violations"`
}

XraySummary represents a summary of threats in Xray

type XrayViolation

type XrayViolation struct {
	Type       string   `json:"type"`
	PolicyName string   `json:"policy_name"`
	WatchName  string   `json:"watch_name"`
	Components []string `json:"components"`
}

XrayViolation represents a violation in Xray

type XrayVulnerabilities

type XrayVulnerabilities struct {
	Vulnerabilities []XrayVulnerabilityDetail `json:"vulnerabilities"`
	TotalCount      int                       `json:"total_count"`
}

XrayVulnerabilities represents vulnerabilities in Xray

type XrayVulnerability

type XrayVulnerability struct {
	CVE           string   `json:"cve"`
	Summary       string   `json:"summary"`
	Severity      string   `json:"severity"`
	ImpactPath    []string `json:"impact_path"`
	FixedVersions []string `json:"fixed_versions"`
	Components    []string `json:"components"`
}

XrayVulnerability represents a vulnerability in Xray

type XrayVulnerabilityDetail

type XrayVulnerabilityDetail struct {
	ID            string   `json:"id"`
	Summary       string   `json:"summary"`
	Description   string   `json:"description"`
	CvssV2Score   float64  `json:"cvss_v2_score"`
	CvssV3Score   float64  `json:"cvss_v3_score"`
	Severity      string   `json:"severity"`
	PublishedDate string   `json:"published_date"`
	LastUpdated   string   `json:"last_updated"`
	References    []string `json:"references"`
	Remediation   string   `json:"remediation"`
}

XrayVulnerabilityDetail represents a detailed vulnerability in Xray

type XrayWebhookData

type XrayWebhookData struct {
	Issues     []XrayIssue `json:"issues"`
	ProjectKey string      `json:"project_key"`
	WatchName  string      `json:"watch_name"`
	PolicyName string      `json:"policy_name"`
}

XrayWebhookData represents the data in a JFrog Xray webhook event

type XrayWebhookEvent

type XrayWebhookEvent struct {
	EventType string          `json:"event_type"`
	Timestamp string          `json:"timestamp"`
	Data      XrayWebhookData `json:"data"`
}

XrayWebhookEvent represents a JFrog Xray webhook event

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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