memory

package
v2.10.3 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package memory is Scribe's durable memory: short records the agent saves so later sessions can recall them. Records live in two SQLite databases: a project store at <root>/.scribe/memory.db and a global store at config.Home()/memory.db. Full-text search uses FTS5 (unicode61); recall blends BM25, file overlap, a hashed bag-of-words embedding and a usage decay (see recall.go).

Index

Constants

View Source
const (
	CatDecision   = "decision"
	CatConvention = "convention"
	CatBug        = "bug"
	CatPreference = "preference"
	CatFact       = "fact"
	CatTodo       = "todo"
)

Categories a record may carry.

View Source
const (
	ScopeProject = "project"
	ScopeGlobal  = "global"
)

Scopes a DB can hold.

View Source
const (
	MaxTitle  = 200
	MaxBody   = 2000
	MaxTags   = 8
	MaxTagLen = 32
	MaxFiles  = 16
)

Size limits on one record. They apply at the tool boundary and in Add, so a memory stays a short note and not a dumped transcript.

View Source
const (
	SourceUser  = "user"
	SourceAgent = "agent"
)

Sources a record may carry.

View Source
const HashModel = "hashbag-512"

HashModel is the tag stored with the local hashed embedding. Rows written before embedding_model existed are migrated to this tag, so a row's tag always says which embedder produced its vector.

View Source
const (

	// MinScore is the score a non-pinned record needs to be recalled.
	MinScore = 0.2
)

Recall weights. The score of a candidate is

0.6*text + 0.25*file + 0.3*similar + 0.15*decay + 0.1*pinned

where text = x/(1+x) for x = BM25 from FTS5, file is 1 when the record names a file passed in, similar is the hash cosine (or, with a provider, the provider cosine rescaled by calibrate so its unrelated level is 0), and decay blends recency of use with the use count.

View Source
const PolicyFile = "memory-config.json"

PolicyFile is the name of the memory settings file. It is read from the project's .scribe directory and from the Scribe home; the project file wins key by key.

Variables

Categories lists every valid category.

View Source
var ErrNotFound = errors.New("memory not found")

ErrNotFound is returned when no record matches an id.

Functions

func NoteCleanupDone

func NoteCleanupDone() error

NoteCleanupDone resets the session counter after the person completed a cleanup action, so the hint waits for a fresh stretch of sessions.

func NoteSessionStart

func NoteSessionStart() error

NoteSessionStart counts one session start toward the cleanup hint. One small file write per session, never per turn.

func OllamaRoot

func OllamaRoot(host string) string

OllamaRoot turns an OLLAMA_HOST value such as "127.0.0.1:11434" or "http://host:11434" into the server root, with no /v1 suffix. Empty means the default local server.

func ParseEmbeddingModel

func ParseEmbeddingModel(id string) (provider, model string, err error)

ParseEmbeddingModel splits a "provider/model" id at the first slash, so model names that contain slashes (such as "hf.co/org/model") survive.

func PolicyPath

func PolicyPath(scope, root string) (string, error)

PolicyPath is the memory-config.json a save writes to: the Scribe home file for the global scope, or <root>/.scribe for the project scope.

func Register

func Register(r *tools.Registry, s *Stores)

Register adds the `memory` tool to r, backed by s.

func SavePolicy

func SavePolicy(path string, p Policy) error

SavePolicy writes p to path, replacing the file. Values that are not recognised are refused rather than written, so a saved file always loads back as it was saved. Empty fields are left out, which means default.

Types

type DB

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

DB is one memory database.

func OpenDB

func OpenDB(path, scope string) (*DB, error)

OpenDB opens (creating if needed) the database file at path for scope.

func (*DB) Add

func (d *DB) Add(r Record) (rec Record, deduped bool, err error)

Add stores r. If an existing record has the same normalized title or a body with token Jaccard similarity >= 0.8, that record is updated instead and deduped is true. Otherwise a new record is inserted.

func (*DB) Backfill

func (d *DB) Backfill(ctx context.Context, e Embedder, limit int) (int, error)

Backfill re-embeds up to limit live rows whose vector was made by another model (or by the hash), most recently used first. It returns how many rows it updated. A failing provider stops the run and keeps what was done.

func (*DB) Clear

func (d *DB) Clear(category string) (int, error)

Clear hard-deletes every record in category (every record when category is ""), and returns how many were removed. It is for user-initiated bulk removal only; the agent has no path to it.

func (*DB) Close

func (d *DB) Close() error

Close closes the database. Close stops background embedding, waits for it to finish, then closes the database.

func (*DB) Delete

func (d *DB) Delete(idOrPrefix string) error

Delete removes the record with id or a unique id prefix.

func (*DB) DuplicateGroups

