migrate

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package migrate owns the on-disk YAML schema for LeanProxy's user-server configuration. It re-exports the canonical transport enum used throughout the codebase so callers can refer to it without depending on pkg/registry (which already depends on this package for ServerConfig).

Index

Constants

View Source
const SimilarityLimit = 5

SimilarityLimit bounds the number of "did you mean" suggestions returned by Install when the requested server id is not in the registry cache.

Variables

This section is empty.

Functions

func ExecutableExists

func ExecutableExists(cmd string) bool

func FormatValidationSummary

func FormatValidationSummary(imported int, result *ValidationResult) string

func IsAlreadyInstalled added in v0.8.0

func IsAlreadyInstalled(err error) bool

IsAlreadyInstalled reports whether err (or any wrapped error) is an ErrAlreadyInstalled.

func IsUnknownServer added in v0.8.0

func IsUnknownServer(err error) bool

IsUnknownServer reports whether err (or any wrapped error) is an ErrUnknownServer.

func MarshalConfig added in v0.2.0

func MarshalConfig(cfg *Config) ([]byte, error)

func SaveConfig added in v0.8.0

func SaveConfig(path string, cfg *Config) error

SaveConfig writes cfg to path with 0600 permissions, creating the parent directory if needed. The write is atomic: a temp file in the same directory is created, fsynced, then renamed over the target.

func SuggestSimilar added in v0.8.0

func SuggestSimilar(needle string, entries []CacheEntry, limit int) []string

SuggestSimilar ranks entries by Levenshtein distance to needle and returns the top-n closest names. Identical matches are excluded (Resolve handles the exact case before calling this helper).

Types

type AuthConfig added in v0.7.0

type AuthConfig struct {
	Type         string   `yaml:"type"` // bearer, oauth2
	ClientID     string   `yaml:"client_id"`
	ClientSecret string   `yaml:"client_secret"`
	Scopes       []string `yaml:"scopes"`
	TokenURL     string   `yaml:"token_url"` // optional, for bearer token exchange
}

type CacheConfig added in v0.8.0

type CacheConfig struct {
	VectorStore *VectorStoreConfig `yaml:"vector_store,omitempty"`
}

type CacheEntry added in v0.8.0

type CacheEntry struct {
	Name          string
	Transport     string
	Command       string
	Args          []string
	Env           map[string]string
	URL           string
	TokensPerTurn int64
}

CacheEntry is the subset of a registry feed record the installer cares about. Defining it here keeps the installer decoupled from the registry package's concrete types.

type CacheSettings

type CacheSettings struct {
	Enabled  bool   `yaml:"enabled"`
	MaxSize  int    `yaml:"max_size"`
	TTL      string `yaml:"ttl"`
	TTLValue time.Duration
}

type CacheSnapshot added in v0.8.0

type CacheSnapshot struct {
	Entries []CacheEntry
}

CacheSnapshot is the materialized view of the registry cache. It is returned by ServerSource.LookupCache.

type ClaudeScanner

type ClaudeScanner struct{}

func (*ClaudeScanner) Name

func (s *ClaudeScanner) Name() string

func (*ClaudeScanner) Scan

type Config

type Config struct {
	Version      string              `yaml:"version"`
	Servers      []*ServerConfig     `yaml:"servers"`
	Reconnect    *ReconnectConfig    `yaml:"reconnect,omitempty"`
	Optimization *OptimizationConfig `yaml:"optimization,omitempty"`
	Cache        *CacheConfig        `yaml:"cache,omitempty"`
	Federation   *FederationConfig   `yaml:"federation,omitempty"`
	Injection    *injection.Config   `yaml:"injection,omitempty"`
}

func LoadConfig

func LoadConfig(ctx context.Context, path string) (*Config, error)

func (*Config) EffectiveReconnect added in v0.9.0

func (c *Config) EffectiveReconnect() ResolvedReconnect

func (*Config) Validate

func (c *Config) Validate() error

type CursorScanner

type CursorScanner struct{}

func (*CursorScanner) Name

func (s *CursorScanner) Name() string

func (*CursorScanner) Scan

type DiscoveredServer

