memory

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: AGPL-3.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultRerankModel = "claude-haiku-4-5-20251001"

DefaultRerankModel is the default Claude model used for re-ranking.

Variables

View Source
var (
	ErrPathEscape    = errors.New("path escapes memory directory")
	ErrReadOnly      = errors.New("file is marked read-only")
	ErrFileNotFound  = errors.New("memory file not found")
	ErrAlreadyPinned = errors.New("file is already in system/")
	ErrNotPinned     = errors.New("file is not in system/")
)

Sentinel errors for memory operations.

View Source
var ErrNoChanges = errors.New("no changes to commit")

ErrNoChanges is returned by AutoCommit when the working tree is clean.

View Source
var ErrRepoBusy = errors.New("memory repo busy")

ErrRepoBusy is returned when a memory repo lock cannot be acquired in time.

Functions

func FormatFrontmatter

func FormatFrontmatter(fm Frontmatter, body string) string

FormatFrontmatter prepends a YAML frontmatter block to body. If fm is zero-value, body is returned unchanged.

func FormatTree

func FormatTree(entries []TreeEntry) string

FormatTree renders entries as a compact ASCII tree suitable for CLAUDE.md injection.

func GitEnabledFromConfig

func GitEnabledFromConfig(cfg *config.Config) bool

GitEnabledFromConfig returns whether memory git versioning should be enabled. Defaults to true when unset.

Types

type Chunk

type Chunk struct {
	StartLine int
	EndLine   int
	Text      string
	Hash      string
}

Chunk is a text segment from a memory file.

type ClaudeReranker

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

ClaudeReranker uses a local claude CLI process to re-rank FTS5 keyword results by semantic relevance. It works with any claude auth method — API key or Max subscription — because auth is handled by the claude binary.

func NewClaudeReranker

func NewClaudeReranker(model string) (*ClaudeReranker, error)

NewClaudeReranker creates a ClaudeReranker. If model is empty, defaults to claude-haiku-4-5-20251001. Returns an error if the claude binary is not found in PATH.

func (*ClaudeReranker) Name

func (r *ClaudeReranker) Name() string

Name implements Reranker.

func (*ClaudeReranker) Rerank

func (r *ClaudeReranker) Rerank(query string, results []SearchResult) ([]SearchResult, error)

Rerank re-orders results by semantic relevance to the query. On any error (timeout, parse failure, claude unavailable), it returns the original results unchanged — search still works via FTS5 order.

type EmbeddingProvider

type EmbeddingProvider interface {
	Embed(texts []string) ([][]float32, error)
	Dims() int
	Name() string
}

EmbeddingProvider abstracts an embedding API.

type FileInfo

type FileInfo struct {
	Path       string // relative to memory dir
	SizeBytes  int64
	UpdatedAt  int64 // Unix ms
	ChunkCount int
}

FileInfo is metadata about one memory file, returned by List.

type Frontmatter

type Frontmatter struct {
	Description string                 `yaml:"description,omitempty"`
	ReadOnly    bool                   `yaml:"read-only,omitempty"`
	Tags        []string               `yaml:"tags,omitempty"`
	Source      string                 `yaml:"source,omitempty"`
	Limit       int                    `yaml:"limit,omitempty"`
	Metadata    map[string]interface{} `yaml:"metadata,omitempty"`
	Extra       map[string]interface{} `yaml:"-"`
}

Frontmatter is optional YAML metadata at the top of a memory file.

func ParseFrontmatter

func ParseFrontmatter(content string) (Frontmatter, string)

ParseFrontmatter extracts YAML frontmatter from content. If no frontmatter is present, it returns a zero-value Frontmatter and the full content unchanged. Frontmatter must be delimited by "---" on its own line.

type GitBranchInfo

type GitBranchInfo struct {
	Current string   `json:"current"`
	Default string   `json:"default"`
	All     []string `json:"all"`
}

GitBranchInfo describes branch metadata for a memory repo.

type GitLogEntry

