engine

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 21 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 engine implements Recall's typed memory, event histories, and audit replay. Applications use the public github.com/Polign/recall package.

Index

Constants

View Source
const (
	PointerGitRef   = "git_ref"
	PointerObject   = "object"
	PointerEnv      = "env"
	PointerExternal = "external"
	PointerProcess  = "process"
)

Pointer types. A pointer says where a piece of the agent's work lives; the work itself stays in the system that already persists it.

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.
	//
	// v2 orders a retraction after the assertion it withdraws when the two
	// share an instant. v1 ordered that tie on the event id, so the same log
	// can fold differently under the two, and a v1 bundle must not be replayed
	// here as though nothing had changed.
	FoldVersion = "recall-fold-v2"
)
View Source
const DefaultSubject = "user"

DefaultSubject is who a note is about when the text yielded no proposal to take a subject from.

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.

View Source
const NotePredicate = "note"

NotePredicate is where a statement goes when no registered predicate fits it. Every client and store registers it, so "nothing matched" always has a place to be written instead of being dropped. A note is multi-valued free text: it never supersedes anything, and recall ranks it after typed beliefs.

Variables

View Source
var (
	// ErrLeaseHeld means another process holds the agent's lease. Nothing was
	// written; the caller may wait and retry, or give up.
	ErrLeaseHeld = errors.New("recall: agent lease is held by another process")
	// ErrLeaseLost means another process took the agent over. The holder must
	// stop acting for it: every later write from this Agent fails.
	ErrLeaseLost = errors.New("recall: agent lease was lost to another process")
	// ErrLeaseUnsupported means the backend cannot grant leases. Resume with
	// Unleased only when something else guarantees one process per agent.
	ErrLeaseUnsupported = errors.New("recall: backend does not support agent leases")
	// ErrAgentClosed means Release already ran on this Agent.
	ErrAgentClosed = errors.New("recall: agent was released")
	// ErrLeaseNotHeld means a deferred resume has not taken the lease yet.
	// Nothing was written; call AcquireLease, then write.
	ErrLeaseNotHeld = errors.New("recall: agent lease not acquired yet; call AcquireLease before writing")
)
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

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

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

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

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 Agent added in v0.6.0

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

Agent is a resumed agent. Its methods are safe for concurrent use; writes are refused once the lease is lost or Release has run.

func (*Agent) AcquireLease added in v0.6.0

func (a *Agent) AcquireLease(ctx context.Context) error

AcquireLease takes the lease for an agent resumed with Deferred. It tries once: while another process holds the lease it returns a *LeaseHeldError, and the caller retries when it likes. On success it rereads the newest turn and working state, because the previous holder may have written after the deferred read, and later writes must continue from its records rather than overwrite them. Calling it again once held does nothing.

func (*Agent) Collection added in v0.6.0

func (a *Agent) Collection() string

Collection returns the collection holding the agent's records.

func (*Agent) Epoch added in v0.6.0

func (a *Agent) Epoch() uint64

Epoch returns the current lease epoch, or zero for an agent that holds no lease.

func (*Agent) FetchOutput added in v0.6.0

func (a *Agent) FetchOutput(ctx context.Context, ref string) (Output, error)

FetchOutput returns a stored output by reference.

func (*Agent) ID added in v0.6.0

func (a *Agent) ID() string

ID returns the agent's id.

func (*Agent) LeaseHeld added in v0.6.0

func (a *Agent) LeaseHeld() bool

LeaseHeld reports whether this process holds the agent's lease: always true for an unleased agent, false for a deferred one until AcquireLease.

func (*Agent) Milestone added in v0.6.0

func (a *Agent) Milestone(ctx context.Context, name, progress string) (WorkingState, error)

Milestone records that the agent reached a durable point: the working state's LastMilestone and Progress are updated together. Everything after the last milestone is what a crash can cost.

func (*Agent) Pointers added in v0.6.0

func (a *Agent) Pointers(ctx context.Context) ([]Pointer, error)

Pointers returns the agent's current pointers, sorted by name.

