recall

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 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.

README

Recall

Give your agent memory it can correct and explain.

“I use vim.” → “Actually, I use neovim.” → Recall remembers neovim and can show when it changed. Start a new session and the memory is still there.

Try it in Claude Code

Install Polign v0.6.4+ and start a durable local server. No embedding API key or model download is needed:

polign-server -store fs:./recall-data

Then in Claude Code:

/plugin marketplace add Polign/polign
/plugin install recall@polign

Restart Claude Code, ask it to remember your preferred editor, then correct it in a new session. Ask “What did you remember before the correction?”

The plugin uses polign mcp -memory-only -write. It comes with 15 predicates for preferences, identity, and project facts. Your existing agent extracts facts; the registry validates them; Recall decides what is currently believed. Plugin setup.

Use it from Python

From this checkout, with Python 3.10+ and polign on PATH:

pip install ./python
from polign_recall import Client

with Client() as memory:
    memory.remember("user", "prefers_editor", "vim")
    memory.remember("user", "prefers_editor", "neovim")
    print(memory.recall("user", "prefers_editor")[0].value)  # neovim
    print(memory.history("user", "prefers_editor"))  # the complete history

Python client · Cross-session example

Free text, without a second model

The calling agent proposes facts from the text and sends one remember call:

{
  "text": "I prefer neovim now.",
  "statements": [{
    "subject": "user",
    "predicate": "prefers_editor",
    "value": "neovim",
    "evidence": "I prefer neovim now."
  }]
}

Recall checks the predicate, typed value, subject, and verbatim evidence before writing. An invalid proposal rejects the whole batch before any write. Storage failures can leave a completed prefix, reported in the error. Extracted facts are marked agent_inferred with a default confidence of 0.8; this is a convention, not a calibrated model probability. The evidence quote is returned with the proposal; it is not stored in the durable event metadata. Validation cannot prove that an extracted statement is true. Typed remember also remains available.

The default search uses local lexical word overlap, not semantic synonyms. Set -embed-url with a dedicated collection to use model embeddings instead. Never mix embedding spaces in one collection. Exact subject/predicate reads work without semantic search.

Go library

Recall is the memory layer for Polign and can use any backend implementing three operations. The library has no external dependencies.

go get github.com/Polign/recall@v0.3.0

Use recall.DefaultRegistry() and recall.LexicalEmbedder{} to start without writing a schema or running an embedding service. Add Materialize: true to cache folded beliefs against a backend log watermark. Repeated exact reads then skip unchanged history. Materialization contract.

What it does differently

Most "AI memory" puts text in a vector store and hopes similarity search finds it again. Recall treats memory as what it actually is: state, with rules.

Every memory is a typed record. Predicates come from a closed registry that declares each one's cardinality and value type. An agent cannot invent editor_preference alongside prefers_editor and split one fact across two names that never meet.

kind:        preference
subject:     user
predicate:   prefers_editor
value:       neovim
confidence:  1.0
source:      user_stated
observed_at: 2026-09-12T04:31:07.000000000Z

Supersession is deterministic. A single-valued predicate holds one value: a newer statement replaces an older one. A multi-valued predicate accumulates. Which happens is decided by the registry, never by model judgment.

Beliefs are derived, never mutated. The log is the truth, and Fold is the only thing that reads it. Nothing is rewritten when a belief changes, so no crash between two writes can leave an agent believing two contradictory things at once.

History is queryable. Forgetting is a retraction event, not a deletion, so asking what the agent believed last Tuesday still works after Wednesday's correction. With a value supplied, a retraction withdraws only that value, including for single-valued predicates: vim → emacs → retract vim still leaves emacs believed. With no value it clears the pair. Retracting the current value never revives one that was superseded.

Using it

registry := recall.DefaultRegistry()
store := recall.NewStore(db, "memories", registry, embed)

store.Remember("preference", "user", "prefers_editor", "neovim", 1.0, "user_stated")

// What is believed now.
beliefs, err := store.Recall(recall.Query{Subject: "user", Predicate: "prefers_editor"})

// What was believed on Tuesday. Same call, one more field.
beliefs, err = store.Recall(recall.Query{
    Subject:   "user",
    Predicate: "prefers_editor",
    AsOf:      tuesday,
})

