memory

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 27 Imported by: ? 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 the harness's memory service: per-user entries with a path, title, content, tags, importance and metadata, searched with Work's hybrid ranking, written under Work's policy (triggers, warn/strict write mode, secret redaction, soft/hard delete), recalled in the system prompt and consolidated periodically (deduplication, cleanup of deleted entries).

Index

Constants

View Source
const (
	WriteWarn   = "warn"
	WriteStrict = "strict"
)

Write modes of the policy: warn records violations, strict blocks them.

View Source
const (
	DeleteSoft = "soft"
	DeleteHard = "hard"
)

Delete modes: soft keeps the entry as status deleted, hard removes it.

View Source
const (
	// PinnedBudget bounds the always-on block: pinned entries are in every run of the memory.
	PinnedBudget = 2500
	// PinnedEntryMax bounds one pinned entry in that block (the rest is one memory_get away).
	PinnedEntryMax = 1200
	// RelevantItems is how many query-matched entries are recalled.
	RelevantItems = 6
	// MinRelevance is the least hybrid score of a recalled entry.
	MinRelevance = 0.12
	// MaxRecallTotal bounds the whole block.
	MaxRecallTotal = 6500
)

Recall budgets (characters).

View Source
const (
	MaxTopK                = 50
	DefaultTopK            = 5
	DefaultMaxContentBytes = 200_000
	DefaultMaxEntries      = 1000
	// DefaultMaxPending caps the entries waiting for confirmation apart from
	// MaxEntries, so the agent's proposals cannot fill the memory.
	DefaultMaxPending = 100
	MaxBatch          = 100
	MaxTags           = 50
	MaxTagChars       = 100
	MaxTitleChars     = 200
	MaxPathChars      = 512
	MaxRecallItems    = 4
)

Limits. Work bounds top_k to 1..50 and a memory file to 200 000 bytes (DEVFACTORY_MAX_ARTIFACT_CONTENT_BYTES); it has no entry count, tag or batch limits, which a shared Postgres store needs (see README "Memory").

View Source
const MaxRecallChars = 4000

MaxRecallChars bounds the whole recall block (heading and fences included): MaxRecallItems lines of at most a 512-char path plus a SnippetChars line fit.

View Source
const Redacted = "[REDACTED]"

Redacted replaces secrets in memory content, metadata, tags and queries.

View Source
const SearchIndexVersion = 1