type GitLogEntry struct {
	SHA         string   `json:"sha"`
	ParentSHA   string   `json:"parent_sha,omitempty"`
	Message     string   `json:"message"`
	Date        string   `json:"date"`
	AuthorName  string   `json:"author_name,omitempty"`
	AuthorEmail string   `json:"author_email,omitempty"`
	Additions   int      `json:"additions,omitempty"`
	Deletions   int      `json:"deletions,omitempty"`
	Branch      string   `json:"branch,omitempty"`
	Files       []string `json:"files,omitempty"`
}

GitLogEntry represents a single commit in the memory git log.

type GitRepo

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

GitRepo manages a git repository for memory versioning.

func InitGitRepo

func InitGitRepo(dir string) (*GitRepo, error)

InitGitRepo initialises a git repo in dir if one doesn't already exist. It creates a .gitignore that excludes the .index/ directory. This is idempotent — calling it on an already-initialised repo is safe.

func (*GitRepo) AutoCommit

func (g *GitRepo) AutoCommit(message string) error

AutoCommit stages all changes and commits with the given message. Returns ErrNoChanges if the working tree is clean.

func (*GitRepo) BranchInfo

func (g *GitRepo) BranchInfo() (GitBranchInfo, error)

BranchInfo returns current/default branch and the complete branch list.

func (*GitRepo) Branches

func (g *GitRepo) Branches() ([]string, error)

Branches returns all branch names in the repo.

func (*GitRepo) CreateBranch

func (g *GitRepo) CreateBranch(name, fromRef string) error

CreateBranch creates a new branch from fromRef (or default branch when empty).

func (*GitRepo) CurrentBranch

func (g *GitRepo) CurrentBranch() (string, error)

CurrentBranch returns the currently checked-out branch name.

func (*GitRepo) DefaultBranch

func (g *GitRepo) DefaultBranch() (string, error)

DefaultBranch returns the preferred default branch for this memory repo.

func (*GitRepo) DeleteBranch

func (g *GitRepo) DeleteBranch(name string, force bool) error

DeleteBranch deletes a branch. If force=true it uses -D.

func (*GitRepo) DiffRefs

func (g *GitRepo) DiffRefs(baseRef, headRef, path string) (string, error)

DiffRefs returns the git diff between two refs. Optional path limits the diff.

func (*GitRepo) IsInitialized

func (g *GitRepo) IsInitialized() bool

IsInitialized returns true if the directory contains a .git directory.

func (*GitRepo) ListMarkdownFilesAtRef

func (g *GitRepo) ListMarkdownFilesAtRef(ref string) (map[string]string, error)

ListMarkdownFilesAtRef returns markdown files and raw content at a ref.

func (*GitRepo) Log

func (g *GitRepo) Log(path string, count int) ([]GitLogEntry, error)

Log returns the most recent commits, optionally filtered by file path. If path is empty, all commits are returned.

func (*GitRepo) LogWithBranch

func (g *GitRepo) LogWithBranch(path string, count int, branch string) ([]GitLogEntry, error)

LogWithBranch returns the most recent commits on a specific branch/ref. When branch is empty, history is read from HEAD.

func (*GitRepo) MergeBranch

func (g *GitRepo) MergeBranch(source, target, strategy string) ([]string, error)

MergeBranch merges source into target (or default branch when target is empty). Supported strategies: "ff-only" (default), "no-ff".

func (*GitRepo) ReadFileAtRef

func (g *GitRepo) ReadFileAtRef(ref, relPath string) (string, error)

ReadFileAtRef reads file content at a specific git ref.

type Manager

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

Manager is the primary interface for IDE-wide memory operations. It is safe for concurrent use from multiple goroutines (or processes via WAL).

func NewManager

func NewManager(dir string, provider EmbeddingProvider) (*Manager, error)

NewManager opens (or creates) a MemoryManager rooted at dir. provider may be nil for keyword-only search.

func NewManagerFromConfig

func NewManagerFromConfig(cfg *config.Config) (*Manager, error)

NewManagerFromConfig creates a MemoryManager from the application config. Returns (nil, nil) if memory is disabled or not configured.

func NewManagerWithOptions

func NewManagerWithOptions(dir string, provider EmbeddingProvider, opts ManagerOptions) (*Manager, error)

