engine

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 22 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.
	// v2 adds Evidence and EvidenceID, and its bundles are checksummed with
	// DigestV3, which covers them. v1 bundles still replay and verify.
	//
	// v3 adds Replaces and ReplacedBy, the links a correction across
	// predicates writes, and its bundles are checksummed with DigestV4. A
	// bundle with no such links is still written as v2.
	EventVersion = "recall-event-v3"

	// 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.
	//
	// v3 adds three registry rules: a retroactive definition governs the
	// predicate's history before it, an automatic definition of a name
	// already defined is ignored, and a merge record makes one name read as
	// another. A bundle whose registry log uses neither
	// folds the same under v2 and is still written as v2, so its checksum
	// and older verifiers are unaffected.
	//
	// v4 adds exclusions: a value asserted under a predicate withdraws the
	// same value under the predicates it excludes, except historical ones.
	// A bundle whose registry declares none folds the same under v3 and is
	// still written as v3 (or v2).
	FoldVersion = "recall-fold-v4"
)
View Source
const (
	StarterCoding  = "coding"
	StarterSupport = "support"
	StarterSales   = "sales"
	StarterVoice   = "voice"
	// StarterPersonal is for an assistant that remembers a person's life. It
	// seeds an open vocabulary: generic relations that many facts share, so
	// an extractor reuses them instead of coining one predicate per fact.
	StarterPersonal = "personal"
)

Starter registries, by the kind of agent each is written for.

View Source
const (
	ExtractionSubject   = "recall:extraction"
	ExtractionPredicate = "extraction"
)

The proposals each model extraction made are recorded beside the episode they came from, as an event about ExtractionSubject whose EvidenceID is the episode. Remembering the same text again replays them instead of asking the model again, so a write retried after a crash files the text exactly as the first attempt did, and restating something files it the way it was filed before. Replayed proposals still go through the fold, so restating "I prefer vim" after a switch to zed makes vim current again. Answers leave these records out.

View Source
const (
	RegistrySubject   = "recall:registry"
	RegistryPredicate = "registry_change"
)

The registry's own history lives in the log it governs. Each change is an ordinary event about RegistrySubject under RegistryPredicate, whose value is one predicate's definition as JSON. Being an event, it is immutable, it is ordered by observation time like everything else, and it travels with exports. Reads leave these events out unless a query names them.

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 MaxEvidenceBytes = 2048

MaxEvidenceBytes bounds the excerpt a statement keeps as its evidence. The whole text lives in the evidence event; the excerpt is the quoted part.

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 MaxGetEvents = 1000

MaxGetEvents bounds one Events call.

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 MaxObservationSkew = time.Minute

MaxObservationSkew is how far past the writer's clock an observation time may be. A statement observed in the future would stay hidden from every query about the present until its time came, so a later one is refused.

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 MaxTranscript = 32768

MaxTranscript bounds a conversation remembered at once, as the text tools bound a passage.

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.

View Source
const TextField = "text"

TextField is the metadata key that holds an event's searchable text.

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 (
	// ErrPositionBehind means the agent's records are ahead of the position
	// the write was made from: the process was restored from an earlier
	// snapshot, or another process wrote meanwhile. Nothing was written. Call
	// Since with the position the error carries, then continue.
	ErrPositionBehind = errors.New("recall: agent records are ahead of this process; it was restored from an earlier point")
	// ErrPositionAhead means the caller's position is ahead of the records:
	// the backend lost writes the caller saw acknowledged. Nothing was written.
	ErrPositionAhead = errors.New("recall: position is ahead of the agent's records; the backend lost writes")
	// ErrRecordExists is what a CreateBackend returns when the id already
	// holds a record.
	ErrRecordExists = errors.New("recall: a record with this id already exists")
)
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 ErrGetUnsupported = errors.New("recall: this backend cannot read events by id")

ErrGetUnsupported reports a backend that cannot read records by id.

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 ErrRegistryMismatch = errors.New("recall: registry does not match the store's registry log")

ErrRegistryMismatch means this client's configured registry disagrees with the registry recorded in the store, or asks for a change that would make stored values unreadable. Two clients folding one log under different rules would give different answers, so the disagreement is an error rather than a silent second opinion. SyncRegistry records an intended change.

View Source
var ErrTextSearchUnsupported = errors.New("recall: text search unsupported")

ErrTextSearchUnsupported reports that a lexical search is not available for a collection, such as before its first index is published.

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. It does not cover Evidence or EvidenceID; DigestV3 does.

func DigestV3 added in v0.8.0

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

DigestV3 is DigestV2 that also covers each event's Evidence and EvidenceID, so an export cannot alter what a statement was drawn from undetected.

func DigestV4 added in v0.15.0

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

DigestV4 is DigestV3 that also covers each event's Replaces and ReplacedBy, so an export cannot alter what a correction withdrew.

func ObservedAt added in v0.9.0

func ObservedAt(ctx context.Context) time.Time

ObservedAt is when the text an extractor is reading was said, as given to RememberTextAt. Zero means now. An extractor uses it to resolve relative dates such as "last week".

func OpenVocabulary added in v0.14.0

func OpenVocabulary(ctx context.Context) bool

OpenVocabulary reports whether the client asking for an extraction accepts predicates the extractor coins. A closed client files only the predicates it offered.

func Sentence added in v0.14.0

func Sentence(subject, predicate string, value any) string

Sentence tells one statement in words. A note is its own words; anything else is the subject, the predicate's words, and the value.

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 StarterNames added in v0.9.0

func StarterNames() []string

StarterNames lists the starter registries StarterRegistry knows.

func Transcript added in v0.20.0

func Transcript(messages []Message) (string, error)

Transcript writes a conversation as text an extractor reads by speaker, one "User:" or "Assistant:" line per turn, so only what the user said or agreed to becomes a statement about them. Roles are user and assistant.

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.

