cortext

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cortext.go

Pure Go package for Cortext — no CGO required.

Natives and AIST model shards are not in this module. On first use the package downloads the matching augmem/cortext.cpp release asset, verifies its SHA-256, and unpacks it:

cortext-assets-<version>.tar.gz
cortext-assets-<version>.tar.gz.sha256

Default assets version: 2.0.0 (AssetsVersion), i.e. engine v2.0.0.

Install

The module path is github.com/augmem/cortext.go/v2 from v2.0.0 on (Go's major-version rule). Upgrading from v1 means changing the import path:

import cortext "github.com/augmem/cortext.go/v2"
go get github.com/augmem/cortext.go/v2@v2.0.0

Use

package main

import (
	"fmt"

	cortext "github.com/augmem/cortext.go/v2"
)

func main() {
	engine, err := cortext.New(":memory:", nil)
	if err != nil {
		panic(err)
	}
	defer engine.Close()

	ctx, err := engine.ProcessText("Bailey likes tennis balls.", "chat/main")
	if err != nil {
		panic(err)
	}
	fmt.Println(ctx["should_interrupt"])

	embedding, err := engine.EmbedText("embed without storing")
	if err != nil {
		panic(err)
	}
	fmt.Println(len(embedding))
}

The features below need engine v2.0.0 (engine v5) or later, which the default assets version provides. An older native loaded through CORTEXT_LIBRARY_PATH returns errors for the options it cannot read.

Context packet

A query context leads with standing_memory (standing directives such as "Always ...", outside the retrieved ranking; show it ahead of retrieved_memory and do not count it against a cut of the retrieved list), then retrieved_memory, then working_memory.

Each memory carries content: every signal payload of the memory as {size_bytes, mimetype, timestamp, base64}, in signal order. timestamp is that payload's stored signal time in ms since the Unix epoch (0 when unknown). modality is the modality the signals share, or "mixed" when they differ (for example a turn's text and the photo sent with it under one source), and the memory's mimetype is that of its first signal. Memories come back whole unless you set an evidence budget.

Evidence budget

ProcessOptions.EvidenceBudgetBytes (zero = whole memories) fits standing_memory plus retrieved_memory within a byte budget on any process call: text counts its UTF-8 bytes, other payloads 480 bytes each, grouped memories keep their members most similar to the query, and more distinct memories are kept trimmed before lower-ranked ones are left out (8,000 tokens at 4.35 chars/token is 34,800 bytes).

ctx, err := engine.ProcessTextWithOptions("When is the marathon long run?", "query/main",
	&cortext.ProcessOptions{Retention: cortext.RetentionEphemeral, EvidenceBudgetBytes: 34_800})
Reference time

A query (RetentionEphemeral) call can be asked about a point in time. ProcessOptions.ReferenceTime adds the long-term memories nearest that time (past or future) to the retrieval candidates; nothing is dropped for being later. AsOf: true also hides memories that start after it. The zero ReferenceTime leaves retrieval unchanged; non-query calls ignore it.

ctx, err := engine.ProcessTextWithOptions("Which pier does the ferry leave from?", "query/main",
	&cortext.ProcessOptions{
		Retention:     cortext.RetentionEphemeral,
		ReferenceTime: time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
		AsOf:          true,
	})

An option the loaded native cannot read (an evidence budget or reference time on an older engine) returns an error instead of being ignored.

Text with media

ProcessTextWithMedia (and its JSON / AndOptions variants) encodes the text but stores Media.Data as the signal's payload under Media.MimeType. Nil or empty media stores the text itself. A text/* payload is used as text (keyword index, standing memories, packet text); any other MIME type is an opaque payload. Natives without the text-media entry point return an error.

withMedia, err := engine.ProcessTextWithMedia(
	"A photo of the parking ticket.", "chat/main",
	&cortext.Media{Data: jpegBytes, MimeType: "image/jpeg"},
)

