extended

package
v1.33.1 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package extended implements the Extended Memory subsystem for odek.

Extended Memory stores atomic memory units ("atoms") extracted from user messages and recalled via semantic search. It is opt-in and invisible when disabled.

Index

Constants

View Source
const (
	SourceUserSaid       = "user_said"
	SourceInferred       = "inferred"
	SourceUserApproved   = "user_approved"
	SourceToolOutput     = "tool_output"
	SourceFileRead       = "file_read"
	SourceWeb            = "web"
	SourceMCP            = "mcp"
	SourceSubagent       = "subagent"
	SourceAgentGenerated = "agent_generated"
)

Source classes. The zero-trust boundary is external content.

View Source
const (
	TypeFact       = "fact"
	TypePreference = "preference"
	TypeIntent     = "intent"
	TypeDecision   = "decision"
	TypeGoal       = "goal"
	TypeConvention = "convention"
	TypeFile       = "file"
	TypeError      = "error"
	TypeQuestion   = "question"

	// TypeObservation is a fallback for unknown atom types. It is no longer
	// part of the recommended design set, but preserved so older data loads.
	TypeObservation = "observation"
)

Atom types. The design recognizes durable, reusable categories; unknown or legacy values fall back to TypeObservation (kept for backward compat).

View Source
const (
	NudgeKindOpenQuestion = "open_question"
	NudgeKindStaleGoal    = "stale_goal"
	NudgeKindBlocker      = "blocker"
	NudgeKindDrift        = "drift"
)

Nudge kinds produced by the proactive-nudges engine.

Variables

This section is empty.

Functions

func DecayFactor

func DecayFactor(createdAt time.Time, halfLifeDays int) float32

DecayFactor computes exponential time decay based on CreatedAt. halfLifeDays controls the decay rate; the default is 30 days.

func IsTaintedSourceClass

func IsTaintedSourceClass(sourceClass string) bool

IsTaintedSourceClass reports whether a source class originates outside the trust boundary.

func NormalizeAtom

func NormalizeAtom(atom *MemoryAtom)

NormalizeAtom sanitizes atom fields, applying safe defaults.

func RetentionScore

func RetentionScore(atom MemoryAtom, halfLifeDays int) float32

RetentionScore combines confidence, trust boost, and time decay.

func ScanContent

func ScanContent(content string) error

ScanContent checks atom content for security threats. It delegates to the shared guard package so Extended Memory and legacy memory share the same scanning logic without an import cycle.

func StripUntrustedWrappers

func StripUntrustedWrappers(text string) string

StripUntrustedWrappers removes <untrusted_content_*> blocks from text.

func TrustBoost

func TrustBoost(sourceClass string) float32

TrustBoost returns a multiplicative boost for high-trust source classes. External / generated sources receive a zero boost so they cannot be recalled without promotion. Inferred atoms are also untrusted because they are not directly user-sourced and are quarantined until promotion.

func ValidType

func ValidType(t string) bool

ValidType reports whether t is a known atom type.

Types

type Associations

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

Associations stores bidirectional links between related atoms.

func NewAssociations

func NewAssociations() *Associations

NewAssociations returns an in-memory association map.

func NewAssociationsWithDir

func NewAssociationsWithDir(dir string) *Associations

NewAssociationsWithDir returns an Associations that persists to dir.

func (a *Associations) Link(fromID, toID string)

Link creates an undirected link between two atoms.

func (*Associations) Load

func (a *Associations) Load() error

Load reads the association map from disk.

func (*Associations) Persist

func (a *Associations) Persist() error

Persist saves the association map to disk.

func (*Associations) Related

func (a *Associations) Related(id string) []string

Related returns the atom IDs linked to id, sorted.

func (*Associations) RemoveAtom

func (a *Associations) RemoveAtom(id string)

RemoveAtom removes all links to and from an atom.

type AtomContext

