memory

package
v0.1.4898 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 26 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 is what the agents know from earlier conversations, kept once for all of them: a preference the user stated in Claude Code is known to Codex the next day. Each memory is one short fact with where it holds (everywhere, a project, an agent), what kind of fact it is, the user's tags, and where it came from. The agents read and add to it through the memory MCP server (gateway/memory_mcp.go), and the ones the user picks are also given a digest of it in their instructions (library/instructions.go). The Library's Memory tab lists and edits it.

It is a folder of Markdown files in magpie's config folder, one a memory (store.go): one writer at a time across magpies (filelock), a change to several written all or none (a journal), and a file that can't be read is unknown, never empty, so nothing is written over it.

Index

Constants

View Source
const (
	Profile    = "profile"    // who the user is: role, languages, what they know
	Preference = "preference" // how the user wants things done
	Rule       = "rule"       // a rule learned from a correction, with why
	Fact       = "fact"       // something true of a project the code doesn't say
	Reference  = "reference"  // where something is: a host, a dashboard, a URL
	Procedure  = "procedure"  // how something is done: steps that worked
	Episode    = "episode"    // what happened or was decided, and when
)

The kinds of memory. A kind decides how long a memory stays true and where it goes in a digest, so it is a field of its own, not a tag.

View Source
const (
	FromUser     = "user"     // typed or edited by the user
	FromAgent    = "agent"    // saved by an agent through the MCP server
	FromImported = "imported" // read from an agent's own memory files
	FromInferred = "inferred" // distilled from a conversation
)

Where a memory came from.

View Source
const (
	Active     = "active"
	Candidate  = "candidate"  // waiting for the user to keep or drop it
	Archived   = "archived"   // set aside: out of searches and digests, kept
	Superseded = "superseded" // replaced by SupersededBy
)

A memory's state.

View Source
const (
	ToGlobal = "global"
	ToSkill  = "skill"
)

What memory suggests the user make more of (Suggest): a memory learned in two or more projects is one that holds everywhere, and a procedure the agents search for often is worth a skill of its own.

View Source
const (
	ByTidy   = "tidy"
	ByExpiry = "expiry"
	ByYou    = "you"
	ByAgent  = "agent"
)

Who set a memory aside, for Day.Cleaned.

View Source
const (
	Merged     = "merge"      // IDs were superseded by Into
	SetAside   = "aside"      // IDs were archived
	Unreviewed = "unreviewed" // Why of a candidate set aside for its age
)

What a Change did.

View Source
const Global = "global"

Global is the scope of a memory that holds everywhere. A project's is "project:" and its key (ProjectOf), an agent's "agent:" and its id.

View Source
const Keep = 30 * 24 * time.Hour

Keep is how long a candidate waits to be reviewed, and how long an archived or superseded memory is kept, before Prune moves it on.

View Source
const MaxText = 2000

MaxText is the longest a memory's text may be: one fact, not a document.

Variables

View Source
var (
	Near   = 0.30
	Within = 0.15
)

A memory counts as meaning what was searched for at a cosine of Near or more, and Within of the nearest. Over 97 real memories and 16 searches (half in Chinese, for memories in English), the memory sought was at a median of 0.47, the rest at a median of 0.16 and a 95th percentile of 0.36. Near alone let ~11 of the rest in a search; with Within, 12 of the 16 were found and ~4 of the rest came along, behind them, and the word ranking finds most of the four it misses.

View Source
var ErrNotFound = errors.New("no memory with that id")

ErrNotFound is a memory id that isn't there.

View Source
var ErrNotSuggested = errors.New("that isn't suggested any more")

ErrNotSuggested is a suggestion taken that is no longer made.

Kinds are the kinds in the order a digest gives them.

View Source
var Path = func() string { return appdir.Join(appdir.Config(), "memory.json") }

Path is memory.json, where memory was kept before Dir; a variable for tests, which moves Dir with it.

View Source
var Semantic func(text string, pool []*Memory) map[string]float64

Semantic, when set (memembed, with search by meaning switched on), is how near in meaning each memory of pool is to text, a cosine, for the ones it has read; nil when it can't say (switched off, the model not there, or failing), and the search is by words alone.

Functions

func CleanTags

func CleanTags(tags []string) []string

CleanTags are tags as kept: trimmed, lower case, no "#", each once, in the order given.

func Decline

func Decline(key string) error

Decline turns a suggestion down: it isn't made again. A ToGlobal one that another project's memory joins later is another suggestion.

func Digest

func Digest(agent string) (string, error)

