memory

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package memory bridges Claude Code's auto memory (MEMORY.md) into the .context/ directory with discovery, mirroring, and drift detection.

Claude Code maintains per-project auto memory at ~/.claude/projects/<slug>/memory/MEMORY.md. This package locates that file from the project root, mirrors it into .context/memory/mirror.md (git-tracked), and archives previous versions before each sync.

Discovery encodes the project root path into the Claude Code slug format: absolute path with "/" replaced by "-", prefixed with "-".

Sync state is tracked in .context/state/memory-import.json to support drift detection and future import/publish phases.

Index

Constants

View Source
const TargetSkip = "skip"

TargetSkip indicates an entry that doesn't match any classification rule.

Variables

This section is empty.

Functions

func Archive

func Archive(contextDir string) (string, error)

Archive copies the current mirror.md to archive/mirror-<timestamp>.md. Returns the archive path. Returns an error if no mirror exists.

func ArchiveCount

func ArchiveCount(contextDir string) int

ArchiveCount returns the number of archived mirror snapshots.

func Diff

func Diff(contextDir, sourcePath string) (string, error)

Diff returns a simple line-based diff between the mirror and the source. Returns empty string when files are identical.

func DiscoverMemoryPath

func DiscoverMemoryPath(projectRoot string) (string, error)

DiscoverMemoryPath locates Claude Code's auto memory file for the given project root. The path is derived from how Claude Code encodes project directories: absolute path with "/" replaced by "-", prefixed with "-".

Returns the resolved path if the file exists, or an error if auto memory has not been created yet.

func EntryHash

func EntryHash(text string) string

EntryHash computes a deduplication hash for an entry. Uses SHA-256 of the text, truncated to 16 hex chars.

func HasDrift

func HasDrift(contextDir, sourcePath string) bool

HasDrift checks whether MEMORY.md has been modified since the last sync. Returns false if either file is missing (no drift to report).

func MergePublished

func MergePublished(existing, published string) (string, bool)

MergePublished inserts or replaces the marker block in existing MEMORY.md content.

If markers exist, replaces everything between them. If markers are missing, appends the block at the end (recovery).

Parameters:

  • existing: current MEMORY.md content
  • published: formatted publish block to insert

Returns:

  • string: merged content
  • bool: true if markers were missing (appended instead of replaced)

func ProjectSlug

func ProjectSlug(absPath string) string

ProjectSlug encodes an absolute project path into the Claude Code project directory slug format: "/" replaced by "-", prefixed with "-".

Example: /home/jose/WORKSPACE/ctx → -home-jose-WORKSPACE-ctx

func Promote

func Promote(e Entry, classification Classification) error

Promote writes a classified entry to the appropriate .context/ file.

Uses the entry package for consistent formatting and indexing.

Parameters:

  • e: the memory entry to promote
  • classification: target type and confidence from classification

Returns:

  • error: non-nil if the entry write fails

func RemovePublished

func RemovePublished(content string) (string, bool)

RemovePublished strips the marker block from MEMORY.md content.

Parameters:

  • content: current MEMORY.md content

Returns:

  • string: content with the publish block removed
  • bool: true if markers were found and removed

func SaveState

func SaveState(contextDir string, s State) error

SaveState writes the sync state to .context/state/memory-import.json.

Types

type Classification

type Classification struct {
	Target   string   // config.Entry* constant or "skip"
	Keywords []string // Keywords that triggered the match
}

Classification is the result of heuristic entry classification.

func Classify

func Classify(entry Entry) Classification

Classify assigns a target file type to an entry based on keyword heuristics.

Matching is case-insensitive. The first rule with a keyword match wins (priority: conventions > decisions > learnings > tasks > skip).

type Entry

type Entry struct {
	Text      string    // Raw text of the entry (trimmed)
	StartLine int       // 1-based line number where the entry begins
	Kind      EntryKind // How the entry was delimited
}

Entry is a discrete block parsed from MEMORY.md.

func ParseEntries

func ParseEntries(content string) []Entry

ParseEntries splits MEMORY.md content into discrete entries.

Entry boundaries:

  • Markdown headers (## or ###) start a new entry
  • Blank lines separate paragraphs into distinct entries
  • Consecutive list items (- or *) are grouped into a single entry

The top-level heading (# Title) is skipped as it's structural, not content.

type EntryKind

type EntryKind int

EntryKind identifies how an entry was delimited in MEMORY.md.

const (
	// EntryHeader is a Markdown heading (## or ###).
	EntryHeader EntryKind = iota
	// EntryParagraph is a blank-line-separated paragraph.
	EntryParagraph
	// EntryList is one or more consecutive list items.
	EntryList
)

type PublishResult

type PublishResult struct {
	Tasks       []string
	Decisions   []string
	Conventions []string
	Learnings   []string
	TotalLines  int
}

PublishResult holds what was selected for publishing.

func Publish

func Publish(contextDir, memoryPath string, budget int) (PublishResult, error)

Publish writes selected content to MEMORY.md with marker-based merge.

Parameters:

  • contextDir: path to the .context/ directory
  • memoryPath: path to the MEMORY.md file
  • budget: maximum number of lines in the published block

Returns:

  • PublishResult: the content that was published
  • error: non-nil if selection or file write fails

func SelectContent

func SelectContent(contextDir string, budget int) (PublishResult, error)

SelectContent reads .context/ files and selects content within the line budget.

Priority order: tasks > decisions > conventions > learnings. If over budget, trims from bottom (learnings, conventions, decisions).

Parameters:

  • contextDir: path to the .context/ directory
  • budget: maximum number of lines in the published block

Returns:

  • PublishResult: selected content with per-section slices
  • error: non-nil if content selection fails

func (*PublishResult) Format

func (r *PublishResult) Format() string

Format renders the publish result as a Markdown block (without markers).

Returns:

  • string: formatted Markdown with section headings and items

type State

type State struct {
	LastSync       *time.Time `json:"last_sync"`
	LastImport     *time.Time `json:"last_import"`
	LastPublish    *time.Time `json:"last_publish"`
	ImportedHashes []string   `json:"imported_hashes"`
}

State tracks memory bridge sync timestamps and import/publish progress.

func LoadState

func LoadState(contextDir string) (State, error)

LoadState reads the sync state from .context/state/memory-import.json. Returns a zero-value State if the file does not exist.

func (*State) Imported

func (s *State) Imported(hash string) bool

Imported reports whether an entry hash has already been imported. Stored entries use format "hash:target:date"; matches on hash prefix.

func (*State) MarkImported

func (s *State) MarkImported(hash, target string)

MarkImported records an entry hash with its target and date.

func (*State) MarkImportedDone

func (s *State) MarkImportedDone()

MarkImportedDone updates LastImport to the current time.

func (*State) MarkSynced

func (s *State) MarkSynced()

MarkSynced updates the state with the current timestamp.

type SyncResult

type SyncResult struct {
	SourcePath  string
	MirrorPath  string
	ArchivedTo  string // empty if no prior mirror existed
	SourceLines int
	MirrorLines int // lines in the previous mirror (0 if first sync)
}

SyncResult holds the outcome of a Sync operation.

func Sync

func Sync(contextDir, sourcePath string) (SyncResult, error)

Sync copies sourcePath to .context/memory/mirror.md, archiving the previous mirror if one exists. Creates directories as needed.

Jump to

Keyboard shortcuts

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