memory

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 17 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 discovers and parses Claude Code memory files. It contains no UI code.

Index

Constants

View Source
const IndexFile = "MEMORY.md"

IndexFile is the per-folder human index Claude Code loads each session.

Variables

View Source
var Caps = source.Caps{Edit: true, Create: true, Delete: true, Share: true}

Caps declares what the TUI may offer the user on memories: everything. Memories are engram's own domain — editing keeps the promise that engram only ever adds frontmatter keys it owns, which is ENGR-12's governing test for granting Edit.

View Source
var DocsCaps source.Caps

DocsCaps declares the files source's capabilities: none — deliberately the zero value. Instruction files are maintained by their own assistant (or by hand outside engram), and engram cannot promise an edit stays compatible with the tool that owns the file, so they are browsable only and repairs route through the @ assistant handoff — any of the four providers, not Claude Code alone (ENGR-12).

Functions

func ContentDigest

func ContentDigest(raw string) (string, error)

ContentDigest returns a stable short hex hash of a memory's shared content — its body plus Claude's frontmatter — with engram's own `engram:` block excluded so bookkeeping (the sync anchor, owner, scope, id) never perturbs it, and line endings normalized. Two files that carry the same body and Claude frontmatter digest equal regardless of engram metadata or CRLF/LF. It underpins the sync anchor: a copy's stored SyncedHash is the digest of the content it was last synced to, so a later digest mismatch means that copy's content has moved.

func Create

func Create(memDir, title string) (string, error)

Create writes a new memory file (with a frontmatter template) into memDir and returns its path. The filename is derived from the title and made unique.

func Delete

func Delete(path string) error

Delete removes a memory file from disk.

func DocsSignature

func DocsSignature(root string, scanRoots []string) (string, error)

DocsSignature fingerprints the same files DiscoverDocs surfaces (path + modtime + size), reading no contents — so polling notices an external edit to any of them. Both walk projectRuleFiles and globalRuleFiles, which is what keeps them in step: a file surfaced there but missed here would reload only on restart. (MEMORY.md is also covered by Signature; the overlap is harmless.)

func EngramPresent

func EngramPresent(raw string) bool

EngramPresent reports, best-effort, whether the frontmatter carries an `engram:` key at all — even when the block is malformed enough that ReadEngram errors (e.g. a non-mapping value like `engram: oops`). It lets a caller tell a genuinely personal memory (no block) from a shared one whose block got corrupted, without guessing a sync direction. Returns false when the frontmatter itself can't be parsed (a wholly-unparseable file is indistinguishable from personal here).

func HasEngramLine added in v0.7.0

func HasEngramLine(raw string) bool

HasEngramLine reports whether the frontmatter has a top-level `engram:` line, read as text rather than YAML, so it still answers when the frontmatter fails to parse and EngramPresent can only say false.

func IndexDrift

func IndexDrift(memDir string) (unindexed, dangling []string, err error)

IndexDrift reports the gap between MEMORY.md and the memory files on disk: `unindexed` are files with no bullet, `dangling` are bullets whose file is gone. Both empty means the index is in sync.

func IsDir added in v0.6.1

func IsDir(p string) bool

IsDir reports whether p is an existing directory (following symlinks). It is exported for the TUI, which asks instead of touching the filesystem itself.

func NewID

func NewID() (string, error)

NewID returns a random RFC-4122 v4 UUID for engram.id, built from crypto/rand so engram pulls in no external dependency.

func RealPath added in v0.7.0

func RealPath(p string) string

RealPath is p with every symlink resolved, for comparing where two paths really are. When p itself doesn't exist (a file not written yet), its nearest existing parent is resolved and the rest joined back on, so a missing file under a symlinked folder (macOS's /var is /private/var) still compares equal to that folder. A dangling symlink on the way is followed to its target, not treated as a missing file in place: a link that points out of a folder must not count as inside it. Exported for the TUI, which asks instead of touching the filesystem itself.

func ReconcileIndex

func ReconcileIndex(memDir string) (added, removed int, err error)

ReconcileIndex brings MEMORY.md back in sync with the files: it drops dangling bullets and appends bullets for unindexed files, preserving the header and the existing curated order. It does not rewrite already-correct entries. Returns the counts added and removed.

func RemoveIndex

func RemoveIndex(memDir, file string) error

RemoveIndex drops file's bullet from memDir/MEMORY.md, leaving the rest untouched. It's a no-op if the index doesn't exist.

func RemoveIndexForPath

func RemoveIndexForPath(path string) error

func ShareContent

func ShareContent(raw string) (string, error)

ShareContent returns a memory's shared content — Claude's frontmatter and body with engram's own block removed and the frontmatter canonicalized. It is exactly what ContentDigest hashes and what the conflict editor presents, so a resolution saved from it re-digests consistently against the store copy.

func Signature

func Signature(root string) (string, error)

