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

operations

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package operations holds LadyM's cognitive operations (activation, recall, consolidation, decay, proceduralization, supersedes, attention, L5/L6).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ActivationScore

func ActivationScore(mem *schema.Memory, querySimilarity float64, w config.ActivationWeights, neighbourCounts map[string]int, queryTypes []schema.MemoryType, now float64) float64

ActivationScore computes the full ACT-R-inspired activation score.

func FrequencyFactor

func FrequencyFactor(accessCount int) float64

FrequencyFactor is the diminishing-returns log curve log(1 + n).

func GraphFactor

func GraphFactor(mem *schema.Memory, neighbourCounts map[string]int, weight float64) float64

GraphFactor is spreading activation: items with more current graph neighbours get a small boost.

func InferQueryTypes

func InferQueryTypes(query string) []schema.MemoryType

InferQueryTypes heuristically detects whether a query is about code (boosting code_symbol/code_file) or a how-to (boosting playbook).

func IsConsolidated added in v0.5.2

func IsConsolidated(m *schema.Memory) bool

IsConsolidated reports whether the episode has completed a consolidation pass (stamped for every ADD/UPDATE/DELETE/NOOP verdict).

func IsRetired

func IsRetired(mem *schema.Memory) bool

IsRetired reports whether mem was retired by an UPDATE or DELETE consolidation pass. A nil memory is treated as not-retired.

func LatestInChain

func LatestInChain(store storage.Store, memID string) (string, error)

LatestInChain walks supersedes edges forward and returns the newest version id.

func NeighbourCountsFor

func NeighbourCountsFor(mems []*schema.Memory, counts map[string]int) map[string]int

NeighbourCountsFor projects a {id: count} map onto just the given memories.

func NormalizeAction added in v0.7.0

func NormalizeAction(raw string, cfg *config.Config) string

NormalizeAction maps a raw action string onto a canonical vocabulary word. Matching is lowercased, trimmed, and exact against the merged alias table the merged alias table (cfg.Resource.ActionAliases over builtins — config wins on conflicts) and then the merged canonical word list (cfg.Resource.Actions over builtins). Unmatched input returns "" — the caller keeps the raw string for later backfill instead of forcing a semantic merge.

func Recall

func Recall(store storage.Store, embedder storage.EmbeddingProvider, query string, cfg *config.Config, workspace string, topK int, layers []schema.Layer, types []schema.MemoryType, minSimilarity float64) (*schema.RecallResponse, error)

Recall runs the full two-tier retrieval pipeline.

func RecencyFactor

func RecencyFactor(lastAccessAt, halfLifeS, now float64) float64

RecencyFactor is exponential decay: 1.0 right after access, 0.5 after halfLifeS seconds.

func ResolveResource added in v0.7.0

func ResolveResource(store storage.Store, embedder storage.EmbeddingProvider,
	cfg *config.Config, ws, name string) (*schema.Memory, bool, error)

ResolveResource resolves a resource name (or alias) to a workspace-scoped L2 resource entity, creating one when nothing matches (spec §5.1):

  1. Exact alias/content match over the workspace's resource memories (case-insensitive) — zero vector work.
  2. Vector nearest neighbor: embed the name, VectorSearch top-50, then filter in Go for type=resource in this workspace (VectorSearch has no type filter). A hit with sim >= cfg.Resource.ResolveThreshold wins and the queried name is appended to its aliases (lazy alias growth).
  3. Otherwise create a new resource entity.

The bool result reports whether a new entity was created.

func Retire

func Retire(store storage.Store, old *schema.Memory, newID string) error

Retire retires old. When newID is non-empty it writes a supersedes edge old→new (UPDATE chain); otherwise it sets superseded=true (DELETE). Outgoing still-valid edges of old are closed so the graph does not leak through a retired node.

func TypeBoostForQuery

func TypeBoostForQuery(mem *schema.Memory, queryTypes []schema.MemoryType, weight float64) float64

TypeBoostForQuery boosts items whose type matches a query-type prior.

Types

type Action

type Action string

