models

package
v0.1.23 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package models defines shared types used across the Samverk system.

Index

Constants

View Source
const SchemaVersion = "1.1.0"

SchemaVersion is the current issue schema version.

Variables

This section is empty.

Functions

func FormatDuration added in v0.1.14

func FormatDuration(d time.Duration) string

FormatDuration returns a human-friendly string for a time.Duration. Examples: "just now", "5m", "2h", "3d".

func IsEven added in v0.1.11

func IsEven(n int) bool

IsEven returns true if n is divisible by 2.

func IsOdd added in v0.1.11

func IsOdd(n int) bool

IsOdd returns true if n is not divisible by 2.

func RenderFrontmatter

func RenderFrontmatter(fm *IssueFrontmatter, markdown string) string

RenderFrontmatter produces an issue body with YAML frontmatter followed by markdown.

Types

type AgentType

type AgentType string

AgentType identifies which agent pool should handle an issue.

const (
	AgentTypeOrchestrator AgentType = "orchestrator"
	AgentTypeDispatcher   AgentType = "dispatcher"
	AgentTypeCodeGen      AgentType = "code-gen"
	AgentTypeTest         AgentType = "test"
	AgentTypeDocs         AgentType = "docs"
	AgentTypeResearch     AgentType = "research"
	AgentTypeQC           AgentType = "qc"
	AgentTypeHuman        AgentType = "human"
	AgentTypeInfra        AgentType = "infra"
	AgentTypePC           AgentType = "pc"
)

type Complexity

type Complexity string

Complexity hints at whether work should run locally or in the cloud.

const (
	ComplexityLocal     Complexity = "local"
	ComplexityCloud     Complexity = "cloud"
	ComplexityAmbiguous Complexity = "ambiguous"
)

type CorrectionEvent added in v0.1.16

type CorrectionEvent struct {
	ID           string       `json:"id"`
	IssueNumber  int          `json:"issue_number"`
	FailureClass FailureClass `json:"failure_class"`
	Action       string       `json:"action"`
	Scope        string       `json:"scope"`
	Reason       string       `json:"reason"`
	NewProvider  string       `json:"new_provider,omitempty"`
	Outcome      string       `json:"outcome"` // pending, applied, failed
	CreatedAt    time.Time    `json:"created_at"`
}

CorrectionEvent records a correction decision made by the failure response engine.

type CostRecord

type CostRecord struct {
	ID           string    `json:"id"`
	SessionID    string    `json:"session_id"`
	Provider     string    `json:"provider"`
	Model        string    `json:"model"`
	InputTokens  int       `json:"input_tokens"`
	OutputTokens int       `json:"output_tokens"`
	CostUSD      float64   `json:"cost_usd"` // 0 for local models
	CreatedAt    time.Time `json:"created_at"`
}

CostRecord tracks token usage for a single API call.

type CostSummary

type CostSummary struct {
	TotalInputTokens  int     `json:"total_input_tokens"`
	TotalOutputTokens int     `json:"total_output_tokens"`
	TotalCostUSD      float64 `json:"total_cost_usd"`
	RecordCount       int     `json:"record_count"`
}

CostSummary aggregates cost data over a time period.

type Dependency added in v0.1.16

type Dependency struct {
	Owner  string // empty for same-project
	Repo   string // empty for same-project
	Number int
}

