fabriqbrain

package module
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package fabriqbrain adapts the fabriq agent toolkit to cortex as a plug-n-play brain: a knowledge.Provider for recall, rich tools, and a learning-loop plugin. The package directory is integrations/fabriq; the package name is fabriqbrain to avoid colliding with github.com/xraph/fabriq.

Package fabriqbrain makes fabriq a plug-n-play living brain for cortex agents.

It adapts fabriq's core/agent toolkit to three cortex seams:

  • knowledge.Provider — multi-channel recall (vector + full-text + graph, RRF-fused, distillation-aware) exposed as the engine's knowledge_search.
  • rich tools — fabriq's graph_traverse, remember, map/digest/resolve registered as cortex tools (engine.WithTool).
  • learning loop — a plugin.Extension that writes agent run activity into the fabric so fabriq's embed + distillation workers turn it into future recall material.

Wiring (auto-discovers the fabriq facade from the DI container):

eng, _ := engine.New(append(
    []engine.Option{engine.WithStore(store), engine.WithLLM(client)},
    fabriqbrain.EngineOptions(container,
        fabriqbrain.WithEmbedder(emb),
        fabriqbrain.WithEntities("doc", "note", "agent_memory"),
        fabriqbrain.WithWritePolicy(agent.WritePolicy{
            Allow: map[string][]command.Op{"agent_memory": {command.OpCreate}},
        }),
    )...,
)...)

Host setup for the learning loop (turnkey):

// 1. Register the memory entity (dynamic, content vector-indexed).
reg.MustRegister(fabriqbrain.MemorySpec("agent_memory"))
// 2. Provision its table once (migration, or postgres.Adapter.EnsureDynamic
//    in setup) — fabriq.Open does not auto-create dynamic tables.
// 3. Allow writes to it. WithMemoryEntity must match the name passed to
//    MemorySpec above; hosts using a non-default entity name MUST pass it
//    explicitly (the default is "agent_memory").
opts := fabriqbrain.EngineOptions(container,
    fabriqbrain.WithEmbedder(emb),
    fabriqbrain.WithEntities("agent_memory"),
    fabriqbrain.WithMemoryEntity("agent_memory"),
    fabriqbrain.WithWritePolicy(fabriqbrain.MemoryWritePolicy("agent_memory")),
)

The plugin writes {content, meta} rows; fabriq's embed worker vectorizes `content` and distillation rolls them up, so future recall surfaces them.

The package directory is integrations/fabriq; the package name is fabriqbrain to avoid colliding with github.com/xraph/fabriq.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EngineOption

func EngineOption(c vessel.Vessel, opts ...Option) engine.Option

EngineOption wires ONLY the knowledge provider (parity with weave.EngineOption). Returns a no-op option when no fabriq facade is in the container.

func EngineOptions

func EngineOptions(c vessel.Vessel, opts ...Option) []engine.Option

EngineOptions wires the FULL brain: knowledge provider + rich tools + learning-loop plugin. Returns nil (safe to spread) when no fabriq facade is present.

func LessonSpec

func LessonSpec(entity string) registry.EntitySpec

LessonSpec supplies the shared physically provisioned lesson entity schema.

func MemorySpec

func MemorySpec(entity string) registry.EntitySpec

MemorySpec returns the fabriq registry spec for the learning-loop memory entity: a dynamic entity with a `content` text column (the embedding target) and a `meta` JSON column (structured run fields), with `content` vector-indexed.

Register it before opening fabriq, e.g.:

reg.MustRegister(fabriqbrain.MemorySpec("agent_memory"))

The physical table is NOT auto-created by fabriq.Open — provision it via a migration or postgres.Adapter.EnsureDynamic before serving writes.

func MemoryWritePolicy

func MemoryWritePolicy(entity string) agent.WritePolicy

MemoryWritePolicy returns the deny-by-default write allowlist the learning-loop plugin needs: create on the memory entity. Pass it via WithWritePolicy.

Types

type Adapter

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

Adapter implements cortex's knowledge.Provider over fabriq's recall pipeline.

func NewProvider

func NewProvider(rec recaller, opts ...Option) *Adapter

NewProvider builds a knowledge.Provider over a fabriq recaller (a *agent.Toolkit satisfies recaller).

func (*Adapter) ListCollections