func WithHeld added in v0.19.0

func WithHeld(ctx context.Context, held []Belief) context.Context

WithHeld returns a context carrying held as what Held reports, for testing an extractor without a store.

Types

type Action added in v0.21.0

type Action struct {
	Seq   int64       `json:"seq"`
	Tool  string      `json:"tool"`
	Class ActionClass `json:"class"`
	// Args is the call's arguments as the harness gave them, usually JSON.
	Args string `json:"args,omitempty"`
	// Key is fixed when the action begins and is the same on every retry:
	// the idempotency key an idempotent tool passes to the outside system.
	Key string `json:"key"`
	// CallID is the harness's id for the tool call, when it gave one. A
	// begin repeated with it returns this action instead of a new one.
	CallID string       `json:"call_id,omitempty"`
	Status ActionStatus `json:"status"`
	Result string       `json:"result,omitempty"`
	Error  string       `json:"error,omitempty"`
	// ArgsRef and ResultRef are set when Args or Result was too large to keep
	// in the record and was stored as an output; the field keeps its opening.
	ArgsRef   string `json:"args_ref,omitempty"`
	ResultRef string `json:"result_ref,omitempty"`
	// Resolution says how an action was closed after a crash.
	Resolution string    `json:"resolution,omitempty"`
	Epoch      uint64    `json:"epoch,omitempty"`
	StartedAt  time.Time `json:"started_at"`
	EndedAt    time.Time `json:"ended_at,omitzero"`
}

Action is one recorded tool call.

type ActionClass added in v0.21.0

type ActionClass string

ActionClass says what running a tool again would do. It decides what a resume does with an action a crash left open.

const (
	// ActionPure reads and changes nothing: run it again if still needed.
	ActionPure ActionClass = "pure"
	// ActionIdempotent changes the world, but running it again with the same
	// Key does no more than running it once: a PUT by id, a push of a known
	// sha, a payment with an idempotency key. The tool must pass Key on.
	ActionIdempotent ActionClass = "idempotent"
	// ActionExternal changes the world and running it again could do it
	// twice: send a message, post, charge without a key, delete. It is never
	// run again blindly.
	ActionExternal ActionClass = "external"
)

type ActionEnd added in v0.21.0

type ActionEnd struct {
	Status ActionStatus
	Result string
	Error  string
	// Resolution notes how an action interrupted by a crash was settled.
	Resolution string
}

ActionEnd is how an action finished.

type ActionStatus added in v0.21.0

type ActionStatus string

ActionStatus is where an action stands. Started and Unknown are open.

const (
	ActionStarted ActionStatus = "started"
	ActionDone    ActionStatus = "done"
	ActionFailed  ActionStatus = "failed"
	// ActionAbandoned closes a pure action a crash interrupted; nothing came
	// of it, and the agent redoes it if it still needs the answer.
	ActionAbandoned ActionStatus = "abandoned"
	// ActionUnknown marks an external action no one could confirm either
	// way. It stays open, and in every briefing, until it is ended.
	ActionUnknown ActionStatus = "unknown"
)

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) BeginAction added in v0.21.0

func (a *Agent) BeginAction(ctx context.Context, tool string, class ActionClass, args string, opts ...WriteOption) (Action, error)

BeginAction records that a tool call is about to run. Call it before the call and run the tool only if it succeeds; pass the returned Key to an idempotent tool.

With CallID, a call already begun is returned as it stands, whatever its status, and nothing is written: a harness restored from an earlier snapshot sees "done" and skips the call, or sees "started" and settles it as after a crash. With At, a begin from a position the records have moved past fails with ErrPositionBehind, as does, on a CreateBackend, a seq already used.

func (*Agent) Collection added in v0.6.0

func (a *Agent) Collection() string

Collection returns the collection holding the agent's records.

func (*Agent) EndAction added in v0.21.0

func (a *Agent) EndAction(ctx context.Context, seq int64, end ActionEnd, opts ...WriteOption) (Action, error)

EndAction closes an open action with how it finished. Ending an action already closed with the same outcome returns it, so a retried end is a no-op; a different outcome is an error: the first outcome stands.

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, opts ...WriteOption) (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) PendingActions added in v0.21.0

func (a *Agent) PendingActions(ctx context.Context) ([]Action, error)

PendingActions returns the open actions, oldest first.

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) Position added in v0.26.0

func (a *Agent) Position() Position

Position returns how far the agent's records go, as this Agent knows them.

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) Reconcile added in v0.21.0

func (a *Agent) Reconcile(ctx context.Context, resolve Resolver) (ReconcileReport, error)

Reconcile settles every action a crash left open, before the agent takes another step:

  • pure actions are abandoned; the agent redoes them if it needs to;
  • idempotent actions go to resolve, which runs them again with their Key; without a resolver they stay open for the harness;
  • external actions go to resolve, which checks whether they happened; without a resolver, or when it cannot tell, they are marked unknown and stay open, flagged in every briefing until someone ends them.

Nothing is ever run again by Recall itself.

func (*Agent) RecordTurn added in v0.6.0

func (a *Agent) RecordTurn(ctx context.Context, t Turn, opts ...WriteOption) (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.

A turn whose MessageID is already recorded is returned as recorded, and nothing is written: the first one stands. With At, a write from a position the records have moved past fails with ErrPositionBehind. On a CreateBackend a turn seq already used fails the same way, so a process restored from an earlier snapshot cannot replace its later turns.

func (*Agent) Refresh added in v0.21.0

func (a *Agent) Refresh(ctx context.Context) (ResumeContext, error)

Refresh rebuilds the resume context from the records as they stand now, for a harness that settled actions itself after the resume. Resumed returns the new context afterwards.

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) Settle added in v0.27.0

