core

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultVectorModelPath is the default GGUF embedding model path used by local runtime configuration.
	DefaultVectorModelPath = "./dist/MiniLM-L6-v2.Q8_0.gguf"

	// DefaultVectorEnabled keeps semantic/hybrid search on by default for internal usage.
	DefaultVectorEnabled = true
)
View Source
const (
	// DefaultMaxNeuronContentBytes defines the default hard upper boundary for neuron text payloads.
	// Larger contents should be chunked by upstream clients/wrappers.
	DefaultMaxNeuronContentBytes = 64 * 1024

	// MaxNeuronContentBytes is retained as a compatibility alias for tests and callers.
	MaxNeuronContentBytes = DefaultMaxNeuronContentBytes
)

Variables

View Source
var (
	ErrNeuronNotFound    = errors.New("neuron not found")
	ErrSynapseNotFound   = errors.New("synapse not found")
	ErrMatrixNotFound    = errors.New("matrix not found for user")
	ErrMatrixFull        = errors.New("matrix has reached maximum capacity")
	ErrDimensionLimit    = errors.New("dimension limit reached")
	ErrInvalidContent    = errors.New("invalid neuron content")
	ErrContentTooLarge   = errors.New("neuron content exceeds maximum allowed size")
	ErrDuplicateNeuron   = errors.New("neuron with same content hash exists")
	ErrSelfLink          = errors.New("cannot create synapse to self")
	ErrBrainNotActive    = errors.New("brain is not active")
	ErrBrainSleeping     = errors.New("brain is in sleep/consolidation state")
	ErrPersistenceFailed = errors.New("failed to persist matrix")
	ErrLoadFailed        = errors.New("failed to load matrix from persistence")
	ErrInvalidQuery      = errors.New("invalid query")
	ErrUserNotFound      = errors.New("user not found")
)

Functions

func GetMaxNeuronContentBytes

func GetMaxNeuronContentBytes() int64

GetMaxNeuronContentBytes returns the active runtime neuron content size limit.

func HashContent

func HashContent(content string) string

HashContent generates a consistent hash for content deduplication Exported for use across packages

func PrintBanner

func PrintBanner()

PrintBanner prints the QubicDB ASCII art banner to stdout.

func SetMaxNeuronContentBytes

func SetMaxNeuronContentBytes(limit int64) error

SetMaxNeuronContentBytes overrides the runtime neuron content size limit.

func TimeSince

func TimeSince(t time.Time) time.Duration

TimeSince is a wrapper for time.Since for easier mocking in tests

func ValidateNeuronContent

func ValidateNeuronContent(content string) error

ValidateNeuronContent ensures neuron content is non-empty and within size boundaries.

func WaitForShutdown

func WaitForShutdown(ctx context.Context, cancel context.CancelFunc)

WaitForShutdown blocks until an OS interrupt or termination signal is received, then cancels the provided context to initiate graceful shutdown.

Types

type ActivityState

type ActivityState int

ActivityState represents the current activity level

const (
	StateActive   ActivityState = iota // User actively interacting
	StateIdle                          // User paused
	StateSleeping                      // Consolidation in progress
	StateDormant                       // Persisted, not in memory
)

type AdminConfig

type AdminConfig struct {
	// Enabled controls whether admin endpoints are active.
	// When false, all /admin/* routes return 404.
	Enabled bool `yaml:"enabled"`

	// User is the admin username for /admin/login authentication.
	User string `yaml:"user"`

	// Password is the admin password for /admin/login authentication.
	// WARNING: Change the default before deploying to production.
	Password string `yaml:"password"`
}

AdminConfig groups server administration settings.

type BrainState

type BrainState struct {
	IndexID        IndexID       `msgpack:"index_id"`
	State          ActivityState `msgpack:"state"`
	LastInvoke     time.Time     `msgpack:"last_invoke"`
	InvokeCount    uint64        `msgpack:"invoke_count"`
	SessionStart   time.Time     `msgpack:"session_start"`
	IdleThreshold  time.Duration `msgpack:"idle_threshold"`
	SleepThreshold time.Duration `msgpack:"sleep_threshold"`
}