NewManagerWithOptions opens (or creates) a MemoryManager rooted at dir with explicit options.

func (*Manager) Append

func (m *Manager) Append(relPath, content string) error

Append adds content to an existing memory file, re-indexes, and auto-commits.

func (*Manager) AppendOnBranch

func (m *Manager) AppendOnBranch(relPath, content, branch string) error

AppendOnBranch adds content to an existing memory file and commits it to the selected branch.

func (*Manager) Close

func (m *Manager) Close()

Close releases resources held by the Manager.

func (*Manager) CreateBranch

func (m *Manager) CreateBranch(name, fromRef string) error

CreateBranch creates a memory git branch from an optional source ref.

func (*Manager) Delete

func (m *Manager) Delete(relPath string) error

Delete removes a memory file, its index, and auto-commits.

func (*Manager) DeleteBranch

func (m *Manager) DeleteBranch(name string, force bool) error

DeleteBranch deletes a memory git branch.

func (*Manager) DeleteOnBranch

func (m *Manager) DeleteOnBranch(relPath, branch string) error

DeleteOnBranch removes a memory file on the selected branch.

func (*Manager) DiffRefs

func (m *Manager) DiffRefs(baseRef, headRef, relPath string) (string, error)

DiffRefs returns the diff between two refs. Optional path limits output.

func (*Manager) Dir

func (m *Manager) Dir() string

Dir returns the root directory of the memory store.

func (*Manager) Get

func (m *Manager) Get(relPath string, from, lines int) (string, error)

Get reads lines from a memory file. from=0 means start; lines=0 means all.

func (*Manager) GetAtRef

func (m *Manager) GetAtRef(relPath string, from, lines int, ref string) (string, error)

GetAtRef reads lines from a memory file at a specific git ref. from=0 means start; lines=0 means all.

func (*Manager) GitBranchInfo

func (m *Manager) GitBranchInfo() (GitBranchInfo, error)

GitBranchInfo returns current/default branch and all branches for this memory repo.

func (*Manager) GitBranches

func (m *Manager) GitBranches() (current string, branches []string, err error)

GitBranches returns the current branch and all branch names for this memory git repo. When git versioning is disabled it returns zero values.

func (*Manager) GitEnabled

func (m *Manager) GitEnabled() bool

GitEnabled reports whether git versioning is active for this manager.

func (*Manager) History

func (m *Manager) History(relPath string, count int) ([]GitLogEntry, error)

History returns git log entries for a file, or all files if relPath is empty. Returns nil if git is not available.

func (*Manager) HistoryWithBranch

func (m *Manager) HistoryWithBranch(relPath string, count int, branch string) ([]GitLogEntry, error)

HistoryWithBranch returns git log entries for a file on a specific branch/ref.

func (*Manager) List

func (m *Manager) List() ([]FileInfo, error)

List returns metadata for all memory files (recursive).

func (*Manager) ListAtRef

func (m *Manager) ListAtRef(ref string) ([]FileInfo, error)

ListAtRef returns metadata for all markdown files at a specific git ref.

func (*Manager) MergeBranch

func (m *Manager) MergeBranch(source, target, strategy string) error

MergeBranch merges source into target branch and re-syncs changed markdown files when the target is the default branch.

func (*Manager) Move

func (m *Manager) Move(from, to string) error

Move renames a memory file, re-indexes both paths, and auto-commits.

func (*Manager) MoveOnBranch

func (m *Manager) MoveOnBranch(from, to, branch string) error

MoveOnBranch renames/moves a memory file on the selected branch.

func (*Manager) Pin

func (m *Manager) Pin(relPath string) error

Pin moves a file into the system/ directory (always-in-context).

func (*Manager) PinOnBranch

func (m *Manager) PinOnBranch(relPath, branch string) error

PinOnBranch moves a file into system/ on the selected branch.

func (*Manager) Read

func (m *Manager) Read(relPath string) (string, error)

Read returns the body of a memory file with frontmatter stripped.

func (*Manager) ReadAtRef

func (m *Manager) ReadAtRef(relPath string, ref string) (string, error)

ReadAtRef returns the body of a memory file with frontmatter stripped at a specific ref.