type DiscoveredServer struct {
	Name      string
	Source    string
	Transport TransportType
	Stdio     *StdioConfig
	HTTP      *HTTPConfig
	Enabled   *bool
}

type ErrAlreadyInstalled added in v0.8.0

type ErrAlreadyInstalled struct {
	ServerID string
}

ErrAlreadyInstalled is returned when the server name already exists in the user config and neither Force nor an interactive confirmation has been supplied.

func (*ErrAlreadyInstalled) Error added in v0.8.0

func (e *ErrAlreadyInstalled) Error() string

type ErrUnknownServer added in v0.8.0

type ErrUnknownServer struct {
	ServerID  string
	Suggested []string
}

ErrUnknownServer is returned by Install when the requested server id is not present in the local registry cache. It carries suggested similar names so callers can present a "did you mean" hint without re-running the search.

func (*ErrUnknownServer) Error added in v0.8.0

func (e *ErrUnknownServer) Error() string

type FederationConfig added in v0.7.0

type FederationConfig struct {
	Enabled bool          `yaml:"enabled"`
	Peers   []*PeerConfig `yaml:"peers"`
}

type GenericScanner

type GenericScanner struct{}

func (*GenericScanner) Name

func (s *GenericScanner) Name() string

func (*GenericScanner) Scan

type HTTPConfig

type HTTPConfig struct {
	URL     string            `yaml:"url"`
	Headers map[string]string `yaml:"headers"`
	Auth    *AuthConfig       `yaml:"auth,omitempty"`
}

type ImportResult

type ImportResult struct {
	Imported   int
	Duplicates int
	Errors     []error
	Validation *ValidationResult
}

type InstallOptions added in v0.8.0

type InstallOptions struct {
	// Force, when true, allows overwriting an existing server definition.
	Force bool

	// StopExisting, when true, asks the stopper to gracefully stop any
	// running instance that shares the target name before the new definition
	// is written.
	StopExisting bool

	// GracefulTimeout is the budget for the graceful stop before the caller
	// proceeds with the install regardless. Zero means use the stop call's
	// default context.
	GracefulTimeout time.Duration

	// Stopper, when set, is invoked to stop existing instances when
	// StopExisting is true. It may be nil for offline (config-only) installs.
	Stopper LifecycleStopper

	// Logger is used for operational logs. Defaults to slog.Default().
	Logger *slog.Logger

	// DryRun, when true, prevents any filesystem writes and any stopper
	// calls. The result still reflects what would have happened.
	DryRun bool
}

InstallOptions controls Install behavior. The zero value performs an additive install with no graceful stop and no lifecycle manager.

type InstallResult added in v0.8.0

type InstallResult struct {
	ServerID        string
	ServerName      string
	Transport       string
	Replaced        bool
	Stopped         bool
	ConfigPath      string
	DryRun          bool
	EstimatedTools  int
	SnapshotSummary string
}

InstallResult captures the outcome of a successful Install call. It is always non-nil when err is nil.

type Installer added in v0.8.0

type Installer struct {
	Source     ServerSource
	ConfigPath string
	Logger     *slog.Logger
}

Installer is the top-level facade used by cmd/add. It composes a cache source and a config path.

func NewInstaller added in v0.8.0

func NewInstaller(source ServerSource, configPath string, logger *slog.Logger) *Installer

NewInstaller wires an Installer with the given cache source and config path. Either may be overridden after construction by setting the fields directly.

func (*Installer) Install added in v0.8.0

func (i *Installer) Install(ctx context.Context, entry CacheEntry, opts InstallOptions) (*InstallResult, error)

Install builds a ServerConfig from the cache entry, merges it into the user config at i.ConfigPath (writing through MarshalConfig), and — if StopExisting is true — gracefully stops any running instance that shares the target name via the provided Stopper.

The returned result is always non-nil when err is nil.

func (*Installer) Resolve added in v0.8.0

func (i *Installer) Resolve(ctx context.Context, serverID string) (CacheEntry, error)

Resolve returns the registry entry for serverID (case-insensitive). If no exact match is found, it returns an *ErrUnknownServer populated with up to SimilarityLimit suggestions ranked by edit distance.