BrainState tracks the lifecycle state of a user's brain

func NewBrainState

func NewBrainState(indexID IndexID) *BrainState

NewBrainState creates initial brain state

type CLIOverrides

type CLIOverrides struct {
	ConfigPath             *string
	HTTPAddr               *string
	DataPath               *string
	Compress               *bool
	MinDimension           *int
	MaxDimension           *int
	MaxNeurons             *int
	IdleThreshold          *time.Duration
	SleepThreshold         *time.Duration
	DormantThreshold       *time.Duration
	DecayInterval          *time.Duration
	ConsolidateInt         *time.Duration
	PruneInterval          *time.Duration
	PersistInterval        *time.Duration
	ReorgInterval          *time.Duration
	MaxIdleTime            *time.Duration
	RegistryEnabled        *bool
	VectorEnabled          *bool
	VectorModelPath        *string
	VectorGPULayers        *int
	VectorAlpha            *float64
	VectorQueryRepeat      *int
	VectorEmbedContextSize *uint32
	AdminEnabled           *bool
	AdminUser              *string
	AdminPassword          *string
	AllowedOrigins         *string
	MaxRequestBody         *int64
	MaxNeuronContentBytes  *int64
	TLSCert                *string
	TLSKey                 *string
}

CLIOverrides carries optional values set via command-line flags. Pointer fields are nil when the flag was not explicitly provided, allowing the caller to distinguish "not set" from the zero value.

type Config

type Config struct {
	Server    ServerConfig    `yaml:"server"`
	Storage   StorageConfig   `yaml:"storage"`
	Matrix    MatrixConfig    `yaml:"matrix"`
	Lifecycle LifecycleConfig `yaml:"lifecycle"`
	Daemons   DaemonConfig    `yaml:"daemons"`
	Worker    WorkerConfig    `yaml:"worker"`
	Registry  RegistryConfig  `yaml:"registry"`
	Vector    VectorConfig    `yaml:"vector"`
	Admin     AdminConfig     `yaml:"admin"`
	MCP       MCPConfig       `yaml:"mcp"`
	Security  SecurityConfig  `yaml:"security"`
}

Config is the root configuration object for a QubicDB server.

func ConfigFromEnv

func ConfigFromEnv(cfg *Config) *Config

ConfigFromEnv applies environment variable overrides to the given Config. If cfg is nil a new default Config is created first.

Environment variable mapping (all optional, prefix QUBICDB_):