func (a *Agent) Settle(ctx context.Context, seq int64, end ActionEnd) (Action, error)

Settle closes an open action with an outcome learned outside the agent's run: a person checked whether the email went out, or a resolver looked the charge up. It is EndAction, plus the tool turn Reconcile writes for a done or failed outcome, so the model reads what happened in its history and does not make the call again. The action must be open, and end must be done, failed or abandoned.

The turn moves the agent's position. A process restored from before the settle is then told its records moved on, and reads the outcome when it catches up.

func (*Agent) Since added in v0.26.0

func (a *Agent) Since(ctx context.Context, from Position, budget int) (SinceReport, error)

Since reports what the records hold after from, within a token budget (zero means 8000). The actions and the working state are always included; the newest turns fill what is left. A position ahead of the records is ErrPositionAhead. Since reads only, and moves the Agent to the records' position, so a caller that adopts Position carries on from there.

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, opts ...WriteOption) (WorkingState, error)

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

The versioned copy is a create-only write: a process restored from an earlier snapshot, writing a version that already exists, gets ErrPositionBehind and the newer state is left alone.

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 AgentList added in v0.27.0

type AgentList struct {
	Collection string         `json:"collection"`
	Agents     []AgentSummary `json:"agents"`
	// Truncated means the collection holds more than one listing reads, so
	// some agents or open calls are missing.
	Truncated bool `json:"truncated,omitempty"`
}

AgentList is the agents found in one collection.

type AgentSummary added in v0.27.0

type AgentSummary struct {
	AgentID string `json:"agent_id"`
	// Goal, Progress and LastMilestone come from the working state, and are
	// empty for an agent that has not written one.
	Goal          string `json:"goal,omitempty"`
	Progress      string `json:"progress,omitempty"`
	LastMilestone string `json:"last_milestone,omitempty"`
	// StateVersion is the working state's version; zero when there is none.
	StateVersion int64     `json:"state_version,omitempty"`
	UpdatedAt    time.Time `json:"updated_at,omitzero"`
	// Open are the tool calls begun and not ended, or ended unknown, oldest
	// first.
	Open []Action `json:"open,omitempty"`
}

AgentSummary is one agent as its records show it, read without its lease.

type AskRequest added in v0.20.0

type AskRequest struct {
	// Question searches what is remembered. Empty reads without searching:
	// everything believed about the user (a profile), or, with Since,
	// everything that changed.
	Question string
	// AsOf answers as of an earlier instant; zero means now.
	AsOf time.Time
	// Since keeps only what was stated after this instant, each with what
	// it replaced: what changed since an agent last looked. Zero means any
	// time.
	Since time.Time
}

AskRequest is a read in words.

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"`
	// RegistryLog holds the store's recorded registry changes, when it has
	// any, so a replay folds each event under the cardinality in effect when
	// it was observed. They are kept apart from Events, which Scope bounds.
	RegistryLog []Event `json:"registry_log,omitempty"`
	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"`
	// Evidence and EvidenceID are the surviving event's: the excerpt this
	// belief was drawn from and the event holding the whole text.
	Evidence   string `json:"evidence,omitempty"`
	EvidenceID string `json:"evidence_id,omitempty"`
	// Via is set on a belief that Query.FollowRefs added: the event of the
	// belief whose ref value led to this one's subject.
	Via string `json:"via,omitempty"`
	// Replaced lists the values this belief displaced when it was asserted,
	// so a reader sees the correction alongside the answer: what was believed
	// before, when, and on what basis. It goes back one step; the whole chain
	// is in the history. Empty when the belief displaced nothing, which is
	// always the case for a multi-valued predicate.
	Replaced []PriorValue `json:"replaced,omitempty"`
	// Elsewhere lists the subject's current beliefs under other predicates
	// that hold the same value, each with its predicate and when it was
	// stated: dislikes mangoes beside likes mangoes. A correction that was
	// never linked shows up here, so a reader is not answered from one
	// predicate alone. Client reads fill it unless Query.NoElsewhere is set.
	Elsewhere []PriorValue `json:"elsewhere,omitempty"`
	// Relevance is how close the question was to this belief's best
	// matching statement, as the vector search scored it; zero for exact
	// reads and for beliefs only the keyword search found.
	Relevance float32 `json:"relevance,omitempty"`
}

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.

func Held added in v0.19.0

func Held(ctx context.Context) []Belief

Held returns the beliefs memory held when the extractor was asked: the ones the text is about first, then the newest, at most maxHeld in all, so it can file a statement that updates one of them under that fact's predicate, or name it in Proposal.Replaces. Notes and the records of earlier extractions are left out. Empty for proposals the caller made itself.

type BeliefRef added in v0.15.0

type BeliefRef struct {
	Predicate string `json:"predicate"`
	Value     any    `json:"value"`
}

BeliefRef names a belief of the statement's own subject by what it says.

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) Agents added in v0.27.0

func (c *Client) Agents(ctx context.Context, collection string) (AgentList, error)

Agents lists the agents with records in collection: each one that has written a working state or has an open tool call. An agent that has only recorded turns is not listed; Resume it by id to read it. An empty collection means the memory collection's name with "_agents" appended, as in Resume. It reads only and takes no lease.

func (*Client) Ask added in v0.14.0

func (c *Client) Ask(ctx context.Context, question string) ([]Memory, error)

Ask answers a question in words with what is believed now: a search over everything remembered, folded to current beliefs and told as sentences. A time the question names, such as "last week", is searched first.

func (*Client) AskAt added in v0.14.0

func (c *Client) AskAt(ctx context.Context, question string, asOf time.Time) ([]Memory, error)

AskAt is Ask about what was believed at asOf. Zero means now.

func (*Client) AskWith added in v0.20.0