// Semantic recall, folded like every other read, so a superseded statement
// ranking top of the search still cannot come back as a live belief.
beliefs, err = store.Recall(recall.Query{Text: "which editor do I use"})

// Every event behind a belief, oldest first: the audit trail.
events, err := store.History("user", "prefers_editor")

Remember writes at most one record, and only after folding what is already there. Restating a belief that already holds writes nothing at all.

Context-aware client

NewClient(Config) adds context-aware operations while NewStore and its existing method signatures remain available. A Backend implements Put, List, and Search with a context.Context; an Embedder returns both vectors and an error. EmbedFunc adapts a function. Errors preserve errors.Is/errors.As, and failed or cancelled embeddings cannot fall through to a write or vector search.

client, err := recall.NewClient(recall.Config{
    Backend: backend,
    Collection: "memories",
    Registry: registry,
    Embedder: recall.EmbedFunc(embedWithContext),
})
if err != nil { return err }

result, err := client.Remember(ctx, recall.RememberRequest{
    Subject: "user", Predicate: "prefers_editor", Value: "vim",
})
beliefs, err := client.Recall(ctx, recall.Query{Subject: "user"})
withdrawn, err := client.Forget(ctx, recall.ForgetRequest{
    Subject: "user", Predicate: "prefers_editor", Value: "vim",
})

Typed values are strings, float64 numbers, or booleans. ForgetRequest requires exactly one value or All: true; false and zero are real values, and an omitted value does not clear the pair. Remember defaults to kind fact, source user_stated, and confidence 1. Set its optional confidence pointer to record an explicit zero. Exact reads, history, and exports work without an embedder.

Client configuration is validated and its registry is copied. Both Client and legacy Store return a registry copy, so callers cannot mutate their configuration through Registry(). Backends and embedders must support concurrent calls and honor context cancellation. Each operation has independent request state; this does not add cross-writer serialization or a database-wide read snapshot.

Polign HTTP adapter

The github.com/Polign/recall/polign package implements Backend using the standard library. It preserves typed metadata and retrieves exact listings across the server's 1,000-row page limit.

backend, err := polign.New(polign.Config{
    BaseURL: "http://localhost:8080",
    APIKey: os.Getenv("POLIGN_API_KEY"),
})
if err != nil { return err }
client, err := recall.NewClient(recall.Config{
    Backend: backend,
    Collection: "memories",
    Registry: registry,
    Embedder: recall.EmbedFunc(embedWithContext),
})
if err != nil { return err }

The API key is sent as a bearer token on every request; namespaced credentials use the server's namespace isolation. Context cancellation reaches each HTTP request, including later listing pages. Failed or inconsistent pages return an error with no partial history. Pagination detects changing totals and repeated or reordered IDs, but does not establish a snapshot across concurrent writes.

The default HTTP client has a 30-second timeout and does not follow redirects. Set HTTPClient to supply your own timeout and redirect policy. Responses are bounded at 64 MiB per request; increase MaxResponseBytes for large vectors. HTTP failures expose *polign.StatusError through errors.As. Writes are not automatically retried.

The session example runs remember, correction, as-of reads, and forgetting in separate processes, with instructions for a server restart. It uses fixture vectors for exact reads and needs no embedding service. Cold persistence and restart require Polign v0.6.4+, containing polign_db #99. The v0.6.3 server predates that support.

Input and stored-event validation

Queries return at most MaxRecall (1,000) beliefs and exports read at most MaxExport (10,000) events, including explicitly limited exports. Larger limits return errors before any backend call. Zero or negative limits retain their default behavior. Numeric values, confidence, and query ranges must be finite; confidence must be in [0, 1], and a range minimum cannot exceed its maximum.

Store reads validate event IDs, timestamps, typed fields, and the value type of known predicates. Corrupt histories return ErrIncompleteHistory wrapping ErrInvalidEvent, so a malformed correction or retraction cannot revive an old belief or authorize a write. Candidate reads and limited exports also reject invalid events. Legacy assertions without a retraction field, RFC3339 timestamps, and records without observed_ms remain readable. DecodeEvent exposes this strict decoder; EventFromMetadata retains its permissive behavior for existing callers.

Complete histories