QUBICDB_HTTP_ADDR           → Server.HTTPAddr
QUBICDB_DATA_PATH           → Storage.DataPath
QUBICDB_COMPRESS            → Storage.Compress          ("true"/"false")
QUBICDB_WAL_ENABLED         → Storage.WALEnabled        ("true"/"false")
QUBICDB_FSYNC_POLICY        → Storage.FsyncPolicy       (always|interval|off)
QUBICDB_FSYNC_INTERVAL      → Storage.FsyncInterval     (duration string)
QUBICDB_CHECKSUM_VALIDATION_INTERVAL → Storage.ChecksumValidationInterval (duration string, 0=off)
QUBICDB_STARTUP_REPAIR      → Storage.StartupRepair     ("true"/"false")
QUBICDB_MIN_DIMENSION       → Matrix.MinDimension
QUBICDB_MAX_DIMENSION       → Matrix.MaxDimension
QUBICDB_MAX_NEURONS         → Matrix.MaxNeurons
QUBICDB_IDLE_THRESHOLD      → Lifecycle.IdleThreshold   (duration string)
QUBICDB_SLEEP_THRESHOLD     → Lifecycle.SleepThreshold  (duration string)
QUBICDB_DORMANT_THRESHOLD   → Lifecycle.DormantThreshold(duration string)
QUBICDB_DECAY_INTERVAL      → Daemons.DecayInterval     (duration string)
QUBICDB_CONSOLIDATE_INTERVAL→ Daemons.ConsolidateInterval
QUBICDB_PRUNE_INTERVAL      → Daemons.PruneInterval
QUBICDB_PERSIST_INTERVAL    → Daemons.PersistInterval
QUBICDB_REORG_INTERVAL      → Daemons.ReorgInterval
QUBICDB_MAX_IDLE_TIME       → Worker.MaxIdleTime
QUBICDB_REGISTRY_ENABLED    → Registry.Enabled          ("true"/"false")
QUBICDB_ADMIN_ENABLED       → Admin.Enabled             ("true"/"false")
QUBICDB_ADMIN_USER          → Admin.User
QUBICDB_ADMIN_PASSWORD      → Admin.Password
QUBICDB_MCP_ENABLED         → MCP.Enabled               ("true"/"false")
QUBICDB_MCP_PATH            → MCP.Path
QUBICDB_MCP_API_KEY         → MCP.APIKey
QUBICDB_MCP_STATELESS       → MCP.Stateless             ("true"/"false")
QUBICDB_MCP_RATE_LIMIT_RPS  → MCP.RateLimitRPS          (float)
QUBICDB_MCP_RATE_LIMIT_BURST→ MCP.RateLimitBurst        (integer)
QUBICDB_MCP_ENABLE_PROMPTS  → MCP.EnablePrompts         ("true"/"false")
QUBICDB_MCP_ALLOWED_TOOLS   → MCP.AllowedTools          (comma-separated)
QUBICDB_ALLOWED_ORIGINS     → Security.AllowedOrigins
QUBICDB_MAX_REQUEST_BODY    → Security.MaxRequestBody   (bytes, integer)
QUBICDB_MAX_NEURON_CONTENT_BYTES → Security.MaxNeuronContentBytes (bytes, integer)
QUBICDB_TLS_CERT            → Security.TLSCert
QUBICDB_TLS_KEY             → Security.TLSKey
QUBICDB_READ_TIMEOUT        → Security.ReadTimeout      (duration string)
QUBICDB_WRITE_TIMEOUT       → Security.WriteTimeout     (duration string)

func ConfigFromFile

func ConfigFromFile(path string) (*Config, error)

ConfigFromFile reads a YAML configuration file and merges it on top of the built-in defaults. Fields absent from the file retain their defaults.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config populated with production-safe defaults.

func LoadConfig

func LoadConfig(configPath string) (*Config, error)

LoadConfig implements the full four-level configuration hierarchy:

  1. Start with built-in defaults.
  2. If configPath is non-empty, overlay the YAML file.
  3. Apply environment variable overrides.
  4. The caller may then apply programmatic overrides (e.g. CLI flags).

Returns the merged Config or an error if the file cannot be read/parsed.

func (*Config) ApplyCLIOverrides

func (c *Config) ApplyCLIOverrides(o *CLIOverrides)

ApplyCLIOverrides patches the Config with any explicitly-set CLI flags. Only non-nil fields in the CLIOverrides are applied, preserving all values resolved from earlier hierarchy layers.

func (*Config) Validate

func (c *Config) Validate() error

Validate performs structural validation of the entire configuration. Returns a descriptive error for the first invalid field encountered.

type ConnInfo

type ConnInfo struct {
	// Scheme is the protocol scheme ("qubicdb" or "qubicdb+tls").
	Scheme string

	// User is the authentication username (empty if not provided).
	User string

	// Password is the authentication password (empty if not provided).
	Password string

	// Hosts is a list of host:port pairs. At least one is always present.
	Hosts []string

	// IndexID is the optional default index (path segment after the first slash).
	IndexID string

	// TLS is true when the scheme is "qubicdb+tls".
	TLS bool
}

ConnInfo holds parsed connection string components.

func ParseConnString

func ParseConnString(raw string) (*ConnInfo, error)

ParseConnString parses a QubicDB connection string.

qubicdb://[user:password@]host1[:port1][,host2[:port2]...][/indexID]
qubicdb+tls://[user:password@]host1[:port1][,host2[:port2]...][/indexID]

Returns an error if the scheme is invalid or no hosts are found.

func (*ConnInfo) BaseURL

func (c *ConnInfo) BaseURL() string

BaseURL returns the HTTP(S) base URL for the primary host.