func (a *Adapter) ListCollections(_ context.Context) ([]knowledge.CollectionInfo, error)

ListCollections reports the configured recall-able entities as collections. Counts are best-effort (0) — fabriq entities are not document collections.

func (*Adapter) Retrieve

func (a *Adapter) Retrieve(ctx context.Context, query string, p *knowledge.RetrieveParams) ([]knowledge.ScoredChunk, error)

Retrieve runs fabriq recall and maps the context pack to scored chunks.

type LessonAdapter

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

LessonAdapter publishes and recalls accepted ordinary lessons through Fabriq.

func NewLessonStore

func NewLessonStore(toolkit LessonTransport, fabric query.Fabric, config LessonConfig) (*LessonAdapter, error)

NewLessonStore accepts only a policy-bound toolkit; CheckReady verifies the physical destination and configured semantic channels before serving calls.

func (*LessonAdapter) CheckReady

func (a *LessonAdapter) CheckReady(ctx context.Context) error

CheckReady checks every physical column and strict recall without writing a lesson.

func (*LessonAdapter) Delete

Delete erases local payloads, then removes the authoritative remote row and vector using the installed tenant-scoped command API. Repeating this call reconciles lost acknowledgments. An optional configured AggregateEraser also removes the named local history targets and irreversibly reserves the identity. Downstream copies remain unconfirmed.

func (*LessonAdapter) Deliver

func (a *LessonAdapter) Deliver(ctx context.Context, request learning.Publication) (learning.Receipt, error)

Deliver reconciles an immutable outbox payload, including withdrawal after a source is gone. The publisher retains the receipt in local durable storage.

func (*LessonAdapter) Publish

func (a *LessonAdapter) Publish(ctx context.Context, lesson learning.Lesson) (learning.Receipt, error)

Publish reconciles only a matching accepted local publication.

func (*LessonAdapter) Recall

func (a *LessonAdapter) Recall(ctx context.Context, request learning.Query) (learning.Page, error)

Recall applies exact eligibility predicates in Fabriq's authoritative hydration, then checks current source evidence and host grants before returning content.

func (*LessonAdapter) Revoke

func (a *LessonAdapter) Revoke(ctx context.Context, request learning.RevokeRequest) error

Revoke commits local withdrawal before attempting remote delivery.

func (*LessonAdapter) SweepDeleted

func (a *LessonAdapter) SweepDeleted(ctx context.Context, after string) (string, error)

SweepDeleted resumes active-copy cleanup from durable local tombstones. Hosts schedule this bounded scan with their retention worker's current delete grant. Replaying old tombstones is safe and also removes delayed destination writes.

type LessonConfig

type LessonConfig struct {
	Entity     string
	Repository learning.Repository
	Guard      *learning.Guard
	Tenant     func(context.Context, cortex.Scope) (string, error)
	Now        func() time.Time
}

LessonConfig requires local accepted state and explicit current source authority.

type LessonDeletion

type LessonDeletion struct {
	Tombstone           learning.Tombstone
	ActiveCopiesRemoved bool
	HistoryErased       bool
	LocalPayloadsErased bool
	LocalErasure        *command.ErasureReceipt
}

LessonDeletion distinguishes active removal and named local payload erasure. HistoryErased remains false because downstream copies are not confirmed.

type LessonProvider

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

LessonProvider exposes governed lessons through the installed engine knowledge interface. Applicability and contraindications remain alongside each statement.

func NewLessonProvider

func NewLessonProvider(adapter *LessonAdapter, domain string) (*LessonProvider, error)

NewLessonProvider binds one governed domain; query parameters cannot broaden it.

func (*LessonProvider) ListCollections

func (p *LessonProvider) ListCollections(ctx context.Context) ([]knowledge.CollectionInfo, error)

ListCollections checks the same current read grant used by retrieval.

func (*LessonProvider) Retrieve

func (p *LessonProvider) Retrieve(ctx context.Context, query string, params *knowledge.RetrieveParams) ([]knowledge.ScoredChunk, error)

Retrieve returns individually qualified lessons and their evidence references.

type LessonToolkit

type LessonToolkit = lessontransport.Toolkit

LessonToolkit owns the same typed write policy and strict recall used by optimization.

func NewLessonToolkit