The VectorDB.List implementation must return exact matches and their total count, paging internally if its backend caps page size. Recall checks that it has the complete subject-and-predicate log before deriving a belief or writing a correction or retraction. A partial listing returns ErrIncompleteHistory. Approximate vector search cannot replace this listing: a missed correction or retraction would change the answer.

Histories are bounded at MaxHistoryEvents (10,000 events per subject and predicate). New events are refused at that bound; existing complete histories remain readable. A default export likewise fails if it cannot return the complete log within MaxExport. An explicit export limit requests a subset.

With Polign, use a collection that supports exact vector listings. A cold-served collection without a complete listing index returns an error for memory operations, including semantic recall when it resolves candidate histories.

Broad exact queries

A query with only a subject, only a predicate, or neither keeps widening exact candidate discovery until it fills the requested belief limit or exhausts the matching events. Withdrawn pairs and beliefs excluded by kind, confidence, time, or numeric range do not hide later matching pairs. Each discovered pair still requires its complete history.

Discovery is bounded at MaxCandidateEvents (10,000 candidate events). If that budget cannot fill the requested limit or prove the candidate set exhausted, Recall returns ErrIncompleteCandidates with no partial answer. Narrowing to a specific subject and predicate bypasses broad discovery. Semantic retrieval remains approximate; its candidate budget is not an exhaustive listing.

VectorDB.List must extend the same ordered prefix when its limit grows and the data is unchanged. Changing totals, reordered or overwritten prefixes, duplicate IDs, and short pages fail explicitly. This detects inconsistent discovery reads; it does not provide a database-wide snapshot across separate history reads.

Audit bundles

client.ExportAudit(ctx, request) captures complete histories with their registry, fold version, and fixed as-of time. bundle.Replay() verifies the checksum and reproduces exact beliefs offline. The recall-audit command verifies JSON bundles from stdin.

DigestV2 detects changes to exact typed values, including string case, while Digest and VerifyDigest preserve legacy checksum compatibility. See the audit format and concurrency contract for usage, canonical encoding, and the limits of replay and retries.

The registry

{
  "prefers_editor": {
    "cardinality": "single",
    "value_type": "string",
    "description": "the editor the user works in"
  },
  "likes": {
    "cardinality": "multi",
    "value_type": "string",
    "description": "things the user likes"
  }
}

cardinality is single or multi. value_type is string, number, or boolean, and values are stored with that type, so a number compares numerically in a filter instead of lexically.

Registry.PromptTable() renders the registry for an agent's system prompt.

Embeddings

Recall does not embed anything itself. Pass an Embedder to NewClient, or an embed func(string) []float32 to legacy NewStore. Whatever produced the stored vectors has to produce the query vectors too.

License

Apache 2.0. See LICENSE.

Documentation

Overview

Package recall is the typed agent-memory layer: a closed registry of predicates, an append-only event log per subject, and the fold that turns that log into what the agent believes, now or at any past instant.

The central decision is that a belief is derived, never mutated. An earlier design flipped a record's status to "superseded" in a second write after storing its replacement, which left two live beliefs for a single-valued predicate whenever a process died between the two. Here the log is the truth and Fold deterministically interprets the events visible to a reader. This does not serialize concurrent writers or establish a read snapshot. Current and historical beliefs use the same fold with a different ceiling.

Retraction is likewise an event, not a deletion. Forgetting a fact on Wednesday must not change what the agent believed on Tuesday, and a log that erases its own history cannot answer that.

Index

Constants

View Source
const (
	// AuditVersion identifies the bundle envelope and its canonical checksum.
	AuditVersion = "recall-audit-v1"
	// EventVersion identifies the typed Event fields recorded in a bundle.
	EventVersion = "recall-event-v1"
	// FoldVersion identifies observation-time ordering and the current single
	// and multi-value fold rules. Incompatible changes need a new replay path.
	FoldVersion = "recall-fold-v1"
)
View Source
const LexicalSpace = "recall-lexical-v1-256"
View Source
const MaxCandidateEvents = 10000

MaxCandidateEvents bounds event discovery for broad exact queries. A query for one explicit subject/predicate uses MaxHistoryEvents instead.

View Source
const MaxExport = 10000

MaxExport bounds an unbounded export, so that asking for everything cannot turn into an unbounded scan by accident.

View Source
const MaxHistoryEvents = 10000