type AtomContext struct {
	SessionID      string   `json:"session_id,omitempty"`
	Turn           int      `json:"turn,omitempty"`
	Project        string   `json:"project,omitempty"`
	RelatedAtomIDs []string `json:"related_atom_ids,omitempty"`
}

AtomContext carries provenance metadata for an atom.

type AtomStore

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

AtomStore persists MemoryAtoms to disk. Atom text is stored in extended/chunks/<id>.md; metadata is kept in extended/atoms.json. Operations are serialized by a per-instance RWMutex; instances sharing a directory also coordinate via the per-directory lock returned by dirLock.

func NewAtomStore

func NewAtomStore(dir string) *AtomStore

NewAtomStore creates an AtomStore rooted at dir (e.g. ~/.odek/memory/extended).

func (*AtomStore) Add

func (s *AtomStore) Add(atom MemoryAtom, maxChars int) error

Add persists a new atom. The atom ID is validated for path safety and the text is capped to maxChars.

func (*AtomStore) AtomSize

func (s *AtomStore) AtomSize(id string) (int64, error)

AtomSize returns the estimated on-disk bytes for a single atom: its chunk file plus its proportional share of atoms.json.

func (*AtomStore) Get

func (s *AtomStore) Get(id string) (MemoryAtom, error)

Get loads an atom by ID.

func (*AtomStore) List

func (s *AtomStore) List() ([]MemoryAtom, error)

List returns all persisted atoms sorted by CreatedAt descending.

func (*AtomStore) Pin

func (s *AtomStore) Pin(id string, pin bool) error

Pin sets or clears the Pin flag on an atom.

func (*AtomStore) Refresh

func (s *AtomStore) Refresh() error

Refresh reloads the store from disk. It is a no-op now that all reads go straight to disk, but it remains the extension point for future caching.

func (*AtomStore) Remove

func (s *AtomStore) Remove(id string) error

Remove deletes an atom by ID.

func (*AtomStore) Size

func (s *AtomStore) Size() (int64, error)

Size returns the total on-disk size of the trusted atom store in bytes (chunks + atoms.json).

type Config

type Config struct {
	Enabled                         *bool             `json:"enabled,omitempty"`
	MaxSizeMB                       int               `json:"max_size_mb,omitempty"`
	SemanticSearchTopK              int               `json:"semantic_search_top_k,omitempty"`
	SemanticSearchOverfetch         int               `json:"semantic_search_overfetch,omitempty"`
	SemanticSearchMinScore          float32           `json:"semantic_search_min_score,omitempty"`
	SemanticSearchRerank            *bool             `json:"semantic_search_rerank,omitempty"`
	AtomMaxChars                    int               `json:"atom_max_chars,omitempty"`
	MemoryBudgetChars               int               `json:"memory_budget_chars,omitempty"`
	DecayHalfLifeDays               int               `json:"decay_half_life_days,omitempty"`
	QuarantineTTLDays               int               `json:"quarantine_ttl_days,omitempty"`
	EvictionPolicy                  string            `json:"eviction_policy,omitempty"`
	PredictiveIntents               int               `json:"predictive_intents,omitempty"`
	AutoExtractPerTurn              *bool             `json:"auto_extract_per_turn,omitempty"`
	InferUserState                  *bool             `json:"infer_user_state,omitempty"`
	UserStateTurnInterval           int               `json:"user_state_turn_interval,omitempty"`
	UserStateMaxPending             int               `json:"user_state_max_pending,omitempty"`
	AssociationsEnabled             *bool             `json:"associations_enabled,omitempty"`
	AssociationSemanticTopK         int               `json:"association_semantic_top_k,omitempty"`
	SemanticDedupThreshold          *float32          `json:"semantic_dedup_threshold,omitempty"`
	ConsolidateSimilarityThreshold  float32           `json:"consolidate_similarity_threshold,omitempty"`
	ProactiveReturnAfterBreak       *bool             `json:"proactive_return_after_break,omitempty"`
	StyleMirroringEnabled           *bool             `json:"style_mirroring_enabled,omitempty"`
	AnaphoraResolutionEnabled       *bool             `json:"anaphora_resolution_enabled,omitempty"`
	FollowUpAnticipationEnabled     *bool             `json:"follow_up_anticipation_enabled,omitempty"`
	FollowUpSuggestionsEnabled      *bool             `json:"follow_up_suggestions_enabled,omitempty"`
	FollowUpSuggestionMinConfidence float32           `json:"follow_up_suggestion_min_confidence,omitempty"`
	ProactiveNudgesEnabled          *bool             `json:"proactive_nudges_enabled,omitempty"`
	NudgeMaxPerDay                  int               `json:"nudge_max_per_day,omitempty"`
	NudgeCooldownHours              int               `json:"nudge_cooldown_hours,omitempty"`
	NudgeStaleGoalDays              int               `json:"nudge_stale_goal_days,omitempty"`
	NudgeOpenQuestionMinAgeHours    int               `json:"nudge_open_question_min_age_hours,omitempty"`
	LLM                             *LLMConfig        `json:"llm,omitempty"`
	Embedding                       *embedding.Config `json:"embedding,omitempty"`
}

