memory

package
v1.5.188 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 16 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 implements the persistent memory storage layer for golder.

It is backed by a pure-Go SQLite database (modernc.org/sqlite, no CGO) with an FTS5 full-text index over Markdown memory files. This file provides the Store type together with database opening and idempotent schema migration. The package also holds path resolution, reconcile (lazy indexing/pruning) and BM25 search.

Index

Constants

View Source
const (
	GlobalRecallLimit = 2
	GlobalRecallGap   = 5
	GlobalRecallDelay = 10 * time.Minute
)

Variables

This section is empty.

Functions

func ProjectID added in v1.5.183

func ProjectID(absRepoPath string) string

ProjectID returns the stable project-scope id for an absolute repository path. Callers must pass the same path shape used when writing project memories; SetupEnv and dream both resolve their cwd through this helper.

Types

type CoreBlock added in v1.5.183

type CoreBlock struct {
	Name        string `json:"name"`
	Scope       Scope  `json:"scope"`
	ScopeID     string `json:"scope_id,omitempty"`
	Path        string `json:"path"`
	Description string `json:"description,omitempty"`
	Size        int64  `json:"size"`
}

CoreBlock is the metadata returned by CoreReader.List. Name is the stable reference accepted by CoreReader.Read, e.g. "global/preferences" or "project/constraints".

type CoreContent added in v1.5.183

type CoreContent struct {
	Block     CoreBlock `json:"block"`
	Body      string    `json:"body"`
	Truncated bool      `json:"truncated"`
}

CoreContent is one loaded block plus the exact truncation state.

type CoreReader added in v1.5.183

type CoreReader struct {
	Root      string
	ProjectID string
}

CoreReader exposes small, durable core-memory blocks on demand. It never renders them into a prompt: callers list metadata first and read one block only when the model asks for it.

func (CoreReader) List added in v1.5.183

func (r CoreReader) List() ([]CoreBlock, error)

List returns core blocks from the global scope and the current project only. Other projects' core directories are intentionally invisible.

func (CoreReader) Read added in v1.5.183

func (r CoreReader) Read(name string, maxChars int) (CoreContent, error)

Read loads one block named as returned by List. maxChars <= 0 uses the default; values are capped. Content is redacted and frontmatter is omitted from the returned body.

type Locator

type Locator struct {
	Scope   Scope
	ScopeID string
	Type    Type
	Path    string
}

Locator is the parsed identity of a memory file on disk: which scope it belongs to, the scope id (project-id / session-id / slug; "" for global), the semantic type, and the absolute path of the file itself.

type Result

type Result struct {
	Indexed int
	Pruned  int
}

Result reports what a Reconcile pass changed: Indexed counts rows inserted or updated (new or changed files), Pruned counts rows deleted because their file no longer exists on disk.

type Scope

type Scope string

Scope identifies the memory dimension a file belongs to.

const (
	ScopeGlobal   Scope = "global"
	ScopeProjects Scope = "projects"
	ScopeSessions Scope = "sessions"
	ScopeCC       Scope = "cc"
)

Recognized scopes.

type ScopeRef added in v1.5.183

type ScopeRef struct {
	Scope   Scope
	ScopeID string
}

ScopeRef identifies one exact memory scope. An empty ScopeID addresses the global scope; project and session scopes carry their stable id.

func DefaultScopes added in v1.5.183

func DefaultScopes(projectID, sessionID string) []ScopeRef

DefaultScopes is the local retrieval policy: the shared global scope, the current project when known, and the current session when known. An empty project or session id is omitted rather than matching every row with an empty id.

type SearchOptions

type SearchOptions struct {
	// Scopes, when non-empty, restricts results to exact (scope, scope_id)
	// pairs. It takes precedence over Scope/ScopeID. This is the local
	// global+project+session retrieval policy.
	Scopes []ScopeRef
	// Scope, ScopeID and Type, when non-empty, restrict results to rows whose
	// corresponding memory_index column matches exactly.
	Scope   string
	ScopeID string
	Type    string
	Types   []Type // optional allowlist, intersected with Type
	// Limit caps the number of returned results; <=0 means the default of 10.
	Limit int
	// ReconcileFirst runs a lazy Store.Reconcile before searching so that
	// off-tool writes are picked up. Its counts are ignored; hard errors
	// propagate.
	ReconcileFirst bool
	// ScoreFloor is the relative floor ratio: trailing rows scoring below
	// topScore*ScoreFloor are dropped. <=0 keeps all matches when 0, but the
	// default of 0.15 is used when the field is left at its zero value; pass a
	// negative value to explicitly disable the floor.
	ScoreFloor float64
	// SkipCheckpoint avoids automatically injecting a duplicate of the live
	// conversation summary (including older indexes which classified it as free).
	SkipCheckpoint bool
}

