brain

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package brain is Tacklr's knowledge-base retrieval engine.

Canonical architecture (Engrams, two jobs, search, graph, tools): docs/knowledge.md.

Public surface

Hosts build one Engine (NewEngine) over a Store, add a Graph with WithGraph, and register kinds (ApplyKinds / WithKinds). The agent-facing operations are the five tools' methods: Search (and Next for more), Open, Related, Save and Link. Hosts also use PutTree, SoftDelete, PurgeDeleted, Erase, Get, Resolve and the session-message methods. MemoryStore is an in-process store for tests and offline hosts. Durable backends are injected: brain/postgres.Store and brain/helixgraph.Graph (or any backend that passes brain/storetest or brain/graphtest). The harness registers the tools when AgentOptions.Brain is set: search, open and related always, save for AgentOptions.BrainWriteKinds, and link when the engine has a graph.

The engine brokers between the store and the graph. A missing graph is a missing source, not an error: Search and Related return the store's results, and only Link needs a graph (ErrUnsupported). Every committed write of a record goes to the store, then each Index (a graph is one; WithIndex adds others), then the audit record.

A store implements Store and passes brain/storetest; a graph implements Graph and passes brain/graphtest. The backend owns its retrieval: its own Embedder, channels, ranking and fusion, filters, and the scope and readers rules. Engine owns orchestration and domain rules: validation, the kind catalog and the text that represents an object (Indexed), content-derived part ids, the write order, fusing the sources by reciprocal rank, reading every result from the store (the source of truth), promoting parts to their records, paging, reranking and audit. Backend authors can reuse Embedding (batched, bounded embedding with EmbedBatches for tree writes), Ranking (RRF fusion with recency decay) and Filter.Compile / FilterPlan (filter evaluation and translation).

This package does not import postgres, helixgraph, the harness, session, or telemetry; Scope is passed in by the caller.

Search takes free text, an optional kind and filters, and returns one ranked list: records (with the parts that matched as evidence) and, with a graph and no kind or filters, links whose notes matched. The store ranks records and parts; the graph ranks objects and links; Engine fuses the lists and reads each result from the store. A UUID query returns that object; a query in double quotes is matched literally. Filters test the record (for a part, its parent). Each page carries facets (the kinds and common field values among its objects) and a Rest that Next pages through; a SearchContext keeps the last Rest of each tool, so a tool call with more continues it, across checkpoints too.

Related returns a record's children (or a part's parent and nearby parts) and, with a graph, the records its relations reach, each tagged with how it is related. Open reads one object in full with its kind's fields.

Kind schemas (host migrations)

Object kinds are host/user-defined for determinism. Register with ApplyKinds (or WithKinds). Agent-defined kinds are out of scope. The tools take the registered record kinds as a JSON-schema enum; errors on an unknown kind or filter name the valid choices.

Explicit writes (no handoff side effects)

Durable product objects are written via Engine.Save / PutTree / SoftDelete (host SDK) or the save tool. A plan handoff saves the exact live window with Engine.SaveSessionMessages into session_messages (host namespace plus the session id at the tail). Those rows are not the harness checkpoint. Search returns them together with host-namespace knowledge for the active session. PutTree is how a host attaches corpus chunks under a parent. It streams the parts, embeds only those whose content changed (part ids come from content), stages them in batches, and swaps them in with one atomic commit.

Isolation

Every Engine and store call takes a Scope with a non-empty Namespace; an empty one fails with ErrInvalid. The namespace's first attr is the tenant: a scope reaches only rows with the same tenant, and stores match it by equality before anything else. Writes are guarded: an object must lie inside the scope, and an id already held outside the scope returns ErrNotFound, so a tenant cannot overwrite another tenant's row. Objects with Readers (source ACLs) are visible only to scopes holding one of those Principals, in the store and in the graph: an object the caller cannot read takes no ranking slot, nor does an edge that touches it, and no walk goes through it. PurgeDeleted, Erase, and PurgeSessionMessages hard-delete for retention and erasure; Erase erases the indexes by scope first, so a retry finishes an erase that failed part way. WithAudit records every served read and write.

Index text: parents are represented by EntityIndexText, parts by IndexText with the parent title prefix. WithIndexText rewrites that text at Save without changing the stored object. Each backend embeds it with its own Embedder (none: text only); a backend's vector dimension is its own option (postgres.Options.EmbeddingDim, helixgraph.Options.Dimension). A write whose text does not embed fails; a search whose query does not embed is answered by its words.

Boot sketch

emb := brain.Embedding{Embedder: myEmbedder}
opts := postgres.Options{EmbeddingDim: 1536, Embedding: emb}
cfg, err := pgxpool.ParseConfig(dsn)
if err := postgres.Configure(cfg, opts); err != nil { return err }
pool, err := pgxpool.NewWithConfig(ctx, cfg)
store, err := postgres.Open(pool, opts)
if err := store.Setup(ctx, specs...); err != nil { return err }
client, err := helix.NewClient(helixURL)
g, err := helixgraph.Open(ctx, client, helixgraph.Options{Dimension: 1536, EdgeRelations: []string{"about"}, Embedding: emb})
eng, err := brain.NewEngine(store, brain.WithGraph(g))
if err := eng.LoadKindsFromStore(ctx); err != nil { return err }

Integration tests need Docker (Testcontainers):

  • postgres.Store: pgvector/pgvector (internal/pgtest.Image)
  • helixgraph: ghcr.io/helixdb/helixdb:v0.0.12 (in-memory)

Index

Constants

View Source
const (
	FieldKind      = "kind"
	FieldTitle     = "title"
	FieldCreatedAt = "created_at"
	FieldUpdatedAt = "updated_at"

	OpEq  = "eq"
	OpIn  = "in"
	OpGte = "gte"
	OpLt  = "lt"
)

Filter condition fields and operators.

View Source
const (
	DirectionOut  = "out"
	DirectionIn   = "in"
	DirectionBoth = "both"
)

Edge directions, as seen from the object a walk leaves.

View Source
const (
	RelationChild   = "child"
	RelationParent  = "parent"
	RelationSibling = "sibling"
)

Relation types of the containment results of Related.

View Source
const (
	// SessionTailName is the namespace attribute appended for session messages.
	// Tool callers cannot set it.
	SessionTailName = "session"
	// KindSessionMessage is the kind of one saved context message.
	KindSessionMessage = "SessionMessage"
)
View Source
const (
	PropSlug    = "slug"
	PropVFSPath = "vfs_path"
)

Reserved store properties persisted on objects without a KindSpec field. slug is the Engram filename stem. vfs_path is Provider-internal (full virtual path); it is not a Markdown front-matter key.

Variables

View Source
var (
	// ErrNotFound is returned when an object is missing, soft-deleted, or outside scope.
	ErrNotFound = errors.New("brain: object not found")
	// ErrInvalid groups validation failures (empty query, missing args, frozen catalog).
	ErrInvalid = errors.New("brain: invalid")
	// ErrUnsupported groups missing backend capabilities (no writer, no graph, no listing).
	ErrUnsupported = errors.New("brain: unsupported")
	// ErrConflict is returned when another write changed the object first.
	// Nothing was written; retry from a fresh read.
	ErrConflict = errors.New("brain: conflict")
	// ErrIndexPut and ErrIndexRemove are index write failures (a graph is an
	// index). The store row is the source of truth: re-Put after fixing the
	// index.
	ErrIndexPut    = errors.New("brain: index put")
	ErrIndexRemove = errors.New("brain: index remove")
)