MaxHistoryEvents bounds a complete subject-and-predicate history. Histories beyond this bound fail explicitly; a partial fold could revive a retraction.

View Source
const MaxRecall = 1000

MaxRecall bounds the number of beliefs a query can request. Candidate discovery and result allocations are bounded independently of caller input.

Variables

View Source
var (
	// ErrInvalidAudit marks unsupported versions or invalid bundle inputs.
	ErrInvalidAudit = errors.New("recall: invalid audit bundle")
	// ErrDigestMismatch means validated content differs from its checksum.
	ErrDigestMismatch = errors.New("recall: digest mismatch")
)
View Source
var ErrEmbedderRequired = errors.New("recall: an embedder is required for this operation")

ErrEmbedderRequired means an operation needs vectors but no embedder was configured.

View Source
var ErrIncompleteCandidates = errors.New("recall: complete exact candidate discovery unavailable")

ErrIncompleteCandidates means a broad exact query could not discover enough matching beliefs or prove it exhausted the candidate set. No partial answer is returned; callers can narrow the query to an explicit subject/predicate.

View Source
var ErrIncompleteHistory = errors.New("recall: complete exact history unavailable")

ErrIncompleteHistory means the backend could not supply a complete exact log. No belief or write may be derived from such a log.

View Source
var ErrInvalidEvent = errors.New("recall: invalid stored event")

ErrInvalidEvent means a stored record cannot safely participate in a fold.

View Source
var ErrWatermarkUnsupported = errors.New("recall: backend does not support watermarks")

Functions

func Digest added in v0.2.0

func Digest(events []Event) string

Digest is the legacy stable checksum over a log. It uses case-insensitive value identity, so it does not detect changes only to string capitalization. Use DigestV2 for exact typed values or ExportAudit for reproducible bundles.

A separately trusted digest lets two parties compare logs without exchanging them. A checksum alone does not authenticate an exporter or prove completeness. The input is each event's canonical fields in a fixed order, so the digest depends on the content of the log and not on how it was serialised, paged, or which node answered.

func DigestV2 added in v0.3.0

func DigestV2(events []Event) (string, error)

DigestV2 hashes exact typed event fields, including case-sensitive strings and the IEEE-754 bits of finite numbers (so -0 and +0 differ). Instants are canonical UTC timestamps. It rejects invalid events and duplicate IDs. Digest remains the legacy, case-insensitive checksum for existing exports.

func SortEvents added in v0.2.0

func SortEvents(events []Event)

SortEvents orders a log oldest first, breaking ties on id so that two exports of the same events are byte-identical.

func ValueKey

func ValueKey(v any) string

ValueKey renders a value in the canonical form used to tell two values apart. Strings fold case, so "Neovim" stated twice with different capitals is one belief rather than two; the event keeps whatever form was written, and only identity is case-insensitive. Numbers render without exponent drift so that 8000 and 8000.0 are one value rather than two.

func VerifyDigest added in v0.3.0

func VerifyDigest(events []Event, expected string) error

VerifyDigest verifies either a legacy sha256: digest or a sha256:v2: digest. Legacy verification intentionally retains its original identity semantics.

Types

type AuditBundle added in v0.3.0

type AuditBundle struct {
	Version      string     `json:"version"`
	EventVersion string     `json:"event_version"`
	FoldVersion  string     `json:"fold_version"`
	Scope        AuditScope `json:"scope"`
	AsOf         time.Time  `json:"as_of"`
	Registry     Registry   `json:"registry"`
	Events       []Event    `json:"events"`
	Digest       string     `json:"digest"`
}

AuditBundle records the inputs needed to reproduce exact beliefs offline. The digest covers every field except Digest itself, independent of event or registry iteration order. It is a checksum, not a signature or proof that the exporter supplied every event. Retain its digest through a trusted channel.

func (AuditBundle) Replay added in v0.3.0

func (b AuditBundle) Replay() ([]Belief, error)

Replay verifies the bundle then folds all included pairs at its fixed AsOf. Results are ordered by subject, predicate, then the fold's value order. This reproduces exact beliefs in Scope, not semantic ranking or a past read made against a different registry or a different set of visible events.

func (AuditBundle) Verify added in v0.3.0

func (b AuditBundle) Verify() error