Config controls the Extended Memory subsystem.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default Extended Memory configuration. Extended Memory is opt-in: Enabled defaults to false.

func Resolve

func Resolve(cfg Config) Config

Resolve merges cfg over DefaultConfig, producing a fully populated Config.

type Evictor

type Evictor interface {
	// SelectForEviction returns atom IDs to remove to free at least needBytes.
	// sizedAtoms provides the actual disk size for each atom. freed reports the
	// number of bytes that removing ids would release, and ok is true when the
	// requested needBytes can be covered by non-pinned atoms.
	SelectForEviction(sizedAtoms []sizedAtom, needBytes int64) (ids []string, freed int64, ok bool)
}

Evictor selects atoms for eviction when the store approaches its size cap.

type ExtendedMemory

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

ExtendedMemory orchestrates atom storage, embedding, extraction, recall, and eviction for the Extended Memory subsystem.

func New

func New(dir string, llm LLMClient, cfg Config) *ExtendedMemory

New creates an ExtendedMemory instance rooted at dir.

func (*ExtendedMemory) AddAtom

func (em *ExtendedMemory) AddAtom(ctx context.Context, atom MemoryAtom) error

AddAtom manually adds an atom. Manual adds are treated as user-approved.

func (*ExtendedMemory) AddAtoms

func (em *ExtendedMemory) AddAtoms(ctx context.Context, atoms []MemoryAtom) error

AddAtoms adds multiple atoms in one call. It batches embeddings indirectly by marking the index dirty once at the end. Per-atom failures are logged and tolerated: the remaining atoms are still stored.

func (*ExtendedMemory) AnaphoraResolve

func (em *ExtendedMemory) AnaphoraResolve(ctx context.Context, msg string) (string, bool)

AnaphoraResolve replaces the first pronoun in a user message with the most likely antecedent from recent trusted atoms when the semantic score is high enough. It returns the resolved message and true when a replacement happened, otherwise the original message and false.

func (*ExtendedMemory) Close

func (em *ExtendedMemory) Close() error

Close waits for background operations to finish. It is safe to call multiple times.

func (*ExtendedMemory) Compact

func (em *ExtendedMemory) Compact()

Compact triggers a background compaction of the vector index.

func (*ExtendedMemory) ConfirmPendingReview

func (em *ExtendedMemory) ConfirmPendingReview(id string) error

ConfirmPendingReview applies a pending review to the user model.

func (*ExtendedMemory) ConsolidateAtoms added in v1.15.0

func (em *ExtendedMemory) ConsolidateAtoms(ctx context.Context) (merged int, err error)

ConsolidateAtoms finds groups of live atoms that are near-duplicates (pairwise cosine similarity reaching consolidate_similarity_threshold), asks the LLM to merge each group into one atom, stores the merged atom through the normal add path (so the scan and the size cap apply), and removes the originals. Quarantined atoms are never touched. On any failure for a group (LLM error, empty/garbage response, scan rejection) the originals are kept untouched. It returns the number of groups merged.

