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
- Variables
- func Cosine(left, right map[string]int) float64
- func CosineVec(a, b []float32) float64
- func DedupeContent(content string) (string, int)
- func DefaultKind(content string, metadata map[string]any, tags []string, trigger string) string
- func DefaultPath(id, kind string, now time.Time) string
- func DeriveTitle(content string) string
- func ImportanceScore(tags []string, content string, explicit *float64) float64
- func IsPinned(e *store.MemoryEntry) bool
- func NormalizeItem(item string) string
- func NormalizeTags(tags []string) []string
- func PromptSection(svc *Service) agent.PromptSection
- func PublicProposal(p *store.MemoryProposal) map[string]any
- func RecallContext(items []string) string
- func RecallItems(entries []*store.MemoryEntry, max int) []string
- func RecallSection(svc *Service) agent.PromptSection
- func RecencyScore(ts, now time.Time) float64
- func RedactText(text string) (string, int)
- func RedactValue(v any) (any, int)
- func Snippet(content string) string
- func SplitChunks(content string) []string
- func Tokenize(text string) []string
- type Change
- type Consolidator
- type CreateInput
- type Decision
- type Embedder
- type Entry
- type Error
- type Expect
- type Extractor
- type Hit
- type Layer
- type OpenAIEmbedder
- type Options
- type RankOptions
- type RecallInfo
- type Report
- type Result
- type SearchInput
- type Service
- func (s *Service) Capabilities() Result
- func (s *Service) Confirm(ctx context.Context, login, id string, exp Expect) (*store.MemoryEntry, *Error)
- func (s *Service) Create(ctx context.Context, w Writer, in CreateInput) Result
- func (s *Service) CreateBatch(ctx context.Context, w Writer, entries []CreateInput) Result
- func (s *Service) Delete(ctx context.Context, w Writer, id, path string, metadata map[string]any, ...) Result
- func (s *Service) DeleteBatch(ctx context.Context, w Writer, ids, paths []string) Result
- func (s *Service) DeleteEntry(ctx context.Context, w Writer, target *store.MemoryEntry, ...) Result
- func (s *Service) Enabled(ctx context.Context, login string) (bool, error)
- func (s *Service) Get(ctx context.Context, login, id, path string, includeMetadata bool) Result
- func (s *Service) Key(ctx context.Context, login, threadID string) string
- func (s *Service) Layers(ctx context.Context, login, threadID string) []Layer
- func (s *Service) Options() Options
- func (s *Service) RecallBlock(ctx context.Context, layers []Layer, query string) (string, RecallInfo)
- func (s *Service) Reject(ctx context.Context, login, id string, exp Expect) (*store.MemoryEntry, *Error)
- func (s *Service) Restore(ctx context.Context, login, id string) (*store.MemoryEntry, *Error)
- func (s *Service) Search(ctx context.Context, login string, in SearchInput) Result
- func (s *Service) SearchAll(ctx context.Context, layers []Layer, in SearchInput) Result
- func (s *Service) SharedMemory(ctx context.Context, login, threadID string) bool
- func (s *Service) Stats() Stats
- func (s *Service) Update(ctx context.Context, w Writer, in UpdateInput) Result
- type Stats
- type UpdateInput
- type Writer
Constants ¶
const ( WriteWarn = "warn" WriteStrict = "strict" )
Write modes of the policy: warn records violations, strict blocks them.
const ( DeleteSoft = "soft" DeleteHard = "hard" )
Delete modes: soft keeps the entry as status deleted, hard removes it.
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).
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").
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.
const Redacted = "[REDACTED]"
Redacted replaces secrets in memory content, metadata, tags and queries.
const SearchIndexVersion = 1
SearchIndexVersion is reported with every search result (Work's SEARCH_INDEX_VERSION).
const SnippetChars = 240
SnippetChars bounds a search result snippet.
Variables ¶
var Precedence = []string{"current_user_message", "system_developer_policy", "repo_policy_files", "stored_memory"}
Precedence is the conflict precedence reported with every policy decision.
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).
var SemanticKinds = []string{"decisions", "facts", "constraints", "preferences", "procedures", "notes"}
SemanticKinds are the folders of memories/semantic/ (and shared/memories/semantic/).
Functions ¶
func Cosine ¶
Cosine is the cosine similarity of two bags of words: Work's "simple" embedding backend (term-frequency vectors, no remote embedding model).
func DedupeContent ¶
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 ¶
DefaultKind is Work's _default_semantic_kind: metadata hints (kind, type, category, memory_type), then tags, then the trigger, then the content.
func DefaultPath ¶
DefaultPath is memories/semantic/{kind}/{YYYY-MM-DD}-{id}.md.
func DeriveTitle ¶
DeriveTitle is the first non-empty line of content without markdown marks, whitespace collapsed, at most MaxTitleChars characters.
func ImportanceScore ¶
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 ¶
NormalizeItem is Work's _normalize_entry: no list marker, lowercase, collapsed whitespace, no trailing parenthetical note or punctuation.
func NormalizeTags ¶
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 ¶
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 ¶
RecencyScore is 1 / (1 + age_days / 30).
func RedactText ¶
RedactText replaces secrets in text; it returns the text and the number of replacements.
func RedactValue ¶
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 SplitChunks ¶
SplitChunks is Work's _split_memory_content: paragraphs and list items, headings dropped.
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.
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.
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 ¶
Error is a structured memory error ({"error": {code, message, details}}).
func NormalizePath ¶
NormalizePath applies Work's _normalize_relative_path: a relative path without "..", not under proxy/ (the root prefix .har/memory/ is stripped).
type Expect ¶
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.
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 ¶
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) 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 ¶
SemanticAvailable is false for the keyword-only backends (Work: disabled, none, keyword).
type RankOptions ¶
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 ¶
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 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
// 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 (*Service) Capabilities ¶
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 ¶
Create writes a new entry (Work's MemoryStore.create); after untrusted content it is pending.
func (*Service) CreateBatch ¶
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 ¶
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) 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) SearchAll ¶
SearchAll searches several layers (the shared memory and the user's own) and merges the results by score.
func (*Service) SharedMemory ¶
SharedMemory reports whether the run's primary memory is shared between people.
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).
Source Files
¶
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. |