Coarse categories for errors.Is. Wrap a specific message at the call site (fmt.Errorf("…: %w", ErrInvalid)) instead of adding a sentinel per situation.

Functions

func FilterValueKey added in v0.5.0

func FilterValueKey(v any) (string, bool)

FilterValueKey is the canonical typed form of a scalar filter or property value: values a filter treats as equal (the same string, the same bool, or numbers equal as float64) have equal keys, and values of other types never do. A backend can index property values by key to match filters natively. A non-scalar value has no key.

func Parts added in v0.5.0

func Parts(objs ...Object) iter.Seq2[Object, error]

Parts yields objs as PutTree parts.

func PersistKinds

func PersistKinds(ctx context.Context, store Store, specs ...KindSpec) error

PersistKinds upserts validated kind specs into store (additive).

Types

type Attr added in v0.2.0

type Attr struct {
	Name  string `json:"name" desc:"Attribute name (e.g. org, workspace)."`
	Value string `json:"value" desc:"Attribute value. Must not contain '.'."`
}

Attr is one named isolation dimension (org, workspace, …). Name and Value must be non-empty and must not contain '.'.

type AuditEvent added in v0.5.0

type AuditEvent struct {
	Time       time.Time
	Op         AuditOp
	Namespace  Namespace
	Principals []string
	SessionID  string
	ObjectIDs  []uuid.UUID
	// Count is the number of rows a purge or erase removed.
	Count int
}

AuditEvent is one brain operation: who (namespace, principals, session), what (op), and which objects. Reads list the ids returned to the caller.

type AuditFunc added in v0.5.0

type AuditFunc func(ctx context.Context, ev AuditEvent) error

AuditFunc records one audit event. postgres.Store.Record is one (audit_events).

type AuditOp added in v0.5.0

type AuditOp string

AuditOp names the operation an AuditEvent records.

const (
	AuditRead          AuditOp = "read"
	AuditPut           AuditOp = "put"
	AuditDelete        AuditOp = "delete"
	AuditLink          AuditOp = "link"
	AuditUnlink        AuditOp = "unlink"
	AuditPurge         AuditOp = "purge"
	AuditErase         AuditOp = "erase"
	AuditSessionSave   AuditOp = "session_save"
	AuditSessionDelete AuditOp = "session_delete"
	AuditSessionPurge  AuditOp = "session_purge"
)

Audit operations recorded by Engine.

type EdgeMeta

type EdgeMeta struct {
	Note       string     `json:"note,omitempty"`
	Status     string     `json:"status,omitempty"`     // e.g. active, resolved
	Role       string     `json:"role,omitempty"`       // e.g. primary buyer vs cc
	Confidence float64    `json:"confidence,omitempty"` // 0 means unset; otherwise typically (0,1]
	EvidenceID *uuid.UUID `json:"evidence_id,omitempty"`
	CreatedAt  time.Time  `json:"created_at,omitempty"`
	UpdatedAt  time.Time  `json:"updated_at,omitempty"`
}

EdgeMeta is optional metadata on a non-containment relationship (why/how/when linked). Kept short and relational — full bodies stay on objects in the Store.

type EdgeSearchHit

type EdgeSearchHit struct {
	FromID       uuid.UUID
	ToID         uuid.UUID
	RelationType string
	Meta         EdgeMeta
	Score        float64
}

EdgeSearchHit is one graph edge search result (endpoints + meta + score).

type Embedder added in v0.5.0

type Embedder interface {
	// Embed returns one vector per text, in order.
	Embed(ctx context.Context, texts []string) ([][]float32, error)
	// Model names the model and version (for example
	// "text-embedding-3-small"). Backends store it with every vector and
	// compare only vectors from the same model.
	Model() string
}

Embedder turns text into vectors for a backend's semantic channel. Each backend that embeds owns its Embedder.

type Embedding added in v0.5.0

type Embedding struct {
	Embedder    Embedder
	BatchSize   int
	Concurrency int
}

Embedding is how a backend embeds: its Embedder and how many texts it sends at once. A nil Embedder embeds nothing, so the backend ranks text alone. Zero BatchSize is 128 and zero Concurrency is 2.

func (Embedding) Embed added in v0.5.0

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

Embed returns one vector per text, cloned so the Embedder cannot change stored vectors later. Without an Embedder it returns nil.

func (Embedding) EmbedBatches added in v0.5.0

func (e Embedding) EmbedBatches(ctx context.Context, parts iter.Seq2[Indexed, error], reuse func(uuid.UUID) bool, stage func(context.Context, []TreePart) error) (int, error)

EmbedBatches is the tree-write pipeline a backend can use for Store.PutTree. It reads parts in order, keeps a part that reuse reports live as a reference, embeds the new parts' Text in batches of BatchSize with at most Concurrency batches at once, and passes each batch to stage as it finishes. Memory therefore holds a few batches, whatever the number of parts. It returns how many parts it read. The first error (from parts, embedding or stage) cancels the batches in flight and is returned once they stop.

func (Embedding) EmbedOne added in v0.5.0

func (e Embedding) EmbedOne(ctx context.Context, text string) ([]float32, error)

EmbedOne embeds text, or returns nil without an Embedder or text.

func (Embedding) Enabled added in v0.5.0

func (e Embedding) Enabled() bool

Enabled reports whether e has an Embedder.

func (Embedding) Model added in v0.5.0

func (e Embedding) Model() string

Model is the Embedder's model, or "" without one.

type Engine

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

Engine is the boundary over a Store, an optional Graph and other indexes. It validates requests, shapes index text from the kind catalog, writes the store and then every index, fuses the backends' ranked lists, reads every result from the store, pages, and audits. The backends own retrieval.

func NewEngine

func NewEngine(store Store, opts ...EngineOption) (*Engine, error)

NewEngine builds an Engine over a Store. store must be non-nil.

func (*Engine) ApplyKinds

func (e *Engine) ApplyKinds(ctx context.Context, specs ...KindSpec) error

ApplyKinds is the host migration entry point: desired process catalog + optional durable upsert.

func (*Engine) Catalog

func (e *Engine) Catalog() *KindCatalog

Catalog returns the process kind catalog for inspection. Empty means open mode. Prefer store.Setup plus LoadKindsFromStore, or ApplyKinds; do not mutate catalog fields directly.

func (*Engine) DeleteSessionMessages added in v0.4.0

func (e *Engine) DeleteSessionMessages(ctx context.Context, host Namespace, sessionID string) error

DeleteSessionMessages removes every saved message for sessionID under host.

func (*Engine) Erase added in v0.5.0

func (e *Engine) Erase(ctx context.Context, scope Scope) error

Erase hard-deletes everything under scope (erasure requests and tenant offboarding): it erases every index by scope, then the store's objects and saved session messages. Readers do not limit Erase. A failure leaves the store intact, and calling Erase again finishes the erase everywhere.

func (*Engine) Get added in v0.2.0

func (e *Engine) Get(ctx context.Context, scope Scope, id uuid.UUID) (Object, error)