func (*Agent) RecentTurns added in v0.6.0

func (a *Agent) RecentTurns(ctx context.Context, n int) ([]Turn, error)

RecentTurns returns up to n of the newest turns, oldest first.

func (*Agent) RecordTurn added in v0.6.0

func (a *Agent) RecordTurn(ctx context.Context, t Turn) (Turn, error)

RecordTurn appends one turn. Content larger than the output threshold is stored as an output, and the turn keeps its opening and a reference.

func (*Agent) Release added in v0.6.0

func (a *Agent) Release(ctx context.Context) error

Release ends this process's hold on the agent. The lease is handed over at once rather than left to expire. Later writes fail with ErrAgentClosed.

func (*Agent) RemovePointer added in v0.6.0

func (a *Agent) RemovePointer(ctx context.Context, name string) error

RemovePointer withdraws a pointer. It is kept as a tombstone, so a resume never sees it again.

func (*Agent) Resumed added in v0.6.0

func (a *Agent) Resumed() ResumeContext

Resumed returns the context assembled when the agent was resumed.

func (*Agent) SetPointer added in v0.6.0

func (a *Agent) SetPointer(ctx context.Context, p Pointer) (Pointer, error)

SetPointer records where a piece of the agent's work lives, replacing any pointer of the same name.

func (*Agent) StoreOutput added in v0.6.0

func (a *Agent) StoreOutput(ctx context.Context, o Output) (OutputRef, error)

StoreOutput keeps a large tool output whole. An empty Ref gets one; storing under an existing ref replaces that output.

func (*Agent) UpdateWorkingState added in v0.6.0

func (a *Agent) UpdateWorkingState(ctx context.Context, ws WorkingState) (WorkingState, error)

UpdateWorkingState supersedes the working state. The previous version stays readable through WorkingStateHistory. Library-owned fields are overwritten.

func (*Agent) WorkingState added in v0.6.0

func (a *Agent) WorkingState() WorkingState

WorkingState returns the current working state.

func (*Agent) WorkingStateHistory added in v0.6.0

func (a *Agent) WorkingStateHistory(ctx context.Context, limit int) ([]WorkingState, error)

WorkingStateHistory returns earlier working states, newest first.

type AuditBundle

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

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

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

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

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

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

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

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

NewClient validates configuration and copies the registry.

func (*Client) ExportAudit

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

ExportAudit exports without requiring an embedder and honors cancellation.

func (*Client) ExportEvents

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

ExportEvents returns a validated event export.

func (*Client) Forget

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

Forget appends a targeted or blanket retraction.

func (*Client) History

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

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

func (*Client) Promote

func (c *Client) Promote(ctx context.Context, q PromoteRequest) (RememberResult, error)

Promote records a typed statement and then withdraws the note it came from, in that order: a failure between the two writes leaves the fact stated twice, never not at all. The note stays in history, so the promotion is auditable and can be reversed.

func (*Client) Recall

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

Recall returns current or historical beliefs.

func (*Client) Registry

func (c *Client) Registry() Registry

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

func (*Client) Remember

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

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

func (*Client) RememberText

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.

Nothing stated is dropped. A proposal whose predicate is not registered, or text that yielded no proposals at all, is kept as a note holding the whole text, once per subject. A malformed proposal for a registered predicate still fails the batch, because the caller can correct it.

func (*Client) Resume added in v0.6.0

func (c *Client) Resume(ctx context.Context, req ResumeRequest) (*Agent, error)

Resume takes the agent's lease and rebuilds its context from its records. It is also how an agent starts for the first time: with nothing recorded, the context is marked Fresh and holds only relevant memories.

The returned Agent holds the lease until Release. Call Release on a clean shutdown so the next process need not wait out the TTL.

type Config

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

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

EmbedFunc adapts a function to Embedder.

func (EmbedFunc) Embed

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

type Embedder

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

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

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