Resolve never triggers a Sync; callers are expected to have a fresh cache.

type LazyLoadingSettings added in v0.7.0

type LazyLoadingSettings struct {
	Enabled       bool          `yaml:"enabled"`
	StubTokens    int           `yaml:"stub_tokens"`
	CacheTTL      string        `yaml:"cache_ttl"`
	CacheTTLValue time.Duration `yaml:"-"`
	Prewarm       []string      `yaml:"prewarm"`
}

type LifecycleStopper added in v0.8.0

type LifecycleStopper interface {
	Stop(ctx context.Context, id string) error
}

LifecycleStopper is the narrow surface the installer needs from a server lifecycle manager. The concrete *registry.LifecycleManager satisfies it via its Stop method, but the installer accepts the interface so callers can pass a fake in tests.

type MigrationSummary

type MigrationSummary struct {
	OpenCodeCount int
	ClaudeCount   int
	VSCodeCount   int
	CursorCount   int
	GenericCount  int
	TotalServers  int
}

func (*MigrationSummary) Total

func (s *MigrationSummary) Total() int

type Migrator

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

func NewMigrator

func NewMigrator() *Migrator

func (*Migrator) Import

func (m *Migrator) Import(ctx context.Context, servers []DiscoveredServer, targetPath string, yes bool) (*ImportResult, error)

func (*Migrator) ImportAll

func (m *Migrator) ImportAll(ctx context.Context, servers []DiscoveredServer, yes bool) (*ImportResult, error)

func (*Migrator) Scan

func (m *Migrator) Scan(ctx context.Context) (*ScanResult, error)

func (*Migrator) Summarize

func (m *Migrator) Summarize(servers []DiscoveredServer) *MigrationSummary

func (*Migrator) Validate

func (m *Migrator) Validate(servers []DiscoveredServer) *ValidationResult

type OpenCodeScanner

type OpenCodeScanner struct{}

func (*OpenCodeScanner) Name

func (s *OpenCodeScanner) Name() string

func (*OpenCodeScanner) Scan

type OptimizationConfig added in v0.7.0

type OptimizationConfig struct {
	LazyLoading *LazyLoadingSettings `yaml:"lazy_loading,omitempty"`
}

type PeerConfig added in v0.7.0

type PeerConfig struct {
	Name      string `yaml:"name"`
	URL       string `yaml:"url"`
	AuthToken string `yaml:"auth_token,omitempty"`
}

type PineconeVectorConfig added in v0.8.0

type PineconeVectorConfig struct {
	Index     string `yaml:"index"`
	APIKeyEnv string `yaml:"api_key_env"`
}

type QdrantVectorConfig added in v0.8.0

type QdrantVectorConfig struct {
	URL        string `yaml:"url"`
	APIKey     string `yaml:"api_key"`
	APIKeyEnv  string `yaml:"api_key_env"`
	Collection string `yaml:"collection"`
}

type ReconnectConfig added in v0.9.0

type ReconnectConfig struct {
	Enabled             *bool         `yaml:"enabled"`
	HealthInterval      string        `yaml:"health_check_interval"`
	HealthIntervalValue time.Duration `yaml:"-"`
	MaxFailures         int           `yaml:"health_check_failures"`
	MaxRestartAttempts  int           `yaml:"max_restart_attempts"`
	RestartBackoff      string        `yaml:"restart_backoff"`
	RestartBackoffValue time.Duration `yaml:"-"`
	StableWindow        string        `yaml:"stable_window"`
	StableWindowValue   time.Duration `yaml:"-"`
}

type ResolvedReconnect added in v0.9.0

type ResolvedReconnect struct {
	Enabled            bool
	HealthInterval     time.Duration
	MaxFailures        int
	MaxRestartAttempts int
	RestartBackoff     time.Duration
	StableWindow       time.Duration
}

type SQLiteVectorConfig added in v0.8.0

type SQLiteVectorConfig struct {
	Path string `yaml:"path"`
}

type ScanResult

type ScanResult struct {
	Scanners []string
	Servers  []DiscoveredServer
}