func (*ExtendedMemory) Enabled

func (em *ExtendedMemory) Enabled() bool

Enabled reports whether Extended Memory is active.

func (*ExtendedMemory) ForgetAtom

func (em *ExtendedMemory) ForgetAtom(id string) error

ForgetAtom removes an atom by ID from both the live store and quarantine. An atom that exists in only one of them is still reported as forgotten; an error is returned only when the ID is found in neither.

func (*ExtendedMemory) FormatContext

func (em *ExtendedMemory) FormatContext(ctx context.Context, query string) string

FormatContext is an alias for FormatExtendedContext.

func (*ExtendedMemory) FormatExtendedContext

func (em *ExtendedMemory) FormatExtendedContext(ctx context.Context, query string) string

FormatExtendedContext returns formatted Extended Memory context for the query, or empty string if nothing matches or Extended Memory is disabled.

func (*ExtendedMemory) FormatUserStateContext

func (em *ExtendedMemory) FormatUserStateContext(ctx context.Context) string

FormatUserStateContext returns formatted user-model context.

func (*ExtendedMemory) LastFollowUps added in v1.15.0

func (em *ExtendedMemory) LastFollowUps() []PredictedIntent

LastFollowUps returns a copy of the predicted follow-up intents captured during the most recent recall, or nil when none were captured.

func (*ExtendedMemory) List

func (em *ExtendedMemory) List() ([]MemoryAtom, error)

List returns all stored atoms (trusted only; quarantined atoms are separate).

func (*ExtendedMemory) ListPendingReview

func (em *ExtendedMemory) ListPendingReview() ([]PendingReview, error)

ListPendingReview lists pending user-model inferences.

func (*ExtendedMemory) ListQuarantine

func (em *ExtendedMemory) ListQuarantine() ([]MemoryAtom, error)

ListQuarantine returns all quarantined atoms.

func (*ExtendedMemory) ListQuarantineEntries added in v1.15.0

func (em *ExtendedMemory) ListQuarantineEntries() ([]QuarantinedAtom, error)

ListQuarantineEntries returns all quarantined atoms with their review metadata (quarantine time and reason).

func (*ExtendedMemory) MarkDirty

func (em *ExtendedMemory) MarkDirty()

MarkDirty marks the vector index as needing a rebuild.

func (*ExtendedMemory) OnUserMessage

func (em *ExtendedMemory) OnUserMessage(ctx AtomContext, msg string)

OnUserMessage extracts atoms from a user message and stores them.

func (*ExtendedMemory) OpenLoops added in v1.15.0

func (em *ExtendedMemory) OpenLoops(ctx context.Context, limit int) ([]MemoryAtom, error)

OpenLoops returns trusted question/goal/intent atoms, newest first, capped at limit (limit <= 0 returns all). It lists the store directly instead of running a semantic query: open loops are a recency-ordered data view, so the embedding search, min-score filtering, and LLM rerank of the recall pipeline would only add cost without improving the answer.

func (*ExtendedMemory) PinAtom

func (em *ExtendedMemory) PinAtom(id string) error

PinAtom pins a live atom by ID so it is never evicted.

func (*ExtendedMemory) ProactiveNudges added in v1.15.0

func (em *ExtendedMemory) ProactiveNudges(ctx context.Context, maxN int) ([]Nudge, error)

ProactiveNudges computes up to maxN nudges as a preview: it performs no anti-annoyance checks and records nothing. All failures degrade to an empty result with a nil error — proactive features must never break the caller.

func (*ExtendedMemory) PromoteAtom

func (em *ExtendedMemory) PromoteAtom(id string) error

PromoteAtom moves an atom from quarantine into the live store with SourceUserApproved. This is the human-gated escape hatch for tainted and guard-rejected atoms. The guard rescan is skipped: the human review IS the approval, and a rescan would reject guard false positives again.