func (d *DB) DuplicateGroups(limit int) ([][]Record, error)

DuplicateGroups groups the live records of this store whose normalised titles are the same (spec 05 §1.9 findDuplicates, title key). Each group is ordered keeper first: pinned before unpinned, then most recently used. Only groups of two or more are returned. Nothing is changed.

func (*DB) Export

func (d *DB) Export(w io.Writer) error

Export writes every record as an indented JSON array.

func (*DB) Get

func (d *DB) Get(idOrPrefix string) (Record, error)

Get returns the record with id or a unique id prefix.

func (*DB) Hide

func (d *DB) Hide(idOrPrefix string) error

Hide soft-deletes the record idOrPrefix: it stays on disk, but recall, search, list and dedupe no longer see it until Restore. Hiding a record that is already hidden is a no-op.

func (*DB) Import

func (d *DB) Import(r io.Reader) (added, merged int, err error)

Import reads a JSON array written by Export and adds each record through Add, so dedupe applies. Ids in the file are not reused. It returns how many records were new and how many were merged into existing ones.

func (*DB) List

func (d *DB) List(o ListOptions) ([]Record, error)

List returns live records (not superseded), pinned first, then most recently used.

func (*DB) ListHidden

func (d *DB) ListHidden(limit int) ([]Record, error)

ListHidden returns the hidden records of this store, most recently updated first. Superseded records are not included.

func (*DB) Path

func (d *DB) Path() string

Path is the database file.

func (*DB) Pin

func (d *DB) Pin(idOrPrefix string, pinned bool) error

Pin sets or clears the pinned flag.

func (*DB) Prune

func (d *DB) Prune(maxAge time.Duration, minUses int) (int, error)

Prune deletes unpinned records not used within maxAge that have fewer than minUses uses. It returns how many were deleted.

func (*DB) Recall

func (d *DB) Recall(query string, files []string, limit int) ([]Scored, error)

Recall returns the records most relevant to query and the files being worked on. The top limit non-pinned records scoring at least MinScore are returned, plus every pinned record. Results are sorted by score. Recall does not change usage counters; Stores.Inject does.

func (*DB) Restore

func (d *DB) Restore(idOrPrefix string) error

Restore brings a hidden record back into recall, search and list.

func (*DB) Scope

func (d *DB) Scope() string

Scope is "project" or "global".

func (*DB) Search

func (d *DB) Search(query string, limit int) ([]Scored, error)

Search runs a full-text query over title, body and tags, best match first. Word matches come from the unicode61 index; substring matches from the trigram index (see textHits). Score is BM25 normalised to (0,1).

func (*DB) SetSession

func (d *DB) SetSession(id string)

SetSession stamps records saved from now on with id. An empty id stops stamping. It does not touch existing records.

func (*DB) Similar

func (d *DB) Similar(idOrPrefix string, min float64, limit int) ([]Scored, error)

Similar returns live records whose hashed embedding has cosine >= min to the record idOrPrefix, most similar first. The record itself is excluded. It is how a save reports near-duplicates for the agent to supersede.

func (*DB) StaleCandidates

func (d *DB) StaleCandidates(maxAge time.Duration, minUses, limit int) ([]Record, error)

StaleCandidates lists unpinned live records not used within maxAge and used fewer than minUses times, least recently used first. It only reports: nothing is deleted, so the agent or the person decides what to remove.

func (*DB) Supersede

func (d *DB) Supersede(oldIDOrPrefix, newID string) error

Supersede marks the record oldIDOrPrefix as replaced by newID. Both must be in this database. A superseded record stays on disk for inspection but is no longer recalled, searched, listed or deduplicated against.

func (*DB) Update

func (d *DB) Update(r Record) error

Update overwrites title, body, category, tags and files of the record with r.ID. Uses, pinned state and created time are kept.

type Embedder

type Embedder interface {
	// Model is the "provider/model" id stored with each vector.
	Model() string
	// Embed returns one L2-normalised vector for text.
	Embed(ctx context.Context, text string) ([]float32, error)
	// EmbedBatch returns one L2-normalised vector per text, in input order.
	EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)
}

Embedder turns text into vectors from one provider model. Recall compares a query only with rows tagged with the same Model(), so two models' vectors are never mixed.

func NewEmbedder

func NewEmbedder(id, baseURL, apiKey string) (Embedder, error)

NewEmbedder builds the embedder named by id. An empty id means no provider, and the local hash embedding is used (nil, nil). The caller supplies the base URL and key, so this package never reads key files. For "ollama", baseURL is the server root and "" means the default. Any other provider is treated as OpenAI-compatible and needs baseURL.

type ListOptions

type ListOptions struct {
	Category   string
	Topic      string // matched case-insensitively against tags
	PinnedOnly bool
	Limit      int // default 100
}