Get returns the stored object id names under scope, as the store holds it (with Readers and properties), for hosts. The agent tools use Open.

func (*Engine) HasGraph added in v0.5.0

func (e *Engine) HasGraph() bool

HasGraph reports whether the engine has a graph, so the harness registers the link tool.

func (e *Engine) Link(ctx context.Context, scope Scope, req LinkRequest) error

Link creates or updates a non-containment edge between two visible first-class objects, or removes it when req.Remove is set (removing a missing edge succeeds). The edge takes the source object's namespace. Link needs a graph (ErrUnsupported without one).

func (*Engine) LoadKindsFromStore

func (e *Engine) LoadKindsFromStore(ctx context.Context) error

LoadKindsFromStore replaces the process catalog from the store.

func (*Engine) Next added in v0.5.0

func (e *Engine) Next(ctx context.Context, scope Scope, rest Rest, limit int) (Page, error)

Next returns the next page of rest, at most limit results.

func (*Engine) Open added in v0.5.0

func (e *Engine) Open(ctx context.Context, scope Scope, id uuid.UUID) (Opened, error)

Open reads the object id names in full under scope, with its first children, in one store read. The store returns a saved session message when Scope.SessionID is set and id is one. Kind fields come from the catalog; in open mode, from the store's kind registry, which the engine reads once (kinds persisted later show after a restart).

func (*Engine) PurgeDeleted added in v0.5.0

func (e *Engine) PurgeDeleted(ctx context.Context, scope Scope, before time.Time) (int, error)

PurgeDeleted hard-deletes objects under scope that were soft-deleted before cutoff (retention). It returns how many rows it removed.

func (*Engine) PurgeSessionMessages added in v0.5.0

func (e *Engine) PurgeSessionMessages(ctx context.Context, host Namespace, before time.Time) (int, error)

PurgeSessionMessages removes saved messages under host older than cutoff, for every session (retention for sessions that are never closed). It returns how many rows it removed.

func (*Engine) PutTree added in v0.5.0

func (e *Engine) PutTree(ctx context.Context, scope Scope, parent Object, parts iter.Seq2[Object, error]) (Object, error)

PutTree upserts a first-class parent and makes parts its only parts, in order.

Part ids come from content: a part whose kind, content type, title, summary, content and index text match a live part has that part's id, so the store keeps its row and index and indexes only new parts. Engine prepares each part as the store reads it (ParentID, the parent's namespace and readers, Position from its index unless set, times, validation), so memory never holds every part. The store commits the tree atomically: until then reads and searches see the previous parts, and a failure leaves them in place.

Part ids must be nil. When another PutTree of the same parent commits between this one's read and commit, PutTree returns ErrConflict and changes nothing.

func (*Engine) Related added in v0.5.0

func (e *Engine) Related(ctx context.Context, scope Scope, req RelatedRequest) (Page, error)

Related returns the objects related to req.ID in one list, each tagged with how it is related: a record's children ("child"), or a part's parent ("parent") and nearby parts ("sibling"), then, with a graph, the objects its relations reach (the relation, direction, depth and note). Without a graph Related returns the children only. When the graph fails, Related returns the children unless FailOnGraphError is set or only a graph relation was asked for.

func (*Engine) Resolve added in v0.5.0

func (e *Engine) Resolve(ctx context.Context, scope Scope, ref Ref) (uuid.UUID, error)

Resolve returns the id ref names under scope.

func (*Engine) Save added in v0.5.0

func (e *Engine) Save(ctx context.Context, scope Scope, obj Object) (Object, error)

Save upserts a knowledge object under scope. Catalog non-empty → ValidateObject. Namespace filled from scope when missing; a namespace outside scope is invalid. A part's parent must be visible under scope. ID generated when nil. An id already held by a row outside scope returns ErrNotFound and changes nothing. Save refuses objects that already have DeletedAt set. The store indexes the object's text (and embeds it when it has an Embedder); an embedding failure fails the Save. A first-class object then goes to every index (a graph upserts its node and keeps its edges). If an index write fails after the store write, the store row remains (source of truth) and the write is still audited; Save again after fixing the index.

func (*Engine) SaveSessionMessages added in v0.4.0

func (e *Engine) SaveSessionMessages(ctx context.Context, host Namespace, sessionID, generationKey string, messages []SessionMessage) (int, error)

SaveSessionMessages writes one pre-handoff context window under host. The store indexes each message; an embedding failure does not fail the save.

func (*Engine) Search

func (e *Engine) Search(ctx context.Context, scope Scope, req SearchRequest) (Page, error)

Search ranks records for a query in one list: the store's records and parts (with the session's messages when Scope.SessionID is set) and, with a graph, its objects and the links whose notes match. Each backend ranks its own data; Search fuses the lists by reciprocal rank, so a record found by several sources ranks higher, and reads every result from the store.

A query that is a UUID returns that object. A query in double quotes is matched literally: only the store's exact search runs. Links rank only in a search without a kind or filters, since filters describe records. When the graph fails, Search returns the store's results unless FailOnGraphError is set.

With no query, a kind or filters list the matching records newest first, from the store. Within searches only the store, for that record's parts: the graph's objects and links are other records, so they do not apply.

func (*Engine) SoftDelete

func (e *Engine) SoftDelete(ctx context.Context, scope Scope, id uuid.UUID) error

SoftDelete marks an object and its parts deleted. A first-class object leaves every index first, so an index failure keeps the store row. If the store SoftDelete then fails, Save puts the object back in the indexes.

func (*Engine) SyncKindsToStore

func (e *Engine) SyncKindsToStore(ctx context.Context) error

SyncKindsToStore pushes the process catalog to the store.

type EngineConfig

type EngineConfig struct {
	CandidateK       int
	EvidenceN        int
	SnippetCap       int
	DefaultLimit     int
	MaxLimit         int
	SiblingRadius    int
	GraphNeighborK   int // max neighbors one graph walk returns (default 50)
	MaxExpandHops    int // max Depth on Related (default 4)
	MaxResultSetSize int
	FailOnGraphError bool
	Now              func() time.Time
}

EngineConfig holds engine-owned knobs (not tool arguments). Ranking, fusion within a backend, recency decay and embedding are each backend's own options. SnippetCap is the evidence quote length in runes (0 selects 240). CandidateK is how many hits Engine asks each source for before it fuses, reranks and pages them. FailOnGraphError false (default) lets Related fall back to the children when the graph fails; true surfaces the error.

func DefaultEngineConfig

func DefaultEngineConfig() EngineConfig

DefaultEngineConfig returns the engine defaults. A zero count on EngineConfig takes the matching field from here.

type EngineOption

type EngineOption func(*Engine)

EngineOption configures NewEngine.

func WithAudit added in v0.5.0

func WithAudit(record AuditFunc) EngineOption

WithAudit records every read and write the Engine serves. An error from record fails the operation, so an operation is never served without its event. The record runs after the operation, so it does not stop when the caller cancels: a committed write still gets its event, within auditTimeout.

func WithConfig

func WithConfig(cfg EngineConfig) EngineOption

WithConfig sets the engine configuration (normalized by NewEngine).

func WithGraph

func WithGraph(g Graph) EngineOption