type ExtractionResult struct {
	Proposals []Proposal       `json:"proposals"`
	Results   []RememberResult `json:"results"`
	// Unfiled lists the proposals whose predicate is not registered. Their
	// text was kept as a note rather than refused; the predicates they name
	// are the ones this registry is missing.
	Unfiled []Proposal `json:"unfiled,omitempty"`
}

type Extractor

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

type ForgetRequest

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 LeaseBackend added in v0.6.0

type LeaseBackend interface {
	AcquireLease(ctx context.Context, collection, name, holder string, ttl time.Duration) (LeaseGrant, error)
	RenewLease(ctx context.Context, collection, name, holder string, epoch uint64, ttl time.Duration) (LeaseGrant, error)
	ReleaseLease(ctx context.Context, collection, name, holder string, epoch uint64) error
}

LeaseBackend optionally grants per-agent leases. Acquire fails with ErrLeaseHeld while another holder's epoch is live; Renew fails with ErrLeaseLost once the chain has moved past the given epoch.

type LeaseGrant added in v0.6.0

type LeaseGrant struct {
	Epoch  uint64
	Holder string
	TTL    time.Duration
}

LeaseGrant is one held epoch. The epoch is the fencing token: it only ever increases, and a holder presenting an old one has been superseded.

type LeaseHeldError added in v0.6.0

type LeaseHeldError struct {
	Holder  string
	Expires time.Time
}

LeaseHeldError names who holds a lease the caller could not take.

func (*LeaseHeldError) Error added in v0.6.0

func (e *LeaseHeldError) Error() string

func (*LeaseHeldError) Unwrap added in v0.6.0

func (e *LeaseHeldError) Unwrap() error

type LexicalEmbedder

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

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

type Materialization

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 Output added in v0.6.0

type Output struct {
	Ref     string    `json:"ref"`
	Tool    string    `json:"tool,omitempty"`
	Summary string    `json:"summary,omitempty"`
	Content string    `json:"content"`
	At      time.Time `json:"at"`
}

Output is a large tool result, kept whole and retrieved by reference.

type OutputRef added in v0.6.0

type OutputRef struct {
	Ref     string    `json:"ref"`
	Tool    string    `json:"tool,omitempty"`
	Summary string    `json:"summary,omitempty"`
	Tokens  int       `json:"tokens"`
	At      time.Time `json:"at"`
}

OutputRef describes a stored output without its content.

type Pointer added in v0.6.0

type Pointer struct {
	Name   string            `json:"name"`
	Type   string            `json:"type"`
	Fields map[string]string `json:"fields"`
	Note   string            `json:"note,omitempty"`
	At     time.Time         `json:"at"`
}

Pointer is a typed reference to where some of the agent's work lives. Setting a pointer with an existing name replaces it.

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 PromoteRequest

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

PromoteRequest files a note under a typed predicate. Note is the note's value exactly as recall returned it; the remaining fields are the typed statement it becomes, with RememberRequest's defaults.

type Proposal

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

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

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

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

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

func (r Registry) Validate() error

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

type RememberRequest

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 ResumeContext added in v0.6.0

type ResumeContext struct {
	AgentID string `json:"agent_id"`
	// Fresh means the agent had no records: this is its first start.
	Fresh bool   `json:"fresh"`
	Epoch uint64 `json:"epoch,omitempty"`
	// LeaseHeld is false after a deferred resume: the context is ready, but
	// writes wait for AcquireLease.
	LeaseHeld    bool          `json:"lease_held"`
	WorkingState *WorkingState `json:"working_state,omitempty"`
	Pointers     []Pointer     `json:"pointers,omitempty"`
	Outputs      []OutputRef   `json:"outputs,omitempty"`
	Memories     []Belief      `json:"memories,omitempty"`
	RecentTurns  []Turn        `json:"recent_turns,omitempty"`
	// Omitted counts what did not fit the budget.
	Omitted struct {
		Turns    int `json:"turns,omitempty"`
		Memories int `json:"memories,omitempty"`
		Outputs  int `json:"outputs,omitempty"`
	} `json:"omitted"`
	// TurnSeq is the newest turn recorded before this resume.
	TurnSeq     int64  `json:"turn_seq"`
	TokenBudget int    `json:"token_budget"`
	Tokens      int    `json:"tokens"`
	Briefing    string `json:"briefing"`
}