func (*ConnInfo) PrimaryHost

func (c *ConnInfo) PrimaryHost() string

PrimaryHost returns the first host in the list.

func (*ConnInfo) String

func (c *ConnInfo) String() string

String reconstructs the connection string (password masked).

type DaemonConfig

type DaemonConfig struct {
	// DecayInterval controls how often the decay daemon runs.
	// Decay reduces energy of unused neurons over time.
	DecayInterval time.Duration `yaml:"decayInterval"`

	// ConsolidateInterval controls how often the consolidation daemon runs.
	// Consolidation moves important neurons to deeper, permanent layers.
	ConsolidateInterval time.Duration `yaml:"consolidateInterval"`

	// PruneInterval controls how often the pruning daemon runs.
	// Pruning removes dead neurons and weak synapses.
	PruneInterval time.Duration `yaml:"pruneInterval"`

	// PersistInterval controls how often in-memory state is flushed to disk.
	PersistInterval time.Duration `yaml:"persistInterval"`

	// ReorgInterval controls how often the matrix reorganisation daemon runs.
	// Reorg optimises spatial locality for frequently co-accessed neurons.
	ReorgInterval time.Duration `yaml:"reorgInterval"`
}

DaemonConfig groups background daemon interval settings.

type IndexID

type IndexID string

IndexID is a unique identifier for a user's brain instance

type LifecycleConfig

type LifecycleConfig struct {
	// IdleThreshold is how long a brain must be inactive before
	// transitioning from Active → Idle.
	IdleThreshold time.Duration `yaml:"idleThreshold"`

	// SleepThreshold is how long a brain must be idle before
	// transitioning from Idle → Sleeping (consolidation begins).
	SleepThreshold time.Duration `yaml:"sleepThreshold"`

	// DormantThreshold is how long a brain must be sleeping before
	// transitioning from Sleeping → Dormant (eligible for eviction).
	DormantThreshold time.Duration `yaml:"dormantThreshold"`
}

LifecycleConfig groups brain state transition thresholds.

type MCPConfig

type MCPConfig struct {
	// Enabled controls whether /mcp endpoint is exposed.
	Enabled bool `yaml:"enabled"`

	// Path is the HTTP route for MCP transport.
	Path string `yaml:"path"`

	// APIKey is optional shared secret validated from X-API-Key or Bearer token.
	APIKey string `yaml:"apiKey"`

	// Stateless enables stateless session-id handling for streamable HTTP.
	Stateless bool `yaml:"stateless"`

	// RateLimitRPS controls per-client rate limiting in requests/second.
	// Set to 0 to disable MCP-specific rate limiting.
	RateLimitRPS float64 `yaml:"rateLimitRPS"`

	// RateLimitBurst controls burst capacity for MCP-specific rate limiting.
	RateLimitBurst int `yaml:"rateLimitBurst"`

	// EnablePrompts toggles MCP prompt registration.
	EnablePrompts bool `yaml:"enablePrompts"`

	// AllowedTools is an optional allowlist; empty means all built-in MCP tools.
	AllowedTools []string `yaml:"allowedTools"`
}

MCPConfig groups Model Context Protocol endpoint settings.

type Matrix

type Matrix struct {
	IndexID    IndexID      `msgpack:"index_id"`
	Bounds     MatrixBounds `msgpack:"bounds"`
	CurrentDim int          `msgpack:"current_dim"`

	// Neurons indexed by ID
	Neurons map[NeuronID]*Neuron `msgpack:"neurons"`

	// Synapses indexed by ID
	Synapses map[SynapseID]*Synapse `msgpack:"synapses"`

	// Adjacency list for fast traversal (neuron -> connected neurons)
	Adjacency map[NeuronID][]NeuronID `msgpack:"adjacency"`

	// Learned parameters (self-tuning)
	DecayRate       float64       `msgpack:"decay_rate"`
	LinkThreshold   float64       `msgpack:"link_threshold"`
	ConsolFrequency time.Duration `msgpack:"consol_freq"`

	// Statistics
	TotalActivations  uint64    `msgpack:"total_activations"`
	LastActivity      time.Time `msgpack:"last_activity"`
	LastConsolidation time.Time `msgpack:"last_consolidation"`

	// Version for persistence
	Version    uint64    `msgpack:"version"`
	CreatedAt  time.Time `msgpack:"created_at"`
	ModifiedAt time.Time `msgpack:"modified_at"`
	// contains filtered or unexported fields
}