Verify checks supported versions, registry, event validity, scope, and digest. Unknown versions and duplicate IDs are refused, never silently interpreted.

type AuditRequest added in v0.3.0

type AuditRequest struct {
	Scope AuditScope
	AsOf  time.Time
}

AuditRequest selects histories and the instant at which to replay them. A zero AsOf captures the store's current time once, before reading events.

type AuditScope added in v0.3.0

type AuditScope struct {
	Subject   string `json:"subject"`
	Predicate string `json:"predicate"`
}

AuditScope selects complete histories. Empty fields match all subjects or predicates. Unlike Export, this scope cannot request a truncated event subset.

type Backend added in v0.3.0

type Backend interface {
	Put(ctx context.Context, collection, id string, values []float32, metadata map[string]any) error
	List(ctx context.Context, collection string, filter map[string]any, limit int) ([]StoredVector, int, error)
	Search(ctx context.Context, collection string, values []float32, k int, filter map[string]any) ([]Hit, error)
}

Backend is the context-aware storage contract used by Client. Implementations must be safe for concurrent calls. List must obey VectorDB's exact totals, internal pagination, and stable ordered-prefix contract.

type Belief

type Belief struct {
	Subject    string  `json:"subject"`
	Predicate  string  `json:"predicate"`
	Value      any     `json:"value"`
	Confidence float64 `json:"confidence"`
	Source     string  `json:"source"`
	Kind       string  `json:"kind"`
	// ObservedAt is when the surviving event was observed, which is what
	// "since when has this been true" means.
	ObservedAt time.Time `json:"observed_at"`
	// EventID identifies the event this belief came from, so a caller can
	// fetch its full history or cite it.
	EventID string `json:"event_id"`
}

Belief is a statement that holds at some instant: the result of folding a log, not a stored row.

func Fold

func Fold(events []Event, card Cardinality, asOf time.Time) []Belief

Fold reduces one subject-and-predicate's events to the beliefs that hold at asOf. A zero asOf means now.

Events may arrive in any order and may repeat; the fold is defined by the log's content alone, so a partially applied write, a retried write, or a clock that stepped backwards changes the answer only in so far as it changed the log.

type Cardinality

type Cardinality string

Cardinality decides what a second value for the same subject and predicate means.

const (
	// Single means a newer value replaces the older one: an agent has one
	// preferred editor.
	Single Cardinality = "single"
	// Multi means values accumulate: an agent may like many languages.
	Multi Cardinality = "multi"
)

type Client added in v0.3.0

type Client struct {
	// contains filtered or unexported fields
}

Client is a context-aware memory client. Configuration is immutable, and operations have independent request state. Concurrent writes still follow the backend's consistency guarantees; Client does not promise serializable writes.

func NewClient added in v0.3.0

func NewClient(cfg Config) (*Client, error)

NewClient validates configuration and copies the registry.

func (*Client) ExportAudit added in v0.3.0

func (c *Client) ExportAudit(ctx context.Context, q AuditRequest) (AuditBundle, error)

ExportAudit exports without requiring an embedder and honors cancellation.

func (*Client) ExportEvents added in v0.3.0

func (c *Client) ExportEvents(ctx context.Context, q Export) ([]Event, error)

ExportEvents returns a validated event export.

func (*Client) Forget added in v0.3.0

func (c *Client) Forget(ctx context.Context, q ForgetRequest) (int, error)

Forget appends a targeted or blanket retraction.

func (*Client) History added in v0.3.0

func (c *Client) History(ctx context.Context, subject, predicate string) ([]Event, error)

History returns a complete subject-and-predicate event history.

func (*Client) Recall added in v0.3.0

func (c *Client) Recall(ctx context.Context, q Query) ([]Belief, error)

Recall returns current or historical beliefs.

func (*Client) Registry added in v0.3.0

func (c *Client) Registry() Registry

Registry returns an independent copy of the client's predicate registry.

func (*Client) Remember added in v0.3.0

func (c *Client) Remember(ctx context.Context, q RememberRequest) (RememberResult, error)

Remember records one statement, preserving the embedding or backend error.

func (*Client) RememberText added in v0.3.0

func (c *Client) RememberText(ctx context.Context, text string, extractor Extractor) (ExtractionResult, error)