func (*Manager) ReadFileFrontmatter

func (m *Manager) ReadFileFrontmatter(relPath string) (Frontmatter, error)

ReadFileFrontmatter reads a memory file's frontmatter without loading the full file. It reads up to maxBytes from the start of the file.

func (*Manager) Search

func (m *Manager) Search(query string, opts SearchOpts) ([]SearchResult, error)

Search performs hybrid search: FTS5 BM25 + optional cosine similarity, followed by optional Claude-based re-ranking.

func (*Manager) SetReranker

func (m *Manager) SetReranker(r Reranker)

SetReranker configures an optional post-FTS5 reranker. Safe to call before the Manager is used for searches.

func (*Manager) StartWatcher

func (m *Manager) StartWatcher() (stop func(), err error)

StartWatcher watches the memory directory (recursively) for file changes and triggers re-indexing + auto-commit. Returns a stop function.

func (*Manager) Sync

func (m *Manager) Sync(relPath string) error

Sync re-indexes a specific file: chunks it, updates FTS and vectors.

func (*Manager) SystemFiles

func (m *Manager) SystemFiles(maxChars int) (map[string]string, error)

SystemFiles reads all files from system/ up to maxChars total. Returns a map of relative path → body content (frontmatter stripped).

func (*Manager) Tree

func (m *Manager) Tree() ([]TreeEntry, error)

Tree returns all .md files in the memory directory with frontmatter descriptions.

func (*Manager) TreeAtRef

func (m *Manager) TreeAtRef(ref string) ([]TreeEntry, error)

TreeAtRef returns the markdown tree with descriptions at a specific git ref.

func (*Manager) Unpin

func (m *Manager) Unpin(relPath string) error

Unpin moves a file out of the system/ directory back to root.

func (*Manager) UnpinOnBranch

func (m *Manager) UnpinOnBranch(relPath, branch string) error

UnpinOnBranch moves a file out of system/ on the selected branch.

func (*Manager) Write

func (m *Manager) Write(content, file string) error

Write appends content to a named memory file and triggers re-indexing. If file is empty, the default is today's date (YYYY-MM-DD.md).

func (*Manager) WriteFile

func (m *Manager) WriteFile(relPath, content, commitMsg string) error

WriteFile creates or overwrites a memory file, re-indexes, and auto-commits.

func (*Manager) WriteFileOnBranch

func (m *Manager) WriteFileOnBranch(relPath, content, commitMsg, branch string) error

WriteFileOnBranch creates or overwrites a memory file and commits it to the selected branch.

func (*Manager) WriteWithCommitMessage

func (m *Manager) WriteWithCommitMessage(content, file, commitMsg string) error

WriteWithCommitMessage appends content to a named memory file, re-indexes, and commits with the provided commit message when git is enabled. If commitMsg is empty, a default message is generated.

func (*Manager) WriteWithCommitMessageOnBranch

func (m *Manager) WriteWithCommitMessageOnBranch(content, file, commitMsg, branch string) error

WriteWithCommitMessageOnBranch appends content to a named memory file and commits to the selected branch when provided. When branch is empty, it writes to the repository default branch.

type ManagerOptions

type ManagerOptions struct {
	// GitEnabled controls whether the memory store is git-versioned.
	// Defaults to true when NewManager is used.
	GitEnabled bool
}

ManagerOptions configures optional manager behaviors.

type MemoryStore