Matrix represents the organic memory space for a single user

func NewMatrix

func NewMatrix(indexID IndexID, bounds MatrixBounds) *Matrix

NewMatrix creates a new organic memory matrix for a user

func (*Matrix) Lock

func (m *Matrix) Lock()

Matrix lock methods for external packages

func (*Matrix) RLock

func (m *Matrix) RLock()

func (*Matrix) RUnlock

func (m *Matrix) RUnlock()

func (*Matrix) Unlock

func (m *Matrix) Unlock()

type MatrixBounds

type MatrixBounds struct {
	MinDimension int `msgpack:"min_dim"`
	MaxDimension int `msgpack:"max_dim"`
	MinNeurons   int `msgpack:"min_neurons"`
	MaxNeurons   int `msgpack:"max_neurons"`
}

MatrixBounds defines the organic growth limits

func DefaultBounds

func DefaultBounds() MatrixBounds

DefaultBounds returns sensible defaults

type MatrixConfig

type MatrixConfig struct {
	// MinDimension is the initial dimensionality of a new brain matrix.
	MinDimension int `yaml:"minDimension"`

	// MaxDimension is the upper limit the matrix can grow to.
	MaxDimension int `yaml:"maxDimension"`

	// MaxNeurons is the hard cap on the number of neurons per brain.
	MaxNeurons int `yaml:"maxNeurons"`
}

MatrixConfig groups organic memory matrix bounds.

type Neuron

type Neuron struct {
	ID          NeuronID `msgpack:"id"`
	Content     string   `msgpack:"content"`
	ContentHash string   `msgpack:"content_hash"`

	// Spatial position in N-dimensional matrix (organic, grows/shrinks)
	Position []float64 `msgpack:"position"`

	// Activation dynamics
	Energy     float64 `msgpack:"energy"`      // Current activation level (0.0 - 1.0)
	BaseEnergy float64 `msgpack:"base_energy"` // Resting energy level

	// Depth in the memory hierarchy (0 = surface/hot, higher = deeper/consolidated)
	Depth int `msgpack:"depth"`

	// Temporal markers
	CreatedAt   time.Time `msgpack:"created_at"`
	LastFiredAt time.Time `msgpack:"last_fired_at"`
	LastDecayAt time.Time `msgpack:"last_decay_at"`
	AccessCount uint64    `msgpack:"access_count"`

	// Classification tags (emergent, not predefined)
	Tags []string `msgpack:"tags"`

	// Sentiment classification (set on creation, updated on content change)
	SentimentLabel string  `msgpack:"sentiment_label,omitempty"` // happiness|sadness|fear|anger|disgust|surprise|neutral
	SentimentScore float64 `msgpack:"sentiment_score,omitempty"` // VADER compound [-1, 1]

	// Vector embedding for semantic search (set once on creation, nil if vector layer disabled)
	Embedding []float32 `msgpack:"embedding,omitempty"`

	// Metadata
	Metadata map[string]any `msgpack:"metadata"`
	// contains filtered or unexported fields
}

Neuron represents a single memory unit in the brain

func NewNeuron

func NewNeuron(content string, initialDim int) *Neuron

NewNeuron creates a new neuron with given content

func (*Neuron) Decay

func (n *Neuron) Decay(rate float64)

Decay reduces energy based on time elapsed since the last decay tick, not since last fire. This prevents compounding decay on long-idle neurons.

func (*Neuron) Fire

func (n *Neuron) Fire()

Fire activates the neuron, boosting its energy

func (*Neuron) IsAlive

func (n *Neuron) IsAlive() bool

IsAlive checks if neuron is still active enough Note: Neurons never truly "die" - they become dormant with very low energy This is used for search relevance, not deletion