SearchOptions tunes a Store.Search call. All fields are optional; the zero value performs an unfiltered search with default limit and score floor.

type SearchResult

type SearchResult struct {
	Path    string
	Snippet string
	Score   float64
	Scope   Scope
	ScopeID string
	Type    Type
	// Importance is the normalized 0..1 frontmatter signal used in ranking.
	Importance float64
	Version    string `json:"-"` // index fingerprint, for recall deduplication
}

SearchResult is a single ranked hit from Store.Search. Score is normalized so that higher = better (the raw FTS5 bm25 value, where lower is better, is negated).

type Store

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

Store is the handle to the memory database. Fields are unexported; later nodes access the underlying *sql.DB via DB() and the configured roots via the package-internal fields.

func Open

func Open(dbPath, root, ccBase string) (*Store, error)

Open opens (creating if necessary) the SQLite database at dbPath and runs the idempotent schema migration. The parent directory of dbPath is created with os.MkdirAll before opening. root is the memory root directory and ccBase is the optional Claude Code base directory; both are retained for use by later nodes and are not required to exist here.

Calling Open twice on the same file is safe: the migration uses CREATE ... IF NOT EXISTS throughout.

func (*Store) Close

func (s *Store) Close() error

Close closes the underlying database connection.

func (*Store) CountByScope

func (s *Store) CountByScope() (map[Scope]int, error)

CountByScope returns the number of indexed memory entries grouped by scope. Scopes with no entries are omitted from the map. It reflects the current contents of memory_index; callers that want fresh counts should Reconcile first. A nil store or nil db yields an empty map.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the underlying *sql.DB for use by later nodes and tests. It may be nil if the store was not successfully opened.

func (*Store) MarkRecallDelivered added in v1.5.183

func (s *Store) MarkRecallDelivered(ctx context.Context, sessionID, sourceVersion string) (bool, error)

MarkRecallDelivered deduplicates by a content-version identity, not by the query or snippet. No plaintext query, path, or recalled body is stored here.

func (*Store) Reconcile

func (s *Store) Reconcile() (Result, error)

Reconcile performs a lazy sync between the memory files on disk and the memory_index table. It walks both the mimo root and (when configured) the cc base, prunes rows whose file no longer exists, and indexes new or changed files. Unchanged files are skipped via a size-mtime fingerprint. The FTS index is kept consistent by the memory_ai/ad/au triggers, so only memory_index is touched here.

func (*Store) ReserveRecall added in v1.5.183

func (s *Store) ReserveRecall(ctx context.Context, sessionID, inputID string, scope Scope, now time.Time) (string, error)

ReserveRecall records a genuine input once, even if it doesn't need a query. Inserting before searching makes misses and interrupted searches consume the same budget. The transaction's first operation acquires the SQLite write lock, so concurrent processes cannot both spend the same global allowance.

func (*Store) Root

func (s *Store) Root() string

Root returns the memory root directory the store was opened with (the magic layout root holding global/projects/sessions). It is the canonical source for the memory root used by checkpoint persistence and context rebuild (<root>/sessions/<id>/checkpoint.md); callers must resolve the memory root through this accessor rather than re-deriving it from another store's dir. It is "" for a nil store.

func (*Store) Search

func (s *Store) Search(query string, opts SearchOptions) ([]SearchResult, error)

Search runs a BM25 full-text query over the indexed memory bodies.

The free-form query is tokenized and OR-joined by buildFtsQuery; an empty token set returns (nil, nil) without touching SQL. Results are ranked by BM25 (converted to higher = better), over-fetched 3x (capped at 50) so a relative score floor can trim common-word-only noise, then sliced to the requested limit. Optional scope/scope_id/type filters restrict the corpus.

type Type

type Type string

Type identifies the semantic kind of a memory file.

const (
	TypeUser       Type = "user"
	TypeFeedback   Type = "feedback"
	TypeProject    Type = "project"
	TypeReference  Type = "reference"
	TypeCheckpoint Type = "checkpoint"
	TypeProgress   Type = "progress"
	TypeNotes      Type = "notes"
	TypeFree       Type = "free"
)

Recognized types.

Jump to

Keyboard shortcuts

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