WithGraph adds the knowledge graph: it receives every committed write as an Index, ranks objects and links for Search, and walks relations for Related. It also enables Link.

func WithIndex added in v0.5.0

func WithIndex(ix Index) EngineOption

WithIndex adds an index that receives every committed write of a first-class object (a second search system, a change feed).

func WithIndexText added in v0.3.0

func WithIndexText(fn IndexTextFunc) EngineOption

WithIndexText sets how Save builds an object's index text.

func WithKinds

func WithKinds(specs ...KindSpec) EngineOption

WithKinds registers host-defined object kinds at construct time. Invalid specs cause NewEngine to fail. Kinds are host/user-owned for determinism.

func WithReranker

func WithReranker(fn RerankFunc) EngineOption

WithReranker reranks the head of every search with fn. Without it, Search keeps the fused order.

type Evidence

type Evidence struct {
	PartID     uuid.UUID      `json:"part_id"`
	Title      string         `json:"title,omitempty"`
	Snippet    string         `json:"snippet,omitempty"`
	Score      float64        `json:"score,omitempty"`
	Position   *int           `json:"position,omitempty"`
	Properties map[string]any `json:"properties,omitempty"`
}

Evidence is a part that justified a parent hit during search.

type Facets added in v0.5.0

type Facets struct {
	Kinds      map[string]int            `json:"kinds,omitempty"`
	Properties map[string]map[string]int `json:"properties,omitempty"`
}

Facets count the kinds and the common property values of a page's objects, so a caller can narrow a search with values that exist. With registered kinds they cover each kind's fields; in open mode, the properties with at most maxFacetValues distinct values on the page.

type FieldSpec

type FieldSpec struct {
	Name        string    `json:"name"`
	Type        FieldType `json:"type"`
	Description string    `json:"description,omitempty"`
	Required    bool      `json:"required,omitempty"`
	Operators   []string  `json:"operators,omitempty"`  // always eq, or eq+in (see KindSpec.Normalize)
	Examples    []string  `json:"examples,omitempty"`   // documentation only; not enforced
	Enum        []string  `json:"enum,omitempty"`       // closed set for string fields; enforced on Put
	SkipIndex   bool      `json:"skip_index,omitempty"` // omit from entity index text; still stored and filterable
}

FieldSpec describes one property on a kind (filters and Put validation).

type FieldType

type FieldType string

FieldType is the closed set of property types for kind schemas.

const (
	FieldTypeString   FieldType = "string"
	FieldTypeNumber   FieldType = "number"
	FieldTypeBoolean  FieldType = "boolean"
	FieldTypeDateTime FieldType = "datetime"
)

type Filter added in v0.2.0

type Filter struct {
	Kind          StringMatch
	Title         StringMatch
	CreatedAfter  string
	CreatedBefore string
	UpdatedAfter  string
	UpdatedBefore string
	Props         map[string]PropFilter
}

Filter narrows retrieval. Well-known fields plus Props. Eq or list (In).

func DecodeFilter added in v0.2.0

func DecodeFilter(m map[string]any) (Filter, error)

DecodeFilter maps a JSON object (tool boundary) onto Filter.

func (Filter) Compile added in v0.5.0

func (f Filter) Compile() (FilterPlan, error)

Compile validates f and compiles it.

func (Filter) Validate added in v0.5.0

func (f Filter) Validate() error

Validate checks well-known fields and property value shapes. Empty is valid.

func (Filter) ValidateAgainst added in v0.5.0

func (f Filter) ValidateAgainst(cat *KindCatalog) error

ValidateAgainst runs structural validation, then catalog rules when non-empty.

type FilterCondition added in v0.5.0

type FilterCondition struct {
	// Field is FieldKind, FieldTitle, FieldCreatedAt, FieldUpdatedAt, or a
	// property key when Property is set.
	Field    string
	Property bool
	// Op is OpEq (Values has one value), OpIn (any of Values), OpGte or
	// OpLt (against Time). Values keep their JSON types: a property matches
	// only a value of the same type (string, bool, or a number compared as
	// float64).
	Op     string
	Values []any
	Time   time.Time
}

FilterCondition is one condition of a FilterPlan; an object passes the plan when it meets every condition.

type FilterPlan added in v0.5.0

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

FilterPlan is the compiled form of a Filter. A backend evaluates it in process with Match, or translates its Conditions into its own query language (brain/postgres does so for SQL).

func (FilterPlan) Conditions added in v0.5.0

func (p FilterPlan) Conditions() []FilterCondition

Conditions lists the plan's conditions.

func (FilterPlan) Match added in v0.5.0

func (p FilterPlan) Match(obj Object) bool

Match reports whether obj meets every condition.

type Graph added in v0.5.0

type Graph interface {
	// Put (Index) upserts the node of a first-class object, indexes its
	// Text, and keeps the node's edges. The node holds what the backend
	// needs to rank and filter: namespace, readers, kind, title, times,
	// properties. Remove (Index) drops the node and its edges.
	Index
	// Link creates or replaces the edge e.From→e.To with e.RelationType and
	// indexes its note. Both nodes must exist (ErrNotFound otherwise).
	Link(ctx context.Context, e GraphEdge) error
	// Unlink drops the edge from→to with rel (a missing edge succeeds).
	Unlink(ctx context.Context, from, to uuid.UUID, rel string) error

	// FindObjects returns the readable nodes that pass q.Filters, best
	// first, at most q.Limit.
	FindObjects(ctx context.Context, q ObjectSearch) ([]ScoredID, error)
	// FindLinks returns the readable edges of q.RelationType (every indexed
	// relation when it is empty), best first, at most q.Limit.
	FindLinks(ctx context.Context, q LinkSearch) ([]EdgeSearchHit, error)
	// Neighborhood walks breadth-first from q.ObjectID. Each object appears
	// once, at its smallest depth; the start never appears. Results are
	// ordered by depth, then relation (request order), then outbound first.
	// Empty Relations follows every relation.
	Neighborhood(ctx context.Context, q NeighborhoodQuery) ([]GraphNeighbor, error)
}

Graph is the knowledge graph Engine links and walks objects in (WithGraph): a node per first-class object and labeled edges between them. A backend owns its retrieval: its Embedder (node text and edge notes), channels, ranking and fusion, filters, and the scope and readers rules. helixgraph implements it, and brain/graphtest is the contract a graph must pass. A backend without a feature returns ErrUnsupported from that method.

Engine validates and normalizes every call first: ids are set, the namespace is valid, relations are trimmed and unique, the direction is a Direction constant, and limits and depths are positive. Engine also hydrates every result from the Store, the source of truth.

type GraphEdge added in v0.5.0

type GraphEdge struct {
	// Namespace is the edge's own (its source object's), which edge search
	// filters on.
	Namespace    Namespace
	From, To     uuid.UUID
	RelationType string
	Meta         EdgeMeta
}

GraphEdge is one directed, labeled non-containment edge.

type GraphNeighbor

type GraphNeighbor struct {
	ObjectID     uuid.UUID
	SourceID     uuid.UUID // the object the edge was followed from
	RelationType string
	Direction    string // DirectionOut or DirectionIn, from SourceID
	Depth        int    // hops from the walk's start
	Meta         EdgeMeta
}

GraphNeighbor is one object a neighborhood walk reached.

type Index added in v0.5.0