func (c *Client) AskWith(ctx context.Context, r AskRequest) ([]Memory, error)

AskWith answers an AskRequest. With a question it searches, as Ask does. Without one it reads, with no model and no search: the user's current beliefs, or with Since, every subject's beliefs stated since then, newest first.

func (*Client) Diff added in v0.22.0

func (c *Client) Diff(ctx context.Context, r DiffRequest) ([]PairChange, error)

Diff says what was believed differently at r.To than at r.From.

func (*Client) Events added in v0.8.0

func (c *Client) Events(ctx context.Context, ids []string) ([]Event, error)

Events reads events by id, in the order asked, skipping ids that are not stored. It is how a caller reads the text behind a belief's EvidenceID.

func (*Client) Explain added in v0.14.0

func (c *Client) Explain(ctx context.Context, question string) ([]Explanation, error)

Explain explains each belief a question finds, as Ask would answer it.

func (*Client) ExplainBelief added in v0.14.0

func (c *Client) ExplainBelief(ctx context.Context, b Belief) (Explanation, error)

ExplainBelief explains one belief.

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) ForgetText added in v0.14.0

func (c *Client) ForgetText(ctx context.Context, request string, selector Selector) (ForgetTextResult, error)

ForgetText withdraws the beliefs a request in words names. It searches the current beliefs for the request, asks the selector which of them it means, and withdraws each one. Like Forget it records retractions and deletes nothing, so a wrong choice is undone by remembering the value again.

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) ImportEvents added in v0.20.0

func (c *Client) ImportEvents(ctx context.Context, events []Event) (int, error)

ImportEvents writes events exported from another collection or backend into this one, each embedded with this client's embedder, and returns how many were written. Event IDs are kept, and a write with an ID already stored replaces it with the same event, so importing twice stores each event once. Moving a log to a new embedder this way re-embeds it without asking an extractor again.

func (*Client) Merge added in v0.14.0

func (c *Client) Merge(ctx context.Context, name, into string) error

Merge makes one predicate read as another. See Store.Merge.

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) Redefine added in v0.14.0

func (c *Client) Redefine(ctx context.Context, name string, p Predicate) error

Redefine corrects a predicate's definition for its whole history. See Store.Redefine. It writes, so it needs an embedder.

func (*Client) Registry

func (c *Client) Registry() Registry

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

func (*Client) RegistryLog added in v0.9.0

func (c *Client) RegistryLog(ctx context.Context) ([]RegistryChange, error)

RegistryLog returns every recorded registry change, oldest first.

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.

The text itself is kept first, whole, as a note about DefaultSubject: the episode. Every statement then records its quoted excerpt as Evidence and the episode as EvidenceID, so what was said stays readable however it was interpreted. A proposal whose predicate is not registered is also kept as a note under its own subject. A malformed proposal for a registered predicate still fails the batch, because the caller can correct it.

func (*Client) RememberTextAt added in v0.7.0

func (c *Client) RememberTextAt(ctx context.Context, text string, extractor Extractor, observedAt time.Time) (ExtractionResult, error)

RememberTextAt is RememberText for text that was said at observedAt, such as an imported conversation. Every statement and note it writes carries that time; zero means now. See RememberRequest.ObservedAt.

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.

func (*Client) Split added in v0.14.0

func (c *Client) Split(ctx context.Context, name string) error

Split undoes a merge. See Store.Split.

func (*Client) SyncRegistry added in v0.9.0

func (c *Client) SyncRegistry(ctx context.Context) ([]string, error)

SyncRegistry records the client's configured registry in the store's log. See Store.SyncRegistry. It writes, so it needs an embedder.

func (*Client) Timeline added in v0.22.0

func (c *Client) Timeline(ctx context.Context, subject, predicate string) (Timeline, error)

Timeline tells one subject and predicate's history as changes.

func (*Client) TimelinesFor added in v0.22.0

func (c *Client) TimelinesFor(ctx context.Context, question string) ([]Timeline, error)

TimelinesFor tells the timeline of each subject and predicate a question reaches, including ones whose every value has since been withdrawn, so "what happened to my editor" finds a forgotten editor too.

func (*Client) Vocabulary added in v0.14.0

func (c *Client) Vocabulary(ctx context.Context) (Registry, error)

Vocabulary returns every predicate the store can read: the configured registry plus everything its registry log defines. For an open client this is also everything it can write.

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
	// Open lets writes define predicates. A write naming a predicate nothing
	// has defined records its definition in the store's registry log, and a
	// predicate defined there by any client is writable. Registry then only
	// seeds the vocabulary and may be empty. Without Open the registry is a
	// closed set and an unregistered predicate is refused.
	Open bool
	// MatchThreshold is how similar, from 0 to 1, a new predicate name must
	// be to an existing one for an open write to use the existing one
	// instead of defining it ("favorite_editor" for "editor_favorite").
	// Similarity is the cosine of the embedder's vectors for the two names,
	// and their descriptions when both have one. Zero means 0.9; a negative
	// value turns matching off. Only a predicate with the same stored type,
	// and the same cardinality when the write names one, can match.
	MatchThreshold float64
}

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

type CreateBackend added in v0.26.0

type CreateBackend interface {
	Create(ctx context.Context, collection, id string, values []float32, metadata map[string]any, fence *Fence) error
}

CreateBackend optionally writes a record only when its id holds none. Create must fail with an error wrapping ErrRecordExists, and write nothing, when the id holds a record. A non-nil fence applies as in PutFenced. A backend that cannot tell (an older server) may write as Put does; the position and the ids still catch a replay over HTTP.

type DiffRequest added in v0.22.0

type DiffRequest struct {
	// Subject limits the diff to one subject; empty compares every subject.
	Subject string
	// From is the earlier instant; zero means before anything was stated.
	From time.Time
	// To is the later instant; zero means now.
	To time.Time
}