ListOptions filters List.

type OllamaEmbedder

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

OllamaEmbedder calls Ollama's native /api/embed.

func NewOllamaEmbedder

func NewOllamaEmbedder(model, root string, client *http.Client) *OllamaEmbedder

NewOllamaEmbedder returns an embedder for model on the Ollama server at root. A nil client gets a default with providerTimeout.

func (*OllamaEmbedder) Embed

func (e *OllamaEmbedder) Embed(ctx context.Context, text string) ([]float32, error)

Embed embeds one text.

func (*OllamaEmbedder) EmbedBatch

func (e *OllamaEmbedder) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

EmbedBatch sends texts in one /api/embed request.

func (*OllamaEmbedder) Model

func (e *OllamaEmbedder) Model() string

Model is "ollama/<model>".

type OpenAIEmbedder

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

OpenAIEmbedder calls an OpenAI-compatible /v1/embeddings endpoint. OpenAI itself and most gateways speak this shape.

func NewOpenAIEmbedder

func NewOpenAIEmbedder(provider, model, baseURL, apiKey string, client *http.Client) *OpenAIEmbedder

NewOpenAIEmbedder returns an embedder for model behind baseURL. baseURL may be the API root ("https://api.openai.com") or already end in /v1. apiKey may be empty for a gateway that does not need one.

func (*OpenAIEmbedder) Embed

func (e *OpenAIEmbedder) Embed(ctx context.Context, text string) ([]float32, error)

Embed embeds one text.

func (*OpenAIEmbedder) EmbedBatch

func (e *OpenAIEmbedder) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

EmbedBatch sends texts in one /v1/embeddings request. The response carries an index per item, and the vectors are put back in input order.

func (*OpenAIEmbedder) Model

func (e *OpenAIEmbedder) Model() string

Model is "<provider>/<model>".

type Policy

type Policy struct {
	// WriteScope is where a save with no scope goes: "project", "global" or
	// "none" (saves are refused). "all" is accepted and means "project".
	// Empty means project when a project store is open, else global.
	WriteScope string `json:"writeScope,omitempty"`
	// ReadScope is which stores automatic recall reads: "project", "global",
	// "all" or "none". Empty means all. Explicit search and list calls name
	// their own scope and are not affected.
	ReadScope string `json:"readScope,omitempty"`
}

Policy controls where memory is written and read. Values that are not recognised are ignored, so a typo falls back to the default rather than switching memory off without a trace.

func LoadPolicy

func LoadPolicy(root string) Policy

LoadPolicy reads memory-config.json from the Scribe home and then from <root>/.scribe, the project file overriding the home file. A missing or unreadable file contributes nothing.

type Record

type Record struct {
	ID       string    `json:"id"`
	Scope    string    `json:"scope"`
	Category string    `json:"category"`
	Title    string    `json:"title"`
	Body     string    `json:"body"`
	Tags     []string  `json:"tags,omitempty"`
	Files    []string  `json:"files,omitempty"`
	Created  time.Time `json:"created"`
	Updated  time.Time `json:"updated"`
	Uses     int       `json:"uses"`
	LastUsed time.Time `json:"last_used"`
	Pinned   bool      `json:"pinned"`
	// Source is who wrote the record: "user" (the person, through the TUI
	// or an import) or "agent" (the memory tool).
	Source string `json:"source,omitempty"`
	// SupersededBy is the id of the record that replaced this one. A
	// superseded record is kept but never recalled, searched or listed.
	SupersededBy string `json:"superseded_by,omitempty"`
	// Hidden is the soft-delete state: a hidden record is kept on disk but
	// never recalled, searched, listed or deduplicated against. Restore
	// clears it. The memory tool's delete is still a hard delete.
	Hidden bool `json:"hidden,omitempty"`
	// SessionID is the session that saved the record ("" when unknown).
	SessionID string `json:"session_id,omitempty"`
}

Record is one memory.

type Scored

type Scored struct {
	Record
	Score float64  `json:"score"`
	Why   []string `json:"why,omitempty"`
	// Sim is the cosine of the query and the record's embedding. It is set
	// only by a recall, and is shown when Why carries "similar".
	Sim float64 `json:"sim,omitempty"`
}

Scored is a recalled record with its relevance score and the signals that produced it ("fts", "trigram", "file", "similar", "pinned", "co-change").

type Stores

type Stores struct {
	Project *DB
	Global  *DB
	// Policy says where saves with no scope go and what automatic recall
	// reads. The zero value is the default: save to the project store when
	// there is one, and recall from every open store.
	Policy Policy

	// session, surfaced and surfacedDir are set by SetSession. surfaced is
	// the ids Inject has already put in front of the model in this session.
	// CoChange returns the files that change with file in git history, most
	// frequent first. The app sets it from the repo map; nil means none.
	CoChange func(file string) []string
	// contains filtered or unexported fields
}

