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
- Variables
- func NoteCleanupDone() error
- func NoteSessionStart() error
- func OllamaRoot(host string) string
- func ParseEmbeddingModel(id string) (provider, model string, err error)
- func PolicyPath(scope, root string) (string, error)
- func Register(r *tools.Registry, s *Stores)
- func SavePolicy(path string, p Policy) error
- type DB
- func (d *DB) Add(r Record) (rec Record, deduped bool, err error)
- func (d *DB) Backfill(ctx context.Context, e Embedder, limit int) (int, error)
- func (d *DB) Clear(category string) (int, error)
- func (d *DB) Close() error
- func (d *DB) Delete(idOrPrefix string) error
- func (d *DB) DuplicateGroups(limit int) ([][]Record, error)
- func (d *DB) Export(w io.Writer) error
- func (d *DB) Get(idOrPrefix string) (Record, error)
- func (d *DB) Hide(idOrPrefix string) error
- func (d *DB) Import(r io.Reader) (added, merged int, err error)
- func (d *DB) List(o ListOptions) ([]Record, error)
- func (d *DB) ListHidden(limit int) ([]Record, error)
- func (d *DB) Path() string
- func (d *DB) Pin(idOrPrefix string, pinned bool) error
- func (d *DB) Prune(maxAge time.Duration, minUses int) (int, error)
- func (d *DB) Recall(query string, files []string, limit int) ([]Scored, error)
- func (d *DB) Restore(idOrPrefix string) error
- func (d *DB) Scope() string
- func (d *DB) Search(query string, limit int) ([]Scored, error)
- func (d *DB) SetSession(id string)
- func (d *DB) Similar(idOrPrefix string, min float64, limit int) ([]Scored, error)
- func (d *DB) StaleCandidates(maxAge time.Duration, minUses, limit int) ([]Record, error)
- func (d *DB) Supersede(oldIDOrPrefix, newID string) error
- func (d *DB) Update(r Record) error
- type Embedder
- type ListOptions
- type OllamaEmbedder
- type OpenAIEmbedder
- type Policy
- type Record
- type Scored
- type Stores
- func (s *Stores) BeginTurn()
- func (s *Stores) CleanupHintCount() int
- func (s *Stores) Close() error
- func (s *Stores) DB(scope string) (*DB, error)
- func (s *Stores) DBs() []*DB
- func (s *Stores) FileHint(rel string) string
- func (s *Stores) Index() string
- func (s *Stores) Inject(query string, files []string) string
- func (s *Stores) LiveCount() int
- func (s *Stores) MarkSearched()
- func (s *Stores) Prune(maxAge time.Duration, minUses int) (int, error)
- func (s *Stores) Recall(query string, files []string, limit int) ([]Scored, error)
- func (s *Stores) ResetSurfaced() error
- func (s *Stores) SaveCompaction(summary, workdir string) (Record, bool, error)
- func (s *Stores) Session() string
- func (s *Stores) SetEmbedder(e Embedder) error
- func (s *Stores) SetPolicy(p Policy)
- func (s *Stores) SetSession(id, dir string) error
- func (s *Stores) StaleCount() int
- func (s *Stores) Surfaced(id string) bool
Constants ¶
const ( CatDecision = "decision" CatConvention = "convention" CatBug = "bug" CatPreference = "preference" CatFact = "fact" CatTodo = "todo" )
Categories a record may carry.
const ( ScopeProject = "project" ScopeGlobal = "global" )
Scopes a DB can hold.
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.
const ( SourceUser = "user" SourceAgent = "agent" )
Sources a record may carry.
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.
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.
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 ¶
var Categories = []string{CatDecision, CatConvention, CatBug, CatPreference, CatFact, CatTodo}
Categories lists every valid category.
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 ¶
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 ¶
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 ¶
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 SavePolicy ¶
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 (*DB) Add ¶
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 ¶
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 ¶
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 ¶
Close closes the database. Close stops background embedding, waits for it to finish, then closes the database.
func (*DB) DuplicateGroups ¶
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) Hide ¶
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 ¶
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 ¶
ListHidden returns the hidden records of this store, most recently updated first. Superseded records are not included.
func (*DB) Prune ¶
Prune deletes unpinned records not used within maxAge that have fewer than minUses uses. It returns how many were deleted.
func (*DB) Recall ¶
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) Search ¶
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 ¶
SetSession stamps records saved from now on with id. An empty id stops stamping. It does not touch existing records.
func (*DB) Similar ¶
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 ¶
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.
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 ¶
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) EmbedBatch ¶
EmbedBatch sends texts in one /api/embed request.
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) EmbedBatch ¶
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 ¶
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 ¶
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 ¶
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) FileHint ¶
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 ¶
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 ¶
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 ¶
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) Recall ¶
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 ¶
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 ¶
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) SetEmbedder ¶
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 ¶
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 ¶
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 ¶
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.