Digest is the published digest an agent is given: the global part, the agent's own, and each project's under the folders it was seen in, held to the whole budget, the projects with the newest memories first. "" when there is nothing, or memory can't be read (unknown: the caller keeps what the agent has).

func DigestOmitWhy

func DigestOmitWhy() (bool, error)

DigestOmitWhy reports whether published digests omit "(why: ...)" rationale suffixes while keeping each memory's Why stored (#7780).

func Dir

func Dir() string

Dir is the folder memory is kept in.

func Fixed

func Fixed(m *Memory) bool

Fixed is a memory a tidy never changes: the user's own, or pinned.

func Indented

func Indented(s, pad string) string

Indented is a memory's text with its line breaks kept, each line after the first led by pad, so a memory the user wrote in several lines reads as they wrote it and stays one item of a list. Spaces closing a line and blank lines' pads are left out.

func MadeSkill

func MadeSkill(id, name string) error

MadeSkill notes that the procedure with id was made the skill called name: it is archived, since the skill holds it now, and isn't suggested again. Restored, it is searched again, still noted as that skill's.

func Modified

func Modified() time.Time

Modified is when memory last changed, zero when there is none: for a reader to tell whether it changed.

func NoteProject

func NoteProject(p *Project) error

NoteProject records a project memories may be kept for, for its name to be shown and its folders known.

func Publish

func Publish() (changed bool, err error)

Publish makes what memory holds now the digest agents are given. It reports whether any digest changed, for the caller to write it into the agents' instructions.

func PublishDue

func PublishDue() (bool, error)

PublishDue publishes when the digest was last published more than a day ago, and memory holds something or held something then. It reports whether any digest changed.

func Put

func Put(b *Bundle) (changed bool, err error)

Put merges b into memory here (Combine), writing only when that changes it. It reports whether it did; a file here that can't be read is an error, and nothing is written over it.

func RemoteKey

func RemoteKey(u string) string

RemoteKey is a git remote's address as a project key, the same for each way of writing it: https://github.com/a/b.git, git@github.com:a/b and ssh://git@github.com/a/b all are github.com/a/b. "" for a local path.

func Remove

func Remove(ids ...string) error

Remove deletes the memories with ids for good.

func ScopeOf

func ScopeOf(p *Project) string

ScopeOf is the scope of a project's memories.

func SetDigestOmitWhy

func SetDigestOmitWhy(omit bool) (changed bool, err error)

SetDigestOmitWhy sets whether published digests omit "(why: ...)" rationale suffixes and republishes the digest at once. It reports whether the published digest changed.

func SetStatus

func SetStatus(status string, ids ...string) (n int, err error)

SetStatus gives the user's status to the memories with ids, in one write: those to review kept at once, or archived or brought back, as Edit would one by one (RealZeroP27 on X). An id no longer there is passed over; n is how many were changed, and none found is ErrNotFound. A status that isn't one changes nothing.

func Untidy

func Untidy(cs []Change) (int, error)

Untidy undoes cs: each memory a tidy superseded or set aside, and still left so, goes back to the state it had, and a memory a merge made is removed, unless the user has made it theirs since (it stays then, with the ones it was made from back beside it). It returns how many memories came back. A merged memory stays, too, when one it was made from has been removed since (Prune): it is all that is left of it.

func Words

func Words(s string) []string

Words are the words of s as searched: letters and digits in lower case, and a run of Chinese, Japanese or Korean characters as each character and each pair of them, since those are written without spaces.

Types

type Bundle

type Bundle struct {
	Memories  []*Memory            `json:"memories"`
	Projects  map[string]*Project  `json:"projects,omitempty"`
	Dismissed []string             `json:"dismissed,omitempty"`
	Removed   map[string]time.Time `json:"removed,omitempty"`
	Declined  []string             `json:"declined,omitempty"`
}

Bundle is what of memory goes to another computer, in a backup or a sync: the memories in every state, the projects they are kept for, the distilled texts the user threw away and the memories deleted. The published digests and the vectors (memembed) are this computer's own, made again from the memories here.

func Collect

func Collect() (*Bundle, error)

Collect is this computer's memory, to carry: nil when there is none (no Dir, no memory.json to move in), an error when it can't be read (a failed read is unknown: a backup of it as nothing would say there was nothing). A memory whose file can't be read is left out: absent from a bundle is not removed (Combine), so no other computer drops it for that.

func Combine

func Combine(a, b *Bundle) *Bundle