func (*ExtendedMemory) RejectPendingReview

func (em *ExtendedMemory) RejectPendingReview(id string) error

RejectPendingReview removes a pending review from the user model.

func (*ExtendedMemory) ReturnAfterBreak

func (em *ExtendedMemory) ReturnAfterBreak(ctx context.Context) string

ReturnAfterBreak generates a resume summary from recent atoms and the user model. It returns empty string if there is no data or the feature is disabled.

func (*ExtendedMemory) SearchAtoms

func (em *ExtendedMemory) SearchAtoms(ctx context.Context, query string) ([]MemoryAtom, error)

SearchAtoms performs an explicit semantic search and returns ranked atoms.

func (*ExtendedMemory) SetEmbedder

func (em *ExtendedMemory) SetEmbedder(emb embedding.TextEmbedder)

SetEmbedder overrides the active embedder used by the vector index.

func (*ExtendedMemory) SetEmbedderFactory

func (em *ExtendedMemory) SetEmbedderFactory(fn func() embedding.TextEmbedder)

SetEmbedderFactory overrides the embedder factory used by the vector index.

func (*ExtendedMemory) SetGuard added in v1.13.0

func (em *ExtendedMemory) SetGuard(g guard.Guard, cfg guard.Config)

SetGuard installs the shared prompt-injection detector and propagates it to the user-model and recall sub-components. The extractor is deliberately not guarded: atoms are scanned once at persistence time in addAtom, which quarantines rejections for human review instead of dropping them.

func (*ExtendedMemory) SetSessionContext

func (em *ExtendedMemory) SetSessionContext(sessionID, project string)

SetSessionContext sets the current session and project identifiers.

func (*ExtendedMemory) Size

func (em *ExtendedMemory) Size() int64

Size returns the current on-disk size of the Extended Memory store.

func (*ExtendedMemory) Stats added in v1.15.0

func (em *ExtendedMemory) Stats() Stats

Stats returns a snapshot of live/quarantine atom counts, index state, on-disk store size, and recall error counters.

func (*ExtendedMemory) TakeNudges added in v1.15.0

func (em *ExtendedMemory) TakeNudges(ctx context.Context, maxN int) ([]Nudge, error)

TakeNudges computes up to maxN nudges and delivers the ones allowed by the anti-annoyance caps: the proactive_nudges_enabled master switch (opt-in, default off), nudge_max_per_day, and the per-kind nudge_cooldown_hours. Delivered nudges are recorded in nudges.json. All failures degrade to an empty result with a nil error.

func (*ExtendedMemory) UserStateStyle

func (em *ExtendedMemory) UserStateStyle() *StyleState

UserStateStyle returns the inferred style state for style mirroring, or nil if style mirroring is disabled or no style has been inferred.

type Extractor

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

Extractor turns raw text (typically a user message) into MemoryAtoms using an LLM JSON extraction prompt. Extracted atoms are NOT scanned here: the single guard gate is at persistence time (ExtendedMemory.addAtom), which quarantines rejections for human review instead of silently dropping them.

func NewExtractor

func NewExtractor(llm LLMClient, cfg Config) *Extractor

NewExtractor creates an Extractor.

func (*Extractor) Extract

func (e *Extractor) Extract(ctx context.Context, text string) ([]MemoryAtom, error)

Extract atoms from text. Returns nil if the LLM is unavailable, the output is unparseable, or no atoms are found. Extracted atoms are sourced from the user ("user_said").

type FocusState

type FocusState struct {
	Project string `json:"project,omitempty"`
	Task    string `json:"task,omitempty"`
	Blocker string `json:"blocker,omitempty"`
}

FocusState captures the user's current project/task focus.

type InteractionPatterns

type InteractionPatterns struct {
	CommonOpeners         []string `json:"common_openers,omitempty"`
	FollowupAfterRefactor string   `json:"followup_after_refactor,omitempty"`
	FollowupAfterBugfix   string   `json:"followup_after_bugfix,omitempty"`
}