type Scanner

type Scanner interface {
	Name() string
	Scan(ctx context.Context) ([]DiscoveredServer, error)
}

type ServerConfig

type ServerConfig struct {
	Name                string             `yaml:"name"`
	Enabled             *bool              `yaml:"enabled"`
	Transport           TransportType      `yaml:"transport"`
	ComplexityTier      string             `yaml:"complexity_tier,omitempty"`
	Stdio               *StdioConfig       `yaml:"stdio,omitempty"`
	HTTP                *HTTPConfig        `yaml:"http,omitempty"`
	Timeout             string             `yaml:"timeout"`
	TimeoutValue        time.Duration      `yaml:"-"`
	ConnectTimeout      string             `yaml:"connect_timeout"`
	ConnectTimeoutValue time.Duration      `yaml:"-"`
	IdleTimeout         string             `yaml:"idle_timeout"`
	IdleTimeoutValue    time.Duration      `yaml:"-"`
	CacheSettings       *CacheSettings     `yaml:"cache_settings,omitempty"`
	SummarizeSettings   *SummarizeSettings `yaml:"summarize_settings,omitempty"`
}

func (*ServerConfig) Validate

func (c *ServerConfig) Validate() error

type ServerSource added in v0.8.0

type ServerSource interface {
	// LookupCache returns the list of (name, transport, command, url,
	// tokens-per-turn) records available locally. The bool reports whether
	// any cache was present; an empty slice with bool == true means "cache
	// exists but is empty".
	LookupCache(ctx context.Context) (CacheSnapshot, error)
}

ServerSource is the minimal interface the installer needs from a registry cache. It is satisfied by *registry.FeedFetcher (which returns a *registry.FeedIndex) but defined here to avoid an import cycle with the registry package, which in turn depends on this package for the ServerConfig schema.

type StdioConfig

type StdioConfig struct {
	Command string   `yaml:"command"`
	Args    []string `yaml:"args"`
	Env     []string `yaml:"env"`
	CWD     string   `yaml:"cwd"`
}

type SummarizeSettings

type SummarizeSettings struct {
	Enabled   bool   `yaml:"enabled"`
	MaxTokens int    `yaml:"max_tokens"`
	Strategy  string `yaml:"strategy"`
}

type TransportType added in v0.8.0

type TransportType string

TransportType enumerates the wire transports a server may speak. The string values are part of the public YAML schema and must not change without a migration step.

const (
	TransportStdio TransportType = "stdio"
	TransportHTTP  TransportType = "http"
	TransportSSE   TransportType = "sse"
)

type VSCodeScanner

type VSCodeScanner struct{}

func (*VSCodeScanner) Name

func (s *VSCodeScanner) Name() string

func (*VSCodeScanner) Scan

type ValidationError

type ValidationError struct {
	ServerName string
	Message    string
	Field      string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationResult

type ValidationResult struct {
	Errors   []ValidationError
	Warnings []ValidationError
}

func (*ValidationResult) ErrorCount

func (r *ValidationResult) ErrorCount() int

func (*ValidationResult) HasErrors

func (r *ValidationResult) HasErrors() bool

func (*ValidationResult) HasWarnings

func (r *ValidationResult) HasWarnings() bool

func (*ValidationResult) WarningCount

func (r *ValidationResult) WarningCount() int

type Validator

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

func NewValidator

func NewValidator() *Validator

func NewValidatorWithoutExecutableCheck

func NewValidatorWithoutExecutableCheck() *Validator

func (*Validator) ValidateServers

func (v *Validator) ValidateServers(servers []DiscoveredServer) *ValidationResult

type VectorStoreConfig added in v0.8.0

type VectorStoreConfig struct {
	Backend   string                `yaml:"backend"`
	Dimension int                   `yaml:"dimension"`
	SQLite    *SQLiteVectorConfig   `yaml:"sqlite,omitempty"`
	Qdrant    *QdrantVectorConfig   `yaml:"qdrant,omitempty"`
	Pinecone  *PineconeVectorConfig `yaml:"pinecone,omitempty"`
}

Jump to

Keyboard shortcuts

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