DiffRequest names two instants to compare.

type Earlier added in v0.14.0

type Earlier struct {
	Text  string    `json:"text"`
	Since time.Time `json:"since"`
}

Earlier is a value a memory replaced.

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"`
	// Evidence is the exact excerpt a statement was drawn from, when it came
	// from text. EvidenceID is the event that holds that text whole, a note
	// written by RememberText. Both are empty for a statement made directly.
	Evidence   string `json:"evidence,omitempty"`
	EvidenceID string `json:"evidence_id,omitempty"`
	// Replaces, on an assertion, records the beliefs under other predicates
	// (or other values) that this statement made untrue when it was made:
	// "dislikes mangoes" replacing "likes mangoes". Each one was withdrawn by
	// a retraction in its own history whose ReplacedBy names this event, so
	// every history still folds on its own; this snapshot is what lets the
	// new belief say what it corrected.
	Replaces []PriorValue `json:"replaces,omitempty"`
	// ReplacedBy, on a retraction, is the event whose statement withdrew the
	// value: a correction, not a request to forget.
	ReplacedBy string `json:"replaced_by,omitempty"`
}

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 Explanation added in v0.14.0

type Explanation struct {
	Memory    string    `json:"memory"`
	Subject   string    `json:"subject"`
	Predicate string    `json:"predicate"`
	Value     any       `json:"value"`
	StatedAt  time.Time `json:"stated_at"`
	Source    string    `json:"source"`
	// WrittenAs is the name the statement was written under, when a merge
	// files it under another.
	WrittenAs string `json:"written_as,omitempty"`
	// Evidence is the excerpt the statement was drawn from, and SourceText
	// the whole text it came from.
	Evidence   string `json:"evidence,omitempty"`
	SourceText string `json:"source_text,omitempty"`
	// Rules are the definitions of the predicate and every name it reads,
	// oldest first.
	Rules []Rule `json:"rules"`
	// History is every statement about this subject and predicate, oldest
	// first, including the ones replaced or withdrawn.
	History []Event `json:"history"`
}

Explanation says why one belief is held: what it was drawn from, the name it was written under, the definitions that decide how its history folds, and that history.

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"`
	// Episode is the note holding the whole text, written first so that every
	// statement can name it as its evidence. Restating text already kept
	// returns the existing note.
	Episode *RememberResult `json:"episode,omitempty"`
}

type Extractor

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

type Fence added in v0.21.0

type Fence struct {
	Lease  string
	Holder string
	Epoch  uint64
}

Fence names the lease epoch an agent write is made under.

type FencedBackend added in v0.21.0

type FencedBackend interface {
	PutFenced(ctx context.Context, collection, id string, values []float32, metadata map[string]any, fence Fence) error
}

FencedBackend optionally refuses an agent write the lease no longer backs, on the server, so a process that stalled past its lease cannot land a late write over its successor's. PutFenced must fail with an error wrapping ErrLeaseLost when the fence does not hold, and write nothing.

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 ForgetTextResult added in v0.14.0

type ForgetTextResult struct {
	Withdrawn []Belief `json:"withdrawn"`
}

ForgetTextResult reports what a request to forget withdrew.

type GetBackend added in v0.8.0

type GetBackend interface {
	Get(ctx context.Context, collection string, ids []string) ([]StoredVector, error)
}

GetBackend is an optional Backend capability: reading records by id. It is how a caller follows a belief's EvidenceID to the text it came from. Unknown ids are omitted from the result, not reported as errors.

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 Memory added in v0.14.0

type Memory struct {
	// Text says what is believed: "user favorite editor: zed". A note is its
	// own words.
	Text string `json:"text"`
	// Since is when it was stated.
	Since time.Time `json:"since"`
	// Before lists, as text, what this replaced, with when each was stated.
	Before []Earlier `json:"before,omitempty"`
	// Elsewhere lists, as text, what else is believed about the same subject and
	// value under another wording, with when it was stated: "user likes:
	// mangoes" beside "user dislikes: mangoes". The newer one is usually
	// the one that holds.
	Elsewhere []Earlier `json:"elsewhere,omitempty"`
	// EventID identifies the statement, for history and audits.
	EventID string `json:"event_id"`
	// Said is the sentence of the original text the memory was drawn from,
	// so a reader sees how it was said ("Bluefin got acquired by Orca Labs,
	// so I work at Orca Labs now, same role."), not only the fact.
	Said string `json:"said,omitempty"`
}

Memory is one belief told as a sentence, for callers that never see predicates.

type Message added in v0.20.0

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message is one turn of a conversation to remember.

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 PairChange added in v0.22.0

type PairChange struct {
	Subject   string   `json:"subject"`
	Predicate string   `json:"predicate"`
	Before    []string `json:"before"`
	After     []string `json:"after"`
	Added     []string `json:"added,omitempty"`
	Removed   []string `json:"removed,omitempty"`
}

PairChange is how one subject and predicate's beliefs differ between two instants.

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 Position added in v0.26.0

type Position struct {
	Turns   int64 `json:"turns"`
	Actions int64 `json:"actions"`
	State   int64 `json:"state"`
}

Position is how far an agent's records go: the newest turn and action seqs and the working state version.

func ParsePosition added in v0.26.0

func ParsePosition(s string) (Position, error)

ParsePosition reads the turns.actions.state form.

func (Position) String added in v0.26.0

func (p Position) String() string

String formats a position as turns.actions.state, the If-Position form.

type PositionError added in v0.26.0

type PositionError struct {
	// At is the position the write was made from.
	At Position
	// Position is where the records stand. After ErrPositionBehind the Agent
	// has already moved to it, so the next write continues from the records.
	Position Position
	Ahead    bool
}