InteractionPatterns captures recurring interaction patterns.

type LLMClient

type LLMClient interface {
	SimpleCall(ctx context.Context, system, user string) (string, error)
}

LLMClient abstracts the LLM calls needed by Extended Memory.

func ResolveLLM

func ResolveLLM(cfg Config, mainLLM LLMClient, thinking string) LLMClient

ResolveLLM returns the LLM client to use for Extended Memory. If cfg.LLM is set, it builds a dedicated client; otherwise it returns the provided main client unchanged. Fields left empty in cfg.LLM are inherited from the main client (when it is an *llm.Client), so operators can override a single knob — e.g. `"llm": {"thinking": "disabled"}` — without duplicating base_url, api_key, and model. When falling back to the main client and the main model has thinking enabled, a warning is logged because reasoning tokens are wasted on memory-only calls.

type LLMConfig

type LLMConfig struct {
	BaseURL        string  `json:"base_url,omitempty"`
	APIKey         string  `json:"api_key,omitempty"`
	Model          string  `json:"model,omitempty"`
	Thinking       string  `json:"thinking,omitempty"`
	MaxTokens      int     `json:"max_tokens,omitempty"`
	Temperature    float64 `json:"temperature,omitempty"`
	TimeoutSeconds int     `json:"timeout_seconds,omitempty"`
}

LLMConfig selects a dedicated LLM for Extended Memory extraction and reranking. When nil, the wiring layer reuses the main agent llm.Client.

type MemoryAtom

type MemoryAtom struct {
	ID          string      `json:"id"`
	Text        string      `json:"text"`
	SourceClass string      `json:"source_class"`
	Type        string      `json:"type"`
	CreatedAt   time.Time   `json:"created_at"`
	Context     AtomContext `json:"context,omitempty"`
	Pin         bool        `json:"pin,omitempty"`
	Confidence  float32     `json:"confidence,omitempty"`

	// Vector is the embedding of Text. It is not persisted directly; the
	// vector index is rebuilt from atom content on demand.
	Vector vector.Vector `json:"-"`
}

MemoryAtom is the atomic unit of Extended Memory.

type Nudge added in v1.15.0

type Nudge struct {
	Text          string   `json:"text"`
	Kind          string   `json:"kind"`
	SourceAtomIDs []string `json:"source_atom_ids,omitempty"`
}

Nudge is a single proactive, user-facing suggestion synthesized from trusted memory atoms.

type PendingReview