RememberText validates the entire proposal batch before the first write. Writes are sequential, not transactional. On a storage failure, the returned result contains the successful prefix, so callers must not blindly retry.

type Config added in v0.3.0

type Config struct {
	Backend    Backend
	Collection string
	Registry   Registry
	Embedder   Embedder
	// Materialize caches current pair beliefs when the backend supplies watermarks.
	Materialize bool
}

Config configures an immutable Client. Embedder is optional for exact reads, histories, and exports; writes and semantic recall require it.

type EmbedFunc added in v0.3.0

type EmbedFunc func(context.Context, string) ([]float32, error)

EmbedFunc adapts a function to Embedder.

func (EmbedFunc) Embed added in v0.3.0

func (f EmbedFunc) Embed(ctx context.Context, text string) ([]float32, error)

type Embedder added in v0.3.0

type Embedder interface {
	Embed(ctx context.Context, text string) ([]float32, error)
}

Embedder supplies compatible document and query vectors. Implementations must honor cancellation and be safe for concurrent calls.

type Event

type Event struct {
	// ID is derived from subject, predicate, value identity, retraction, and
	// observation time. It is not a request idempotency key; confidence,
	// source, kind, and string capitalization do not participate in the ID.
	ID string `json:"id"`
	// Kind is "fact" or "preference".
	Kind string `json:"kind"`
	// Subject is who or what the statement is about, lowercased.
	Subject string `json:"subject"`
	// Predicate names the relation, and selects the cardinality that decides
	// how this event interacts with its neighbours.
	Predicate string `json:"predicate"`
	// Value holds the predicate's declared type: string, float64, or bool.
	// It is nil on a retraction that clears every value for the pair.
	Value any `json:"value"`
	// Confidence is in [0, 1].
	Confidence float64 `json:"confidence"`
	// Source is how the statement was come by: user_stated, agent_inferred,
	// or tool_result.
	Source string `json:"source"`
	// Retraction marks this event as withdrawing a belief rather than
	// asserting one. With Value set it withdraws that one value; with Value
	// nil it withdraws every value for the pair.
	Retraction bool `json:"retraction,omitempty"`
	// ObservedAt is the writer's observation time, not database acceptance
	// order. Fold orders by this instant and then ID; skewed writer clocks
	// can place a later accepted write earlier in the log.
	ObservedAt time.Time `json:"observed_at"`
}

Event is one durable statement about a subject, or the retraction of one. Events are immutable once written: a correction is a later event, never an edit of an earlier one.

func DecodeEvent added in v0.3.0

func DecodeEvent(id string, m map[string]any) (Event, error)

DecodeEvent validates typed event metadata before returning it. Store reads use this strict decoder so a malformed correction or retraction cannot be silently skipped. EventFromMetadata remains available as a permissive decoder. Missing retraction denotes a legacy assertion; observed_ms is optional because observed_at is the authoritative timestamp.

func EventFromMetadata

func EventFromMetadata(id string, m map[string]any) Event

EventFromMetadata decodes without validation, retaining its legacy behavior. Invalid fields become their zero values. Use DecodeEvent before deriving beliefs from stored metadata; Store uses that strict decoder internally.

func (Event) Metadata

func (e Event) Metadata() map[string]any

Metadata flattens an event to typed metadata. Confidence stays a number so range filters compare numerically rather than lexically, and the instant is stored twice: once human readable and lexically sortable, once as milliseconds for numeric range filters.

func (Event) Text

func (e Event) Text() string

Text is the natural-language rendering an event is embedded from, so that semantic recall searches the same statements exact recall filters.

type Export added in v0.2.0

type Export struct {
	Subject   string
	Predicate string
	// Limit bounds how many events are read. Zero uses MaxExport.
	Limit int
}

Export selects part of the log for audit. An empty field means "every one of these": zero Export exports everything the store holds.

type ExtractionResult added in v0.3.0

type ExtractionResult struct {
	Proposals []Proposal       `json:"proposals"`
	Results   []RememberResult `json:"results"`
}

type Extractor added in v0.3.0

type Extractor interface {
	Extract(context.Context, string, Registry) ([]Proposal, error)
}

type ForgetRequest added in v0.3.0

type ForgetRequest struct {
	Subject   string
	Predicate string
	Value     any
	All       bool
}