type Index interface {
	// Put upserts obj and indexes its Text.
	Put(ctx context.Context, obj Indexed) error
	// Remove drops the object.
	Remove(ctx context.Context, id uuid.UUID) error
	// Erase drops every object scope's namespace covers, whatever its
	// readers, in one step. It is idempotent, so Engine runs it before the
	// store's erase and a retry finishes an erase that failed part way.
	Erase(ctx context.Context, scope Scope) error
}

Index receives every committed write of a first-class object: Engine writes the store, then each index, then the audit record. A Graph is an Index; WithIndex adds others (a second search system, a change feed).

type IndexTextFunc added in v0.3.0

type IndexTextFunc func(obj Object, defaultText string) string

IndexTextFunc returns the text that represents obj in the store and the graph (Indexed.Text), which each backend indexes and embeds its own way. defaultText is Engine's index text for this object (SkipIndex already applied). Return defaultText to keep it, or any rewrite that should occupy the vector space (prefix, replace, drop the body, join related titles, …). Empty means do not index. Title, Summary, Content, and Properties on the stored object are not modified.

type Indexed added in v0.5.0

type Indexed struct {
	Object
	Text string
}

Indexed is an object and the text the engine chose to represent it in search (entity text for a parent, parent-prefixed text for a part, as shaped by WithIndexText). A backend indexes Text its own way: lexical, embedded with its own Embedder, or both. Empty Text is not indexed.

type KindCatalog

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

KindCatalog is the process-local enforcement view of registered kinds. Empty means open mode. Specs are treated as immutable after registration.

func (*KindCatalog) All

func (c *KindCatalog) All() []KindSpec

func (*KindCatalog) Empty

func (c *KindCatalog) Empty() bool

func (*KindCatalog) Freeze

func (c *KindCatalog) Freeze()

func (*KindCatalog) Get

func (c *KindCatalog) Get(kind string) (KindSpec, bool)

func (*KindCatalog) Names

func (c *KindCatalog) Names() []string

func (*KindCatalog) RecordKinds added in v0.5.0

func (c *KindCatalog) RecordKinds() []string

RecordKinds are the registered kinds a record can have (not part kinds), sorted: the kinds a search or a save names.

type KindSpec

type KindSpec struct {
	Kind        string
	Description string
	IsParent    bool
	IsPart      bool
	Fields      []FieldSpec
}

KindSpec is the host-facing definition of a knowledge object kind.

func (KindSpec) Field

func (s KindSpec) Field(name string) (FieldSpec, bool)

Field returns the named field when present.

func (KindSpec) Info added in v0.5.0

func (spec KindSpec) Info() ObjectKindInfo

Info builds the agent-facing schema payload for one kind.

func (KindSpec) Normalize added in v0.5.0

func (spec KindSpec) Normalize() (KindSpec, error)

Normalize validates a kind and fills default operators (eq / eq+in).

type LinkRequest added in v0.5.0

type LinkRequest struct {
	From, To uuid.UUID
	Relation string
	// Meta (note, status, role, …) describes the edge; the graph indexes
	// the note for Search.
	Meta   EdgeMeta
	Remove bool
}

LinkRequest creates, updates or removes the edge From→To with Relation.

type LinkResult added in v0.5.0

type LinkResult struct {
	From     RichObject `json:"from"`
	To       RichObject `json:"to"`
	Relation string     `json:"relation"`
	Meta     EdgeMeta   `json:"meta"`
	Score    float64    `json:"score"`
}

LinkResult is a relationship whose note matched, with both of its ends.

type LinkSearch added in v0.5.0

type LinkSearch struct {
	// Namespace and Principals limit the ranking: only an edge Namespace
	// covers whose two ends they can read (as Scope.CanRead decides) ranks.
	Namespace  Namespace
	Principals []string
	// RelationType names one relation; empty searches every relation the
	// graph indexes.
	RelationType string
	Query        string
	Limit        int
}

LinkSearch is one edge search. Query matches the edge note.

type MemoryOption added in v0.5.0

type MemoryOption func(*MemoryStore)

MemoryOption configures NewMemoryStore.

func WithMemoryEmbedding added in v0.5.0

func WithMemoryEmbedding(e Embedding) MemoryOption

WithMemoryEmbedding sets how the store embeds objects, parts, session messages and queries.

func WithMemoryRanking added in v0.5.0

func WithMemoryRanking(r Ranking) MemoryOption

WithMemoryRanking sets how the store fuses its search channels.

type MemoryStore

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

MemoryStore is an in-process Store for tests, fixtures and offline hosts. It embeds with its own Embedding (none means lexical search only) and fuses its channels with its Ranking.

func NewMemoryStore

func NewMemoryStore(opts ...MemoryOption) *MemoryStore

NewMemoryStore returns an empty memory-backed store.

func (*MemoryStore) DeleteSessionMessages added in v0.4.0

func (s *MemoryStore) DeleteSessionMessages(_ context.Context, host Namespace, sessionID string) error

DeleteSessionMessages implements Store.

func (*MemoryStore) Erase added in v0.5.0

func (s *MemoryStore) Erase(_ context.Context, scope Scope) ([]uuid.UUID, error)

Erase implements Store.

func (*MemoryStore) Get

func (s *MemoryStore) Get(_ context.Context, scope Scope, id uuid.UUID) (Object, error)

Get implements Store.

func (*MemoryStore) GetByProperty added in v0.2.0

func (s *MemoryStore) GetByProperty(_ context.Context, scope Scope, key, value string) (Object, error)

GetByProperty implements Store.

func (*MemoryStore) GetMany

func (s *MemoryStore) GetMany(_ context.Context, scope Scope, ids []uuid.UUID) ([]Object, error)

GetMany implements Store.

func (*MemoryStore) GetTree added in v0.5.0

func (s *MemoryStore) GetTree(_ context.Context, scope Scope, id uuid.UUID, limit int) (Tree, error)

GetTree implements Store.

func (*MemoryStore) ListKinds

func (s *MemoryStore) ListKinds(_ context.Context) ([]ObjectKind, error)

ListKinds implements Store.

func (*MemoryStore) PurgeDeleted added in v0.5.0

func (s *MemoryStore) PurgeDeleted(_ context.Context, scope Scope, before time.Time) (int, error)

PurgeDeleted implements Store.

func (*MemoryStore) PurgeSessionMessages added in v0.5.0

func (s *MemoryStore) PurgeSessionMessages(_ context.Context, host Namespace, before time.Time) (int, error)

PurgeSessionMessages implements Store.

func (*MemoryStore) Put

func (s *MemoryStore) Put(ctx context.Context, scope Scope, in Indexed) (Object, error)

Put implements Store. It embeds obj.Text before it takes the lock, and clones maps and slices so callers cannot change the store through them.

func (*MemoryStore) PutKind

func (s *MemoryStore) PutKind(_ context.Context, k ObjectKind) error

PutKind implements Store.

func (*MemoryStore) PutTree added in v0.5.0

func (s *MemoryStore) PutTree(ctx context.Context, scope Scope, parent Indexed, parts iter.Seq2[Indexed, error]) (Object, error)

PutTree implements Store: it reads the tree's revision and reusable parts, embeds only new parts in batches, then commits under the lock, failing with ErrConflict when another tree write committed first.