type PendingReview struct {
	ID         string    `json:"id"`
	Field      string    `json:"field"`
	Value      string    `json:"value"`
	Evidence   string    `json:"evidence,omitempty"`
	Confidence float32   `json:"confidence,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
}

PendingReview is an inferred preference that requires user confirmation before it is merged into the authoritative user model.

type PredictedIntent

type PredictedIntent struct {
	Text       string  `json:"text"`
	Confidence float32 `json:"confidence"`
}

PredictedIntent is a likely follow-up intent generated from the current user message and user model.

type Predictor

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

Predictor generates likely follow-up intents from user messages.

func NewPredictor

func NewPredictor(llm LLMClient, cfg Config) *Predictor

NewPredictor creates a Predictor.

func (*Predictor) Predict

func (p *Predictor) Predict(ctx context.Context, userMsg string, recent []string, state UserState) ([]PredictedIntent, error)

Predict returns up to PredictiveIntents likely follow-up intents. It returns an empty slice when prediction is disabled or the LLM is unavailable.

type Quarantine

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

Quarantine stores tainted atoms separately from the live atom corpus. They count toward the overall size cap but are excluded from recall until a human promotes them.

func NewQuarantine

func NewQuarantine(dir string) *Quarantine

NewQuarantine creates a Quarantine store rooted at dir.

func (*Quarantine) EvictExpired

func (q *Quarantine) EvictExpired(ttlDays int) (int, error)

EvictExpired removes quarantined atoms older than ttlDays, returning the number removed. ttlDays <= 0 disables expiration.

func (*Quarantine) Forget

func (q *Quarantine) Forget(id string) error

Forget removes a quarantined atom by ID.

func (*Quarantine) List

func (q *Quarantine) List() ([]MemoryAtom, error)

List returns all quarantined atoms (newest first). The full write lock is required because loadLocked may evict expired entries and rewrite the file.

func (*Quarantine) ListEntries added in v1.15.0

func (q *Quarantine) ListEntries() ([]QuarantinedAtom, error)

ListEntries returns all quarantined atoms with their review metadata (quarantine time and reason), newest first. The full write lock is required because loadLocked may evict expired entries and rewrite the file.

func (*Quarantine) Promote

func (q *Quarantine) Promote(id string) (MemoryAtom, error)

Promote moves an atom from quarantine into a MemoryAtom. It does NOT remove the atom from quarantine; callers must call Forget after promoting if they want it removed from quarantine.

func (*Quarantine) SetTTLDays

func (q *Quarantine) SetTTLDays(days int)

SetTTLDays configures the TTL used when evicting expired entries at load time. Extended Memory calls this during construction.

func (*Quarantine) Size

func (q *Quarantine) Size() (int64, error)

Size returns the on-disk size of quarantine.json in bytes.

func (*Quarantine) Store

func (q *Quarantine) Store(atom MemoryAtom) error

Store persists a tainted atom in quarantine.

func (*Quarantine) StoreWithReason added in v1.15.0

func (q *Quarantine) StoreWithReason(atom MemoryAtom, reason string) error

StoreWithReason persists an atom in quarantine, recording why it was held.

type QuarantinedAtom added in v1.15.0

type QuarantinedAtom struct {
	MemoryAtom
	QuarantinedAt time.Time
	Reason        string
}

QuarantinedAtom is a quarantined atom with its review metadata, as returned by ListEntries for human inspection.

type QueryResult

type QueryResult struct {
	Atoms   []MemoryAtom
	Context string
}

QueryResult carries the atoms and formatted context from a recall query.

type Recall

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

Recall performs semantic search over the atom store.

func NewRecall

func NewRecall(store *AtomStore, index *atomVectorIndex, llm LLMClient, cfg Config) *Recall

NewRecall creates a Recall instance.

func (*Recall) Query

func (r *Recall) Query(ctx context.Context, query string, recent []string, state UserState) (string, error)

Query searches for relevant atoms. It returns a formatted context string bounded by MemoryBudgetChars, or empty string if nothing matches.

func (*Recall) SetFollowUpSink added in v1.15.0

func (r *Recall) SetFollowUpSink(fn func([]PredictedIntent))

SetFollowUpSink installs the callback that receives the follow-up suggestions captured at recall time (zero extra LLM cost: the intents are already generated for predictive recall).

func (*Recall) SetGuard added in v1.13.0

func (r *Recall) SetGuard(g guard.Guard, cfg guard.Config)

SetGuard installs the shared prompt-injection detector.

func (*Recall) SetPredictor

func (r *Recall) SetPredictor(p *Predictor)

SetPredictor sets the optional predictor used for predictive recall.

type Stats added in v1.15.0

type Stats struct {
	LiveAtoms         int
	QuarantinedAtoms  int
	QuarantineReasons map[string]int
	IndexVectors      int
	IndexDirty        bool
	StoreSizeBytes    int64
	RecallTimeouts    uint64
	RecallFailures    uint64
}

Stats is an observability snapshot of the Extended Memory subsystem.

type StyleState

type StyleState struct {
	Verbosity        string `json:"verbosity,omitempty"`
	Humor            string `json:"humor,omitempty"`
	Formality        string `json:"formality,omitempty"`
	ExplanationDepth string `json:"explanation_depth,omitempty"`
	Tone             string `json:"tone,omitempty"`
}

StyleState captures the user's preferred communication style.

type TechnicalState

type TechnicalState struct {
	Languages []string `json:"languages,omitempty"`
	Patterns  []string `json:"patterns,omitempty"`
	Tools     []string `json:"tools,omitempty"`
}

TechnicalState captures the user's technical context.

type UserModel

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

UserModel infers and persists a user-state model from trusted atoms.

func NewUserModel

func NewUserModel() *UserModel

NewUserModel returns an in-memory stub. Use NewUserModelWithStore for persistence.

func NewUserModelWithStore

func NewUserModelWithStore(dir string, llm LLMClient, cfg Config) *UserModel

NewUserModelWithStore creates a persistent UserModel rooted at dir.

func (*UserModel) ConfirmPendingReview

func (u *UserModel) ConfirmPendingReview(id string) error

ConfirmPendingReview applies a pending review to the model and persists it.

func (*UserModel) Enabled

func (u *UserModel) Enabled() bool

Enabled reports whether user-state inference is configured.

func (*UserModel) FocusChanged

func (u *UserModel) FocusChanged() bool

FocusChanged reports whether the inferred focus has shifted since the last inference run.

func (*UserModel) Infer

func (u *UserModel) Infer(ctx context.Context) error

Infer runs the LLM over recent atoms and the current state, applying a diff.

func (*UserModel) ListPendingReview

func (u *UserModel) ListPendingReview() []PendingReview

ListPendingReview returns pending reviews in creation order.

func (*UserModel) Load

func (u *UserModel) Load() error

Load reads the persisted user model, if any. Missing files are not errors. Loaded string values are scanned for injection patterns; fields that fail the scan are dropped so a tampered user_model.json cannot poison the system prompt.

func (*UserModel) RecentAtoms

func (u *UserModel) RecentAtoms() []MemoryAtom

RecentAtoms returns a snapshot of the recent trusted atom buffer.

func (*UserModel) RejectPendingReview

func (u *UserModel) RejectPendingReview(id string) error

RejectPendingReview removes a pending review without applying it.

func (*UserModel) ResetFocusChanged

func (u *UserModel) ResetFocusChanged()

ResetFocusChanged clears the focus-shift flag.

func (*UserModel) Save

func (u *UserModel) Save() error

Save persists the current user model atomically.

func (*UserModel) SetGuard added in v1.13.0

func (u *UserModel) SetGuard(g guard.Guard, cfg guard.Config)

SetGuard installs the shared prompt-injection detector.

func (*UserModel) State

func (u *UserModel) State() UserState

State returns a copy of the current user state.

func (*UserModel) Summary

func (u *UserModel) Summary() string

Summary formats the user model for system-prompt injection. The formatted output is scanned before being returned; if it fails the scan, an empty string is returned so a poisoned value cannot reach the system prompt.

func (*UserModel) Update

func (u *UserModel) Update(atom MemoryAtom)

Update records a trusted atom for future inference.

type UserState

type UserState struct {
	Version             string              `json:"version,omitempty"`
	Style               StyleState          `json:"style"`
	Technical           TechnicalState      `json:"technical"`
	CurrentFocus        FocusState          `json:"current_focus"`
	InteractionPatterns InteractionPatterns `json:"interaction_patterns"`
	PendingReview       []PendingReview     `json:"pending_review"`
}

UserState is a live, evolving model of the user inferred from trusted atoms.

type UserStateStore

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

UserStateStore persists UserState atomically to disk.

func NewUserStateStore

func NewUserStateStore(dir string) *UserStateStore

NewUserStateStore creates a UserStateStore rooted at dir.

func (*UserStateStore) Load

func (s *UserStateStore) Load() (UserState, error)

Load reads the persisted UserState. Missing or empty files return a zero state.

func (*UserStateStore) Save

func (s *UserStateStore) Save(state UserState) error

Save writes the UserState atomically with restricted permissions.

Jump to

Keyboard shortcuts

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