ResumeContext is what a resumed agent starts from: its own note, where its work lives, what it remembers that bears on its focus, and its last few turns, assembled within a token budget. Briefing renders all of it as one message a harness can hand the model; the fields carry the same content for harnesses that want to lay it out themselves.

type ResumeRequest added in v0.6.0

type ResumeRequest struct {
	AgentID string
	// Collection holds the agent's records; empty means the memory
	// collection's name with "_agents" appended.
	Collection string
	// TokenBudget bounds the assembled context. Zero means 8000.
	TokenBudget int
	// LeaseTTL is how long each lease epoch lasts. Zero means 60 seconds.
	LeaseTTL time.Duration
	// Holder identifies this process in lease records. Empty means
	// host:pid:random.
	Holder string
	// Unleased skips the lease. Use it only on a backend without leases, when
	// something else already guarantees one process per agent.
	Unleased bool
	// Deferred reads the agent's records without taking its lease, so the
	// context is ready at once even while a crashed process's lease is still
	// live. Writes fail with ErrLeaseNotHeld until AcquireLease succeeds.
	// Reading needs no lease: only writes can conflict.
	Deferred bool
	// NoKeepAlive stops the background renewal. The lease is then renewed
	// only by writes, and an agent idle past its TTL can be taken over.
	NoKeepAlive bool
	// OutputThreshold is the size, in estimated tokens, above which a turn's
	// content is stored as an output and the turn keeps a reference. Zero
	// means 2000; negative disables it.
	OutputThreshold int
}

ResumeRequest names the agent to resume and how to build its context.

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.

An invalid registry is recorded rather than returned, because this constructor has never had an error to return. Every operation reports it, so a bad cardinality surfaces at the first call instead of silently folding a multi-valued predicate as single-valued and appearing much later as a malformed audit.

func (*Store) ExportAudit

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

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 Turn added in v0.6.0

type Turn struct {
	Seq  int64  `json:"seq"`
	Role string `json:"role"`
	// Name is the tool that produced a tool turn.
	Name    string `json:"name,omitempty"`
	Content string `json:"content"`
	// OutputRef is set when the content was too large to keep in the turn and
	// was stored as an output instead; Content then holds its opening.
	OutputRef string `json:"output_ref,omitempty"`
	// MessageID is the harness's own id for the message, when it has one.
	// A harness that restores its message history after a resume uses it to
	// tell messages already recorded from new ones.
	MessageID string    `json:"message_id,omitempty"`
	At        time.Time `json:"at"`
}

Turn is one message of the agent's run, kept verbatim.

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

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.

A revision must never be reused once it has changed. A counter that resets on restart lets a revision repeat, and a repeat silently revalidates a cached fold that the log has since moved past. Entries also expire after materializeTTL so that a backend which under-reports bounds, rather than keeps, the staleness it causes.

type WorkingState added in v0.6.0

type WorkingState struct {
	Goal          string   `json:"goal,omitempty"`
	Plan          []string `json:"plan,omitempty"`
	Progress      string   `json:"progress,omitempty"`
	Focus         string   `json:"focus,omitempty"`
	Decisions     []string `json:"decisions,omitempty"`
	OpenQuestions []string `json:"open_questions,omitempty"`
	Notes         string   `json:"notes,omitempty"`
	// Step is the harness's step counter when the note was written.
	Step int64 `json:"step,omitempty"`
	// LastMilestone names the last point the agent declared durable.
	LastMilestone string `json:"last_milestone,omitempty"`

	// Written by the library; ignored on input.
	Version   int64     `json:"version,omitempty"`
	TurnSeq   int64     `json:"turn_seq,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitzero"`
}

WorkingState is the agent's note to its next instance. Resume always includes it, whole, ahead of everything else, so it should say what a colleague would need to pick the work up: the goal, the plan, what is done, what is being done now, and why things were decided the way they were.

Jump to

Keyboard shortcuts

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