SearchIndexVersion is reported with every search result (Work's SEARCH_INDEX_VERSION).

View Source
const SnippetChars = 240

SnippetChars bounds a search result snippet.

Variables

View Source
var Precedence = []string{"current_user_message", "system_developer_policy", "repo_policy_files", "stored_memory"}

Precedence is the conflict precedence reported with every policy decision.

View Source
var PriorityRecallPaths = []string{
	"shared/memories/semantic/decisions.md",
	"shared/memories/semantic/facts.md",
	"shared/memories/semantic/constraints.md",
	"memories/semantic/decisions.md",
	"memories/semantic/facts.md",
	"memories/semantic/constraints.md",
}

PriorityRecallPaths are recalled first (Work's PRIORITY_RECALL_PATHS).

View Source
var SemanticKinds = []string{"decisions", "facts", "constraints", "preferences", "procedures", "notes"}

SemanticKinds are the folders of memories/semantic/ (and shared/memories/semantic/).

Functions

func Cosine

func Cosine(left, right map[string]int) float64

Cosine is the cosine similarity of two bags of words: Work's "simple" embedding backend (term-frequency vectors, no remote embedding model).

func CosineVec

func CosineVec(a, b []float32) float64

CosineVec is the cosine of two vectors (0 when their sizes differ).

func DedupeContent

func DedupeContent(content string) (string, int)

DedupeContent removes the duplicate list items of a markdown file (Work's _find_duplicates: same text without the marker, or same normalized text), keeping the first; only the removed items' lines go (blank lines, headers, paragraphs and fenced code blocks are kept as they are). It returns the content and the count removed.

func DefaultKind

func DefaultKind(content string, metadata map[string]any, tags []string, trigger string) string

DefaultKind is Work's _default_semantic_kind: metadata hints (kind, type, category, memory_type), then tags, then the trigger, then the content.

func DefaultPath

func DefaultPath(id, kind string, now time.Time) string

DefaultPath is memories/semantic/{kind}/{YYYY-MM-DD}-{id}.md.

func DeriveTitle

func DeriveTitle(content string) string

DeriveTitle is the first non-empty line of content without markdown marks, whitespace collapsed, at most MaxTitleChars characters.

func ImportanceScore

func ImportanceScore(tags []string, content string, explicit *float64) float64

ImportanceScore is Work's _importance_score from tags and content, unless the entry has an explicit importance (set by the user or metadata.importance).

func IsPinned

func IsPinned(e *store.MemoryEntry) bool

IsPinned reports an entry that is recalled in every run: metadata pinned=true, or the tag "pinned".

func NormalizeItem

func NormalizeItem(item string) string

NormalizeItem is Work's _normalize_entry: no list marker, lowercase, collapsed whitespace, no trailing parenthetical note or punctuation.

func NormalizeTags

func NormalizeTags(tags []string) []string

NormalizeTags trims, redacts and de-duplicates (case-insensitively) tags.

func PromptSection

func PromptSection(svc *Service) agent.PromptSection

PromptSection adds the memory policy (prompts.MemoryPolicy) when the user's memory is enabled; the recalled entries go to the dynamic context (RecallSection). Pending and deleted entries are never recalled.

func PublicProposal

func PublicProposal(p *store.MemoryProposal) map[string]any

PublicProposal is the "proposal" object of a proposed memory_update.

func RecallContext

func RecallContext(items []string) string

RecallContext renders recall items fenced as <user_memories>, dropping the items that would make it longer than MaxRecallChars ("" without items).

func RecallItems

func RecallItems(entries []*store.MemoryEntry, max int) []string

RecallItems is Work's collect_recall_items without a query: the lines of the priority files, then of the typed semantic entries, most recently updated first, as "path: line" (at most max).

func RecallSection

func RecallSection(svc *Service) agent.PromptSection

RecallSection is the dynamic-context part of memory: the recalled active entries fenced as <user_memories> data.

func RecencyScore

func RecencyScore(ts, now time.Time) float64

RecencyScore is 1 / (1 + age_days / 30).

func RedactText

func RedactText(text string) (string, int)

RedactText replaces secrets in text; it returns the text and the number of replacements.

func RedactValue

func RedactValue(v any) (any, int)

RedactValue redacts every string of a JSON-like value and the values of sensitive keys (password, token, *_secret…); it returns the count of replacements.

func Snippet

func Snippet(content string) string

Snippet collapses whitespace and cuts at SnippetChars ("..." appended).

func SplitChunks

func SplitChunks(content string) []string

SplitChunks is Work's _split_memory_content: paragraphs and list items, headings dropped.

func Tokenize

func Tokenize(text string) []string

Tokenize is Work's _tokenize: ASCII words (with _ . / : -), lowercased.

Types

type Change

type Change struct {
	// Action is created, updated, proposed (written pending) or deleted.
	Action string
	Entry  *store.MemoryEntry
	Mode   string
	// Proposed marks a delete made after untrusted content: soft, the user can undo it (restore).
	Proposed bool
}

Change is one mutation, announced with work.memory.

type Consolidator

type Consolidator struct {
	Store store.MemoryStore
	// Retention: soft-deleted entries are purged this long after deletion (≤ 0: never).
	Retention time.Duration
	Now       func() time.Time
}

Consolidator is the periodic memory job.

func (Consolidator) Consolidate

func (c Consolidator) Consolidate(ctx context.Context) (Report, error)

Consolidate deduplicates every user's semantic memory, then purges old deleted entries.

func (Consolidator) Run

func (c Consolidator) Run(ctx context.Context) error

Run implements the runtime job.

type CreateInput

type CreateInput struct {
	Content    string
	Metadata   map[string]any
	Tags       []string
	Scope      string
	Repository string
	Path       string
	Title      *string
	Importance *float64
}

CreateInput are the memory_create arguments (Title and Importance: Settings > Memory).

type Decision

type Decision struct {
	Allowed          bool
	Trigger          string
	WriteMode        string
	Violations       []string
	Warnings         []string
	RedactedContent  string
	RedactedMetadata map[string]any
}

Decision is the outcome of the write policy for one mutation.

func Evaluate

func Evaluate(writeMode, action, content string, metadata map[string]any) Decision

Evaluate applies Work's MemoryPolicyEngine: redaction of content and metadata, trigger resolution (create/update need one, delete needs a revocation, contradiction or stale correction) and, in strict mode, blocking.

func (Decision) Payload

func (d Decision) Payload() map[string]any

Payload is the "policy" object of the tool results.

type Embedder

type Embedder interface {
	// Model names the embedding model; vectors of another model are recomputed.
	Model() string
	Embed(ctx context.Context, texts []string) ([][]float32, error)
}

Embedder turns texts into vectors. With one, search and recall compare the meaning of a query with the entries, not only their words.

type Entry

type Entry struct {
	CreatedAt          *string        `json:"created_at"`
	EmbeddingUpdatedAt *string        `json:"embedding_updated_at"`
	ID                 string         `json:"id"`
	Importance         *float64       `json:"importance"`
	Metadata           map[string]any `json:"metadata"`
	Path               string         `json:"path"`
	Repository         string         `json:"repository"`
	Scope              string         `json:"scope"`
	Source             string         `json:"source"`
	Status             string         `json:"status"`
	Tags               []string       `json:"tags"`
	Title              string         `json:"title"`
	UpdatedAt          *string        `json:"updated_at"`
}

Entry is the "memory" object of the tool results and the base of the memory pages' entries (Work's _entry_public_payload plus title, status and importance). The fields are declared in the alphabetical order of their JSON names: that is the order the map this type replaced was encoded in, so the bytes are unchanged.

func PublicEntry

func PublicEntry(e *store.MemoryEntry) Entry

PublicEntry is e as its "memory" object.

type Error

type Error struct {
	Code    string
	Message string
	Details map[string]any
}

Error is a structured memory error ({"error": {code, message, details}}).

func NormalizePath

func NormalizePath(raw string) (string, *Error)

NormalizePath applies Work's _normalize_relative_path: a relative path without "..", not under proxy/ (the root prefix .har/memory/ is stripped).

func (*Error) Error

func (e *Error) Error() string

func (*Error) Payload

func (e *Error) Payload() map[string]any

Payload is the error object of the tool results.

type Expect

type Expect struct {
	ContentHash string
	Pending     bool
}

Expect is what the user saw when they keep or discard a proposal: the content hash shown (the proposal's, or the pending entry's) and whether a proposal must still be waiting (the chat note's Keep / Discard).

type Extractor

type Extractor struct {
	Svc               *Service
	Models            llm.Factory
	SupportsReasoning func(model string) bool
	// contains filtered or unexported fields
}

Extractor is a runtime.Hook that proposes memories after a run.

func (*Extractor) Finishing

func (x *Extractor) Finishing(ctx context.Context, f *runtime.Finish) func(context.Context)

Finishing implements runtime.Hook. The work happens in the background: the run does not wait for it.

type Hit

type Hit struct {
	Entry      *store.MemoryEntry
	ChunkID    string
	Chunk      string
	Score      float64
	Components map[string]float64
}

Hit is one ranked chunk of a search.

func Rank

func Rank(entries []*store.MemoryEntry, query string, topK int, now time.Time) []Hit

Rank scores every chunk of entries against query with Work's hybrid formula (0.45 keyword + 0.25 cosine + 0.15 path/tag + 0.10 importance + 0.05 recency) and returns the topK best (ties: most recent first).

func RankWith

func RankWith(entries []*store.MemoryEntry, query string, topK int, now time.Time, opts RankOptions) []Hit

RankWith is Rank with options.

type Layer

type Layer struct {
	Key  string
	Name string // "project", "user" (personal thread) or "me" (the user's layer inside a project)
}

Layer is one memory a run sees: the shared or personal one (Key), or the user's own inside a project.

type OpenAIEmbedder

type OpenAIEmbedder struct {
	BaseURL   string // default https://api.openai.com/v1
	APIKey    string
	ModelName string // default text-embedding-3-small
	HTTP      *http.Client
}

OpenAIEmbedder calls an OpenAI-compatible /embeddings endpoint.

func (*OpenAIEmbedder) Embed

func (e *OpenAIEmbedder) Embed(ctx context.Context, texts []string) ([][]float32, error)

Embed returns unit-length vectors (so a dot product is the cosine).

func (*OpenAIEmbedder) Model

func (e *OpenAIEmbedder) Model() string

type Options

type Options struct {
	WriteMode        string
	DeleteMode       string
	DefaultScope     string
	EmbeddingBackend string
	MaxEntries       int
	// MaxPending caps the pending entries (0: DefaultMaxPending, < 0: no limit).
	MaxPending      int
	MaxContentBytes int
	// RecallInjection adds the "[Repository Memory Recall]" block to the system prompt.
	RecallInjection bool
	Now             func() time.Time
	// Embedder, when set, gives entries and queries vectors: search and recall then rank by meaning
	// as well as by words (HARNESS_MEMORY_EMBEDDING_BACKEND=openai).
	Embedder Embedder
	// Extract turns on the end-of-run extraction of memories from the conversation; ExtractModel
	// is the model it uses (default: the run's own).
	Extract      bool
	ExtractModel string
}

Options configure the service (HARNESS_MEMORY_*, see config.Memory).

func (Options) SemanticAvailable

func (o Options) SemanticAvailable() bool

SemanticAvailable is false for the keyword-only backends (Work: disabled, none, keyword).

type RankOptions

type RankOptions struct {
	QueryVec []float32
	Vecs     map[string][]float32
}

RankOptions add embeddings to Rank: the query's vector and the entries' by id. An entry with a vector gets the embedding similarity as its semantic component instead of the word cosine.

type RecallInfo

type RecallInfo struct {
	Pinned   []string // entry ids
	Relevant []string
	Fallback bool
	Chars    int
}

RecallInfo says what a recall contained (stats, tests, the UI).

type Report

type Report struct {
	Users int
	// Processed counts the semantic entries checked, ItemsRemoved the duplicate
	// lines removed inside them, Duplicates the entries soft-deleted as copies
	// of an older one, Skipped the entries changed (or deleted) since they were
	// listed (left as they are), Purged the soft-deleted entries past the retention.
	Processed    int
	ItemsRemoved int
	Duplicates   int
	Skipped      int
	Purged       int
}

Report is the outcome of one consolidation.

type Result

type Result struct {
	Data    map[string]any
	IsError bool
	Changes []Change
}

Result is the outcome of a tool operation.

type SearchInput

type SearchInput struct {
	Query      string
	Scope      string
	Repository string
	TopK       int
	Filters    map[string]any
}

SearchInput are the memory_search arguments.

type Service

type Service struct {

	// KeyFor, when set, names the memory a run reads and writes: the login by
	// default, or another key (a team host maps a project thread to the
	// project's memory, so what is learned there is shared by its members and
	// no member's personal memory leaks into a shared thread).
	KeyFor func(ctx context.Context, login, threadID string) string
	// UserKeyFor, when set, names a second, private layer of the same run: what the acting user keeps
	// for themselves inside a shared (project) memory ("" for none).
	UserKeyFor func(ctx context.Context, login, threadID string) string
	// Shared reports whether a memory key is shared between people (a project's), which selects the
	// project memory policy in the prompt.
	Shared func(key string) bool
	// Messages reads a thread's messages (recall uses the last user message as its query; extraction
	// reads the run).
	Messages func(ctx context.Context, threadID string) ([]*store.Message, error)
	// contains filtered or unexported fields
}

Service implements the memory operations on a store.

func New

func New(st store.MemoryStore, o Options) *Service

New returns the service.

func (*Service) Capabilities

func (s *Service) Capabilities() Result

Capabilities is the memory_capabilities result.

func (*Service) Confirm

func (s *Service) Confirm(ctx context.Context, login, id string, exp Expect) (*store.MemoryEntry, *Error)

Confirm keeps what the agent proposed: a pending entry becomes active, the proposal of an active entry is applied. Without anything waiting it returns the entry unchanged, unless exp.Pending (memory_not_pending).

func (*Service) Create

func (s *Service) Create(ctx context.Context, w Writer, in CreateInput) Result

Create writes a new entry (Work's MemoryStore.create); after untrusted content it is pending.

func (*Service) CreateBatch

func (s *Service) CreateBatch(ctx context.Context, w Writer, entries []CreateInput) Result

CreateBatch creates several entries (Work's create_batch): per-entry errors with their index.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, w Writer, id, path string, metadata map[string]any, mode string) Result

Delete removes an entry (Work's MemoryStore.delete) with the configured delete mode, or mode when set (Settings > Memory deletes permanently).

func (*Service) DeleteBatch

func (s *Service) DeleteBatch(ctx context.Context, w Writer, ids, paths []string) Result

DeleteBatch deletes entries by ids, then by paths (Work's delete_batch, reason batch_delete).

func (*Service) DeleteEntry

func (s *Service) DeleteEntry(ctx context.Context, w Writer, target *store.MemoryEntry, metadata map[string]any, mode string) Result

DeleteEntry is Delete of an entry already read: it fails with memory_conflict when the entry changed since (its status for a hard delete, its version for a soft one).

func (*Service) Enabled

func (s *Service) Enabled(ctx context.Context, login string) (bool, error)

Enabled is the user's memory setting.

func (*Service) Get

func (s *Service) Get(ctx context.Context, login, id, path string, includeMetadata bool) Result

Get returns one entry with its content (Work's MemoryStore.get).

func (*Service) Key

func (s *Service) Key(ctx context.Context, login, threadID string) string

Key is the memory key of a run of login on threadID.

func (*Service) Layers

func (s *Service) Layers(ctx context.Context, login, threadID string) []Layer

Layers lists the memories of a run, the primary one first.

func (*Service) Options

func (s *Service) Options() Options

Options returns the normalized options.

func (*Service) RecallBlock

func (s *Service) RecallBlock(ctx context.Context, layers []Layer, query string) (string, RecallInfo)

RecallBlock builds the memory the run starts with: the pinned entries of every layer, then the entries that match the query (the user's last message) by words and, with an embedder, meaning; with no query hit it falls back to the most recent decisions, facts and constraints. "" when empty.

func (*Service) Reject

func (s *Service) Reject(ctx context.Context, login, id string, exp Expect) (*store.MemoryEntry, *Error)

Reject discards what the agent proposed: the proposal of an active entry is dropped (the confirmed entry stays as it is), a pending entry is deleted (it was never confirmed). Nothing waiting: memory_not_pending. It returns the entry kept (nil when deleted).

func (*Service) Restore

func (s *Service) Restore(ctx context.Context, login, id string) (*store.MemoryEntry, *Error)

Restore makes a soft-deleted entry active again.

func (*Service) Search

func (s *Service) Search(ctx context.Context, login string, in SearchInput) Result

Search ranks the user's active entries (Work's MemoryStore.search).

func (*Service) SearchAll

func (s *Service) SearchAll(ctx context.Context, layers []Layer, in SearchInput) Result

SearchAll searches several layers (the shared memory and the user's own) and merges the results by score.

func (*Service) SharedMemory

func (s *Service) SharedMemory(ctx context.Context, login, threadID string) bool

SharedMemory reports whether the run's primary memory is shared between people.

func (*Service) Stats

func (s *Service) Stats() Stats

Stats returns the counters.

func (*Service) Update

func (s *Service) Update(ctx context.Context, w Writer, in UpdateInput) Result

Update changes an entry (Work's MemoryStore.update); after untrusted content the changed entry becomes pending until the user confirms it.

type Stats

type Stats struct {
	RecallRuns      int64 `json:"recallRuns"`
	RecallItems     int64 `json:"recallItems"`
	RecallChars     int64 `json:"recallChars"`
	RecallPinned    int64 `json:"recallPinned"`
	Searches        int64 `json:"searches"`
	SearchHits      int64 `json:"searchHits"`
	ExtractRuns     int64 `json:"extractRuns"`
	ExtractProposed int64 `json:"extractProposed"`
	ExtractSkipped  int64 `json:"extractSkipped"`
	ExtractErrors   int64 `json:"extractErrors"`
	Embedded        int64 `json:"embedded"`
	EmbedErrors     int64 `json:"embedErrors"`
}

Stats is a snapshot of the counters (since the process started).

type UpdateInput

type UpdateInput struct {
	ID       string
	Path     string
	Content  *string
	Metadata map[string]any
	// Tags replace the entry's tags when not nil.
	Tags            *[]string
	Title           *string
	Importance      *float64
	ClearImportance bool
	NewPath         *string
}

UpdateInput are the memory_update arguments (Title, Importance, NewPath: Settings > Memory).

type Writer

type Writer struct {
	Login     string
	ThreadID  string
	Source    string
	Untrusted bool
}

Writer is who writes: the agent of a run (Source proxy) or the user in Settings > Memory (Source user). Untrusted makes every write a proposal.

Directories

Path Synopsis
Package memorytools exposes Work's memory MCP tools (memory_search, memory_get, memory_create, memory_update, memory_delete, memory_create_batch, memory_delete_batch, memory_capabilities) with the same names, input schemas and result shapes, backed by memory.Service.
Package memorytools exposes Work's memory MCP tools (memory_search, memory_get, memory_create, memory_update, memory_delete, memory_create_batch, memory_delete_batch, memory_capabilities) with the same names, input schemas and result shapes, backed by memory.Service.

Jump to

Keyboard shortcuts

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