func (*MemoryStore) SaveSessionMessages added in v0.4.0

func (s *MemoryStore) SaveSessionMessages(ctx context.Context, host Namespace, sessionID, generationKey string, messages []SessionMessage) (int, error)

SaveSessionMessages implements Store. It embeds each message's SearchText in batches; a failed batch is logged and saves without vectors.

func (*MemoryStore) Search added in v0.5.0

func (s *MemoryStore) Search(ctx context.Context, scope Scope, q RecordSearch) ([]ScoredID, error)

Search implements Store. It ranks records, parts and the session's messages by a TF×IDF lexical score and, unless q.Exact, by cosine similarity to the query's embedding (same model only; a failed query embedding leaves the lexical list alone); q.Exact adds case-fold substring and trigram overlap instead, and puts exact title matches first. The lists are fused with the store's Ranking.

func (*MemoryStore) SoftDelete

func (s *MemoryStore) SoftDelete(_ context.Context, scope Scope, id uuid.UUID) error

SoftDelete implements Store.

type Namespace added in v0.2.0

type Namespace []Attr

Namespace is ordered named isolation attrs. The first attr is the tenant: the boundary every store filters on by equality, so no scope ever reaches another tenant's rows. Every Scope needs a namespace; an empty one covers nothing.

func ParseNamespace added in v0.2.0

func ParseNamespace(nameValues ...string) (Namespace, error)

ParseNamespace builds a Namespace from name, value, name, value, ….

func (Namespace) Bind added in v0.2.0

func (ceiling Namespace) Bind(call Namespace) (Namespace, error)

Bind merges a per-call namespace onto this host ceiling: the widest namespace the host lets a caller reach. The ceiling is required. Call may add attrs to narrow it. A call value that disagrees with a ceiling attr is invalid.

func (Namespace) Clone added in v0.2.0

func (n Namespace) Clone() Namespace

Clone returns a copy of n.

func (Namespace) Covers added in v0.2.0

func (scope Namespace) Covers(obj Namespace) bool

Covers reports whether obj is visible under this scope: both have the same tenant (first attr), and every other scope attr is on obj with the same value. An empty scope covers nothing.

func (Namespace) Empty added in v0.2.0

func (n Namespace) Empty() bool

Empty reports whether n has no attributes.

func (Namespace) Equal added in v0.2.0

func (n Namespace) Equal(o Namespace) bool

Equal reports whether n and o have the same attrs in the same order.

func (Namespace) ForSession added in v0.5.0

func (host Namespace) ForSession(sessionID string) Namespace

ForSession is the host namespace with the session id as the last attribute. The session id is stored raw, including ".". Lookup uses the attribute list.

func (Namespace) Key added in v0.5.0

func (n Namespace) Key() string

Key is a canonical, collision-free encoding of n (names and values), for deriving stable ids. Unlike String, {a=x.y} and {a=x, b=y} differ.

func (*Namespace) Scan added in v0.2.0

func (n *Namespace) Scan(src any) error

Scan implements sql.Scanner.

func (Namespace) String added in v0.2.0

func (n Namespace) String() string

String joins attribute values with "." for display.

func (Namespace) Tenant added in v0.5.0

func (n Namespace) Tenant() Namespace

Tenant is n's first attr as a namespace of its own (nil for an empty n).

func (Namespace) Validate added in v0.2.0

func (n Namespace) Validate() error

Validate checks names, values, uniqueness, and that n is non-empty. Every failure wraps ErrInvalid.

func (Namespace) Value added in v0.2.0

func (n Namespace) Value() (driver.Value, error)

Value implements driver.Valuer (jsonb array of {name,value}, as text).

type NeighborhoodQuery added in v0.5.0

type NeighborhoodQuery struct {
	// Namespace and Principals limit the walk as Scope.CanRead does: a node
	// they cannot read is neither returned nor walked through.
	Namespace  Namespace
	Principals []string
	ObjectID   uuid.UUID
	Relations  []string // edge labels to follow; empty follows every relation
	Direction  string   // DirectionOut, DirectionIn or DirectionBoth (the default)
	MaxHops    int
	Limit      int
}

NeighborhoodQuery asks for the objects within MaxHops edges of ObjectID.

type Object

type Object struct {
	ID          uuid.UUID
	Kind        string
	Title       string
	Summary     string
	Properties  map[string]any
	Content     string
	ContentType string
	ParentID    *uuid.UUID
	Position    *int
	// Embedding is the dense vector stored on the row. Store search reads it
	// on parts. Parent embeddings are copied to the graph for FindObjects.
	Embedding []float32
	// EmbeddingModel names the model that made Embedding. Vector search only
	// compares rows from the query's model.
	EmbeddingModel string
	// Namespace is the ordered named isolation attrs stored on the row.
	Namespace Namespace
	// Readers, when set, limits visibility to scopes holding one of these
	// principals (source ACLs, such as Drive or SharePoint sharing).
	Readers   []string
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *time.Time
}

Object is one row from the generic objects store (parent or part).

func (Object) IndexText added in v0.5.0

func (obj Object) IndexText() string

IndexText joins non-empty title, summary, and content for corpus part embeds.

func (Object) IndexTextWithParent added in v0.5.0

func (obj Object) IndexTextWithParent(parentTitle string) string

IndexTextWithParent prefixes parent context (bursting-style) when parentTitle is set.

func (Object) IsPart

func (o Object) IsPart() bool

IsPart reports whether the object has a parent containment link.

func (Object) Rich added in v0.5.0

func (o Object) Rich(includeContent bool) RichObject

Rich maps a stored object to a rich reference.

func (Object) Validate added in v0.5.0

func (obj Object) Validate(cat *KindCatalog) error

Validate checks an object against the kind catalog when non-empty.

func (Object) ValidateIdentity added in v0.5.0

func (obj Object) ValidateIdentity() error

ValidateIdentity checks id, kind, and namespace before a store Put.

type ObjectKind

type ObjectKind struct {
	Kind             string
	Description      string
	IsPart           bool
	IsParent         bool
	FilterableFields json.RawMessage // JSON array from object_kinds.filterable_fields
}

ObjectKind documents a free-form kind for schema() discovery.

type ObjectKindInfo

type ObjectKindInfo struct {
	Kind             string          `json:"kind"`
	Description      string          `json:"description,omitempty"`
	IsPart           bool            `json:"is_part"`
	IsParent         bool            `json:"is_parent"`
	FilterableFields json.RawMessage `json:"filterable_fields,omitempty"`
}

ObjectKindInfo is the JSON form of ObjectKind for agents.

type ObjectSearch added in v0.5.0

type ObjectSearch struct {
	// Namespace and Principals limit the ranking as Scope.CanRead does: only
	// nodes they can read rank.
	Namespace  Namespace
	Principals []string
	Query      string
	// Filters (with Kind holding the requested kinds) apply before ranking,
	// so a node that fails them takes no slot.
	Filters Filter
	Limit   int
}

ObjectSearch is one entity search over a graph's nodes.

type Opened added in v0.5.0

type Opened struct {
	Object RichObject      `json:"object"`
	Kind   *ObjectKindInfo `json:"kind,omitempty"`
	// Children are the first openChildren parts; MoreChildren reports more
	// (Related lists them all).
	Children     []RichObject `json:"children,omitempty"`
	MoreChildren bool         `json:"more_children,omitempty"`
}