PositionError is ErrPositionBehind or ErrPositionAhead with the positions.

func (*PositionError) Error added in v0.26.0

func (e *PositionError) Error() string

func (*PositionError) Unwrap added in v0.26.0

func (e *PositionError) Unwrap() error

type Predicate

type Predicate struct {
	Cardinality string `json:"cardinality"`
	ValueType   string `json:"value_type"`
	Description string `json:"description"`
	// Allowed lists an enum's values. Only an enum has it.
	Allowed []string `json:"allowed,omitempty"`
	// Aliases are names this predicate used to have. Events written under an
	// alias fold with this predicate, and a write naming an alias is stored
	// under this predicate's name. Renaming a predicate is giving the new
	// name the old one as an alias.
	Aliases []string `json:"aliases,omitempty"`
	// Excludes names predicates this one contradicts value for value, such
	// as likes for dislikes, or owns for gave_away. Stating a value under
	// one of them withdraws the same value from the other, so the later
	// statement wins and the earlier one reads as replaced. Declared on
	// either side, it holds both ways, and it applies to the whole log,
	// including events written before it was declared.
	Excludes []string `json:"excludes,omitempty"`
	// Historical marks a predicate that records something that happened,
	// such as did or bought. What happened cannot become untrue, so its
	// values are never withdrawn by a correction: not by an excluding
	// predicate, and not by Replaces. Forget still works, for a record that
	// was wrong.
	Historical bool `json:"historical,omitempty"`
}

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, a boolean, an enum, a date, or a ref. Values are stored with that type, so a number compares numerically in recall filters instead of lexically.

An enum is one of Allowed, stored in the spelling Allowed gives it. A date is a calendar day (2026-10-01) or an RFC3339 instant, stored in one canonical form. A ref names another subject, stored the way subjects are, so the value of one belief is the subject of others.

func (Predicate) Cardinal

func (p Predicate) Cardinal() Cardinality

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

type PriorValue added in v0.10.0

type PriorValue struct {
	// Predicate is set when the displaced value was held under another
	// predicate than this one: likes mangoes, replaced by dislikes mangoes.
	Predicate  string    `json:"predicate,omitempty"`
	Value      any       `json:"value"`
	Source     string    `json:"source"`
	ObservedAt time.Time `json:"observed_at"`
	EventID    string    `json:"event_id"`
}

PriorValue is a value that a newer assertion displaced.

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"`
	// Cardinality ("single" or "multi") and Description define a predicate
	// the proposal coins, for an open client. They are ignored for a
	// predicate that is already defined.
	Cardinality string `json:"cardinality,omitempty"`
	Description string `json:"description,omitempty"`
	// Replaces names beliefs of the same subject that this statement makes
	// untrue, under any predicate. See RememberRequest.Replaces.
	Replaces []BeliefRef `json:"replaces,omitempty"`
}

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
	// ValueAfter and ValueBefore bound date-typed values, both inclusive. A
	// calendar day counts as its first instant in UTC.
	ValueAfter  time.Time
	ValueBefore time.Time
	// RefersTo answers "who points at this subject": the beliefs of
	// ref-typed predicates whose value is the subject named here. It is an
	// exact read and cannot be combined with Text. With Predicate set, only
	// that predicate is searched.
	RefersTo string
	// FollowRefs adds, after each ref-typed belief in the answer, what is
	// believed about the subject it names, one hop and within Limit. The
	// added beliefs carry Via.
	FollowRefs bool
	// ObservedAfter and ObservedBefore keep only beliefs whose surviving
	// event was observed in that span, both inclusive. Either may be zero.
	ObservedAfter  time.Time
	ObservedBefore time.Time
	// NoTimeHint stops a search from reading a time phrase in Text ("two
	// weeks ago", "last Saturday", "in March") as a hint to look at that
	// span first. The hint only reorders candidates; it never drops any.
	NoTimeHint bool
	// NoElsewhere leaves Belief.Elsewhere empty, for a caller that does not
	// want the extra lookups. Client reads otherwise fill it.
	NoElsewhere bool
}

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 ReconcileReport added in v0.21.0

type ReconcileReport struct {
	Closed []Action `json:"closed,omitempty"`
	// Open are the actions still open afterwards: external ones nobody could
	// confirm, and idempotent ones with no resolver to run them.
	Open []Action `json:"open,omitempty"`
}

ReconcileReport lists what Reconcile did.

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, the one for coding agents. Applications may extend the returned map before constructing a Client. StarterRegistry has the others.

func LoadRegistry

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

LoadRegistry parses and validates a registry document.

func StarterRegistry added in v0.9.0

func StarterRegistry(name string) (Registry, error)

StarterRegistry returns an independent copy of a starter vocabulary: a registry that is useful for one kind of agent before anyone has written their own. It is a starting point, to be extended or trimmed, and it always includes the note predicate.

func (Registry) AdmitProposals added in v0.9.0

func (r Registry) AdmitProposals(text string, proposals []Proposal) []Proposal

AdmitProposals keeps the proposals RememberText would accept for text and drops the rest, converting a string value to its predicate's declared number or boolean type. RememberText refuses a whole batch for one bad proposal so that the agent that made it can correct it; an extractor backed by a model cannot be asked, so it filters with this instead. Proposals naming an unregistered predicate are kept, since RememberText files their text as a note.

func (Registry) Clone

func (r Registry) Clone() Registry

Clone returns an independent copy of this registry.

func (Registry) ExcludedBy added in v0.15.0

func (r Registry) ExcludedBy(name string) []string

ExcludedBy lists the predicates that contradict name value for value, declared on either side, sorted.

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, value types, enum values, and aliases of a registry.

type RegistryChange added in v0.9.0