func NewLessonToolkit(fabric query.Fabric, reg *registry.Registry, embedder agent.Embedder, entity string) (*LessonToolkit, error)

NewLessonToolkit verifies the schema and configures strict semantic retrieval.

type LessonTransport

type LessonTransport interface {
	Remember(context.Context, agent.RememberRequest) (command.Result, error)
	Recall(context.Context, agent.RecallRequest) (agent.ContextPack, error)
}

LessonTransport is the installed Fabriq toolkit boundary. Decorators must embed LessonToolkit so its private write-policy binding remains verifiable.

type Option

type Option func(*config)

Option configures the bridge.

func WithBudget

func WithBudget(n int) Option

WithBudget sets the token budget for each recall (default 4096).

func WithEmbedder

func WithEmbedder(e agent.Embedder) Option

WithEmbedder supplies the embedding model for recall's vector channel. It MUST match the embedder fabriq's index/embed worker used (same model + dims); otherwise the vector channel mismatches. When nil, recall degrades to full-text + graph channels only.

func WithEntities

func WithEntities(entities ...string) Option

WithEntities sets the fabriq entity types recall searches and ListCollections reports. Required for recall to return results (fabriq's Recall needs at least one entity).

func WithLogger

func WithLogger(l log.Logger) Option

WithLogger sets the logger used to report swallowed memory-write failures in the learning-loop plugin and toolkit-build failures during wiring. Default is a no-op logger.

func WithMemoryEntity

func WithMemoryEntity(entity string) Option

WithMemoryEntity sets the fabriq entity the learning-loop plugin writes agent activity into (default "agent_memory").

func WithRenderer

func WithRenderer(fn func(agent.ContextItem) string) Option

WithRenderer overrides how a recalled ContextItem becomes chunk text. Default renders the row JSON verbatim.

func WithTenantMapper

func WithTenantMapper(fn func(context.Context) context.Context) Option

WithTenantMapper overrides how a cortex request context is translated into the scope fabriq reads. Default is identity (correct when both share Forge scope).

func WithVectorDims

func WithVectorDims(n int) Option

WithVectorDims sets the embedding dimensionality the toolkit expects, which MUST match the configured embedder's Dims (e.g. 1536 for OpenAI text-embedding-3-small). Default 0 leaves it unset so fabriq applies its own 768 default — correct for 768-dim embedders. Setting this wrong (or leaving the default with a non-768 embedder) makes NewToolkit fail with a dims mismatch, which the wiring path now surfaces via the configured logger.

func WithWritePolicy

func WithWritePolicy(p agent.WritePolicy) Option

WithWritePolicy sets the guarded-write allowlist used by the remember tool and the learning-loop plugin. Empty = no writes permitted (deny-by-default).

type Plugin

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

Plugin is a cortex extension that writes agent run activity back into the fabric so fabriq's embed + distillation workers turn it into future recall material. It implements plugin.RunStarted and plugin.RunCompleted.

func NewPlugin

func NewPlugin(rem rememberer, opts ...Option) *Plugin

NewPlugin builds the learning-loop plugin over a fabriq rememberer (a *agent.Toolkit satisfies rememberer).

func (*Plugin) Name

func (p *Plugin) Name() string

Name identifies the extension.

func (*Plugin) OnRunCompleted

func (p *Plugin) OnRunCompleted(ctx context.Context, agentID id.AgentID, runID id.AgentRunID, output string, elapsed time.Duration) error

OnRunCompleted writes a memory row for the finished run. Write failures are swallowed (logged by the registry) so memory persistence never fails a run.

func (*Plugin) OnRunFailed

func (p *Plugin) OnRunFailed(ctx context.Context, agentID id.AgentID, runID id.AgentRunID, runErr error) error

OnRunFailed removes the run's stashed input (preventing an inflight-map leak) and records the failure as memory so the brain can learn from failed runs. Write/marshal errors are logged and swallowed.

func (*Plugin) OnRunStarted

func (p *Plugin) OnRunStarted(ctx context.Context, _ id.AgentID, runID id.AgentRunID, input string) error

OnRunStarted stashes the run input so OnRunCompleted can persist the full Q/A.

Directories

Path Synopsis
internal
Package optimization connects governed Cortex lessons to Fabriq.
Package optimization connects governed Cortex lessons to Fabriq.

Jump to

Keyboard shortcuts

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