ForgetRequest selects exactly one typed Value or All=true. False and numeric zero are values; an omitted value never implicitly withdraws everything.

type Hit

type Hit struct {
	ID       string
	Distance float32
	Score    float32
	Metadata map[string]any
}

Hit is one search result.

type LexicalEmbedder added in v0.3.0

type LexicalEmbedder struct{}

LexicalEmbedder is a dependency-free signed feature-hashing fallback. It retrieves overlapping words, not semantic synonyms. Use a dedicated collection for this versioned 256-dimensional space; never mix it with model embeddings.

func (LexicalEmbedder) Embed added in v0.3.0

func (LexicalEmbedder) Embed(ctx context.Context, text string) ([]float32, error)

type Materialization added in v0.3.0

type Materialization struct {
	// contains filtered or unexported fields
}

Materialization is a bounded, process-local derived belief view owned by one client. The durable event log remains authoritative. Restart rebuilds the view.

type Predicate

type Predicate struct {
	Cardinality string `json:"cardinality"`
	ValueType   string `json:"value_type"`
	Description string `json:"description"`
}

Predicate is one registry entry. Cardinality decides what a second value for the same subject means: "single" makes a newer value supersede the old one, "multi" makes it an additional fact. ValueType decides what a value IS: a string, a number, or a boolean. Values are stored with that type, so a number compares numerically in recall filters instead of lexically.

func (Predicate) Cardinal

func (p Predicate) Cardinal() Cardinality

Cardinal returns the predicate's cardinality as the fold understands it.

type Proposal added in v0.3.0

type Proposal struct {
	Subject   string `json:"subject"`
	Predicate string `json:"predicate"`
	Value     any    `json:"value"`
	Evidence  string `json:"evidence"`
}

Proposal is an untrusted model suggestion, never a belief until Remember validates and folds it. Evidence must be an exact excerpt from the input.

type ProposedStatements added in v0.3.0

type ProposedStatements []Proposal

ProposedStatements adapts proposals made by the calling agent. This lets an MCP host use its own model for extraction without another model service. RememberText still treats every proposal as untrusted and validates the batch.

func (ProposedStatements) Extract added in v0.3.0

func (p ProposedStatements) Extract(ctx context.Context, _ string, _ Registry) ([]Proposal, error)

type Query

type Query struct {
	// Text runs a semantic search. Empty means an exact, filtered read.
	Text      string
	Subject   string
	Predicate string
	Kind      string
	// AsOf answers as of a past instant. Zero means now, so "what is believed"
	// and "what was believed on Tuesday" are the same call.
	AsOf          time.Time
	MinConfidence float64
	Limit         int
	// ValueMin and ValueMax bound number-typed values.
	ValueMin *float64
	ValueMax *float64
}

Query is one read. With Text set the read is semantic (the text is embedded and searched); without it it is an exact filtered read. Both modes answer with beliefs folded from the same log, so semantic recall can never return something exact recall would say is no longer believed.

type Registry

type Registry map[string]Predicate

Registry is the closed set of predicates the store accepts. A write with an unregistered predicate is rejected, so an agent cannot invent near-duplicate predicates ("editor_preference" beside "prefers_editor") and split one fact across two names that never meet.

func DefaultRegistry added in v0.3.0

func DefaultRegistry() Registry

DefaultRegistry returns an independent starter vocabulary. Applications may extend the returned map before constructing a Client.

func LoadRegistry

func LoadRegistry(raw []byte) (Registry, error)

LoadRegistry parses and validates a registry document.

func (Registry) Clone added in v0.3.0

func (r Registry) Clone() Registry

Clone returns an independent copy of this registry.

func (Registry) Names

func (r Registry) Names() []string

Names returns the registered predicates sorted, for error messages and the system prompt.

func (Registry) PromptTable

func (r Registry) PromptTable() string

PromptTable renders the registry for an agent's system prompt.

func (Registry) Validate added in v0.3.0

func (r Registry) Validate() error

Validate checks the names, cardinalities, and value types of a registry.

type RememberRequest added in v0.3.0

type RememberRequest struct {
	Subject    string
	Predicate  string
	Value      any
	Kind       string
	Confidence *float64
	Source     string
}

RememberRequest records a typed value (string, float64, or bool). Kind defaults to fact and Source to user_stated. Nil Confidence defaults to 1; a pointer to zero records zero confidence rather than selecting the default.