type RegistryChange struct {
	At        time.Time `json:"at"`
	Name      string    `json:"name"`
	Predicate Predicate `json:"predicate"`
	// Auto marks a definition an open client recorded because a write named a
	// predicate nothing had defined yet.
	Auto bool `json:"auto,omitempty"`
	// Retroactive marks a correction: the definition applies to the
	// predicate's whole history up to it, not only from At onward.
	Retroactive bool `json:"retroactive,omitempty"`
	// AliasOf, when set, makes this change a merge rather than a definition:
	// Name is read as AliasOf from now on, and Predicate is empty. Events
	// written under Name keep that name, so a merge is a view of the log; a
	// later definition of Name takes it back (Client.Split).
	AliasOf string `json:"alias_of,omitempty"`
	// EventID is the log event holding this change.
	EventID string `json:"event_id"`
}

RegistryChange is one recorded definition of a predicate: what it was from At until the next change to the same name.

type RememberRequest

type RememberRequest struct {
	Subject    string
	Predicate  string
	Value      any
	Kind       string
	Confidence *float64
	Source     string
	// ObservedAt is when the statement was made, for statements recorded
	// after the fact, such as an imported conversation. Zero means now. A
	// statement observed before a later one for the same subject and
	// predicate is history: it answers as_of queries for its time and does
	// not replace what the later one says.
	ObservedAt time.Time
	// Evidence is the exact excerpt the statement was drawn from, at most
	// MaxEvidenceBytes, and EvidenceID the event holding the whole text.
	// RememberText sets both; a caller recording a quote may set Evidence.
	Evidence   string
	EvidenceID string
	// Cardinality and Description define the predicate when an open client
	// meets it for the first time. Cardinality defaults to Single, because a
	// stated fact is more often an update than an addition; a wrong guess is
	// corrected by recording a new definition, and every answer follows it.
	// Both are ignored for a predicate that is already defined.
	Cardinality Cardinality
	Description string
	// Replaces names beliefs of the same subject, under any predicate, that
	// this statement makes untrue: "dislikes mangoes" replacing "likes
	// mangoes", "lives_in Portland" replacing "moved_to Seattle". Each one
	// still believed is withdrawn by a retraction in its own history, linked
	// to this statement, and listed in the answer's replaced. A single-valued
	// predicate's own old value is replaced without being named here.
	Replaces []BeliefRef
	// Related asks for RememberResult.Related: the subject's current beliefs
	// under other predicates that may contradict this statement. The lookup
	// is advice: if it fails, Related is left empty and the write stands.
	Related bool
}

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"`
	// Unreplaced lists the beliefs a statement named in Replaces that were
	// not believed when it was made, so nothing was withdrawn for them.
	Unreplaced []BeliefRef `json:"unreplaced,omitempty"`
	// Related lists current beliefs about the same subject, under other
	// predicates, that may contradict the statement: those with the same
	// value and those closest in meaning. It is filled only on request
	// (RememberRequest.Related). A belief listed here that the statement
	// makes untrue is corrected by remembering the statement again with it
	// in Replaces.
	Related []Belief `json:"related,omitempty"`
}

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

type Resolver added in v0.21.0

type Resolver func(ctx context.Context, a Action) (ActionEnd, error)

Resolver settles one action a crash left open. Reconcile calls it for idempotent actions, which it should run again with the action's Key, and for external ones, which it should check against the outside system (was a message with this subject sent after StartedAt?). Returning a Status of ActionUnknown, or no Resolver at all, leaves an external action open and flagged in the briefing.

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"`
	// PendingActions are tool calls a crash left open: begun, never ended,
	// or ended unknown. Reconcile settles what it can; the rest stay here
	// and at the top of the briefing.
	PendingActions []Action      `json:"pending_actions,omitempty"`
	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
	// OnRepeat, when set, is called each time a write is answered with what
	// was already recorded under its message id, call id or outcome, as
	// after a retry or a restore. It runs with the agent locked and must not
	// call back into the Agent or block.
	OnRepeat func()
}

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

type Rule added in v0.14.0

type Rule struct {
	At          time.Time `json:"at,omitzero"`
	Name        string    `json:"name"`
	Change      string    `json:"change"`
	Cardinality string    `json:"cardinality,omitempty"`
	ValueType   string    `json:"value_type,omitempty"`
	Description string    `json:"description,omitempty"`
}

Rule is one recorded definition, told for a reader.

type Selector added in v0.14.0

type Selector interface {
	// Select returns the indexes of the candidates the request names, and
	// none when no candidate clearly matches.
	Select(ctx context.Context, request string, candidates []Belief) ([]int, error)
}

Selector picks which remembered statements a request is about. It is how a request in words, such as "forget my editor", becomes withdrawals: the client finds candidate beliefs by searching for the request, and the selector, usually a model, decides which of them it names.

type SinceReport added in v0.26.0

type SinceReport struct {
	AgentID string `json:"agent_id"`
	// From is the position asked about; Position is where the records stand.
	From     Position `json:"from"`
	Position Position `json:"position"`
	Turns    []Turn   `json:"turns,omitempty"`
	// Actions begun after From, in every status, oldest first.
	Actions []Action `json:"actions,omitempty"`
	// WorkingState is the current working state, when it changed after From.
	WorkingState *WorkingState `json:"working_state,omitempty"`
	Omitted      struct {
		Turns int `json:"turns,omitempty"`
	} `json:"omitted"`
	TokenBudget int    `json:"token_budget"`
	Tokens      int    `json:"tokens"`
	Briefing    string `json:"briefing"`
}

SinceReport is what happened after a position: the turns, the actions in every status, and the working state if it changed, with a briefing for the model.

type Step added in v0.22.0