On a native older than engine v5, New rejects Config.SequentialEdgesEnabled and Config.SignalFilter* (that engine's cortext_config still carries procedural_enabled, which shifts those fields), and process options use the older layout so retention still applies.

Assets

Env Purpose
CORTEXT_ASSETS_VERSION Release version to fetch (default 2.0.0)
CORTEXT_ASSETS_DIR Pre-unpacked release tree (native/ + models/) — skips download
CORTEXT_ASSETS_URL Override archive URL
CORTEXT_ASSETS_SHA256 Override expected archive checksum
CORTEXT_ASSET_CACHE_DIR Parent cache dir for downloaded versions
CORTEXT_LIBRARY_PATH Explicit shared library path (skips asset native selection)
CORTEXT_AIST_MODEL_PATH Explicit full .gguf only when you need one on disk
CORTEXT_LI_MODEL_PATH Explicit late-interaction reranker AIST-87M-LI.gguf
CORTEXT_MODEL_CACHE_DIR Where MaterializeModel writes reassembled models

There is no vendored native/ or models/ tree and no sibling-checkout search. Load order:

  1. CORTEXT_LIBRARY_PATH if set
  2. Otherwise EnsureAssets() → native/<platform-tag>/… from the release tarball

Release natives embed AIST and assemble it on first create. MaterializeModel is optional and always reads from the same release asset tree.

Engines from v5 on also need the late-interaction reranker AIST-87M-LI.gguf whenever AIST resolves, or New fails. The engine takes CORTEXT_LI_MODEL_PATH, else the file beside the AIST model, else the copy linked into the library. MaterializeModel checksums the reranker (its own manifest.json entry, sharded beside AIST) and places it beside the reassembled AIST file, and New checks both explicit model paths exist.

Offline prep:

./scripts/fetch_assets.sh /path/to/assets
export CORTEXT_ASSETS_DIR=/path/to/assets

Develop

CGO_ENABLED=0 go test . -timeout 20m
CGO_ENABLED=0 go test . -short   # no network
CORTEXT_REQUIRE_ENGINE_V5=1 CGO_ENABLED=0 go test . -timeout 20m  # as CI: v5 tests fail instead of skipping

Release

git tag -a v2.0.0 -m "cortext.go v2.0.0"
git push origin v2.0.0

Bump AssetsVersion in version.go when pinning a new augmem/cortext.cpp assets line.

Documentation

Overview

Package cortext is a pure-Go (no CGO) binding for the Cortext multimodal memory engine. Shared libraries and model shards come from the augmem/cortext.cpp GitHub Release asset tarball (see EnsureAssets), or from CORTEXT_LIBRARY_PATH / CORTEXT_ASSETS_DIR when set explicitly.

Index

Constants

View Source
const AssetsVersion = "2.0.0"

AssetsVersion is the augmem/cortext.cpp release that provides shared natives and model shards (cortext-assets-<version>.tar.gz). Override with CORTEXT_ASSETS_VERSION.

View Source
const ModuleVersion = "2.0.0"

ModuleVersion is this Go module's release line. It is independent of the bundled engine AssetsVersion but usually tracks the same minor line.

Variables

This section is empty.

Functions

func AssetsDir

func AssetsDir() string

AssetsDir returns the last EnsureAssets root, or empty if not yet loaded.

func EnsureAssets

func EnsureAssets() (string, error)

EnsureAssets downloads (if needed) and unpacks the shared Cortext release asset tarball from github.com/augmem/cortext.cpp, then returns the root that contains native/ and models/.

Layout after unpack:

native/<platform-tag>/libcortext.*
models/manifest.json
models/AIST-87M-GGUF/chunks/…
models/mdbr-leaf-ir/vocab.txt

Resolution order for the asset root:

  1. CORTEXT_ASSETS_DIR (pre-unpacked tree)
  2. User/cache dir for AssetsVersion (download once, reuse)

Override the release with CORTEXT_ASSETS_VERSION or the full archive URL with CORTEXT_ASSETS_URL. Checksum is verified from the release .sha256 asset unless CORTEXT_ASSETS_SHA256 is set.

func LastError

func LastError() string

LastError returns the last error produced by this OS thread's C API calls. Note: goroutine migration between calls can lose thread-local error text; prefer the error returned from each method when available.

func LibraryPath

func LibraryPath() string

LibraryPath returns the absolute path that was successfully loaded, if any.

func LoadLibrary

func LoadLibrary() error

LoadLibrary loads the native Cortext shared library if it is not already loaded. New and Version call this automatically. This may download release assets.

func MaterializeModel

func MaterializeModel(dbPath string) (string, error)

MaterializeModel reassembles AIST model chunks from the release asset tree into a local cache and returns the full .gguf path. When the manifest declares the late-interaction reranker (AIST-87M-LI.gguf, required by v5 engines), it is checksummed and placed beside the AIST file, where the engine looks for it unless CORTEXT_LI_MODEL_PATH is set.

Release natives embed AIST and assemble it inside the library on first create. Call MaterializeModel only when an external filesystem GGUF is required.

Chunks always come from EnsureAssets() (augmem/cortext.cpp release tarball).

Cache location (first match wins):

  1. CORTEXT_MODEL_CACHE_DIR
  2. sibling of dbPath: <dir(dbPath)>/.cortext-assets (":memory:" → cwd)
  3. user cache under augmem/cortext/models

func Ptr

func Ptr[T any](value T) *T

Ptr returns a pointer to value for optional Config fields.

func ResetAssetsForTest

func ResetAssetsForTest()

ResetAssetsForTest clears the process-wide assets singleton (tests only).

func ResetLibraryForTest

func ResetLibraryForTest()

ResetLibraryForTest clears the process-wide library singleton (tests only).

func Version

func Version() string

Version returns the native library version string.

Types

type Config

type Config struct {
	Focus                  *float64
	Sensitivity            *float64
	Stability              *float64
	AffectInterrupt        *bool
	AffectRetrieval        *bool
	ReinforcementEnabled   *bool
	SequentialEdgesEnabled *bool
	SignalFilterAudio      *bool
	SignalFilterImage      *bool
	SignalFilterText       *bool
}

Config overrides native defaults. Nil fields retain their native defaults.

type EmbeddingResult

type EmbeddingResult struct {
	Embedding []float32 `json:"embedding"`
	Dimension int       `json:"dimension"`
}

EmbeddingResult is the JSON shape returned by embed helpers.

type Handle

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

Handle is an open Cortext engine instance.

func New

func New(dbPath string, cfg *Config) (*Handle, error)

New opens a Cortext instance at dbPath (file path or ":memory:"). cfg may be nil for all native defaults.

The native library is loaded via EnsureAssets (augmem/cortext.cpp release tarball). Release natives embed AIST and assemble it on first create. Set CORTEXT_AIST_MODEL_PATH only to force a specific external GGUF file. Engines from v5 on also require the late-interaction reranker (AIST-87M-LI.gguf) whenever AIST resolves: it is found through CORTEXT_LI_MODEL_PATH, beside the AIST file, or linked into the library, and New fails if none resolves.

func (*Handle) Close

func (h *Handle) Close()

Close frees the native handle. Safe to call multiple times.

func (*Handle) Consolidate

func (h *Handle) Consolidate() (map[string]any, error)

func (*Handle) ConsolidateJSON

func (h *Handle) ConsolidateJSON() ([]byte, error)

func (*Handle) EmbedAudio

func (h *Handle) EmbedAudio(pcm []float32) ([]float32, error)

func (*Handle) EmbedAudioJSON

func (h *Handle) EmbedAudioJSON(pcm []float32) ([]byte, error)

func (*Handle) EmbedImage

func (h *Handle) EmbedImage(data []byte, width int, height int, channels int) ([]float32, error)

func (*Handle) EmbedImageJSON

func (h *Handle) EmbedImageJSON(data []byte, width int, height int, channels int) ([]byte, error)

func (*Handle) EmbedText

func (h *Handle) EmbedText(text string) ([]float32, error)

func (*Handle) EmbedTextJSON

func (h *Handle) EmbedTextJSON(text string) ([]byte, error)

func (*Handle) Flush

func (h *Handle) Flush() error

func (*Handle) ProcessAudio

func (h *Handle) ProcessAudio(pcm []float32, sourceID string) (map[string]any, error)

func (*Handle) ProcessAudioJSON

func (h *Handle) ProcessAudioJSON(pcm []float32, sourceID string) ([]byte, error)

func (*Handle) ProcessAudioJSONWithOptions

func (h *Handle) ProcessAudioJSONWithOptions(pcm []float32, sourceID string, options *ProcessOptions) ([]byte, error)

func (*Handle) ProcessAudioWithMedia

func (h *Handle) ProcessAudioWithMedia(pcm []float32, sourceID string, media *Media) (map[string]any, error)

func (*Handle) ProcessAudioWithMediaAndOptions

func (h *Handle) ProcessAudioWithMediaAndOptions(pcm []float32, sourceID string, media *Media, options *ProcessOptions) (map[string]any, error)

func (*Handle) ProcessAudioWithMediaJSON

func (h *Handle) ProcessAudioWithMediaJSON(pcm []float32, sourceID string, media *Media) ([]byte, error)

func (*Handle) ProcessAudioWithMediaJSONWithOptions

func (h *Handle) ProcessAudioWithMediaJSONWithOptions(pcm []float32, sourceID string, media *Media, options *ProcessOptions) ([]byte, error)

func (*Handle) ProcessAudioWithOptions

func (h *Handle) ProcessAudioWithOptions(pcm []float32, sourceID string, options *ProcessOptions) (map[string]any, error)

func (*Handle) ProcessImage

func (h *Handle) ProcessImage(data []byte, width int, height int, channels int, sourceID string) (map[string]any, error)

func (*Handle) ProcessImageJSON

func (h *Handle) ProcessImageJSON(data []byte, width int, height int, channels int, sourceID string) ([]byte, error)

func (*Handle) ProcessImageJSONWithOptions

func (h *Handle) ProcessImageJSONWithOptions(data []byte, width int, height int, channels int, sourceID string, options *ProcessOptions) ([]byte, error)

func (*Handle) ProcessImageWithMedia

func (h *Handle) ProcessImageWithMedia(data []byte, width int, height int, channels int, sourceID string, media *Media) (map[string]any, error)

func (*Handle) ProcessImageWithMediaAndOptions

func (h *Handle) ProcessImageWithMediaAndOptions(data []byte, width int, height int, channels int, sourceID string, media *Media, options *ProcessOptions) (map[string]any, error)

func (*Handle) ProcessImageWithMediaJSON

func (h *Handle) ProcessImageWithMediaJSON(data []byte, width int, height int, channels int, sourceID string, media *Media) ([]byte, error)

func (*Handle) ProcessImageWithMediaJSONWithOptions

func (h *Handle) ProcessImageWithMediaJSONWithOptions(data []byte, width int, height int, channels int, sourceID string, media *Media, options *ProcessOptions) ([]byte, error)

func (*Handle) ProcessImageWithOptions

func (h *Handle) ProcessImageWithOptions(data []byte, width int, height int, channels int, sourceID string, options *ProcessOptions) (map[string]any, error)

func (*Handle) ProcessText

func (h *Handle) ProcessText(text string, sourceID string) (map[string]any, error)

func (*Handle) ProcessTextJSON

func (h *Handle) ProcessTextJSON(text string, sourceID string) ([]byte, error)

func (*Handle) ProcessTextJSONWithOptions

func (h *Handle) ProcessTextJSONWithOptions(text string, sourceID string, options *ProcessOptions) ([]byte, error)

func (*Handle) ProcessTextWithMedia

func (h *Handle) ProcessTextWithMedia(text string, sourceID string, media *Media) (map[string]any, error)

ProcessTextWithMedia is ProcessTextWithMediaJSON decoded into a map.

func (*Handle) ProcessTextWithMediaAndOptions

func (h *Handle) ProcessTextWithMediaAndOptions(text string, sourceID string, media *Media, options *ProcessOptions) (map[string]any, error)

ProcessTextWithMediaAndOptions is ProcessTextWithMediaJSONWithOptions decoded into a map.

func (*Handle) ProcessTextWithMediaJSON

func (h *Handle) ProcessTextWithMediaJSON(text string, sourceID string, media *Media) ([]byte, error)

ProcessTextWithMediaJSON processes text and stores media (see Media) as the signal's payload in place of the text. Nil or empty media stores the text.

func (*Handle) ProcessTextWithMediaJSONWithOptions

func (h *Handle) ProcessTextWithMediaJSONWithOptions(text string, sourceID string, media *Media, options *ProcessOptions) ([]byte, error)

ProcessTextWithMediaJSONWithOptions is ProcessTextWithMediaJSON with ProcessOptions (embedding, retention, evidence budget, reference time).

func (*Handle) ProcessTextWithOptions

func (h *Handle) ProcessTextWithOptions(text string, sourceID string, options *ProcessOptions) (map[string]any, error)

func (*Handle) Reset

func (h *Handle) Reset() error

type Media

type Media struct {
	Data     []byte
	MimeType string
}

Media is caller source media stored as the signal's payload in place of the canonical input (text, PCM or pixels), which is still what the signal is encoded from. Nil or empty Data stores the canonical input. MimeType is required with Data; a text/* payload is used as text (keyword index, standing memories, packet text), any other MIME type is opaque.

type ProcessOptions

type ProcessOptions struct {
	OmitEmbedding bool
	// Retention is Natural when zero-value / omitted.
	Retention Retention
	// EvidenceBudgetBytes is the evidence budget for the returned packet, in
	// bytes. Zero (omitted) returns recalled memories whole. A positive value
	// fits standing_memory plus retrieved_memory (with attached neighbours)
	// within it, text counted by its UTF-8 bytes and other payloads as 480
	// bytes each; grouped memories keep their members most similar to the
	// query, and more distinct memories are kept trimmed before lower-ranked
	// ones are left out. Convert a token budget with the reader's tokenizer
	// rate (8,000 tokens at 4.35 chars/token is 34,800).
	EvidenceBudgetBytes uint64
	// ReferenceTime is the query reference time, read only by
	// RetentionEphemeral calls. The zero value leaves retrieval unchanged. Set,
	// the long-term memories nearest that time (past or future) join the
	// retrieval candidates; nothing is dropped for being later unless AsOf is
	// set. It is sent at millisecond precision and must not precede the Unix
	// epoch.
	ReferenceTime time.Time
	// AsOf additionally hides memories that start after ReferenceTime (and
	// later turns or restatements attached to retrieved ones). It requires a
	// non-zero ReferenceTime.
	AsOf bool
}

ProcessOptions configures JSON process result payloads.

type Retention

type Retention int

Retention controls whether an input is naturally gated, committed, bounded, or used only for retrieval. Its zero value is Natural.

const (
	RetentionNatural Retention = iota
	RetentionDurable
	RetentionBoundary
	RetentionEphemeral
)

Jump to

Keyboard shortcuts

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