Combine is a and b together, either nil, each memory once:

  • of the same memory on both sides, the one changed later, unless that change wasn't the user's (an agent's save, a tidy) and the other is pinned or the user's (Fixed) while it isn't: what the user made theirs is never written over by what a machine did on another computer before it saw that;
  • when a search last returned it and how often, the most of both;
  • one deleted on either side stays deleted, unless it was changed after the deletion;
  • the projects, dismissed texts, deletions and suggestions turned down of both.

It is the same whichever side is a: memories by id, projects by key.

func (*Bundle) Hash

func (b *Bundle) Hash() string

Hash is what tells a change in b: the memories, projects, dismissed texts and deletions, but not when a search last returned a memory nor how often (Used, Uses), which an agent's search changes and which alone is no change worth a sync. A nil b hashes as "".

type Change

type Change struct {
	Action string `json:"action"`
	// Into is the memory merged into; New when the merge made it
	Into string `json:"into,omitempty"`
	New  bool   `json:"new,omitempty"`
	// IDs are the memories superseded or set aside, Was their states
	// before
	IDs []string `json:"ids"`
	Was []string `json:"was"`
	// Text is what Into says, or what was set aside
	Text string `json:"text"`
	Why  string `json:"why,omitempty"`
}

Change is one thing a tidy did, with what it takes to undo it.

func Tidy

func Tidy(p Plan) ([]Change, error)

Tidy does p, as far as it still holds: a memory gone, no longer in use or the user's own is left alone, and a merge across scopes or of two of the user's own isn't done. It returns what it did.

type Day

type Day struct {
	Created  map[string]int `json:"created,omitempty"`
	Updated  int            `json:"updated,omitempty"`
	Cleaned  map[string]int `json:"cleaned,omitempty"`
	Searches int            `json:"searches,omitempty"`
	Found    int            `json:"found,omitempty"`
	Recalled int            `json:"recalled,omitempty"`
}

Day is one day's counts.

type Hit

type Hit struct {
	*Memory
	Score float64 `json:"score"`
}

Hit is a memory a search found, with how well it matched.

func Rank

func Rank(q Query) ([]Hit, error)

Rank is Search without noting the hits as used: for the Memory tab's search box, which the user types into.

func Search(q Query) ([]Hit, error)

Search finds memories matching q, best first: every word of the text counted by how rare it is among the memories, a memory holding the whole text ahead, pinned ones and a project's or agent's own a little ahead of the rest; with search by meaning on (Semantic), the ones that mean the same in other words too, the two rankings fused. With no text, it lists them by kind and newest change. The hits are noted as used.

type Input

type Input struct {
	Text   *string   `json:"text,omitempty"`
	Kind   *string   `json:"kind,omitempty"`
	Scope  *string   `json:"scope,omitempty"`
	Tags   *[]string `json:"tags,omitempty"`
	Why    *string   `json:"why,omitempty"`
	Status *string   `json:"status,omitempty"`
	Pinned *bool     `json:"pinned,omitempty"`
}

Input is a memory as a caller gives it: to Save a new one, or to Edit one (where a nil field is left as it is).

type Memory

type Memory struct {
	ID    string   `json:"id"`
	Text  string   `json:"text"`
	Kind  string   `json:"kind"`
	Scope string   `json:"scope"`
	Tags  []string `json:"tags,omitempty"`
	// Why is the reason behind a rule or preference, when one was given
	Why          string    `json:"why,omitempty"`
	Origin       string    `json:"origin"`
	Status       string    `json:"status"`
	SupersededBy string    `json:"supersededBy,omitempty"`
	Pinned       bool      `json:"pinned,omitempty"`
	Sources      []Source  `json:"sources,omitempty"`
	Created      time.Time `json:"created"`
	Updated      time.Time `json:"updated"`
	// Edited is when the user last changed it (Edit by the user, Save
	// of what they typed): a change made then is theirs, which a sync
	// from another computer tells apart from an agent's or a tidy's
	// (Combine)
	Edited time.Time `json:"edited,omitzero"`
	// Used is when a search last returned it, Uses how many times
	Used time.Time `json:"used,omitzero"`
	Uses int       `json:"uses,omitempty"`
	// Skill is the Library skill this procedure was made (MadeSkill)
	Skill string `json:"skill,omitempty"`
}

Memory is one thing known.

func All

func All() ([]*Memory, map[string]*Project, error)

All is every memory, in every state, newest change first, and the projects they are kept for.

func Edit

func Edit(id string, in Input, byUser bool) (*Memory, error)

Edit changes the memory with id. An edit by the user (byUser) makes it the user's: what is distilled or saved later never changes it.

func Forget

func Forget(id string) (*Memory, error)

Forget sets the memory with id aside (archived): out of searches and digests, kept to be brought back.

func Get

func Get(id string) (*Memory, error)

Get is the memory with id.

func Promote

func Promote(ids []string) (*Memory, error)

Promote makes the project memories with ids one global memory, as the user asked: the one kept first (the user's own or pinned, the most used, the latest) holds everywhere from now, carrying the others' tags and sources, and the others are superseded by it. It is the user's change, so a sync never undoes it with an older one.

func Save

func Save(in Input, origin string, src *Source, proj *Project) (m *Memory, added bool, err error)

Save adds a memory from origin, with src where it came from (nil for none). A memory with the same text in the same scope, not archived, is not added again: it gets the source, the tags it lacked and the newer kind and why, and is returned with added false. A project scope's project is recorded when proj is given.

One distilled from a conversation (FromInferred) is not added when the user threw the same text away before (dismissed), or set it aside in that scope: m is nil then, or the one set aside, and added false.

type Merge

type Merge struct {
	IDs  []string
	Text string
	Kind string
}

Merge is memories to merge: IDs into one that says Text.

type Plan

type Plan struct {
	Merges []Merge
	Stale  []Stale
	Before time.Time
}

Plan is what a tidy does: the merges, the memories to set aside, and Before, when an unreviewed candidate distilled from a conversation is set aside if it hasn't changed since (zero: none).

type Project

type Project struct {
	Key   string   `json:"key"`
	Name  string   `json:"name"`
	Roots []string `json:"roots,omitempty"`
}

Project is a project memories are kept for: a git repository by its remote, or a folder, with the folders it was seen in.

func ProjectOf

func ProjectOf(dir string) *Project

ProjectOf is the project a folder belongs to: the git repository it is in, keyed by its origin remote (host/owner/repo), so every clone and worktree of one repository is one project; a repository with no remote by its main folder; a folder outside any repository by itself. nil for no folder.

type Pruned

type Pruned struct {
	Archived int // candidates set aside
	Removed  int // archived or superseded memories removed
}

Pruned is what one Prune did.

func Prune

func Prune() (Pruned, error)

Prune applies retention now. It writes nothing when nothing is due.

type Query

type Query struct {
	Text   string
	Scopes []string
	Kinds  []string
	Tags   []string
	Status string
	Limit  int
}

Query is what a search asks for. Scopes are the scopes searched (none: every scope), Kinds and Tags narrow it (a memory has one of the kinds and every tag), Status is the state looked in ("": active).

type Report

type Report struct {
	Days  []StatDay `json:"days"`
	Since string    `json:"since,omitempty"`
	// Active and Candidates are the memories in use and to review now
	Active     int `json:"active"`
	Candidates int `json:"candidates"`
	// Used are the memories in use that a search returned within the
	// days asked for
	Used int `json:"used"`
}

Report is the last days of counts, oldest first, today last, and memory as it is now.

func Stats

func Stats(n int) (*Report, error)

Stats is the last n days' counts (1 to keepDays).

type Source

type Source struct {
	Agent   string    `json:"agent,omitempty"`
	Session string    `json:"session,omitempty"`
	Dir     string    `json:"dir,omitempty"`  // the folder the agent worked in
	File    string    `json:"file,omitempty"` // an imported memory's file
	Quote   string    `json:"quote,omitempty"`
	At      time.Time `json:"at"`
}

Source is where a memory was said or found.

type Stale

type Stale struct {
	ID  string
	Why string
}

Stale is a memory to set aside, and why.

type StatDay

type StatDay struct {
	Date string `json:"day"`
	Day
	// Recorded is a day counted (on or after Since); Backfilled one
	// before, whose Created comes from the memory files' dates
	Recorded   bool `json:"recorded"`
	Backfilled bool `json:"backfilled,omitempty"`
}

StatDay is one day of a Report.

type Suggestion

type Suggestion struct {
	Key  string   `json:"key"`  // what Decline takes
	To   string   `json:"to"`   // ToGlobal or ToSkill
	IDs  []string `json:"ids"`  // the memories it is about, the one kept first
	Text string   `json:"text"` // the text kept
	// Projects are the projects' keys a ToGlobal one was learned in
	Projects []string `json:"projects,omitempty"`
	Uses     int      `json:"uses,omitempty"` // a ToSkill one's
}

Suggestion is one thing memory suggests.

func Suggest

func Suggest() ([]Suggestion, error)

Suggest is what memory suggests now, none the user turned down: the project memories that say the same in two or more projects, or one whose sources were in two or more, to make global; and the procedures returned skillUses times or more, not made a skill yet, to make one.

Jump to

Keyboard shortcuts

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