func (*Neuron) IsDormant

func (n *Neuron) IsDormant() bool

IsDormant checks if neuron has very low energy but still exists

func (*Neuron) Lock

func (n *Neuron) Lock()

Neuron lock methods for external packages

func (*Neuron) RLock

func (n *Neuron) RLock()

func (*Neuron) RUnlock

func (n *Neuron) RUnlock()

func (*Neuron) Reactivate

func (n *Neuron) Reactivate(boost float64)

Reactivate boosts a dormant neuron's energy when recalled

func (*Neuron) ShouldConsolidate

func (n *Neuron) ShouldConsolidate(accessThreshold uint64, ageThreshold time.Duration) bool

ShouldConsolidate checks if neuron is ready to move deeper. Requires sufficient access count, age, AND that energy has decayed below the active threshold — a neuron still firing frequently should not consolidate.

func (*Neuron) Unlock

func (n *Neuron) Unlock()

type NeuronID

type NeuronID string

NeuronID is a unique identifier for a neuron

func NewNeuronID

func NewNeuronID() NeuronID

NewNeuronID generates a new unique neuron ID

type RegistryConfig

type RegistryConfig struct {
	// Enabled controls whether the UUID registry guard is active.
	// When true, only registered UUIDs may access brain operations.
	Enabled bool `yaml:"enabled"`
}

RegistryConfig groups UUID registry settings.

type SecurityConfig

type SecurityConfig struct {
	// AllowedOrigins controls the CORS Access-Control-Allow-Origin header.
	// Use "*" to allow all origins (development only) or a comma-separated
	// list of allowed origins for production.
	AllowedOrigins string `yaml:"allowedOrigins"`

	// MaxRequestBody is the maximum allowed HTTP request body size in bytes.
	// Requests exceeding this limit are rejected with 413 Payload Too Large.
	// Default: 1048576 (1 MB). Set to 0 to disable the limit (not recommended).
	MaxRequestBody int64 `yaml:"maxRequestBody"`

	// MaxNeuronContentBytes is the maximum allowed neuron content payload size in bytes.
	// Requests that try to write larger neuron content are rejected.
	// Default: 65536 (64 KB).
	MaxNeuronContentBytes int64 `yaml:"maxNeuronContentBytes"`

	// TLSCert is the path to a TLS certificate file for HTTPS.
	// Leave empty to disable TLS (plain HTTP). Requires TLSKey.
	TLSCert string `yaml:"tlsCert"`

	// TLSKey is the path to the TLS private key file.
	// Leave empty to disable TLS. Requires TLSCert.
	TLSKey string `yaml:"tlsKey"`

	// ReadTimeout is the maximum duration for reading the entire request.
	ReadTimeout time.Duration `yaml:"readTimeout"`

	// WriteTimeout is the maximum duration before timing out writes of the response.
	WriteTimeout time.Duration `yaml:"writeTimeout"`
}

SecurityConfig groups network security and request-limiting settings.

type ServerConfig

type ServerConfig struct {
	// HTTPAddr is the TCP address the HTTP/REST API binds to.
	HTTPAddr string `yaml:"httpAddr"`
}

ServerConfig groups network listener settings.

type StorageConfig

type StorageConfig struct {
	// DataPath is the directory where .nrdb brain files are stored.
	DataPath string `yaml:"dataPath"`

	// Compress enables msgpack-level compression for persistence.
	Compress bool `yaml:"compress"`

	// WALEnabled controls write-ahead logging for crash recovery.
	WALEnabled bool `yaml:"walEnabled"`

	// FsyncPolicy controls persistence fsync behavior: always | interval | off.
	FsyncPolicy string `yaml:"fsyncPolicy"`

	// FsyncInterval controls fsync cadence when fsyncPolicy is interval.
	FsyncInterval time.Duration `yaml:"fsyncInterval"`

	// ChecksumValidationInterval controls periodic on-disk .nrdb checksum scans.
	// 0 disables periodic background validation.
	ChecksumValidationInterval time.Duration `yaml:"checksumValidationInterval"`

	// StartupRepair enables startup integrity repair for corrupt/missing persisted data files.
	StartupRepair bool `yaml:"startupRepair"`
}