Opened is an object read in full: its content, its kind's fields (which ones a search can filter on), and its first children.

type Page added in v0.5.0

type Page struct {
	Results Results `json:"results"`
	Facets  Facets  `json:"facets"`
	More    bool    `json:"more"`
	Rest    Rest    `json:"-"`
}

Page is one page of Search or Related results, best first. More reports that Rest holds further results; Next returns the next page of Rest.

type PropFilter added in v0.2.0

type PropFilter struct {
	Eq any
	In []any
}

PropFilter is equality or match-any for one property.

type Ranking added in v0.5.0

type Ranking struct {
	RRFk  int
	Decay float64
	Now   func() time.Time
}

Ranking is how a backend fuses ranked lists: reciprocal rank fusion with constant RRFk (0 is 60), after each list is aged by exp(-Decay * age in days) using UpdatedAt and re-sorted. Decay 0 keeps the lists as ranked. Now is the clock for age (nil is time.Now).

func (Ranking) Fuse added in v0.5.0

func (r Ranking) Fuse(lists ...[]ScoredID) []ScoredID

Fuse ages each list, fuses them, and returns the hits best first. The lists are changed in place.

func (Ranking) FuseEdges added in v0.5.0

func (r Ranking) FuseEdges(lists ...[]EdgeSearchHit) []EdgeSearchHit

FuseEdges fuses ranked edge lists the same way, best first. An edge in several lists keeps its first hit's metadata; decay uses Meta.UpdatedAt.

type RecordSearch added in v0.5.0

type RecordSearch struct {
	Query string
	// Filters apply to the record a row belongs to: a part matches when its
	// parent does.
	Filters Filter
	// Exact asks for literal matching only: no semantic channel, and an
	// exact title match ranks first.
	Exact bool
	// Within, when set, keeps only the parts of that record (a part names
	// its record), and leaves out session messages. The store resolves it.
	Within uuid.UUID
	Limit  int
}

RecordSearch is one search over a store's records and their parts.

type Ref added in v0.5.0

type Ref struct {
	ID   uuid.UUID
	Path string
}

Ref names an object by id, or by the virtual path of an indexed file (its PropVFSPath property). Path wins when both are set.

type RelatedRequest added in v0.5.0

type RelatedRequest struct {
	ID uuid.UUID
	// Relation narrows the result: empty returns children and every graph
	// relation, "contains" only the children, any other name only that
	// graph relation.
	Relation string
	Depth    int // graph hops; default 1, capped by MaxExpandHops
	Limit    int
}

RelatedRequest asks for the objects related to one object.

type Relation

type Relation struct {
	Type      string     `json:"type"`
	Direction string     `json:"direction,omitempty"` // out | in, from Via
	Depth     int        `json:"depth,omitempty"`     // hops from the start
	Via       *uuid.UUID `json:"via,omitempty"`       // the object the edge was followed from
	EdgeMeta
}

Relation is how a related object was reached: a child or parent, or an edge. An edge hop says the object it was followed from (Via), so the hops of one Related call with depth trace a path back to the start. EdgeMeta fields are embedded so agent JSON stays flat (note, status, role, …).

type RerankFunc added in v0.5.0

type RerankFunc func(ctx context.Context, query string, objects []RichObject) ([]RichObject, error)

RerankFunc reorders the objects at the head of a search for query, for example with a cross-encoder. It returns the objects to keep, in order; an object it leaves out is dropped from the results.

type Rest added in v0.5.0

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

Rest is the ranked remainder of a Search or Related call. It holds ids, scores and evidence, not rows, so it stays small; Next reads its next page from the store. It marshals to JSON, so a caller can keep it across processes (a SearchContext does, for the agent tools).

func (Rest) Empty added in v0.5.0

func (r Rest) Empty() bool

Empty reports whether r holds no results.

func (Rest) MarshalJSON added in v0.5.0

func (r Rest) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Rest) UnmarshalJSON added in v0.5.0

func (r *Rest) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Result added in v0.5.0

type Result struct {
	Object *RichObject `json:"object,omitempty"`
	Link   *LinkResult `json:"link,omitempty"`
}

Result is one ranked result of Search or Related: an object, or a link whose note matched a search.

type Results added in v0.5.0

type Results []Result

Results are a page's results, best first.

func (rs Results) Links() iter.Seq[LinkResult]

Links yields the links among rs, in order.

func (Results) Objects added in v0.5.0

func (rs Results) Objects() iter.Seq[RichObject]

Objects yields the objects among rs, in order.

type RichObject

type RichObject struct {
	ID          uuid.UUID      `json:"id"`
	Kind        string         `json:"kind"`
	Title       string         `json:"title,omitempty"`
	Summary     string         `json:"summary,omitempty"`
	Score       *float64       `json:"score,omitempty"`
	Properties  map[string]any `json:"properties,omitempty"`
	Content     string         `json:"content,omitempty"` // set by read; omitted on search hits
	ContentType string         `json:"content_type,omitempty"`
	ParentID    *uuid.UUID     `json:"parent_id,omitempty"`
	Position    *int           `json:"position,omitempty"`
	Evidence    []Evidence     `json:"evidence,omitempty"`
	// Relation is set on expand graph neighbors (how this object was reached).
	Relation  *Relation `json:"relation,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitempty"`
}

RichObject is the agent-facing object reference (never a bare id).

type Scope

type Scope struct {
	Namespace  Namespace
	Principals []string
	SessionID  string
}

Scope is the isolation every Engine and store call runs under. Namespace is required: a call with an empty namespace fails, so no code path reads or writes across tenants by default. A scope sees an object when every scope attr is on the object (Namespace.Covers), so a broader scope sees objects with extra attrs.

Principals are the caller's identities (user and group ids from the host's identity provider). An object with Readers is visible only to a scope that shares at least one principal with it. An object without Readers is visible to every scope that covers its namespace.

SessionID is harness-owned. When set, search and get also read this session's rows in session_messages (Namespace plus the session attribute). The model cannot set it.

func (Scope) CanRead added in v0.5.0

func (s Scope) CanRead(obj Object) bool

CanRead reports whether obj is visible under s: s covers its namespace, and obj has no Readers or shares a principal with s.

type ScoredID

type ScoredID struct {
	ID         uuid.UUID
	Score      float64
	UpdatedAt  time.Time
	ParentID   *uuid.UUID
	Title      string
	Content    string
	Position   *int
	Properties map[string]any // part props (e.g. start_line) when the channel provides them
}

ScoredID is a candidate from a retrieval channel before fusion.

type SearchContext

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

SearchContext is the retrieval state of one agent thread: the host namespace, the caller's principals, and the ranked rest of the last call of each tool, which a call with more continues. The namespace and the principals are host configuration, set every turn (a revoked group membership applies on the next turn); only the rests are session state.

func NewSearchContext

func NewSearchContext() *SearchContext

NewSearchContext returns an empty search context.

func (*SearchContext) Namespace

func (c *SearchContext) Namespace() (Namespace, bool)

Namespace returns the host-set search namespace, if any.

func (*SearchContext) Rest added in v0.5.0

func (c *SearchContext) Rest(key string) Rest