Stores bundles the project and global memory databases. Either may be nil (no project root, or the global home is unavailable).

func Open

func Open(root string) (*Stores, error)

Open opens the project store for root (<root>/.scribe/memory.db) and the global store (config.Home()/memory.db). An empty root skips the project store.

func (*Stores) BeginTurn

func (s *Stores) BeginTurn()

BeginTurn clears the per-turn suppression set by MarkSearched.

func (*Stores) CleanupHintCount

func (s *Stores) CleanupHintCount() int

CleanupHintCount is the number the context bar shows: the stale count when every threshold is met, and 0 otherwise. It never blocks the UI.

func (*Stores) Close

func (s *Stores) Close() error

Close closes every open store.

func (*Stores) DB

func (s *Stores) DB(scope string) (*DB, error)

DB returns the store for scope "project" or "global".

func (*Stores) DBs

func (s *Stores) DBs() []*DB

DBs returns the open stores, project first.

func (*Stores) FileHint

func (s *Stores) FileHint(rel string) string

FileHint returns one line of memory about rel for a read or edit result: the top record that names rel, as "<category> <title> (<id>)". It returns "" when no record names the file, or the model searched memory this turn.

It reads with no query, so it never calls the embedding provider: the file signal alone decides, and a read or edit does not wait on the network.

func (*Stores) Index

func (s *Stores) Index() string

Index is the counts-only line the system prompt carries about saved memories: one clause per open store with its live total, the per-category counts and the pinned count. Nothing is recalled here, so it costs one grouped count per store. It returns "" when both stores are empty.

func (*Stores) Inject

func (s *Stores) Inject(query string, files []string) string

Inject renders the memories relevant to query and files as a <recalled_memories> block for the agent to prepend to its context. It returns "" when nothing clears the threshold. Returned records have their use counters bumped.

func (*Stores) LiveCount

func (s *Stores) LiveCount() int

LiveCount counts the live records (not hidden, not superseded) across the open stores. Errors count as zero.

func (*Stores) MarkSearched

func (s *Stores) MarkSearched()

MarkSearched records that the model searched memory this turn. Until the next BeginTurn, FileHint returns nothing: the model already has the memory it asked for, so repeating it on every read would only cost tokens.

func (*Stores) Prune

func (s *Stores) Prune(maxAge time.Duration, minUses int) (int, error)

Prune runs DB.Prune on every open store.

func (*Stores) Recall

func (s *Stores) Recall(query string, files []string, limit int) ([]Scored, error)

Recall runs recall on every open store and merges the results. The query is embedded once, by the active provider if there is one.

func (*Stores) ResetSurfaced

func (s *Stores) ResetSurfaced() error

ResetSurfaced forgets which memories were surfaced in this session, so the next matching prompt may inject them again. Call it when the model no longer has the earlier injections in its context, such as after compaction.

func (*Stores) SaveCompaction

func (s *Stores) SaveCompaction(summary, workdir string) (Record, bool, error)

SaveCompaction writes the compaction summary to the write store as a diary entry: the summary is the body (it already carries the task, decisions, discoveries and failures), and up to diaryMaxFiles files it names become the record's files. A summary with nothing in it writes nothing. The caller runs this in the background, so a slow or failed write never delays the turn that compacted.

func (*Stores) Session

func (s *Stores) Session() string

Session is the session id set by SetSession, or "".

func (*Stores) SetEmbedder

func (s *Stores) SetEmbedder(e Embedder) error

SetEmbedder turns on a provider embedder for both stores, or turns it off when e is nil. It smoke-tests the provider first, and on failure keeps the hash embedding and returns the error. Switching on the same model again is a no-op. Rows tagged with another model are backfilled in the background.

func (*Stores) SetPolicy

func (s *Stores) SetPolicy(p Policy)

SetPolicy replaces the policy the open stores apply. Callers save the file with SavePolicy first, or the next session reloads the old one.

func (*Stores) SetSession

func (s *Stores) SetSession(id, dir string) error

SetSession binds both stores to the session id and, when dir is not "", loads and persists the set of memories already surfaced in that session (see Inject). Switching to a different session forgets the previous set.

func (*Stores) StaleCount

func (s *Stores) StaleCount() int

StaleCount counts the live, unpinned records across every open store that the stale check would review: not used for 90 days and used fewer than twice. It reads the same rule as the memory tool's "stale" action, and it deletes nothing. Errors count as zero, so a hint never blocks the UI.

func (*Stores) Surfaced

func (s *Stores) Surfaced(id string) bool

Surfaced reports whether id was already injected in this session.

Jump to

Keyboard shortcuts

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