type RememberResult

type RememberResult struct {
	Stored     Belief   `json:"stored"`
	Existing   bool     `json:"already_known,omitempty"`
	Superseded []Belief `json:"superseded,omitempty"`
}

RememberResult is what a write reports back: the assertion stored or found, whether it already held, and anything it displaced.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store turns writes into durable, typed events and reads into beliefs. It derives each answer from the log returned by its backend at read time. Consistency across concurrent operations depends on that backend.

func NewStore

func NewStore(db VectorDB, collection string, registry Registry, embed func(string) []float32) *Store

NewStore returns a store over one collection.

func (*Store) ExportAudit added in v0.3.0

func (s *Store) ExportAudit(q AuditRequest) (AuditBundle, error)

ExportAudit reads complete histories (at most MaxExport events), retaining events after AsOf as well. It fails on missing registry entries or partial reads. Completeness is subject to the backend's listing consistency; this does not acquire a cross-writer snapshot.

func (*Store) ExportEvents added in v0.2.0

func (s *Store) ExportEvents(q Export) ([]Event, error)

ExportEvents returns the raw event log, oldest first.

Reproducing beliefs also requires the applicable registry, fold rules, and as-of time. ExportAudit includes those inputs and refuses partial exports. A later export cannot reconstruct which events an earlier read could see.

func (*Store) Forget

func (s *Store) Forget(subject, predicate, value string) (int, error)

Forget withdraws a belief by appending a retraction.

It is a write, never a delete. Forgetting on Wednesday must not change what the agent believed on Tuesday, and a log that erased its own history could not answer that. With value set only that value is withdrawn; without it every value for the pair is.

func (*Store) History

func (s *Store) History(subject, predicate string) ([]Event, error)

History returns every event recorded for one subject and predicate, oldest first. It is the audit primitive: the fold is a pure function of exactly this, so anything the store answered can be re-derived from it.

func (*Store) Recall

func (s *Store) Recall(q Query) ([]Belief, error)

Recall returns the beliefs that hold at the query's instant.

func (*Store) Registry

func (s *Store) Registry() Registry

Registry returns a copy of the predicates this store accepts.

func (*Store) Remember

func (s *Store) Remember(kind, subject, predicate string, value any, confidence float64, source string) (RememberResult, error)

Remember records one statement.

It writes at most one event, and only after folding the existing log: if the statement already holds, nothing is written at all. Nothing is ever rewritten, so there is no window in which a crash can leave two live beliefs for a single-valued predicate.

type StoredVector

type StoredVector struct {
	ID       string
	Values   []float32
	Metadata map[string]any
}

StoredVector is one record as the database returns it.

type VectorDB

type VectorDB interface {
	Put(collection, id string, values []float32, metadata map[string]any) error
	// List returns up to limit exact matches and the total number of matches.
	// Implementations must page internally when their backend caps a page.
	// Increasing limit must extend the same ordered prefix while data is unchanged.
	List(collection string, filter map[string]any, limit int) ([]StoredVector, int, error)
	Search(collection string, values []float32, k int, filter map[string]any) ([]Hit, error)
}

VectorDB is the database surface the store needs. Keeping it an interface is what lets the memory layer live outside the database it usually runs against, and lets tests exercise the semantics without one.

type WatermarkBackend added in v0.3.0

type WatermarkBackend interface {
	Watermark(context.Context, string) (string, error)
}

WatermarkBackend optionally supplies an opaque revision of the complete collection visible to this reader. It must change on every visible mutation, including overwritten IDs, deletes, late arrivals, restores, and route changes. It is not an observation timestamp or a maximum event ID. Equality is the only meaningful operation; replicas need not expose the same revision.

Directories

Path Synopsis
cmd
recall-audit command
recall-audit verifies a JSON audit bundle from stdin and prints its replayed beliefs.
recall-audit verifies a JSON audit bundle from stdin and prints its replayed beliefs.
examples
sessions command
sessions demonstrates exact memory across separate client processes.
sessions demonstrates exact memory across separate client processes.
Package polign implements Recall's context-aware Backend over the Polign HTTP API.
Package polign implements Recall's context-aware Backend over the Polign HTTP API.

Jump to

Keyboard shortcuts

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