Rest returns the ranked remainder of the last call named key.

func (*SearchContext) Rests added in v0.5.0

func (c *SearchContext) Rests() map[string]Rest

Rests is each call's ranked remainder, for the harness checkpoint.

func (*SearchContext) Scope

func (c *SearchContext) Scope() Scope

Scope returns the retrieval Scope for engine calls.

func (*SearchContext) SetNamespace

func (c *SearchContext) SetNamespace(ns Namespace)

SetNamespace sets host retrieval isolation.

func (*SearchContext) SetPrincipals added in v0.5.0

func (c *SearchContext) SetPrincipals(principals []string)

SetPrincipals sets the caller identities checked against object Readers.

func (*SearchContext) SetRest added in v0.5.0

func (c *SearchContext) SetRest(key string, rest Rest)

SetRest keeps rest as the ranked remainder of the last call named key.

func (*SearchContext) SetRests added in v0.5.0

func (c *SearchContext) SetRests(rests map[string]Rest)

SetRests replaces the rests with ones from a checkpoint.

type SearchRequest

type SearchRequest struct {
	Query   string
	Kind    string // optional; with registered kinds, one of them
	Filters Filter
	// Within is a record, or a part (meaning its record); the results are
	// that record's parts that match the query.
	Within uuid.UUID
	Limit  int
}

SearchRequest is one search: free text, an optional kind, and filters on the records' fields. Without a query, a kind or filters list the matching records. Within limits the search to the parts of one record.

type SessionMessage added in v0.4.0

type SessionMessage struct {
	Role       string
	Body       []byte
	SearchText string
}

SessionMessage is one exact message saved from a context window before a plan handoff. Body is the message JSON. SearchText is the visible text the store indexes (and embeds, when it has an Embedder) for retrieval.

type Store

type Store interface {
	Get(ctx context.Context, scope Scope, id uuid.UUID) (Object, error)
	// GetMany returns the objects for ids in the same order, omitting ids
	// it cannot return.
	GetMany(ctx context.Context, scope Scope, ids []uuid.UUID) ([]Object, error)
	// GetTree returns the object id names with its family in one read: at
	// most limit parts (every part when limit is not positive), and a
	// part's record. A saved session message has no family.
	GetTree(ctx context.Context, scope Scope, id uuid.UUID, limit int) (Tree, error)
	// GetByProperty returns a live object whose string property key is value.
	GetByProperty(ctx context.Context, scope Scope, key, value string) (Object, error)

	// Put stores obj, indexes its Text, and returns the stored object. An
	// embedding failure fails the Put.
	Put(ctx context.Context, scope Scope, obj Indexed) (Object, error)
	// PutTree upserts parent and makes parts its only parts, in one atomic
	// commit: until then reads see the previous parts, and a failure leaves
	// them. Parts arrive in order with content-derived ids, ParentID, the
	// parent's namespace and readers, and Position set. A part whose id is
	// live keeps its row and index, so only new parts are indexed, and
	// memory stays bounded whatever the number of parts (Embedding.
	// EmbedBatches is a pipeline for this). When another PutTree of the
	// same parent commits first, PutTree returns ErrConflict and changes
	// nothing. It returns the stored parent.
	PutTree(ctx context.Context, scope Scope, parent Indexed, parts iter.Seq2[Indexed, error]) (Object, error)
	// SoftDelete marks id and its parts deleted.
	SoftDelete(ctx context.Context, scope Scope, id uuid.UUID) error
	// PurgeDeleted removes objects under scope soft-deleted before cutoff
	// and returns how many it removed. Readers do not limit it.
	PurgeDeleted(ctx context.Context, scope Scope, before time.Time) (int, error)
	// Erase removes every object and saved session message under scope and
	// returns the ids of the first-class objects it removed. Readers do not
	// limit it.
	Erase(ctx context.Context, scope Scope) ([]uuid.UUID, error)

	// Search ranks records and parts (a part's hit carries ParentID) best
	// first, at most q.Limit, over the channels the store chooses, with the
	// session's messages when Scope.SessionID is set. Filters do not apply
	// to session messages. An empty Query lists the records Filters match,
	// newest first (no parts, no session messages).
	Search(ctx context.Context, scope Scope, q RecordSearch) ([]ScoredID, error)

	// ListKinds and PutKind are the durable kind registry: Engine reads it
	// once (LoadKindsFromStore) and writes it from ApplyKinds and PersistKinds.
	ListKinds(ctx context.Context) ([]ObjectKind, error)
	PutKind(ctx context.Context, k ObjectKind) error

	// SaveSessionMessages writes one context window under
	// host.ForSession(sessionID) and returns its generation. A
	// repeated generationKey returns the first save's generation. The
	// store indexes each message's SearchText; an embedding failure does
	// not fail the save.
	SaveSessionMessages(ctx context.Context, host Namespace, sessionID, generationKey string, messages []SessionMessage) (int, error)
	// DeleteSessionMessages removes the session's rows under host.
	DeleteSessionMessages(ctx context.Context, host Namespace, sessionID string) error
	// PurgeSessionMessages removes rows under host saved before cutoff and
	// returns how many it removed.
	PurgeSessionMessages(ctx context.Context, host Namespace, before time.Time) (int, error)
}

Store is the knowledge store Engine runs on: the source of truth for objects and the search over records and their parts. A backend owns its retrieval: its Embedder, channels, ranking and fusion, filters, and the scope and readers rules below. MemoryStore and brain/postgres.Store implement it, and brain/storetest is the contract a store must pass. A backend without a feature returns ErrUnsupported from that method.

Reads return only rows the scope can read (Scope.CanRead) that are not soft-deleted, and omit the rest as if missing. When Scope.SessionID is set, Get, GetMany and Search also reach that session's saved messages.

Every write is guarded by scope: the object's namespace must lie inside scope, and a row that already has the id must be visible under scope. Otherwise the write changes nothing and returns ErrNotFound, so one tenant never overwrites another tenant's row by reusing its id.

type StringMatch added in v0.2.0

type StringMatch struct {
	Eq string
	In []string
}

StringMatch is equality or match-any for a well-known string field.

type Tree added in v0.5.0

type Tree struct {
	Object Object
	// Parent is a part's record; nil for a record.
	Parent *Object
	// Parts are the record's parts by position; for a part, its record's,
	// itself included.
	Parts []Object
}

Tree is an object read with its family in one call: a record with its parts, or a part with its record and that record's parts.

type TreePart added in v0.5.0

type TreePart struct {
	Object Object
	Reused bool
}

TreePart is one part of a tree write as EmbedBatches hands it to a backend. A Reused part is live already: only its ID, ParentID, Namespace, Position and Properties are set. A new part is the whole object, with its embedding when the backend embeds.

Directories

Path Synopsis
Package graphtest is the contract every brain graph backend must meet.
Package graphtest is the contract every brain graph backend must meet.
Package helixgraph is a brain.Graph on HelixDB.
Package helixgraph is a brain.Graph on HelixDB.
Package postgres is the optional Postgres implementation of brain.Store.
Package postgres is the optional Postgres implementation of brain.Store.
Package storetest is the contract every brain store must meet.
Package storetest is the contract every brain store must meet.

Jump to

Keyboard shortcuts

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