Dependency represents an issue dependency that may be same-project (int) or cross-project (owner/repo#number string).

func ParseCrossRef added in v0.1.16

func ParseCrossRef(ref string) (Dependency, error)

ParseCrossRef parses a cross-project reference string in the format "owner/repo#number". Returns an error if the format is invalid.

func (Dependency) IsCrossProject added in v0.1.16

func (d Dependency) IsCrossProject() bool

IsCrossProject returns true if the dependency references another project.

func (Dependency) String added in v0.1.16

func (d Dependency) String() string

String returns the canonical string form: "42" for same-project, "owner/repo#42" for cross-project.

type DependencyList added in v0.1.16

type DependencyList []Dependency

DependencyList is a list of dependencies that supports mixed int and string YAML values.

func (DependencyList) CrossProjectDeps added in v0.1.16

func (dl DependencyList) CrossProjectDeps() []Dependency

CrossProjectDeps returns only cross-project dependencies.

func (DependencyList) LocalDeps added in v0.1.16

func (dl DependencyList) LocalDeps() []int

LocalDeps returns only same-project dependency issue numbers.

func (DependencyList) MarshalYAML added in v0.1.16

func (dl DependencyList) MarshalYAML() (interface{}, error)

MarshalYAML implements the yaml.Marshaler interface for DependencyList.

func (*DependencyList) UnmarshalYAML added in v0.1.16

func (dl *DependencyList) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface for DependencyList. It handles both integer values (same-project) and string values (cross-project refs).

type FailureClass added in v0.1.14

type FailureClass string

FailureClass categorises a failure into an actionable class for circuit breakers and automated analysis.

const (
	FailureClassAuth         FailureClass = "auth"          // 401, OAuth expired, authentication_error
	FailureClassBudget       FailureClass = "budget"        // credit/budget exhausted
	FailureClassPermanent    FailureClass = "permanent"     // model not found, permanent config error
	FailureClassTimeout      FailureClass = "timeout"       // heartbeat timeout / context deadline
	FailureClassProviderDown FailureClass = "provider_down" // connection refused, provider unreachable
	FailureClassOOMKill      FailureClass = "oom_kill"      // signal: killed (OOM or external)
	FailureClassShutdown     FailureClass = "shutdown"      // exit 143 (SIGTERM during graceful shutdown)
	FailureClassPanic        FailureClass = "panic"         // send on closed channel, runtime panic
	FailureClassPostProcess  FailureClass = "post_process"  // PR creation, comment posting failed
	FailureClassClassify     FailureClass = "classify"      // frontmatter parse or agent type validation
	FailureClassCycle        FailureClass = "cycle"         // dependency cycle detected
	FailureClassDecompose    FailureClass = "decompose"     // issue decomposition failed
	FailureClassUnknown      FailureClass = "unknown"       // unrecognised error pattern
)

func (FailureClass) IsPermanent added in v0.1.14

func (fc FailureClass) IsPermanent() bool

IsPermanent returns true if retrying will never succeed.

func (FailureClass) IsProviderFailure added in v0.1.16

func (fc FailureClass) IsProviderFailure() bool

IsProviderFailure returns true if the failure is an infrastructure problem (provider unreachable, unhealthy, or hung) rather than an issue-specific problem. Provider failures should NOT count toward per-issue escalation thresholds.

func (FailureClass) IsRetryable added in v0.1.14

func (fc FailureClass) IsRetryable() bool

IsRetryable returns true if this failure class warrants a retry attempt.

type FailureEvent added in v0.1.14

type FailureEvent struct {
	ID            string        `json:"id"`
	IssueNumber   int           `json:"issue_number"`
	SessionID     string        `json:"session_id,omitempty"` // empty for dispatcher-level failures
	FailureClass  FailureClass  `json:"failure_class"`
	ErrorMessage  string        `json:"error_message"`
	AgentType     string        `json:"agent_type,omitempty"`
	Provider      string        `json:"provider,omitempty"`
	AttemptNumber int           `json:"attempt_number"` // which attempt (1st, 2nd, 3rd, etc.)
	Duration      time.Duration `json:"duration_ms,omitempty"`
	Timestamp     time.Time     `json:"timestamp"`

	// RCA fields — populated when a fix is recorded.
	RootCauseCategory string     `json:"root_cause_category,omitempty"`
	FixClassification string     `json:"fix_classification,omitempty"`
	PreventionMeasure string     `json:"prevention_measure,omitempty"`
	RecurrenceRisk    string     `json:"recurrence_risk,omitempty"`
	DetectionMethod   string     `json:"detection_method,omitempty"`
	TimeToDetectMin   *int       `json:"time_to_detect_min,omitempty"`
	LinkedIssues      string     `json:"linked_issues,omitempty"`
	Component         string     `json:"component,omitempty"`
	ResolvedAt        *time.Time `json:"resolved_at,omitempty"`
	// Status mirrors the session status for KPI queries (e.g. "resolved").
	Status string `json:"status,omitempty"`
}

FailureEvent represents a single failure occurrence in the dispatcher or agent runtime. Every failure path emits one of these to the store for aggregation and analysis.

type FailureSummary added in v0.1.14

type FailureSummary struct {
	TotalFailures  int                  `json:"total_failures"`
	ByClass        map[FailureClass]int `json:"by_class"`
	TopIssues      []IssueFailureCount  `json:"top_issues"`      // issues with most failures
	LoopingIssues  []IssueFailureCount  `json:"looping_issues"`  // issues with 5+ failures
	ProviderHealth map[string]int       `json:"provider_health"` // provider -> failure count
	Since          time.Time            `json:"since"`
}

FailureSummary aggregates failure data for dashboards and digests.

type IssueFailureCount added in v0.1.14

type IssueFailureCount struct {
	IssueNumber int `json:"issue_number"`
	Count       int `json:"count"`
}

IssueFailureCount pairs an issue number with its failure count.

type IssueFrontmatter

type IssueFrontmatter struct {
	SchemaVersion   string         `yaml:"schema_version"`
	Type            IssueType      `yaml:"type"`
	AgentType       AgentType      `yaml:"agent_type"`
	Priority        Priority       `yaml:"priority"`
	ParentIssue     int            `yaml:"parent_issue,omitempty"`
	DependsOn       DependencyList `yaml:"depends_on,omitempty"`
	SourceProject   string         `yaml:"source_project,omitempty"`
	EstimatedTokens int            `yaml:"estimated_tokens,omitempty"`
	ActualTokens    int            `yaml:"actual_tokens,omitempty"`
	ModelUsed       string         `yaml:"model_used,omitempty"`
	TimeoutMinutes  int            `yaml:"timeout_minutes,omitempty"`
}

IssueFrontmatter represents the YAML frontmatter parsed from an issue body.

type IssueType

type IssueType string

IssueType identifies the communication purpose of an issue.

const (
	IssueTypeTask         IssueType = "task"
	IssueTypeQuestion     IssueType = "question"
	IssueTypeResult       IssueType = "result"
	IssueTypeBlock        IssueType = "block"
	IssueTypeCoordination IssueType = "coordination"
)

type KPIReport added in v0.1.23

type KPIReport struct {
	WindowDays           int                       `json:"window_days"`
	FirstTimeFixRate     *float64                  `json:"first_time_fix_rate"`
	FixSuccessRate       *float64                  `json:"fix_success_rate"`
	RecurrenceRate       *float64                  `json:"recurrence_rate"`
	WorkaroundRate       *float64                  `json:"workaround_rate"`
	MeanTimeToFixHours   *float64                  `json:"mean_time_to_fix_hours"`
	PlanningGapRate      *float64                  `json:"planning_gap_rate"`
	UnknownRootCauseRate *float64                  `json:"unknown_root_cause_rate"`
	PreventionCoverage   *float64                  `json:"prevention_coverage"`
	RootCauseBreakdown   []RootCauseBreakdownEntry `json:"root_cause_breakdown"`
	SampleSize           int                       `json:"sample_size"`
}

KPIReport is the response payload for GET /api/v1/kpis. Rates are nil when sample_size < 5 (insufficient data).

type ParseResult

type ParseResult struct {
	Frontmatter *IssueFrontmatter
	Body        string // markdown after the closing ---
}

ParseResult holds the parsed frontmatter and remaining body text.

func ParseFrontmatter

func ParseFrontmatter(body string) (*ParseResult, error)

ParseFrontmatter extracts YAML frontmatter from an issue body. The frontmatter must be delimited by --- on its own line at the start of the body. Returns error if frontmatter is present but malformed. Returns nil Frontmatter (no error) if no frontmatter block exists.

type Priority

type Priority string

Priority determines scheduling order.

const (
	PriorityCritical Priority = "critical"
	PriorityHigh     Priority = "high"
	PriorityNormal   Priority = "normal"
	PriorityLow      Priority = "low"
)

type QualityRecommendation added in v0.1.23

type QualityRecommendation struct {
	ID            string    `json:"id"`
	Level         string    `json:"level"` // "info" | "warn" | "critical"
	Category      string    `json:"category"`
	Title         string    `json:"title"`
	Detail        string    `json:"detail"`
	AffectedCount int       `json:"affected_count"`
	WindowDays    int       `json:"window_days"`
	GeneratedAt   time.Time `json:"generated_at"`
}

QualityRecommendation is one advisory recommendation from the advisory engine.

type RootCauseBreakdownEntry added in v0.1.23

type RootCauseBreakdownEntry struct {
	Category string  `json:"category"`
	Count    int     `json:"count"`
	Pct      float64 `json:"pct"`
}

RootCauseBreakdownEntry holds one row of the root-cause breakdown.

type ScalingControl added in v0.1.11

type ScalingControl struct {
	Paused        bool
	ManualWorkers int
	SetAt         time.Time
	Note          string
}

ScalingControl is a single-row record that holds manual override state written by the REST API or CLI and consumed by the autoscaler on each evaluation cycle. ManualWorkers == 0 means no manual target is set. Paused == true means the autoscaler should hold (take no autonomous action).

type ScalingEvent added in v0.1.11

type ScalingEvent struct {
	ID          string
	Timestamp   time.Time
	Action      string // "scale-up" | "scale-down" | "manual-override"
	FromWorkers int
	ToWorkers   int
	Reason      string
	Confidence  float64
}

ScalingEvent records a single autoscaler decision.

type Session

type Session struct {
	ID               string        `json:"id"`
	IssueNumber      int           `json:"issue_number"`
	AgentType        string        `json:"agent_type"` // e.g., "code-gen", "qc", "research"
	Provider         string        `json:"provider"`   // e.g., "ollama", "claude", "openai"
	Model            string        `json:"model"`      // e.g., "qwen2.5-coder:7b"
	Status           SessionStatus `json:"status"`
	StartedAt        time.Time     `json:"started_at"`
	FinishedAt       *time.Time    `json:"finished_at,omitempty"`
	Error            string        `json:"error,omitempty"`
	EstimatedTimeout time.Duration `json:"estimated_timeout_ms,omitempty"` // timeout predicted at dispatch time
	PartialOutput    string        `json:"partial_output,omitempty"`       // last checkpoint of streaming output
	CheckpointHash   string        `json:"checkpoint_hash,omitempty"`      // SHA-256 of posted checkpoint for dedup
	CreatedAt        time.Time     `json:"created_at"`
	UpdatedAt        time.Time     `json:"updated_at"`
}

Session represents a unit of agent work on an issue.

type SessionStatus

type SessionStatus string

SessionStatus represents the lifecycle state of a work session.

const (
	SessionStatusPending   SessionStatus = "pending"
	SessionStatusActive    SessionStatus = "active"
	SessionStatusCompleted SessionStatus = "completed"
	SessionStatusFailed    SessionStatus = "failed"
	SessionStatusCancelled SessionStatus = "cancelled"
)

type Status

type Status string

Status tracks the lifecycle state of an issue.

const (
	StatusQueued       Status = "queued"
	StatusClaimed      Status = "claimed"
	StatusInProgress   Status = "in-progress"
	StatusBlocked      Status = "blocked"
	StatusNeedsQC      Status = "needs-qc"
	StatusNeedsHuman   Status = "needs-human"
	StatusHumanPending Status = "human-pending"
	StatusDone         Status = "done"
)

type TaskProfile added in v0.1.11

type TaskProfile struct {
	AgentType   string        `json:"agent_type"`
	Provider    string        `json:"provider"`
	AvgDuration time.Duration `json:"avg_duration"`
	P50Duration time.Duration `json:"p50_duration"`
	P90Duration time.Duration `json:"p90_duration"`
	SampleCount int           `json:"sample_count"`
	AvgTokens   int           `json:"avg_tokens"`
	UpdatedAt   time.Time     `json:"updated_at"`
}

TaskProfile holds rolling performance statistics for a specific (AgentType, Provider) combination, computed from completed sessions. Values are updated after each successful task completion.

Jump to

Keyboard shortcuts

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