type MemoryStore interface {
	Dir() string
	GitEnabled() bool

	Search(query string, opts SearchOpts) ([]SearchResult, error)
	Read(relPath string) (string, error)
	ReadAtRef(relPath, ref string) (string, error)
	Get(relPath string, from, lines int) (string, error)
	GetAtRef(relPath string, from, lines int, ref string) (string, error)
	List() ([]FileInfo, error)
	ListAtRef(ref string) ([]FileInfo, error)
	Tree() ([]TreeEntry, error)
	TreeAtRef(ref string) ([]TreeEntry, error)
	History(relPath string, count int) ([]GitLogEntry, error)
	HistoryWithBranch(relPath string, count int, branch string) ([]GitLogEntry, error)

	WriteWithCommitMessage(content, file, commitMsg string) error
	WriteWithCommitMessageOnBranch(content, file, commitMsg, branch string) error
	WriteFile(relPath, content, commitMsg string) error
	WriteFileOnBranch(relPath, content, commitMsg, branch string) error
	Append(relPath, content string) error
	AppendOnBranch(relPath, content, branch string) error
	Move(from, to string) error
	MoveOnBranch(from, to, branch string) error
	Delete(relPath string) error
	DeleteOnBranch(relPath, branch string) error
	Pin(relPath string) error
	PinOnBranch(relPath, branch string) error
	Unpin(relPath string) error
	UnpinOnBranch(relPath, branch string) error

	GitBranches() (current string, branches []string, err error)
	GitBranchInfo() (GitBranchInfo, error)
	CreateBranch(name, fromRef string) error
	DeleteBranch(name string, force bool) error
	MergeBranch(source, target, strategy string) error
	DiffRefs(baseRef, headRef, relPath string) (string, error)
}

MemoryStore defines the local memory operations surface used by higher layers. It intentionally maps to the current Manager API so future daemon/remote adapters can satisfy the same contract.

type OllamaProvider

type OllamaProvider struct {
	URL   string // e.g. "http://localhost:11434"
	Model string // e.g. "nomic-embed-text"
	// contains filtered or unexported fields
}

OllamaProvider calls a local Ollama server for embeddings.

func NewOllamaProvider

func NewOllamaProvider(url, model string) *OllamaProvider

func (*OllamaProvider) Dims

func (p *OllamaProvider) Dims() int

func (*OllamaProvider) Embed

func (p *OllamaProvider) Embed(texts []string) ([][]float32, error)

func (*OllamaProvider) Name

func (p *OllamaProvider) Name() string

type OpenAIProvider

type OpenAIProvider struct {
	APIKey string
	Model  string // default "text-embedding-3-small"
	// contains filtered or unexported fields
}

OpenAIProvider calls the OpenAI embeddings API.

func NewOpenAIProvider

func NewOpenAIProvider(apiKey, model string) *OpenAIProvider

func (*OpenAIProvider) Dims

func (p *OpenAIProvider) Dims() int

func (*OpenAIProvider) Embed

func (p *OpenAIProvider) Embed(texts []string) ([][]float32, error)

func (*OpenAIProvider) Name

func (p *OpenAIProvider) Name() string

type RepoStoreResolution

type RepoStoreResolution struct {
	CanonicalSlug string
	CanonicalPath string
	LegacySlug    string
	LegacyPath    string
}

RepoStoreResolution describes canonical and legacy per-repo memory locations. LegacyPath is only set when both canonical and legacy dirs currently exist.

func ResolveRepoStorePaths

func ResolveRepoStorePaths(baseDir, repoPath, worktreePath string) (RepoStoreResolution, error)

ResolveRepoStorePaths resolves canonical/legacy repo memory dirs and performs one-time migration from legacy (worktree-derived slug) to canonical (repo-derived slug) when canonical does not yet exist.

type Reranker

type Reranker interface {
	Rerank(query string, results []SearchResult) ([]SearchResult, error)
	Name() string
}

Reranker re-orders search results by semantic relevance to a query. It is applied as a post-processing step after FTS5 keyword retrieval, without requiring any embedding storage.

type SearchOpts

type SearchOpts struct {
	MaxResults int     // default 10
	MinScore   float32 // default 0.0 (no filter)
}

SearchOpts configures a Search call.

type SearchResult

type SearchResult struct {
	Path      string // relative to memory dir, e.g. "global.md"
	StartLine int
	EndLine   int
	Score     float32 // 0.0–1.0 combined score
	Snippet   string  // up to 700 chars of matched text
}

SearchResult is one match returned from a memory search.

type TreeEntry

type TreeEntry struct {
	Path        string `json:"path"`
	Description string `json:"description,omitempty"`
	SizeBytes   int64  `json:"size_bytes"`
	IsSystem    bool   `json:"is_system"`
}

TreeEntry describes a single file in the memory tree.

Jump to

Keyboard shortcuts

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