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 ¶
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. The graph filters the walk before it fills a page, and Next continues the walk from a cursor, so every neighbor is reachable; Count reports the totals. Search with Near ranks only the records a walk reaches. 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
- Variables
- func FilterValueKey(v any) (string, bool)
- func Parts(objs ...Object) iter.Seq2[Object, error]
- func PersistKinds(ctx context.Context, store Store, specs ...KindSpec) error
- type Attr
- type AuditEvent
- type AuditFunc
- type AuditOp
- type Counts
- type EdgeFilter
- type EdgeMeta
- type EdgeSearchHit
- type Embedder
- type Embedding
- func (e Embedding) Embed(ctx context.Context, texts []string) ([][]float32, error)
- func (e Embedding) EmbedBatches(ctx context.Context, parts iter.Seq2[Indexed, error], ...) (int, error)
- func (e Embedding) EmbedOne(ctx context.Context, text string) ([]float32, error)
- func (e Embedding) Enabled() bool
- func (e Embedding) Model() string
- type Engine
- func (e *Engine) ApplyKinds(ctx context.Context, specs ...KindSpec) error
- func (e *Engine) Catalog() *KindCatalog
- func (e *Engine) DeleteSessionMessages(ctx context.Context, host Namespace, sessionID string) error
- func (e *Engine) Erase(ctx context.Context, scope Scope) error
- func (e *Engine) Get(ctx context.Context, scope Scope, id uuid.UUID) (Object, error)
- func (e *Engine) HasGraph() bool
- func (e *Engine) Link(ctx context.Context, scope Scope, req LinkRequest) error
- func (e *Engine) LoadKindsFromStore(ctx context.Context) error
- func (e *Engine) Next(ctx context.Context, scope Scope, rest Rest, limit int) (Page, error)
- func (e *Engine) Open(ctx context.Context, scope Scope, id uuid.UUID) (Opened, error)
- func (e *Engine) PurgeDeleted(ctx context.Context, scope Scope, before time.Time) (int, error)
- func (e *Engine) PurgeSessionMessages(ctx context.Context, host Namespace, before time.Time) (int, error)
- func (e *Engine) PutTree(ctx context.Context, scope Scope, parent Object, ...) (Object, error)
- func (e *Engine) Related(ctx context.Context, scope Scope, req RelatedRequest) (Page, error)
- func (e *Engine) Resolve(ctx context.Context, scope Scope, ref Ref) (uuid.UUID, error)
- func (e *Engine) Save(ctx context.Context, scope Scope, obj Object) (Object, error)
- func (e *Engine) SaveSessionMessages(ctx context.Context, host Namespace, sessionID, generationKey string, ...) (int, error)
- func (e *Engine) Search(ctx context.Context, scope Scope, req SearchRequest) (Page, error)
- func (e *Engine) SoftDelete(ctx context.Context, scope Scope, id uuid.UUID) error
- func (e *Engine) SyncKindsToStore(ctx context.Context) error
- type EngineConfig
- type EngineOption
- func WithAudit(record AuditFunc) EngineOption
- func WithConfig(cfg EngineConfig) EngineOption
- func WithGraph(g Graph) EngineOption
- func WithIndex(ix Index) EngineOption
- func WithIndexText(fn IndexTextFunc) EngineOption
- func WithKinds(specs ...KindSpec) EngineOption
- func WithReranker(fn RerankFunc) EngineOption
- type Evidence
- type Facets
- type FieldSpec
- type FieldType
- type Filter
- type FilterCondition
- type FilterPlan
- type Graph
- type GraphEdge
- type GraphNeighbor
- type Index
- type IndexTextFunc
- type Indexed
- type KindCatalog
- type KindSpec
- type LinkRequest
- type LinkResult
- type LinkSearch
- type MemoryOption
- type MemoryStore
- func (s *MemoryStore) DeleteSessionMessages(_ context.Context, host Namespace, sessionID string) error
- func (s *MemoryStore) Erase(_ context.Context, scope Scope) ([]uuid.UUID, error)
- func (s *MemoryStore) Get(_ context.Context, scope Scope, id uuid.UUID) (Object, error)
- func (s *MemoryStore) GetByProperty(_ context.Context, scope Scope, key, value string) (Object, error)
- func (s *MemoryStore) GetMany(_ context.Context, scope Scope, ids []uuid.UUID) ([]Object, error)
- func (s *MemoryStore) GetTree(_ context.Context, scope Scope, id uuid.UUID, limit int) (Tree, error)
- func (s *MemoryStore) ListKinds(_ context.Context) ([]ObjectKind, error)
- func (s *MemoryStore) PurgeDeleted(_ context.Context, scope Scope, before time.Time) (int, error)
- func (s *MemoryStore) PurgeSessionMessages(_ context.Context, host Namespace, before time.Time) (int, error)
- func (s *MemoryStore) Put(ctx context.Context, scope Scope, in Indexed) (Object, error)
- func (s *MemoryStore) PutKind(_ context.Context, k ObjectKind) error
- func (s *MemoryStore) PutTree(ctx context.Context, scope Scope, parent Indexed, ...) (Object, error)
- func (s *MemoryStore) SaveSessionMessages(ctx context.Context, host Namespace, sessionID, generationKey string, ...) (int, error)
- func (s *MemoryStore) Search(ctx context.Context, scope Scope, q RecordSearch) ([]ScoredID, error)
- func (s *MemoryStore) SoftDelete(_ context.Context, scope Scope, id uuid.UUID) error
- type Namespace
- func (ceiling Namespace) Bind(call Namespace) (Namespace, error)
- func (n Namespace) Clone() Namespace
- func (scope Namespace) Covers(obj Namespace) bool
- func (n Namespace) Empty() bool
- func (n Namespace) Equal(o Namespace) bool
- func (host Namespace) ForSession(sessionID string) Namespace
- func (n Namespace) Key() string
- func (n *Namespace) Scan(src any) error
- func (n Namespace) String() string
- func (n Namespace) Tenant() Namespace
- func (n Namespace) Validate() error
- func (n Namespace) Value() (driver.Value, error)
- type Near
- type NeighborPage
- type NeighborhoodQuery
- type Object
- type ObjectKind
- type ObjectKindInfo
- type ObjectSearch
- type Opened
- type Page
- type PropFilter
- type Ranking
- type Reached
- type RecordSearch
- type Ref
- type RelatedRequest
- type Relation
- type RelationSpec
- type RerankFunc
- type Rest
- type Result
- type Results
- type RichObject
- type Scope
- type ScoredID
- type SearchContext
- func (c *SearchContext) Namespace() (Namespace, bool)
- func (c *SearchContext) Rest(key string) Rest
- func (c *SearchContext) Rests() map[string]Rest
- func (c *SearchContext) Scope() Scope
- func (c *SearchContext) SetNamespace(ns Namespace)
- func (c *SearchContext) SetPrincipals(principals []string)
- func (c *SearchContext) SetRest(key string, rest Rest)
- func (c *SearchContext) SetRests(rests map[string]Rest)
- type SearchRequest
- type SessionMessage
- type Store
- type StringMatch
- type Tree
- type TreePart
- type Walk
Constants ¶
const ( FieldKind = "kind" FieldTitle = "title" FieldCreatedAt = "created_at" FieldUpdatedAt = "updated_at" OpEq = "eq" OpIn = "in" OpGte = "gte" OpLt = "lt" )
Filter condition fields and operators.
const ( DirectionOut = "out" DirectionIn = "in" DirectionBoth = "both" )
Edge directions, as seen from the object a walk leaves.
const ( RelationChild = "child" RelationParent = "parent" RelationSibling = "sibling" )
Relation types of the containment results of Related.
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" )
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 ¶
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
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.
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 Counts ¶ added in v0.5.2
type Counts struct {
Total int `json:"total"`
ByRelation map[string]int `json:"by_relation,omitempty"`
}
Counts are the objects a walk reaches. Total counts each object once; ByRelation counts each object under every relation that reached it at its depth, so the values can sum to more than Total.
type EdgeFilter ¶ added in v0.5.2
type EdgeFilter struct {
Status string `json:"status,omitempty"`
Role string `json:"role,omitempty"`
MinConfidence float64 `json:"min_confidence,omitempty"`
UpdatedAfter time.Time `json:"updated_after,omitzero"` // the edge's UpdatedAt is at or after it
}
EdgeFilter keeps the edges a walk follows. Each set field must match; the zero filter follows every edge.
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
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
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
EmbedOne embeds text, or returns nil without an Embedder or text.
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 ¶
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
DeleteSessionMessages removes every saved message for sessionID under host.
func (*Engine) Erase ¶ added in v0.5.0
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
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
HasGraph reports whether the engine has a graph, so the harness registers the link tool.
func (*Engine) Link ¶
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 ¶
LoadKindsFromStore replaces the process catalog from the store.
func (*Engine) Open ¶ added in v0.5.0
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
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
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), in the graph's order. Next pages through all of them: the graph walk continues from a cursor, so no neighbor is out of reach. Without a graph Related returns the children only. When the graph fails, Related returns the children unless FailOnGraphError is set or only graph relations were asked for.
func (*Engine) Save ¶ added in v0.5.0
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 ¶
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. Near asks the graph for the records the walk reaches, at most FrontierK of each hop (Page.Truncated when a hop had more), and ranks the store's records and the graph's objects among them only; links do not rank.
func (*Engine) SoftDelete ¶
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.
type EngineConfig ¶
type EngineConfig struct {
CandidateK int
EvidenceN int
SnippetCap int
DefaultLimit int
MaxLimit int
SiblingRadius int
FrontierK int // max records one hop of a graph walk continues from (default 1000)
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.
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
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
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 returns one page of the walk q describes, at most
// q.Limit objects that pass q.Filters. Each object appears once, at its
// smallest depth, with one edge that reached it (the first relation in
// request order, then outbound first); the start never appears. Pages
// are ordered by depth, then the newest object first (CreatedAt), then
// object id, and Next continues after the last key, which never
// changes: an object written between pages appears only if its key
// falls after the page, and no other object repeats or is skipped.
Neighborhood(ctx context.Context, q NeighborhoodQuery) (NeighborPage, error)
// Reach returns every object the walk reaches, at most FrontierK of
// each hop, so a search can rank within them.
Reach(ctx context.Context, w Walk) (Reached, 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
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
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) 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) Info ¶ added in v0.5.0
func (spec KindSpec) Info() ObjectKindInfo
Info builds the agent-facing schema payload for one kind.
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) GetByProperty ¶ added in v0.2.0
func (s *MemoryStore) GetByProperty(_ context.Context, scope Scope, key, value string) (Object, error)
GetByProperty 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
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 ¶
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 ¶
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
ParseNamespace builds a Namespace from name, value, name, value, ….
func (Namespace) Bind ¶ added in v0.2.0
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) Covers ¶ added in v0.2.0
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) Equal ¶ added in v0.2.0
Equal reports whether n and o have the same attrs in the same order.
func (Namespace) ForSession ¶ added in v0.5.0
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
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) Tenant ¶ added in v0.5.0
Tenant is n's first attr as a namespace of its own (nil for an empty n).
type Near ¶ added in v0.5.2
type Near struct {
ID uuid.UUID
Relations []string // graph relations; empty follows every relation
Direction string // DirectionOut, DirectionIn or DirectionBoth (the default)
Depth int // default 1, capped by MaxExpandHops
Edges EdgeFilter
}
Near limits a search to the records within Depth graph hops of ID over Relations: the ones a related call on ID would walk to.
type NeighborPage ¶ added in v0.5.2
type NeighborPage struct {
Neighbors []GraphNeighbor
// Next continues the walk after this page; empty when it is done.
Next string
// Counts is what the whole walk reaches that passes the filters, when
// the query asked for it.
Counts *Counts
// Truncated reports a hop that reached more than FrontierK objects, so
// the walk's later hops did not start from all of them.
Truncated bool
}
NeighborPage is one page of a walk.
type NeighborhoodQuery ¶ added in v0.5.0
type NeighborhoodQuery struct {
Walk
// Filters apply to the objects returned, before the limit. The walk
// still goes through objects that fail them.
Filters Filter
// After is the Next of the previous page; empty starts the walk.
After string
Limit int
// Count asks for NeighborPage.Counts.
Count bool
}
NeighborhoodQuery asks for one page of the objects a walk reaches.
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
IndexText joins non-empty title, summary, and content for corpus part embeds.
func (Object) IndexTextWithParent ¶ added in v0.5.0
IndexTextWithParent prefixes parent context (bursting-style) when parentTitle is set.
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
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
// IDs, when set, ranks only these objects.
IDs []uuid.UUID
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"`
// Counts is everything a Related call reaches, when it asked to count.
Counts *Counts `json:"counts,omitempty"`
// Truncated reports a graph walk with a hop past FrontierK: its later
// hops, or the records a near search ranked, left some out.
Truncated bool `json:"truncated,omitempty"`
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
PropFilter is equality or match-any for one property.
type Ranking ¶ added in v0.5.0
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
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
// IDs, when set, keeps only these records and their parts, and leaves
// out session messages.
IDs []uuid.UUID
Limit int
}
RecordSearch is one search over a store's records and their parts.
type Ref ¶ added in v0.5.0
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
// Relations narrows the result: empty returns the children and every
// graph relation, "contains" names the children, and any other name a
// graph relation.
Relations []string
// Direction, Depth and Edges shape the graph walk: the direction of the
// edges from ID (DirectionBoth by default), the hops (default 1, capped
// by MaxExpandHops), and the edges it follows.
Direction string
Depth int
Edges EdgeFilter
// Filters keep the records returned, with the same fields as a search,
// before the limit. The walk still goes through records that fail them.
Filters Filter
Limit int
// Count asks for Page.Counts: everything related that passes Filters.
Count bool
}
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 RelationSpec ¶ added in v0.5.3
RelationSpec is one relation an agent may link records with: its label, what it means, and the kinds each end may be. An empty From or To takes any kind.
func (RelationSpec) Ends ¶ added in v0.5.3
func (s RelationSpec) Ends(from, to string) error
Ends checks that a link of s may go from a record of kind from to one of kind to.
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 remainder of a Search or Related call: ranked ids, scores and evidence, not rows, and for Related the cursor of its graph walk, so it stays small. Next reads its next page from the store, continuing the walk when the ids run out. It marshals to JSON, so a caller can keep it across processes (a SearchContext does, for the agent tools).
func (Rest) MarshalJSON ¶ added in v0.5.0
MarshalJSON implements json.Marshaler.
func (*Rest) UnmarshalJSON ¶ added in v0.5.0
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.
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 ¶
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.
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
Near *Near
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, and Near to the records a graph walk reaches.
type SessionMessage ¶ added in v0.4.0
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
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
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.
type Walk ¶ added in v0.5.2
type Walk 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
Edges EdgeFilter
// FrontierK is the most objects of one hop the next hop starts from: the
// first FrontierK by object id. A hop that reaches more is truncated.
FrontierK int
}
Walk is a breadth-first walk of the graph from ObjectID: up to MaxHops edges of Relations in Direction that pass Edges.
Source Files
¶
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. |