StorageConfig groups persistence-related settings.

type Synapse

type Synapse struct {
	ID     SynapseID `msgpack:"id"`
	FromID NeuronID  `msgpack:"from_id"`
	ToID   NeuronID  `msgpack:"to_id"`

	// Connection strength (0.0 - 1.0)
	Weight float64 `msgpack:"weight"`

	// Hebbian learning metrics
	CoFireCount uint64    `msgpack:"co_fire_count"` // Times fired together
	LastCoFire  time.Time `msgpack:"last_co_fire"`

	// Bidirectional flag
	Bidirectional bool `msgpack:"bidirectional"`

	CreatedAt time.Time `msgpack:"created_at"`
	// contains filtered or unexported fields
}

Synapse represents a connection between two neurons

func NewSynapse

func NewSynapse(from, to NeuronID, initialWeight float64) *Synapse

NewSynapse creates a new synapse between two neurons

func (*Synapse) Decay

func (s *Synapse) Decay(rate float64)

Decay reduces weight based on time

func (*Synapse) IsAlive

func (s *Synapse) IsAlive() bool

IsAlive checks if synapse is strong enough to be active in searches Note: Synapses don't die, they become weak but persist

func (*Synapse) IsWeak

func (s *Synapse) IsWeak() bool

IsWeak checks if synapse is very weak (candidate for deep storage, not deletion)

func (*Synapse) Reactivate

func (s *Synapse) Reactivate(boost float64)

Reactivate strengthens a weak synapse when neurons co-fire again

func (*Synapse) ShouldArchive

func (s *Synapse) ShouldArchive() bool

ShouldArchive checks if synapse is old and weak enough for deep storage Returns true if inactive for >30 days and weight < 0.01

func (*Synapse) Strengthen

func (s *Synapse) Strengthen(delta float64)

Strengthen increases synapse weight (Hebbian potentiation)

func (*Synapse) Weaken

func (s *Synapse) Weaken(delta float64)

Weaken decreases synapse weight

type SynapseID

type SynapseID string

SynapseID is a unique identifier for a synapse connection

func NewSynapseID

func NewSynapseID(from, to NeuronID) SynapseID

NewSynapseID generates a synapse ID from two neuron IDs

type VectorConfig

type VectorConfig struct {
	// Enabled activates the vector embedding layer.
	// When false, search falls back to pure lexical matching.
	Enabled bool `yaml:"enabled"`

	// ModelPath is the path to a GGUF BERT embedding model file.
	ModelPath string `yaml:"modelPath"`

	// GPULayers controls how many model layers are offloaded to GPU.
	// 0 = CPU only.
	GPULayers int `yaml:"gpuLayers"`

	// Alpha is the weight of the vector score in hybrid search.
	// finalScore = Alpha*vectorScore + (1-Alpha)*stringScore
	// Range: 0.0 (pure string) to 1.0 (pure vector). Default: 0.6
	Alpha float64 `yaml:"alpha"`

	// QueryRepeat controls how many times the query is repeated before embedding.
	// Repeating the query improves embedding quality for short queries by allowing
	// the model to attend to all query tokens bidirectionally (Springer et al. 2024).
	// 1 = no repeat (baseline), 2 = repeat once (recommended), 3 = repeat twice.
	// Default: 2
	QueryRepeat int `yaml:"queryRepeat"`

	// EmbedContextSize is the llama.cpp context window size used for embedding.
	// Must be >= 512 for MiniLM. Increase if QueryRepeat×queryTokens > 512.
	// Default: 512
	EmbedContextSize uint32 `yaml:"embedContextSize"`
}

VectorConfig groups embedding / vector search settings.

type WorkerConfig

type WorkerConfig struct {
	// MaxIdleTime is the maximum duration a brain worker may remain idle
	// before being evicted from the in-memory pool.
	MaxIdleTime time.Duration `yaml:"maxIdleTime"`
}

WorkerConfig groups worker pool settings.

Jump to

Keyboard shortcuts

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