type Step struct {
	At      time.Time `json:"at"`
	EventID string    `json:"event_id"`
	// Statement tells the event in words. A withdrawal starts "withdrew".
	Statement string `json:"statement"`
	// Predicate is the name the event was written under. It differs from the
	// timeline's own when a statement under an excluding predicate withdrew
	// one of its values: dislikes mangoes ending likes mangoes.
	Predicate string `json:"predicate"`
	Source    string `json:"source"`
	Evidence  string `json:"evidence,omitempty"`
	// Change is "stated" (a value began to be believed), "replaced" (one
	// value took another's place), "withdrawn" (a value stopped being
	// believed with nothing in its place), or "no change" (restated, or
	// dated before a newer statement).
	Change string `json:"change"`
	// Added and Removed are the beliefs this step began and ended, told as
	// sentences: the diff of what was believed just before and just after.
	Added   []string `json:"added,omitempty"`
	Removed []string `json:"removed,omitempty"`
}

Step is one statement in a belief's timeline and what it did to what was believed: the correction told as a change, not just as an event.

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) Diff added in v0.22.0

func (s *Store) Diff(r DiffRequest) ([]PairChange, error)

Diff says what was believed differently at To than at From: for every subject and predicate a statement touched in between, the beliefs at each end and which began and ended. Notes filed into statements are left out, as answers leave them out.

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.

A predicate that was renamed has events under each name it has had. They are one history, returned together, each event under the name it was written with.

func (*Store) Merge added in v0.14.0

func (s *Store) Merge(name, into string) error

Merge makes name read as into from now on: its events fold with into's, under into's definition, and a write naming it is filed under into. Events keep the name they were written under, so Split undoes the merge. Both must store the same type.

func (*Store) Recall

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

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

func (*Store) Redefine added in v0.14.0

func (s *Store) Redefine(name string, p Predicate) error

Redefine corrects a predicate's definition for its whole history, not only from now on. It is how a wrong guess made when an open write defined the predicate is fixed: redefining a single-valued predicate as multi-valued brings back every value it hid, in present and as-of answers alike, because answers are folded from the log at read time and nothing was deleted. The stored type cannot change, because values already written must stay readable.

func (*Store) Registry

func (s *Store) Registry() Registry

Registry returns a copy of the predicates this store accepts.

func (*Store) RegistryLog added in v0.9.0

func (s *Store) RegistryLog() ([]RegistryChange, error)

RegistryLog returns every recorded registry change, oldest first. It is empty for a store whose registry has never been synced.

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.

func (*Store) Split added in v0.14.0

func (s *Store) Split(name string) error

Split undoes a merge: name becomes its own predicate again, defined as the predicate it was merged into, and the events written under it fold on their own again.

func (*Store) SyncRegistry added in v0.9.0

func (s *Store) SyncRegistry() ([]string, error)

SyncRegistry records this store's configured registry in the log, and returns the names of the predicates whose definitions it recorded. A predicate already recorded as configured writes nothing, so calling it at every start is safe.

This is how a registry changes. A new predicate, a new description, a changed cardinality, a wider enum, and a rename (the new name listing the old one in Aliases) each become one event, effective from the moment it is recorded: events observed before a cardinality change keep folding under the old cardinality, so as-of reads answer as they did then. A change of stored type, such as number to string, is refused because the values already written could not be read under it. Splitting one predicate into two is not a registry change: which half an old event belongs to is a judgment about that event, so it is done by re-remembering.

func (*Store) Timeline added in v0.22.0

func (s *Store) Timeline(subject, predicate string) (Timeline, error)

Timeline tells one subject and predicate's history as changes. Each step is a recorded statement with the beliefs it began and ended, found by folding the log just before and just after it, so the timeline says exactly what a read at any instant would have answered. Statements under an excluding predicate appear only when they changed this one.

type StoredVector

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

StoredVector is one record as the database returns it.

type TextSearchBackend added in v0.7.0

type TextSearchBackend interface {
	SearchText(ctx context.Context, collection, text string, k int, filter map[string]any) ([]Hit, error)
}

TextSearchBackend is an optional Backend capability, the context-aware form of TextSearcher.

type TextSearcher added in v0.7.0

type TextSearcher interface {
	// SearchText returns ErrTextSearchUnsupported when this collection has no
	// text index to search yet; recall then uses the vector search alone.
	SearchText(collection, text string, k int, filter map[string]any) ([]Hit, error)
}

TextSearcher is an optional VectorDB capability: a lexical (BM25) search over each event's text metadata field. Semantic recall uses it beside the vector search when the database offers it, because a hashed lexical vector ranks words far worse than an inverted index does.

type Timeline added in v0.22.0

type Timeline struct {
	Subject   string   `json:"subject"`
	Predicate string   `json:"predicate"`
	Now       []string `json:"now"`
	Steps     []Step   `json:"steps"`
}

Timeline is one subject and predicate's history told as changes, oldest first, with what is believed at the end of 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"`
	// Brief is a shorter form of Content for the resume briefing, when the
	// harness has one: a tool call with its long arguments elided, say. The
	// record keeps Content whole; only the briefing shows Brief instead.
	Brief string    `json:"brief,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"`
	ActionSeq int64     `json:"action_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.

type WriteOption added in v0.26.0

type WriteOption func(*writeOptions)

WriteOption adjusts one agent write.

func At added in v0.26.0

func At(p Position) WriteOption

At makes a write conditional on the records standing at p, the position the caller last saw. When they are ahead the write fails with ErrPositionBehind; when behind, with ErrPositionAhead. A write the ids show was already made (a turn's MessageID, an action's CallID) returns the recorded one before the position is checked, so a retried write carrying the position from before it is not refused.

func CallID added in v0.26.0

func CallID(id string) WriteOption

CallID gives BeginAction the harness's id for the tool call, usually the model's tool call id. An action already begun under it is returned with its current status and result instead of a new action.

Jump to

Keyboard shortcuts

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