Action is one of the four consolidation decisions (mem0's ADD/UPDATE/DELETE/NOOP).

const (
	ActionAdd    Action = "ADD"
	ActionUpdate Action = "UPDATE"
	ActionDelete Action = "DELETE"
	ActionNoop   Action = "NOOP"
)

type ConsolidationReport

type ConsolidationReport struct {
	Actions             map[string]int
	KeptEpisodes        int
	PromotedToSemantic  int
	SkippedConsolidated int
	Details             []map[string]any
}

ConsolidationReport reports the outcome of a consolidation pass.

func Consolidate

func Consolidate(store storage.Store, embedder storage.EmbeddingProvider, cfg *config.Config, workspace string, llmClassify LLMClassifier, since float64) (*ConsolidationReport, error)

Consolidate promotes salient episodic events into semantic facts. Selection covers the workspace's unconsolidated episodes (see consolidatedAtKey); when since is non-zero it additionally bounds the scan to episodes created at or after that time, so 0 means "everything still pending".

type DecayReport

type DecayReport struct {
	Examined     int
	Forgotten    int
	ForgottenIDs []string
}

DecayReport reports the outcome of a decay pass.

func Decay

func Decay(store storage.Store, workspace string, weights *config.ActivationWeights, maxAgeS, activationFloor, now float64, dryRun bool) (*DecayReport, error)

Decay forgets episodic events whose activation has fallen below the floor. Code analysis, playbooks, and edges are never auto-forgotten.

type GateDecision

type GateDecision struct {
	Action  string // "pass" | "rewrite" | "drop"
	Content string // populated only on rewrite
	Reason  string
}

GateDecision is the outcome of the attention gate.

func AttentionGate

func AttentionGate(content string, cfg *config.Config, store storage.Store, getAgent func(string) (providers.LLMProvider, error), layer schema.Layer) (GateDecision, error)

AttentionGate applies the pre-remember filter to content destined for layer. getAgent resolves the LLM agent bound to "attention_gate" (nil for offline).

type L5ExtractionReport

type L5ExtractionReport struct {
	NewModels    int
	MergedModels int
	Clusters     []map[string]any
	Skipped      bool
}

L5ExtractionReport reports the outcome of L5 mental-model extraction.

func ExtractL5

func ExtractL5(store storage.Store, embedder storage.EmbeddingProvider, cfg *config.Config, workspace string, llm providers.LLMProvider, prompt string) (*L5ExtractionReport, error)

ExtractL5 clusters uncovered L2/L3 memories into mental models.

type L6PredictionReport

type L6PredictionReport struct {
	Predictions        int
	ExpiredRetired     int
	EpisodesSeen       int
	WatermarkUpdatedTo float64
	Details            []map[string]any
	Skipped            bool
}

L6PredictionReport reports the outcome of L6 forward-intent prediction.

func PredictL6

func PredictL6(store storage.Store, embedder storage.EmbeddingProvider, cfg *config.Config, workspace string, llm providers.LLMProvider, prompt string) (*L6PredictionReport, error)

PredictL6 predicts next intents from recent episodes, with TTL expiry.

type LLMClassifier

type LLMClassifier func(candidate string, similar []string) (Action, string, error)

LLMClassifier is a pluggable (candidate, similar) → (Action, newText) classifier. A non-nil error aborts the consolidation pass (Python: exceptions propagate).

type MaintainAgents added in v0.7.0

type MaintainAgents struct {
	Backfill   providers.LLMProvider
	Link       providers.LLMProvider
	AliasMerge providers.LLMProvider
}

MaintainAgents bundles the per-op LLM providers for MaintainL4's LLM sub-steps. A nil field (or a nil *MaintainAgents) means that sub-step runs in heuristic/offline mode or is skipped.

type MaintainReport added in v0.7.0

type MaintainReport struct {
	Swept      int    // dangling edges deleted (GC)
	Backfilled int    // episodes that got action_class and/or resource edges
	Linked     int    // related_to edges confirmed by the LLM
	Merged     int    // resource entities merged (alias merge)
	Skipped    string // why the LLM sub-steps were skipped ("" = ran)
}

MaintainReport is the outcome of one MaintainL4 pass (spec §8).

func MaintainL4 added in v0.7.0

func MaintainL4(store storage.Store, embedder storage.EmbeddingProvider,
	cfg *config.Config, ws string, agents *MaintainAgents) (*MaintainReport, error)

MaintainL4 runs the worker-maintenance step of a System 2 cycle (spec §8):

① dangling-edge GC (zero LLM, every cycle)
② slot backfill for episodes missing action_class (heuristic, LLM optional)
③ semantic linking (Task 18)
④ alias merge (Task 19)

GC always runs; the remaining sub-steps are gated on cfg.Maintain.Enabled.

type ProceduralizeReport

type ProceduralizeReport struct {
	ClustersExamined int
	PlaybooksCreated int
	Actions          map[string]int
	Details          []map[string]any
}

ProceduralizeReport reports the outcome of a proceduralization pass.

func Proceduralize

func Proceduralize(store storage.Store, embedder storage.EmbeddingProvider, cfg *config.Config, workspace string, minClusterSize int, similarityThreshold float64) (*ProceduralizeReport, error)

Proceduralize clusters successful episodic events into L3 playbooks.

type System2Report

type System2Report struct {
	Consolidate     any
	Proceduralize   any
	L5              any
	L6              any
	Decay           any
	Maintain        any
	SkippedLLMSteps bool
}

System2Report is the outcome of one background consolidation cycle.

func RunSystem2Cycle

func RunSystem2Cycle(runner System2Runner, workspace string) (*System2Report, error)

RunSystem2Cycle runs one System 2 cycle through the runner.

type System2Runner

type System2Runner interface {
	Consolidate(workspace string, since float64) (*ConsolidationReport, error)
	Proceduralize(workspace string, minClusterSize int) (*ProceduralizeReport, error)
	ExtractMentalModels(workspace string) (*L5ExtractionReport, error)
	PredictForwardIntents(workspace string) (*L6PredictionReport, error)
	Decay(workspace string, dryRun bool, maxAgeS, activationFloor float64) (*DecayReport, error)
	CountRecentEpisodes(workspace string) (int, error)
	MinEpisodesToRun() int
	MaintainL4(workspace string) (*MaintainReport, error)
}

System2Runner is the interface the engine satisfies to run a System 2 cycle (kept as an interface so operations does not import engine).

Jump to

Keyboard shortcuts

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