Signature returns a cheap fingerprint of every memory file under root (each file's path + modtime + size, including MEMORY.md so index edits count too). It changes whenever a memory is added, removed, or edited, and reads no file contents — used to poll for external changes. It mirrors Discover's walk so the two never disagree about which files exist. If root is empty it defaults to ~/.claude/projects.

func Slugify

func Slugify(s string) string

Slugify converts a title into a kebab-case slug suitable for a filename.

func UpsertIndex

func UpsertIndex(memDir, file string) error

UpsertIndex adds or refreshes file's bullet in memDir/MEMORY.md. An existing entry is replaced in place (preserving its position and the rest of the file); a new entry is appended after the last bullet. The index is created with a header if it doesn't exist.

func UpsertIndexForPath

func UpsertIndexForPath(path string) error

UpsertIndexForPath / RemoveIndexForPath are convenience wrappers keyed by a memory's full path, so callers needn't split dir and filename themselves.

func WriteEngram

func WriteEngram(raw string, meta EngramMeta) (string, error)

WriteEngram returns raw with the `engram:` frontmatter block set to meta. Every other frontmatter key, the key order, and the body are preserved; a file with no frontmatter gains a block containing only engram's keys. Engram never invents or rewrites Claude's fields.

Types

type DocFile

type DocFile struct {
	Path        string
	Title       string // the file's own basename, e.g. "CLAUDE.md" or "MEMORY.md"
	Body        string // file contents (markdown); for rule-dir files, the body with its frontmatter split off
	Detail      string // rule-dir files only: one-line scoping note from the frontmatter ("applies to src/**"); "" otherwise
	Kind        DocKind
	Provider    DocProvider
	Scope       string // "global" or the project name
	ProjectName string // "" for global
	ProjectDir  string // decoded project dir; "" for global or unresolved
	MemoryDir   string // the project's memory dir; "" for global
	Modified    time.Time
}

DocFile is an instruction file shown read-only in engram's files source: a project's instruction files (see projectRuleFiles) or a MEMORY.md. These are maintained by an assistant (or by hand outside engram), not hand-edited in engram, so DocFile carries no frontmatter — just enough to display and to launch an assistant in the right place.

func DiscoverDocs

func DiscoverDocs(root string, scanRoots []string) ([]DocFile, error)

DiscoverDocs returns the read-only instruction docs: the global ~/.claude/CLAUDE.md plus every globalRuleFiles entry that exists, and per project every projectRuleFiles entry that exists (only when the project dir resolves on disk) plus its MEMORY.md. Sorted global-first, then by project, then in projectRuleFiles order with MEMORY.md last.

scanRoots adds projects Claude Code has never opened: each root and its immediate children are surfaced when they carry an instruction file (see scanRootProjects). Those have no memory directory, so they contribute instruction files only — no MEMORY.md row.

A global doc belongs to no project, so it carries empty ProjectName, ProjectDir and MemoryDir — the same shape ~/.claude/CLAUDE.md has always had. The TUI already reads that as "no project to open" (assistantContext returns claudeHome() when both dirs are empty), so an @ handoff launches in ~/.claude rather than pointing at someone else's repo.

type DocKind

type DocKind string

DocKind classifies what an instruction doc *is*, independent of which assistant wrote it.

const (
	DocRules DocKind = "rules" // instructions an assistant loads (CLAUDE.md, AGENTS.md)
	DocIndex DocKind = "index" // a MEMORY.md (the memory index)
)

type DocProvider added in v0.4.0

type DocProvider string

DocProvider names *whose* doc it is. Kept separate from DocKind because AGENTS.md and CLAUDE.md are the same kind (rules) from different ecosystems — collapsing the two dimensions is what would force a new DocKind per vendor.

const (
	ProviderClaude  DocProvider = "claude"  // CLAUDE.md / MEMORY.md
	ProviderAgents  DocProvider = "agents"  // AGENTS.md, the cross-tool standard
	ProviderGemini  DocProvider = "gemini"  // GEMINI.md, the Gemini CLI's context file
	ProviderCopilot DocProvider = "copilot" // .github/copilot-instructions.md + .github/instructions/*.instructions.md
	ProviderCursor  DocProvider = "cursor"  // .cursor/rules/*.mdc
)

type EngramMeta

type EngramMeta struct {
	ID      string `yaml:"id,omitempty"`
	Scope   string `yaml:"scope,omitempty"`   // "personal" | "team"
	Project string `yaml:"project,omitempty"` // normalized remote key, or "global"
	Owner   string `yaml:"owner,omitempty"`
	// SyncedHash is the ContentDigest of the shared content at the last sync
	// (promote or pull) — the common base engram compares against to tell a clean
	// fast-forward from a real conflict. Empty on personal memories and on copies
	// last synced by a pre-anchor engram; callers must treat an absent anchor as
	// "unknown" and fall back to a direction-less compare.
	SyncedHash string `yaml:"syncedHash,omitempty"`
}

EngramMeta is engram's own frontmatter block (the top-level `engram:` key), describing how a memory is shared. Claude Code ignores these keys; engram owns them entirely and never reads or rewrites Claude's frontmatter fields.

func ReadEngram

func ReadEngram(raw string) (meta EngramMeta, ok bool, err error)

ReadEngram extracts the `engram:` block from a memory file's raw contents. ok is false when there is no engram block (the file may still have other frontmatter).

type Memory

type Memory struct {
	Name        string // slug (frontmatter name, or filename without .md)
	Title       string // human-readable title
	Description string // one-line hook
	Type        Type
	Body        string    // markdown body, frontmatter stripped
	Raw         string    // full original file contents
	Path        string    // absolute path on disk
	Modified    time.Time // file modification time
	Project     Project
	Shared      EngramMeta // engram sharing block; zero value when the memory isn't shared
}

Memory is a single memory file on disk.

func Discover

func Discover(root string) ([]Memory, error)

Discover walks every Claude project under root and returns all memories found. If root is empty it defaults to ~/.claude/projects.

type Project

type Project struct {
	Name      string // friendly name (basename of decoded dir)
	Dir       string // decoded absolute project dir (best-effort)
	MemoryDir string // .../memory
	Remote    string // git remote URL — populated in Phase 2, empty in Phase 1
}

Project is the Claude Code project a memory belongs to.

type Type

type Type string

Type is the category of a memory, taken from Claude's `metadata.type`.

const (
	TypeUser      Type = "user"
	TypeFeedback  Type = "feedback"
	TypeProject   Type = "project"
	TypeReference Type = "reference"
	TypeUnknown   Type = "unknown"
)

Jump to

Keyboard shortcuts

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