palace

package
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultOllamaURL is where a local Ollama daemon listens by default.
	DefaultOllamaURL = "http://localhost:11434"

	// DefaultOllamaEmbedModel is the embedding model used when none is configured.
	//
	// embeddinggemma over all-minilm is a deliberate quality trade. Measured on
	// 80 real drawers from this project's palace (query = first 100 chars,
	// document = the remainder):
	//
	//	model            dim   recall@1   MRR     chunks/sec
	//	all-minilm       384     45.0%    0.584      261
	//	embeddinggemma   768     70.0%    0.798       82
	//
	// Mining is a one-off cost paid per changed chunk; retrieval quality is paid
	// on every search. 3x slower indexing for a 56% relative gain in recall@1 is
	// worth it. Note the 768 dimensions double embedding storage and double the
	// cost of any full scan over them.
	DefaultOllamaEmbedModel = "embeddinggemma"
)
View Source
const (
	DefaultMaxFacts     = 100_000
	DefaultMaxFragments = 8
)

Defaults for RuleOptions.

View Source
const BundleVersion = 1

BundleVersion is the bundle format version.

View Source
const DefaultMaxCascade = 10_000

DefaultMaxCascade bounds the statements one retraction may take with it.

View Source
const ErasedText = "sys:Erased"

ErasedText is how a sealed value decodes once its key is destroyed.

Variables

View Source
var (
	ErrBundleCycle     = errors.New("palace: kg: bundle references a statement that is not imported yet")
	ErrSensitiveBundle = errors.New("palace: kg: bundle holds sealed values; export needs IncludeSensitive")
)

Errors of bundles.

View Source
var (
	ErrElpiProgram   = errors.New("palace: kg: elpi program")
	ErrElpiRun       = errors.New("palace: kg: elpi run")
	ErrElpiOutOfFuel = errors.New("palace: kg: elpi out of fuel")
)

Errors of the ELPI engine.

View Source
var (
	ErrUnsafeRule        = errors.New("palace: kg: unsafe rule")
	ErrUnstratified      = errors.New("palace: kg: program is not stratified")
	ErrNotMaterializable = errors.New("palace: kg: program cannot be materialized")
	ErrRuleParse         = errors.New("palace: kg: rule parse error")
)

Errors returned by the rule engine.

View Source
var (
	ErrNotLive           = errors.New("palace: kg: statement is not live")
	ErrReservedPredicate = errors.New("palace: kg: predicate is reserved for the engine")
	ErrEmptyInterval     = errors.New("palace: kg: valid_from must be before valid_to")
	ErrCascadeLimit      = errors.New("palace: kg: retraction cascade exceeds the limit")
	ErrUniqueViolation   = errors.New("palace: kg: another subject already holds this unique value")
	ErrSchemaViolation   = errors.New("palace: kg: live data violates the predicate schema")
	ErrNoSupport         = errors.New("palace: kg: a derived statement needs at least one support")
	ErrPatchIntoCascade  = errors.New("palace: kg: a correction cannot point into the statement's own layers")
	ErrHistoryConflicts  = errors.New("palace: kg: conflicts are not defined on the history view")
)

Errors returned by knowledge-graph writes.

View Source
var (
	ErrVectorConflict     = errors.New("palace: kg: a different vector is already stored for this statement and model")
	ErrBadVector          = errors.New("palace: kg: vector is not usable")
	ErrChannelUnavailable = errors.New("palace: kg: retrieval channel unavailable")
)

Errors of vectors and recall.

View Source
var ErrBudget = errors.New("palace: kg: budget exceeded")

ErrBudget is wrapped by every budget failure.

View Source
var ErrEmptyGraph = errors.New("palace: kg: graph name is empty")

ErrEmptyGraph is returned for a blank graph name.

View Source
var (
	ErrErased = errors.New("palace: kg: the data subject has been erased")
)

Errors of erasure.

View Source
var ErrKGUnavailable = errors.New("palace: kg: the store has no database")

ErrKGUnavailable is returned when the store has no database behind it.

View Source
var ErrNoAnswer = errors.New("palace: kg: no saved answer by that name")

ErrNoAnswer is returned for an unknown saved answer.

View Source
var (
	ErrNotUnique = errors.New("palace: kg: upsert needs a unique predicate")
)

Errors of the predicate schema.

View Source
var ErrOllamaUnavailable = errors.New("ollama unavailable")

ErrOllamaUnavailable is returned when the Ollama daemon cannot be reached or does not have the requested embedding model. Callers that can degrade (the agent) should warn and continue; callers that cannot (mining) should abort with a message that says how to fix it.

View Source
var ErrProgramNotFound = errors.New("palace: kg: no such program")

ErrProgramNotFound is returned when no live program has the given name.

View Source
var ErrQueryParse = errors.New("palace: kg: query syntax error")

ErrQueryParse is wrapped by every query syntax error; the message carries the position as line:col.

View Source
var ErrSensitiveVolatile = errors.New("palace: kg: a sensitive predicate cannot hold volatile values")

ErrSensitiveVolatile is returned for a volatile write on a sensitive key: it would store plaintext that erasure cannot destroy.

View Source
var ErrUnsupportedQuery = errors.New("palace: kg: unsupported query construct")

ErrUnsupportedQuery is matched (errors.Is) by UnsupportedQueryError.

Functions

func CosineSimilarity

func CosineSimilarity(a, b []float32) float32

CosineSimilarity computes the cosine similarity between two vectors. Returns 0 if either vector has zero magnitude.

func DetectPlatformOnnxFile

func DetectPlatformOnnxFile() string

DetectPlatformOnnxFile returns the ONNX weights file to download for the compiled-in backend.

The right answer depends on the backend, not just the platform, which is why this delegates to platformOnnxFile in the build-tagged file:

  • pure Go (default): fp32. simplego has no int8 kernels and runs the quantized model ~3x slower than fp32 (1.8 vs 5.6 chunks/sec, M2 Max).
  • ORT + CoreML: int8 on arm64. ONNX Runtime has optimized ARM int8 kernels and the Neural Engine is an int8 engine, so quantization is a real win.

Picking the wrong pair silently costs a large multiple of runtime.

func DownloadModel

func DownloadModel(dest string, onnxFilePath string) (string, error)

DownloadModel fetches the all-MiniLM-L6-v2 model to dest and returns the local path.

func ElpiVars added in v0.4.4

func ElpiVars(rows []map[string]Value) []string

ElpiVars returns the sorted variable names a goal binds, for display.

func EmbedderAvailability added in v0.0.48

func EmbedderAvailability(cfg PalaceConfig) error

EmbedderAvailability reports whether the configured embedding backend can be reached, and why not when it cannot. It performs the same checks New would, without building a palace, so commands that require embeddings can fail early with an actionable message.

func EmbedderBackend added in v0.0.41

func EmbedderBackend() string

EmbedderBackend names the compiled-in inference backend.

func FormatConflicts added in v0.4.4

func FormatConflicts(cs []Conflict) string

FormatConflicts renders conflicts as markdown.

func FormatExplanation added in v0.4.4

func FormatExplanation(ex *Explanation) string

FormatExplanation renders an explanation as markdown.

func FormatRows added in v0.4.4

func FormatRows(vars []string, rows []map[string]Value) string

FormatRows renders query rows as a markdown table.

func GenerateDrawerID

func GenerateDrawerID(wing, room, sourceFile string, chunkIndex int, content string) string

GenerateDrawerID creates a deterministic drawer ID from wing, room, and content identity.

func GitIgnoredSet added in v0.0.39

func GitIgnoredSet(dir string) map[string]bool

GitIgnoredSet returns the set of files that git considers ignored in the given directory. It uses `git ls-files --others --ignored --exclude-standard` which respects all .gitignore files (nested, parent, and global), negation rules, and ** globs. Returns nil if git is not available or the directory is not a git repository.

func HasFTS5

func HasFTS5(db *sql.DB) bool

HasFTS5 checks whether the database supports FTS5 for drawers.

func HashContent added in v0.0.41

func HashContent(content string) string

HashContent returns the content hash stored on a drawer and compared by the miner to decide whether a chunk needs re-embedding.

func IsGitIgnoredSet added in v0.0.39

func IsGitIgnoredSet(relPath string, ignored map[string]bool) bool

IsGitIgnoredSet checks whether a relative path is in the ignored set.

func MarshalEmbedding

func MarshalEmbedding(v []float32) []byte

MarshalEmbedding encodes a float32 slice as a little-endian byte slice for BLOB storage.

func ModelReady added in v0.0.41

func ModelReady(modelDir string) bool

ModelReady reports whether modelDir already holds the weights this backend needs.

A directory can exist and still be unusable: installs made before the fp32 switch hold only model_qint8_arm64.onnx, which the pure-Go backend will load and then run ~3x slower. Checking for the *specific* file, rather than merely for the directory, is what lets callers repair such a cache instead of quietly using the wrong model forever. It also means switching backends re-downloads the variant that backend wants.

func OnnxModelFile added in v0.0.41

func OnnxModelFile() string

OnnxModelFile is the bare weights filename the embedder loads.

func OpenDB

func OpenDB(dbPath string) (*sql.DB, error)

OpenDB opens (or creates) a palace SQLite database at the given path with WAL mode and runs pending migrations. Pass ":memory:" for in-memory databases.

func PalaceTools

func PalaceTools(p *Palace) ([]tool.Tool, error)

PalaceTools returns ADK tools for interacting with the palace during agent sessions. Returns nil if palace is nil (palace disabled).

func UnmarshalEmbedding

func UnmarshalEmbedding(b []byte) []float32

UnmarshalEmbedding decodes a little-endian byte slice back into a float32 slice.

Types

type AddDrawerToolInput

type AddDrawerToolInput struct {
	// Wing name (project or domain).
	Wing string `json:"wing"`
	// Room name (topic or subdirectory).
	Room string `json:"room"`
	// The knowledge content to store.
	Content string `json:"content"`
	// Optional source file path.
	SourceFile string `json:"source_file,omitempty"`
	// Optional hall (sub-category).
	Hall string `json:"hall,omitempty"`
	// Importance score 0-10 (default 5).
	Importance int `json:"importance,omitempty"`
}

AddDrawerToolInput defines parameters for the palace-add-drawer tool.

type AddDrawerToolOutput

type AddDrawerToolOutput struct {
	Content string `json:"content"`
	ID      string `json:"id,omitempty"`
}

AddDrawerToolOutput contains the result of adding a drawer.

type Budget added in v0.4.4

type Budget struct {
	// MaxRows bounds the statements read plus the rows produced.
	MaxRows int `json:"max_rows,omitempty"`
	// MaxBytes bounds the decoded literal bytes read and produced.
	MaxBytes int `json:"max_bytes,omitempty"`
}

Budget bounds one operation. Zero fields are unlimited.

type Bundle added in v0.4.4

type Bundle struct {
	Version int        `json:"version"`
	Root    BundleStmt `json:"root"`
}

Bundle is a root statement and everything stated about it.

type BundleOptions added in v0.4.4

type BundleOptions struct {
	// IncludeSensitive allows sealed values; they are written in plaintext and
	// marked "sensitive": true.
	IncludeSensitive bool
}

BundleOptions configures an export.

type BundleStmt added in v0.4.4

type BundleStmt struct {
	// ID is bundle-local ("b1", "b2", ...), numbered in import order.
	ID     string       `json:"id"`
	S      BundleValue  `json:"s"`
	P      BundleValue  `json:"p"`
	O      BundleValue  `json:"o"`
	Valid  *BundleValid `json:"valid,omitempty"`
	Layers []BundleStmt `json:"layers,omitempty"`
}

BundleStmt is one statement of a bundle. Statements are imported in the order they are encountered: subject, object, the statement, then Layers.

type BundleValid added in v0.4.4

type BundleValid struct {
	From *time.Time `json:"from,omitempty"`
	To   *time.Time `json:"to,omitempty"`
}

BundleValid is a valid-time interval; nil bounds are open.

type BundleValue added in v0.4.4

type BundleValue struct {
	Value
	Stmt *BundleStmt `json:"stmt,omitempty"`
	Ref  string      `json:"ref,omitempty"`
	// Sensitive marks a value that was sealed at rest in the source.
	Sensitive bool `json:"sensitive,omitempty"`
}

BundleValue is an entity or literal (the embedded Value), an inlined statement (Stmt) or a statement already in the bundle (Ref).

func (BundleValue) MarshalJSON added in v0.4.4

func (b BundleValue) MarshalJSON() ([]byte, error)

MarshalJSON leaves out the empty Value of a statement reference, so no local eid or meaningless kind is written.

type Conflict added in v0.4.4

type Conflict struct {
	Subject   Value           `json:"subject"`
	Predicate Value           `json:"predicate"`
	Values    []ConflictValue `json:"values"`
}

Conflict is one subject/predicate pair holding two or more distinct objects at the same valid time, each with its evidence.

type ConflictFilter added in v0.4.4

type ConflictFilter struct {
	Subject, Predicate string
	// Limit caps the subject/predicate pairs returned; 0 means 20.
	Limit int
}

ConflictFilter narrows Conflicts.

type ConflictValue added in v0.4.4

type ConflictValue struct {
	Object     Value      `json:"object"`
	Statements []Evidence `json:"statements"`
}

ConflictValue is one of the disagreeing objects.

type Dialect added in v0.4.4

type Dialect int

Dialect selects how the evaluator counts solutions.

const (
	DialectSPARQL Dialect = iota
	DialectCypher
)

The dialects. SPARQL is a set over (s, p, o) triples: statements with equal terms yield one solution. Cypher is a bag over statements: one row per eid, and one MATCH may not bind the same relationship twice.

type DiaryEntry

type DiaryEntry struct {
	ID        int64     `json:"id"`
	Agent     string    `json:"agent"`
	Entry     string    `json:"entry"`
	Topic     string    `json:"topic,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

DiaryEntry is a journal entry written by an agent.

type DiaryReadToolInput

type DiaryReadToolInput struct {
	// The agent name whose diary to read.
	AgentName string `json:"agent_name"`
	// Number of recent entries to return (default 10).
	LastN int `json:"last_n,omitempty"`
}

DiaryReadToolInput defines parameters for the palace-diary-read tool.

type DiaryReadToolOutput

type DiaryReadToolOutput struct {
	Content string `json:"content"`
}

DiaryReadToolOutput contains formatted diary entries.

type DiaryWriteToolInput

type DiaryWriteToolInput struct {
	// The agent name writing the entry.
	AgentName string `json:"agent_name"`
	// The diary entry content.
	Entry string `json:"entry"`
	// Optional topic/category for the entry.
	Topic string `json:"topic,omitempty"`
}

DiaryWriteToolInput defines parameters for the palace-diary-write tool.

type DiaryWriteToolOutput

type DiaryWriteToolOutput struct {
	Content string `json:"content"`
}

DiaryWriteToolOutput contains the result of writing a diary entry.

type Drawer

type Drawer struct {
	ID         string    `json:"id"`
	Wing       string    `json:"wing"`
	Room       string    `json:"room"`
	Hall       string    `json:"hall,omitempty"`
	Content    string    `json:"content"`
	SourceFile string    `json:"source_file,omitempty"`
	ChunkIndex int       `json:"chunk_index,omitempty"`
	AddedBy    string    `json:"added_by,omitempty"`
	Importance int       `json:"importance"` // 0-10
	Embedding  []float32 `json:"-"`          // not serialized
	CreatedAt  time.Time `json:"created_at"`
	// ContentHash identifies the chunk's content. The miner compares it with the
	// stored hash to skip re-embedding chunks that have not changed; the ID alone
	// cannot tell, as it is derived from the source path and chunk index only.
	ContentHash string `json:"content_hash,omitempty"`
}

Drawer is the fundamental unit of knowledge in the palace.

type DrawerFilter

type DrawerFilter struct {
	Wing string
	Room string
	Hall string
}

DrawerFilter constrains drawer queries.

type DrawerInput

type DrawerInput struct {
	Wing       string
	Room       string
	Hall       string
	Content    string
	SourceFile string
	ChunkIndex int
	AddedBy    string
	Importance int
}

DrawerInput is the input for creating a new drawer.

type DrawerService

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

DrawerService combines a PalaceStore and an optional Embedder to provide drawer CRUD with automatic embedding generation and duplicate detection.

func NewDrawerService

func NewDrawerService(store PalaceStore, embedder Embedder, config PalaceConfig) *DrawerService

NewDrawerService creates a DrawerService. The embedder may be nil, in which case drawers are stored without embeddings and deduplication is skipped.

func (*DrawerService) AddDrawer

func (ds *DrawerService) AddDrawer(ctx context.Context, input DrawerInput) (*Drawer, error)

AddDrawer embeds the content, checks for duplicates in the same wing+room, generates an ID, and inserts the drawer. Returns an error wrapping a DuplicateResult if a near-duplicate is found.

func (*DrawerService) CheckDuplicate

func (ds *DrawerService) CheckDuplicate(ctx context.Context, content string, filter DrawerFilter) (*DuplicateResult, error)

CheckDuplicate embeds the content and checks for near-duplicates across all drawers (or within the given filter). Returns nil if no duplicate found or if the embedder is not available.

func (*DrawerService) DeleteDrawer

func (ds *DrawerService) DeleteDrawer(ctx context.Context, id string) error

DeleteDrawer removes a drawer by ID.

func (*DrawerService) Search

func (ds *DrawerService) Search(ctx context.Context, q SearchQuery) ([]SearchResult, error)

Search performs a combined search using both semantic vector similarity and FTS5 keyword matching. When the embedder is available, results from both methods are merged and deduplicated by drawer ID, with semantic results prioritized. Returns results sorted by combined relevance score.

type DuplicateError

type DuplicateError struct {
	Result DuplicateResult
}

DuplicateError is returned by AddDrawer when a near-duplicate is detected.

func (*DuplicateError) Error

func (e *DuplicateError) Error() string

type DuplicateResult

type DuplicateResult struct {
	ExistingID string  `json:"existing_id"`
	Similarity float32 `json:"similarity"`
}

DuplicateResult describes a potential duplicate drawer.

func FindDuplicates

func FindDuplicates(embedding []float32, candidates []EmbeddingRow, threshold float32) []DuplicateResult

FindDuplicates returns candidates whose cosine similarity to embedding exceeds threshold.

type ElpiOptions added in v0.4.4

type ElpiOptions struct {
	Fuel    int // resolution steps; default 100000
	MaxRows int // solutions; default 1000
	Budget  Budget
}

ElpiOptions bounds a run.

type ElpiProgram added in v0.4.4

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

ElpiProgram is a parsed program.

func ParseElpi added in v0.4.4

func ParseElpi(text string) (*ElpiProgram, error)

ParseElpi parses a program.

type ElpiResult added in v0.4.4

type ElpiResult struct {
	// Rows bind each named goal variable; a value that is not ground is
	// returned as its printed form in a string.
	Rows     []map[string]Value `json:"rows"`
	FuelUsed int                `json:"fuel_used"`
}

ElpiResult is the answer to a goal.

type Embedder

type Embedder interface {
	// Embed returns one vector per input text, in order.
	Embed(texts []string) ([][]float32, error)
	// Close releases any resources held by the embedder.
	Close()
}

Embedder produces embedding vectors for text.

Two implementations exist: localEmbedder runs the model in-process through hugot, and ollamaEmbedder delegates to a local Ollama daemon. They are not interchangeable across a populated database — vectors from different models live in different spaces — so switching backends means re-indexing unless the underlying model is the same.

func NewEmbedder

func NewEmbedder(modelPath string) (Embedder, error)

NewEmbedder creates an Embedder on the compiled-in inference backend.

The default build is pure Go (no cgo, no native libraries). Building with -tags ORT swaps in ONNX Runtime with CoreML, which runs on the Apple GPU and Neural Engine. Which backend is compiled in also decides which weights file to use — see platformOnnxFile — so the two must be chosen together.

func NewOllamaEmbedder added in v0.0.48

func NewOllamaEmbedder(baseURL, model string) (Embedder, error)

NewOllamaEmbedder connects to an Ollama daemon and verifies the embedding model is present. Both checks happen here rather than on first Embed so that misconfiguration surfaces at startup, where it can be reported usefully, instead of midway through a mining run.

type EmbeddingRow

type EmbeddingRow struct {
	DrawerID  string
	Embedding []float32
}

EmbeddingRow is a drawer ID paired with its embedding vector.

type Entity

type Entity struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Type      string    `json:"type,omitempty"` // person, file, concept, etc.
	CreatedAt time.Time `json:"created_at"`
}

Entity is a node in the knowledge graph.

type EraseReport added in v0.4.4

type EraseReport struct {
	Tx *TxReport `json:"tx"`
	// Erased is false when the subject had no live key.
	Erased bool `json:"erased"`
	// Checkpointed is true when the WAL was checkpointed and truncated after
	// the commit, so the old key bytes are gone from the file. A busy reader
	// can prevent that; the bytes then leave at the next checkpoint.
	Checkpointed bool `json:"checkpointed"`
}

EraseReport is the result of KnowledgeGraph.Erase.

type Event added in v0.4.4

type Event struct {
	T    int64        `json:"t"`
	EID  int64        `json:"eid"`
	Op   string       `json:"op"` // "assert" or "retract"
	Kind *RetractKind `json:"kind,omitempty"`
}

Event is one entry of the log: a statement asserted or retracted at t.

type Evidence added in v0.4.4

type Evidence struct {
	EID           int64      `json:"eid"`
	ValidFrom     *time.Time `json:"valid_from,omitempty"`
	ValidTo       *time.Time `json:"valid_to,omitempty"`
	AddedAt       time.Time  `json:"added_at"`
	Author        string     `json:"author,omitempty"`
	Confidence    *float64   `json:"confidence,omitempty"`
	Sources       []string   `json:"sources,omitempty"`
	SourceFiles   []string   `json:"source_files,omitempty"`
	Confirmations int        `json:"confirmations,omitempty"`
}

Evidence is what the graph records in support of one statement. Nothing is scored: absent evidence is absent.

type Explanation added in v0.4.4

type Explanation struct {
	Statement Statement `json:"statement"`
	// Visible reports whether the statement is visible in the view asked.
	Visible  bool        `json:"visible"`
	View     string      `json:"view"`
	Evidence Evidence    `json:"evidence"`
	Layers   []Statement `json:"layers,omitempty"`
	// Supports are the statements it was derived from.
	Supports []Statement `json:"supports,omitempty"`
	// Supersedes lists the versions it corrected, newest first;
	// SupersededBy the versions that corrected it, oldest first.
	Supersedes   []int64  `json:"supersedes,omitempty"`
	SupersededBy []int64  `json:"superseded_by,omitempty"`
	Confirmed    []TxInfo `json:"confirmed,omitempty"`
	AddedBy      *TxInfo  `json:"added_by,omitempty"`
	RetractedBy  *TxInfo  `json:"retracted_by,omitempty"`
	// Dependents is what retracting it would take with it, in this view.
	Dependents []int64 `json:"dependents,omitempty"`
}

Explanation is everything the graph knows about one statement.

type ExtractedTriple added in v0.0.48

type ExtractedTriple struct {
	Subject   string `json:"subject"`
	Predicate string `json:"predicate"`
	Object    string `json:"object"`
	// Confidence is a rough score 0-1. Higher means more reliable (e.g. came
	// from a code construct rather than a guessed pair of identifiers).
	Confidence float64 `json:"confidence"`
	// Reason is a short human-readable note for why this triple was emitted.
	// Helps the agent decide whether to keep or reject the candidate.
	Reason string `json:"reason"`
}

ExtractedTriple is a candidate triple produced by the extractor. The agent reviews and may submit to palace-kg-add unchanged; field names match the KGAdd tool's input shape.

type Graph

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

Graph provides BFS traversal and tunnel discovery across the palace.

func NewGraph

func NewGraph(store PalaceStore) *Graph

NewGraph creates a new Graph wrapping the given store.

func (*Graph) FindTunnels

func (g *Graph) FindTunnels(ctx context.Context, wingA, wingB string) ([]Tunnel, error)

FindTunnels returns rooms that appear in 2+ wings, optionally filtered to rooms connecting wingA and wingB.

func (*Graph) Stats

func (g *Graph) Stats(ctx context.Context) (*GraphStats, error)

Stats returns aggregate graph statistics.

func (*Graph) Traverse

func (g *Graph) Traverse(ctx context.Context, startRoom string, maxHops int) ([]TraverseResult, error)

Traverse performs BFS from startRoom, expanding through shared wings. maxHops caps the traversal depth (default 2 if <= 0). Results are sorted by (hops ASC, drawer count DESC) and capped at 50.

type GraphInfo added in v0.4.4

type GraphInfo struct {
	Name    string `json:"name"`
	Members int    `json:"members"`
}

GraphInfo is one named graph with its member count in a view.

type GraphStats

type GraphStats struct {
	TotalRooms  int      `json:"total_rooms"`
	TunnelCount int      `json:"tunnel_count"`
	EdgeCount   int      `json:"edge_count"`
	TopTunnels  []string `json:"top_tunnels,omitempty"`
}

GraphStats are statistics about the palace graph.

type KGAddToolInput

type KGAddToolInput struct {
	// The subject entity name. Omit it when annotating a statement with about.
	Subject string `json:"subject,omitempty"`
	// The predicate (relationship type), e.g. works_on, confidence, note.
	Predicate string `json:"predicate"`
	// The object: an entity name, or a text value when literal is true.
	Object string `json:"object"`
	// Optional validity start date (RFC3339 or YYYY-MM-DD).
	ValidFrom string `json:"valid_from,omitempty"`
	// Optional validity end date, exclusive (RFC3339 or YYYY-MM-DD).
	ValidTo string `json:"valid_to,omitempty"`
	// Store the object as a text value rather than an entity.
	Literal bool `json:"literal,omitempty"`
	// Statement id (the number in e12) to annotate instead of an entity subject.
	About int64 `json:"about,omitempty"`
	// Statement ids this fact is concluded from; it is retracted automatically
	// if any of them is retracted or corrected.
	Support []int64 `json:"support,omitempty"`
	// How sure you are, 0 to 1.
	Confidence *float64 `json:"confidence,omitempty"`
	// Where the fact came from (file, URL, person, test).
	Source string `json:"source,omitempty"`
	// When the fact is already known, record this as a confirmation.
	ConfirmExisting bool `json:"confirm_existing,omitempty"`
	// Put the fact into this named graph (a project, session or topic).
	Graph string `json:"graph,omitempty"`
}

KGAddToolInput defines parameters for the palace-kg-add tool.

type KGAddToolOutput

type KGAddToolOutput struct {
	Content string `json:"content"`
}

KGAddToolOutput contains the result of adding a triple.

type KGBundleToolInput added in v0.4.4

type KGBundleToolInput struct {
	// export (a fact with everything said about it, as JSON) or import.
	Action string `json:"action"`
	// export: the statement id, the number in e12.
	EID int64 `json:"eid,omitempty"`
	// export: the fact as believed then (transaction number or time).
	TxAsOf string `json:"tx_as_of,omitempty"`
	// import: a bundle produced by export.
	Bundle string `json:"bundle,omitempty"`
	// import: where it came from.
	Source string `json:"source,omitempty"`
}

KGBundleToolInput defines parameters for the palace-kg-bundle tool.

type KGBundleToolOutput added in v0.4.4

type KGBundleToolOutput struct {
	Content string `json:"content"`
}

KGBundleToolOutput contains the result.

type KGConflictsToolInput added in v0.4.4

type KGConflictsToolInput struct {
	// Only conflicts about this subject entity.
	Subject string `json:"subject,omitempty"`
	// Only conflicts for this predicate.
	Predicate string `json:"predicate,omitempty"`
	// Maximum subject/predicate pairs (default 20).
	Limit int `json:"limit,omitempty"`
	// Look at what was believed then: a transaction number or a time.
	TxAsOf string `json:"tx_as_of,omitempty"`
}

KGConflictsToolInput defines parameters for the palace-kg-conflicts tool.

type KGConflictsToolOutput added in v0.4.4

type KGConflictsToolOutput struct {
	Content string `json:"content"`
}

KGConflictsToolOutput contains the conflicts.

type KGExplainToolInput added in v0.4.4

type KGExplainToolInput struct {
	// The statement id, the number in e12.
	EID int64 `json:"eid"`
	// Explain it as it was believed then: a transaction number or a time.
	TxAsOf string `json:"tx_as_of,omitempty"`
}

KGExplainToolInput defines parameters for the palace-kg-explain tool.

type KGExplainToolOutput added in v0.4.4

type KGExplainToolOutput struct {
	Content string `json:"content"`
}

KGExplainToolOutput contains the explanation.

type KGExtractToolInput added in v0.0.48

type KGExtractToolInput struct {
	// Text is the chunk to extract from. Required.
	Text string `json:"text"`
	// SourceFile is an optional path to scope the "defined_in" and "part_of"
	// heuristics. When set, identifiers are anchored to this file.
	SourceFile string `json:"source_file,omitempty"`
	// MaxTriples caps the number of returned candidates. Default 20. The tool
	// returns at most this many triples, prioritized as documented below.
	MaxTriples int `json:"max_triples,omitempty"`
}

KGExtractToolInput defines parameters for the palace-kg-extract tool.

The tool takes a chunk of text and (optionally) the source file it came from, and returns a deduplicated list of candidate (subject, predicate, object) triples. It does not write to the knowledge graph: the calling agent is expected to review the candidates and call palace-kg-add for the ones it wants to keep.

The tool is heuristic: it does not call an LLM. That is deliberate — the extraction runs in the hot path of tool use and would otherwise add an extra model call per observation. The agent already has a model; it can reject bad candidates. Code-level signals (imports, declarations, file paths) are reliable enough to extract without a model; free-form text extraction is left to the agent.

type KGExtractToolOutput added in v0.0.48

type KGExtractToolOutput struct {
	Content string            `json:"content"`
	Triples []ExtractedTriple `json:"triples"`
}

KGExtractToolOutput contains the candidate triples and a markdown summary the agent can scan quickly.

type KGGraphToolInput added in v0.4.4

type KGGraphToolInput struct {
	// add (put a fact into a graph), remove (take it out; the fact stays),
	// or list (graphs and their sizes, or the graphs of one fact with eid).
	Action string `json:"action"`
	// The statement id, the number in e12 (add, remove; optional for list).
	EID int64 `json:"eid,omitempty"`
	// The graph name, e.g. a project, session or topic (add, remove).
	Graph string `json:"graph,omitempty"`
}

KGGraphToolInput defines parameters for the palace-kg-graph tool.

type KGGraphToolOutput added in v0.4.4

type KGGraphToolOutput struct {
	Content string `json:"content"`
}

KGGraphToolOutput contains the result.

type KGInvalidateToolInput

type KGInvalidateToolInput struct {
	// The subject entity name.
	Subject string `json:"subject"`
	// The predicate (relationship type).
	Predicate string `json:"predicate"`
	// The object entity name.
	Object string `json:"object"`
}

KGInvalidateToolInput defines parameters for the palace-kg-invalidate tool.

type KGInvalidateToolOutput

type KGInvalidateToolOutput struct {
	Content string `json:"content"`
}

KGInvalidateToolOutput contains the result.

type KGPathToolInput added in v0.4.4

type KGPathToolInput struct {
	// Start entity. At least one of from and to is required.
	From string `json:"from,omitempty"`
	// Target entity.
	To string `json:"to,omitempty"`
	// Only follow these predicates (default: any).
	Predicates []string `json:"predicates,omitempty"`
	// out (default), in, or both.
	Direction string `json:"direction,omitempty"`
	// reach, shortest (default), all_shortest, or trails.
	Mode string `json:"mode,omitempty"`
	// Each step must happen at or after the previous one in valid time.
	TimeRespecting bool `json:"time_respecting,omitempty"`
	// Hop limits (default 1..6, max 16).
	MinHops int `json:"min_hops,omitempty"`
	MaxHops int `json:"max_hops,omitempty"`
	// Maximum paths (default 20).
	Limit int `json:"limit,omitempty"`
	// Only facts in this named graph.
	Graph string `json:"graph,omitempty"`
	// What was believed then: a transaction number or a time.
	TxAsOf string `json:"tx_as_of,omitempty"`
	// Only facts valid at this time.
	AsOf string `json:"as_of,omitempty"`
}

KGPathToolInput defines parameters for the palace-kg-path tool.

type KGPathToolOutput added in v0.4.4

type KGPathToolOutput struct {
	Content string `json:"content"`
}

KGPathToolOutput contains the result.

type KGQuery added in v0.4.4

type KGQuery struct {
	// Entity whose facts to return, or Text to search entity names and string
	// values instead.
	Entity, Text string
	// AsOf narrows to facts valid at that time (RFC3339 or YYYY-MM-DD).
	AsOf string
	// TxAsOf shows what was believed then: a transaction number or a time.
	TxAsOf string
	// Direction is "subject", "object" or "" (both).
	Direction string
	Limit     int
	// Graph restricts the facts to one named graph.
	Graph string
}

KGQuery selects facts for QueryWith.

type KGQueryToolInput

type KGQueryToolInput struct {
	// The entity name to query. Omit it to search with text instead.
	Entity string `json:"entity,omitempty"`
	// Words to search for in entity names and text values.
	Text string `json:"text,omitempty"`
	// Optional point-in-time filter on when facts held (RFC3339 or YYYY-MM-DD).
	AsOf string `json:"as_of,omitempty"`
	// Show what was believed at that moment: a transaction number or a time.
	TxAsOf string `json:"tx_as_of,omitempty"`
	// Direction: "subject", "object", or "both" (default "both").
	Direction string `json:"direction,omitempty"`
	// Maximum facts to return (default all for entity, 20 for text).
	Limit int `json:"limit,omitempty"`
	// Only facts in this named graph.
	Graph string `json:"graph,omitempty"`
}

KGQueryToolInput defines parameters for the palace-kg-query tool.

type KGQueryToolOutput

type KGQueryToolOutput struct {
	Content string `json:"content"`
}

KGQueryToolOutput contains formatted query results.

type KGRecallToolInput added in v0.4.4

type KGRecallToolInput struct {
	// What to recall, in plain words.
	Query string `json:"query"`
	// Maximum facts (default 10).
	Limit int `json:"limit,omitempty"`
	// Only facts in this named graph.
	Graph string `json:"graph,omitempty"`
}

KGRecallToolInput defines parameters for the palace-kg-recall tool.

type KGRecallToolOutput added in v0.4.4

type KGRecallToolOutput struct {
	Content string `json:"content"`
}

KGRecallToolOutput contains the result.

type KGReviseToolInput added in v0.4.4

type KGReviseToolInput struct {
	// supersede (correct the fact), confirm (another source agrees), or
	// retract (it was never true).
	Action string `json:"action"`
	// The statement id, the number in e12.
	EID int64 `json:"eid"`
	// supersede: the corrected object (an entity name, or text with literal).
	Object string `json:"object,omitempty"`
	// supersede: store the corrected object as a text value.
	Literal bool `json:"literal,omitempty"`
	// supersede: corrected validity start / end (RFC3339 or YYYY-MM-DD).
	ValidFrom string `json:"valid_from,omitempty"`
	ValidTo   string `json:"valid_to,omitempty"`
	// Why (recorded on the change).
	Reason string `json:"reason,omitempty"`
	// Who or what says so (file, URL, person, test).
	Source string `json:"source,omitempty"`
	// Preview the change without writing it.
	DryRun bool `json:"dry_run,omitempty"`
}

KGReviseToolInput defines parameters for the palace-kg-revise tool.

type KGReviseToolOutput added in v0.4.4

type KGReviseToolOutput struct {
	Content string `json:"content"`
}

KGReviseToolOutput contains the result.

type KGRulesToolInput added in v0.4.4

type KGRulesToolInput struct {
	// store (save a named program), solve (answer a goal), check (report
	// constraint violations), or materialize (write a stored program's
	// conclusions as derived facts).
	Action string `json:"action"`
	// The program name (store, materialize; or to solve/check a stored one).
	Name string `json:"name,omitempty"`
	// The rules text (store; or inline for solve/check).
	Program string `json:"program,omitempty"`
	// datalog (default), n3, or elpi (solve only: clauses like "reports X Y :- tm.triple X manager Y.").
	Syntax string `json:"syntax,omitempty"`
	// solve: the goal, e.g. reports(alice, Y).
	Goal string `json:"goal,omitempty"`
	// materialize: preview without writing.
	DryRun bool `json:"dry_run,omitempty"`
	// Only facts in this named graph (solve, check, materialize).
	Graph string `json:"graph,omitempty"`
}

KGRulesToolInput defines parameters for the palace-kg-rules tool.

type KGRulesToolOutput added in v0.4.4

type KGRulesToolOutput struct {
	Content string `json:"content"`
}

KGRulesToolOutput contains the result.

type KGSelectToolInput added in v0.4.4

type KGSelectToolInput struct {
	// sparql (default) or cypher.
	Lang string `json:"lang,omitempty"`
	// The query, e.g. SELECT ?who WHERE { ?who <works_on> <auth> } or
	// MATCH (a)-[r:works_on]->(b) WHERE r.confidence > 0.5 RETURN a, b.
	Query string `json:"query,omitempty"`
	// What was believed then: a transaction number or a time.
	TxAsOf string `json:"tx_as_of,omitempty"`
	// Only facts valid at this time.
	AsOf string `json:"as_of,omitempty"`
	// Only facts in this named graph.
	Graph string `json:"graph,omitempty"`
	// Fail instead of returning more than this many rows (default 200).
	MaxRows int `json:"max_rows,omitempty"`
	// Save the answer under this name, to check later whether it still holds.
	SaveAs string `json:"save_as,omitempty"`
	// Check a saved answer by name instead of running a query.
	Check string `json:"check,omitempty"`
}

KGSelectToolInput defines parameters for the palace-kg-select tool.

type KGSelectToolOutput added in v0.4.4

type KGSelectToolOutput struct {
	Content string `json:"content"`
}

KGSelectToolOutput contains the result.

type KGStats

type KGStats struct {
	EntityCount int `json:"entity_count"`
	// TripleCount is the live facts; ActiveTriples those whose valid time
	// is still open.
	TripleCount   int `json:"triple_count"`
	ActiveTriples int `json:"active_triples"`
	// Statements counts every statement ever written, Layers the live
	// statements about statements, Retracted the retracted ones.
	Statements   int      `json:"statements"`
	Layers       int      `json:"layers"`
	Retracted    int      `json:"retracted"`
	Transactions int      `json:"transactions"`
	Predicates   []string `json:"predicates,omitempty"`
}

KGStats are aggregate statistics for the knowledge graph.

type KGTimelineToolInput

type KGTimelineToolInput struct {
	// The entity name to get timeline for.
	Entity string `json:"entity"`
}

KGTimelineToolInput defines parameters for the palace-kg-timeline tool.

type KGTimelineToolOutput

type KGTimelineToolOutput struct {
	Content string `json:"content"`
}

KGTimelineToolOutput contains formatted timeline.

type KGTx added in v0.4.4

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

KGTx is an open knowledge-graph transaction. It is only valid inside the callback passed to KnowledgeGraph.Transact.

func (*KGTx) AddToGraph added in v0.4.4

func (w *KGTx) AddToGraph(eid int64, g string) (int64, bool, error)

AddToGraph puts live statement eid into graph g. It is idempotent and returns the membership statement.

func (*KGTx) Annotate added in v0.4.4

func (w *KGTx) Annotate(eid int64, p, o Value) (int64, bool, error)

Annotate adds a layer: a statement about statement eid.

func (*KGTx) Assert added in v0.4.4

func (w *KGTx) Assert(s, p, o Value, v Valid) (eid int64, isNew bool, err error)

Assert writes (s, p, o) valid during v, or returns the live statement that already says the same thing over an overlapping interval. isNew reports which.

func (*KGTx) ClearVolatile added in v0.4.4

func (w *KGTx) ClearVolatile(s, key Value) error

ClearVolatile removes (s, key). Clearing an absent value succeeds.

func (*KGTx) Confirm added in v0.4.4

func (w *KGTx) Confirm(eid int64) (int64, error)

Confirm records that this transaction's source corroborates live statement eid: (eid sys:ConfirmedBy tx). Confirming twice in one transaction is one confirmation.

func (*KGTx) Create added in v0.4.4

func (w *KGTx) Create(s, p, o Value, v Valid) (int64, error)

Create always writes a new statement, even when an identical live one exists (parallel edges).

func (*KGTx) Derive added in v0.4.4

func (w *KGTx) Derive(s, p, o Value, v Valid, support []int64) (int64, bool, error)

Derive writes a conclusion that rests on every statement in support. If any support is later retracted or corrected, the conclusion is retracted with it. It returns an existing statement only when one with the same content, an overlapping interval and exactly the same live supports exists; an independently asserted identical fact is never reused.

func (*KGTx) DropGraph added in v0.4.4

func (w *KGTx) DropGraph(g string) (int, error)

DropGraph retracts every live membership of graph g and returns how many. The member statements stay.

func (*KGTx) Erase added in v0.4.4

func (w *KGTx) Erase(subject Value) (bool, error)

Erase destroys subject's seal key in this transaction. Every sealed value of the subject, and of every statement about its statements, decodes as sys:Erased from now on. Saved answers are marked stale and lose their stored rows, since those may hold decrypted values. It returns false when the subject has no live key.

func (*KGTx) ImportBundle added in v0.4.4

func (w *KGTx) ImportBundle(b *Bundle) (map[string]int64, error)

ImportBundle writes bundle b through idempotent Assert, depth-first, and returns the eid each bundle id became. Importing the same bundle again changes nothing. The whole bundle is validated before anything is written: a reference to an id not yet imported is ErrBundleCycle; any engine predicate other than sys:InGraph is rejected; a sensitive value needs a sensitive target predicate (ErrSchemaViolation), and is then sealed by the normal write path.

func (*KGTx) RemoveFromGraph added in v0.4.4

func (w *KGTx) RemoveFromGraph(eid int64, g string) (bool, error)

RemoveFromGraph retracts statement eid's live membership of graph g. The statement itself stays. It returns false when eid was not a member.

func (*KGTx) Retract added in v0.4.4

func (w *KGTx) Retract(eid int64) (bool, error)

Retract ends the belief in statement eid and, in the same transaction, in everything that stands on it: statements whose subject or object is a retracted statement, and statements derived from one. It returns false when eid was already retracted.

func (*KGTx) SetPredicate added in v0.4.4

func (w *KGTx) SetPredicate(p Value, sch PredicateSchema) error

SetPredicate declares p's schema, replacing the previous one. It fails with ErrSchemaViolation when live data already breaks a new constraint, or when the combination is not supported (sensitive with unique: sealed values of different subjects never compare equal).

func (*KGTx) SetVolatile added in v0.4.4

func (w *KGTx) SetVolatile(s, key, o Value) error

SetVolatile sets (s, key) to o, replacing any previous value. updated_at is this transaction's instant.

func (*KGTx) StoreProgram added in v0.4.4

func (w *KGTx) StoreProgram(name, syntax, text string) (int64, error)

StoreProgram validates text in the given syntax ("datalog" or "n3") and records it as (program:<name> sys:RuleText text). Storing the same text again returns the live statement; storing different text supersedes it, so the conclusions of the old version are withdrawn and must be materialized again. It returns the program's eid.

func (*KGTx) Supersede added in v0.4.4

func (w *KGTx) Supersede(eid int64, patch Patch) (int64, error)

Supersede corrects statement eid. It retracts the statement and its layers (kind "superseded"), writes the corrected statement under a new eid, replays every layer onto it under new eids, and records (new sys:Supersedes old). Derived statements that rested on the old version are not replayed: their input changed, so they must be derived again. Subject and predicate cannot change, because that would be a different fact.

func (*KGTx) T added in v0.4.4

func (w *KGTx) T() int64

T is the transaction number.

func (*KGTx) Upsert added in v0.4.4

func (w *KGTx) Upsert(p, o Value) (node Value, eid int64, isNew bool, err error)

Upsert returns the subject of the live statement (n p o) on a unique predicate p, or creates a fresh node n and asserts (n p o). On a predicate that is not unique it fails with ErrNotUnique.

func (*KGTx) UpsertDerived added in v0.4.4

func (w *KGTx) UpsertDerived(p, o Value, support []int64) (node Value, eid int64, isNew bool, err error)

UpsertDerived returns the node n of a live key (n p o) derived from exactly support, or a fresh node whose key is written through Derive. A key that was asserted independently, or derived from other support, is never reused, so a rule engine's invented nodes are stable across runs and fall with their support (Tiramemsu D51).

type KnowledgeGraph

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

KnowledgeGraph is the palace's bitemporal statement graph, a pure-Go port of Tiramemsu's core model (specs/memory/tiramemsu). Every fact is a statement with its own eid, so facts about facts — confidence, source, derivations, confirmations — are statements too ("layers"). Every change is kept with the transaction that made it (transaction time) and the interval during which the fact held (valid time); nothing is deleted.

Writes go through Transact and the KGTx verbs (Assert, Create, Retract, Supersede, Confirm, Derive, SetPredicate). Reads go through views (Now, AsOf, AsOfInstant, History, ValidAt). The triple-shaped methods below (Add, Query, Invalidate, Timeline) keep the original palace API on top.

func NewKnowledgeGraph

func NewKnowledgeGraph(store PalaceStore) *KnowledgeGraph

NewKnowledgeGraph creates a KnowledgeGraph on the store's database. The database is resolved on first use, so a store that is never asked for knowledge-graph data (a test stub) need not provide one.

func (*KnowledgeGraph) Add

func (kg *KnowledgeGraph) Add(ctx context.Context, input TripleInput) (*Triple, error)

Add records a fact, auto-creating entities. An identical live fact with an overlapping valid interval is returned instead of a duplicate (and confirmed when ConfirmExisting is set). Confidence and Source become layers on the fact; About annotates an existing statement instead of an entity; Support derives the fact from existing statements.

func (*KnowledgeGraph) AsOf added in v0.4.4

func (kg *KnowledgeGraph) AsOf(t int64) View

AsOf is the view of what was believed right after transaction t.

func (*KnowledgeGraph) AsOfInstant added in v0.4.4

func (kg *KnowledgeGraph) AsOfInstant(ctx context.Context, at time.Time) (View, error)

AsOfInstant is the view of what was believed at wall-clock time at: the last transaction committed at or before it. Before the first transaction it is empty.

func (*KnowledgeGraph) CheckAnswer added in v0.4.4

func (kg *KnowledgeGraph) CheckAnswer(ctx context.Context, name string) (*SavedAnswer, error)

CheckAnswer replays the events after the answer's checkpoint. An answer on an as-of view is fixed and stays fresh. Otherwise it becomes stale when a statement it rests on is retracted, when a statement with a predicate it reads is asserted (it may add rows), when a query with OPTIONAL, NOT EXISTS or COUNT sees a retraction of such a statement (it may add or change rows), or, for a graph-scoped view, on any membership change. A fresh check advances the checkpoint; a stale answer keeps its checkpoint until it is refreshed. Checking is idempotent.

func (*KnowledgeGraph) DeleteAnswer added in v0.4.4

func (kg *KnowledgeGraph) DeleteAnswer(ctx context.Context, name string) error

DeleteAnswer removes a saved answer. Deleting an unknown one succeeds.

func (*KnowledgeGraph) EmbedStatements added in v0.4.4

func (kg *KnowledgeGraph) EmbedStatements(ctx context.Context, emb Embedder, model string, batch int) (int, error)

EmbedStatements backfills a vector for model on every live, non-engine statement that has none (so a superseded statement's replacement is picked up), in one knowledge-graph transaction authored "palace-embed"; the vectors are visible from that transaction. Statements holding sealed values are skipped. It returns how many vectors were stored.

func (*KnowledgeGraph) Erase added in v0.4.4

func (kg *KnowledgeGraph) Erase(ctx context.Context, opts TxOptions, subject string) (*EraseReport, error)

Erase destroys subject's key in its own transaction and then checkpoints the WAL, so that the destroyed key leaves the file (secure_delete zeroes freed pages). Backups taken earlier still hold the key; that is documented, not solved.

func (*KnowledgeGraph) Events added in v0.4.4

func (kg *KnowledgeGraph) Events(ctx context.Context, since, until int64) ([]Event, error)

Events returns the log of committed transactions after since and up to until (0 = the last committed one), ordered by t, asserts before retracts, then eid. The log ignores views: it is the whole history, and replaying it up to t reproduces AsOf(t).

func (*KnowledgeGraph) Get added in v0.4.4

func (kg *KnowledgeGraph) Get(ctx context.Context, eid int64) (*Statement, error)

Get returns statement eid whatever its state, or nil when it does not exist.

func (*KnowledgeGraph) History added in v0.4.4

func (kg *KnowledgeGraph) History() View

History is the view of every statement ever written, retracted or not.

func (*KnowledgeGraph) Invalidate

func (kg *KnowledgeGraph) Invalidate(ctx context.Context, subject, predicate, object string) error

Invalidate ends every live, still-open fact (subject, predicate, object) now: each is superseded by the same fact with valid_to = now, so its layers carry over and the open version stays visible in history. Facts whose interval is already closed are left alone.

func (*KnowledgeGraph) InvalidateWith added in v0.4.4

func (kg *KnowledgeGraph) InvalidateWith(ctx context.Context, subject, predicate, object string, opts TxOptions) error

InvalidateWith is Invalidate with transaction metadata.

func (*KnowledgeGraph) ListAnswers added in v0.4.4

func (kg *KnowledgeGraph) ListAnswers(ctx context.Context) ([]SavedAnswer, error)

ListAnswers returns every saved answer, by name.

func (*KnowledgeGraph) LoadProgram added in v0.4.4

func (kg *KnowledgeGraph) LoadProgram(ctx context.Context, name string) (*Program, int64, error)

LoadProgram returns the live program stored under name and its eid.

func (*KnowledgeGraph) Materialize added in v0.4.4

func (kg *KnowledgeGraph) Materialize(ctx context.Context, opts TxOptions, name string, view View, ro RuleOptions) (*MaterializeReport, error)

Materialize evaluates stored program name over view and writes every derived tuple as a derived statement in one transaction. Each fragment is written through Derive with the support of its stored statements plus the program statement, so a conclusion falls with any premise and with the program. The program's own earlier conclusions are not input. A live conclusion with the same support and a narrower interval is widened with Supersede (support links are replayed). Conclusions of this program that are no longer derivable are retracted only when view is the plain Now view (no valid-time or graph restriction); any other view only adds. A second run with nothing changed writes no statements.

Programs with negation are rejected (ErrNotMaterializable): a conclusion that rests on the absence of a statement cannot fall with a premise.

func (*KnowledgeGraph) Now added in v0.4.4

func (kg *KnowledgeGraph) Now() View

Now is the view of what is believed now.

func (*KnowledgeGraph) PutVector added in v0.4.4

func (kg *KnowledgeGraph) PutVector(ctx context.Context, eid int64, model string, vec []float32) error

PutVector stores a caller-supplied vector for statement eid under model, in its own transaction. The same vector again is a no-op; a different one is ErrVectorConflict. The vector must be finite with a non-zero norm and match the model's recorded dimension (the first vector of a model records it). A statement holding a sealed value is refused.

func (*KnowledgeGraph) Query

func (kg *KnowledgeGraph) Query(ctx context.Context, entity string, asOf string, direction string) ([]*Triple, error)

Query returns facts involving the named entity. If asOf is non-empty, only facts valid at that time ([valid_from, valid_to)) are returned. Direction can be "subject", "object", or "" (both).

func (*KnowledgeGraph) QueryWith added in v0.4.4

func (kg *KnowledgeGraph) QueryWith(ctx context.Context, in KGQuery) ([]*Triple, error)

QueryWith runs a KGQuery, newest knowledge last.

func (*KnowledgeGraph) RefreshAnswer added in v0.4.4

func (kg *KnowledgeGraph) RefreshAnswer(ctx context.Context, name string) (*SavedAnswer, error)

RefreshAnswer re-evaluates a saved answer. Only success clears its stale mark and moves its checkpoint; a failure leaves it as it was.

func (*KnowledgeGraph) SaveAnswer added in v0.4.4

func (kg *KnowledgeGraph) SaveAnswer(ctx context.Context, name, lang, query string, v View) (*SavedAnswer, error)

SaveAnswer evaluates the query on v and saves it under name, replacing an answer of the same name.

func (*KnowledgeGraph) Schema added in v0.4.4

func (kg *KnowledgeGraph) Schema(ctx context.Context, predicate string) (PredicateSchema, error)

Schema returns predicate p's current schema.

func (*KnowledgeGraph) Stats

func (kg *KnowledgeGraph) Stats(ctx context.Context) (*KGStats, error)

Stats returns aggregate knowledge-graph statistics. TripleCount and ActiveTriples keep their old meaning: live facts, and live facts whose valid time is still open.

func (*KnowledgeGraph) Timeline

func (kg *KnowledgeGraph) Timeline(ctx context.Context, entity string) ([]*Triple, error)

Timeline returns every fact ever recorded for the named entity, including ended, superseded and retracted ones, in the order they were learned.

func (*KnowledgeGraph) Transact added in v0.4.4

func (kg *KnowledgeGraph) Transact(ctx context.Context, opts TxOptions, fn func(*KGTx) error) (*TxReport, error)

Transact runs fn in one knowledge-graph transaction: one t, one instant, all-or-nothing. fn's error rolls everything back.

func (*KnowledgeGraph) Transaction added in v0.4.4

func (kg *KnowledgeGraph) Transaction(ctx context.Context, t int64) (*TxInfo, error)

Transaction returns committed transaction t, or nil.

func (*KnowledgeGraph) View added in v0.4.4

func (kg *KnowledgeGraph) View(ctx context.Context, txAsOf, asOf string) (View, error)

View resolves the query's transaction-time and valid-time selection.

type MaterializeReport added in v0.4.4

type MaterializeReport struct {
	// Program is the eid of the program statement the conclusions rest on.
	Program int64
	// Derived are the new conclusions, Existing the ones already stored,
	// Widened the replacements of conclusions whose interval grew, Reconciled
	// the conclusions retracted because they are no longer derivable.
	Derived, Existing, Widened, Reconciled []int64
	Tx                                     *TxReport
}

MaterializeReport is what one Materialize run did.

type MemoryStack

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

MemoryStack implements the 4-layer memory system for system prompt context injection. L0 = identity, L1 = essential story, L2 = on-demand recall, L3 = search (delegated to DrawerService.Search).

func NewMemoryStack

func NewMemoryStack(store PalaceStore, embedder Embedder, config PalaceConfig) *MemoryStack

NewMemoryStack creates a MemoryStack from the given store, embedder, and config.

func (*MemoryStack) Recall

func (ms *MemoryStack) Recall(ctx context.Context, wing, room string) (string, error)

Recall returns L2 on-demand context: drawers matching wing+room, up to L2MaxDrawers items, each truncated to L2MaxCharsPerDrawer characters.

func (*MemoryStack) WakeUp

func (ms *MemoryStack) WakeUp(ctx context.Context, wing string) (string, error)

WakeUp returns the combined L0 + L1 context string for system prompt injection.

type MineConfig

type MineConfig struct {
	Wing     string       `yaml:"wing"`
	Rooms    []RoomDef    `yaml:"rooms"`
	Progress ProgressFunc `yaml:"-"`
	Phase    PhaseFunc    `yaml:"-"`
}

MineConfig is the per-project configuration loaded from mempalace.yaml.

type MineResult

type MineResult struct {
	Added     int
	Skipped   int // duplicates
	Processed int
	Errors    int
}

MineResult tracks the outcome of a mining operation.

func MineConversations

func MineConversations(ctx context.Context, palace *Palace, dir string, cfg *MineConfig) (*MineResult, error)

MineConversations reads conversation files from a directory and inserts extracted exchanges as drawers. It supports pi-go JSONL, Claude Code JSONL, and plain text with ">" markers.

func MineProject

func MineProject(ctx context.Context, palace *Palace, dir string, cfg *MineConfig) (*MineResult, error)

MineProject walks a directory, chunks source files, and inserts them as drawers into the palace. It respects .gitignore and mempalace.yaml room definitions. The wing defaults to the directory basename if not set in cfg.

This implementation uses batch embedding and single-pass collection for significantly faster mining.

type ObjClass added in v0.4.4

type ObjClass uint8

ObjClass restricts what a triple's object may be.

const (
	ObjAny ObjClass = iota
	ObjEntity
	ObjLiteral
)

Object classes: Cypher relationships have entity objects, properties literal ones.

type ObservationBridge

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

ObservationBridge converts memory.Observation records into palace drawers, connecting the existing observation pipeline to the palace system.

func NewObservationBridge

func NewObservationBridge(palace *Palace) *ObservationBridge

NewObservationBridge creates a bridge that routes observations into the palace.

func (*ObservationBridge) ConvertAndStore

func (b *ObservationBridge) ConvertAndStore(ctx context.Context, obs *memory.Observation)

ConvertAndStore maps a memory.Observation to a DrawerInput and stores it. Errors are logged but never propagated — bridge failures must not block the observation pipeline.

type Option

type Option func(*PalaceConfig)

Option is a functional option for configuring a Palace.

func WithDBPath

func WithDBPath(path string) Option

WithDBPath sets the database file path.

func WithDeduplicationThreshold

func WithDeduplicationThreshold(t float32) Option

WithDeduplicationThreshold sets the cosine similarity threshold for duplicate detection.

func WithIdentityFile

func WithIdentityFile(path string) Option

WithIdentityFile sets the path to the L0 identity file.

func WithLocalEmbedder added in v0.0.48

func WithLocalEmbedder() Option

WithLocalEmbedder forces the in-process model, bypassing Ollama. Used when no daemon is available and the caller would rather be slow than fail.

func WithModelPath

func WithModelPath(path string) Option

WithModelPath sets the path to the embedding model directory.

func WithOllamaEmbedder added in v0.0.48

func WithOllamaEmbedder(baseURL, model string) Option

WithOllamaEmbedder points the palace at an Ollama daemon for embedding. Empty arguments fall back to DefaultOllamaURL and DefaultOllamaEmbedModel.

type Palace

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

Palace is the top-level facade that ties all palace components together.

func New

func New(opts ...Option) (*Palace, error)

New creates a Palace, opening the database, optionally loading the embedder, and wiring all components together. Functional options configure the behavior.

func NewWithStore

func NewWithStore(store PalaceStore, embedder Embedder, opts ...Option) *Palace

NewWithStore creates a Palace using the provided store and optional embedder. This is useful for testing with in-memory stores.

func (*Palace) AddDrawer

func (p *Palace) AddDrawer(ctx context.Context, input DrawerInput) (*Drawer, error)

AddDrawer embeds content, checks for duplicates, and stores a new drawer.

func (*Palace) Close

func (p *Palace) Close() error

Close releases all palace resources.

func (*Palace) DeleteDrawer

func (p *Palace) DeleteDrawer(ctx context.Context, id string) error

DeleteDrawer removes a drawer by ID.

func (*Palace) DiaryRead

func (p *Palace) DiaryRead(ctx context.Context, agent string, lastN int) ([]*DiaryEntry, error)

DiaryRead returns recent diary entries for an agent.

func (*Palace) DiaryWrite

func (p *Palace) DiaryWrite(ctx context.Context, agent, entry, topic string) error

DiaryWrite stores a diary entry for an agent.

func (*Palace) FindTunnels

func (p *Palace) FindTunnels(ctx context.Context, wingA, wingB string) ([]Tunnel, error)

FindTunnels returns rooms that bridge multiple wings.

func (*Palace) GetDrawer

func (p *Palace) GetDrawer(ctx context.Context, id string) (*Drawer, error)

GetDrawer retrieves a drawer by ID.

func (*Palace) GetTaxonomy

func (p *Palace) GetTaxonomy(ctx context.Context) (*Taxonomy, error)

GetTaxonomy returns the full wing → room hierarchy.

func (*Palace) GraphStats

func (p *Palace) GraphStats(ctx context.Context) (*GraphStats, error)

GraphStats returns palace graph statistics.

func (*Palace) KG added in v0.4.4

func (p *Palace) KG() *KnowledgeGraph

KG returns the knowledge graph, for transactions and views beyond the triple-shaped methods above.

func (*Palace) KGAdd

func (p *Palace) KGAdd(ctx context.Context, input TripleInput) (*Triple, error)

KGAdd creates a triple, auto-creating entities if needed.

func (*Palace) KGInvalidate

func (p *Palace) KGInvalidate(ctx context.Context, subject, predicate, object string) error

KGInvalidate ends an active fact now (a supersede with valid_to = now).

func (*Palace) KGQuery

func (p *Palace) KGQuery(ctx context.Context, entity, asOf, direction string) ([]*Triple, error)

KGQuery returns triples involving the named entity.

func (*Palace) KGStats

func (p *Palace) KGStats(ctx context.Context) (*KGStats, error)

KGStats returns knowledge graph statistics.

func (*Palace) KGTimeline

func (p *Palace) KGTimeline(ctx context.Context, entity string) ([]*Triple, error)

KGTimeline returns all triples for an entity ordered chronologically.

func (*Palace) ListDrawers

func (p *Palace) ListDrawers(ctx context.Context, filter DrawerFilter) ([]*Drawer, error)

ListDrawers returns drawers matching the given filter.

func (*Palace) ListRooms

func (p *Palace) ListRooms(ctx context.Context, wing string) ([]RoomSummary, error)

ListRooms returns rooms within a wing.

func (*Palace) ListWings

func (p *Palace) ListWings(ctx context.Context) ([]WingSummary, error)

ListWings returns aggregate wing summaries.

func (*Palace) Recall

func (p *Palace) Recall(ctx context.Context, wing, room string) (string, error)

Recall returns L2 on-demand context for a specific wing and room.

func (*Palace) Search

func (p *Palace) Search(ctx context.Context, q SearchQuery) ([]SearchResult, error)

Search performs semantic or FTS5 keyword search.

func (*Palace) Status

func (p *Palace) Status(ctx context.Context) (*PalaceStatus, error)

Status returns an aggregate view of the palace.

func (*Palace) Traverse

func (p *Palace) Traverse(ctx context.Context, startRoom string, maxHops int) ([]TraverseResult, error)

Traverse performs BFS traversal from a starting room.

func (*Palace) WakeUp

func (p *Palace) WakeUp(ctx context.Context, wing string) (string, error)

WakeUp returns the combined L0 + L1 context string.

type PalaceConfig

type PalaceConfig struct {
	DBPath                 string
	ModelPath              string
	IdentityFile           string
	DeduplicationThreshold float32
	L1TopK                 int
	L1MaxChars             int
	L2MaxDrawers           int
	L2MaxCharsPerDrawer    int

	// UseOllama selects the Ollama daemon for embedding instead of the
	// in-process model. Default on: it is an order of magnitude faster and
	// retrieves better. See DefaultOllamaEmbedModel for the measurements.
	UseOllama bool
	// OllamaURL is the daemon address; empty means DefaultOllamaURL.
	OllamaURL string
	// OllamaModel is the embedding model; empty means DefaultOllamaEmbedModel.
	OllamaModel string
}

PalaceConfig holds configuration for the Palace system.

func DefaultConfig

func DefaultConfig() PalaceConfig

DefaultConfig returns a PalaceConfig with sensible defaults.

type PalaceStatus

type PalaceStatus struct {
	DrawerCount int      `json:"drawer_count"`
	WingCount   int      `json:"wing_count"`
	RoomCount   int      `json:"room_count"`
	KG          *KGStats `json:"kg,omitempty"`
	ModelLoaded bool     `json:"model_loaded"`
}

PalaceStatus is an aggregate status of the entire palace.

type PalaceStore

type PalaceStore interface {
	// Drawer operations
	InsertDrawer(ctx context.Context, d *Drawer) error
	BatchInsertDrawers(ctx context.Context, drawers []*Drawer) (int, error)
	DeleteDrawer(ctx context.Context, id string) error
	GetDrawer(ctx context.Context, id string) (*Drawer, error)
	ListDrawers(ctx context.Context, filter DrawerFilter) ([]*Drawer, error)
	CountDrawers(ctx context.Context) (int, error)
	// DrawerHashes returns id → content_hash for a wing, so the miner can skip
	// re-embedding chunks whose content has not changed since the last run.
	DrawerHashes(ctx context.Context, wing string) (map[string]string, error)

	// Embedding operations
	GetEmbedding(ctx context.Context, id string) (*EmbeddingRow, error)
	GetAllEmbeddings(ctx context.Context, filter DrawerFilter) ([]EmbeddingRow, error)
	// FindByContentHash returns the id of an existing drawer with identical
	// content in the same wing and room, or "" when there is none.
	FindByContentHash(ctx context.Context, wing, room, hash string) (string, error)

	// Search operations
	KeywordSearch(ctx context.Context, query string, filter DrawerFilter, limit int) ([]SearchResult, error)

	// Hierarchy operations
	ListWings(ctx context.Context) ([]WingSummary, error)
	ListRooms(ctx context.Context, wing string) ([]RoomSummary, error)
	GetTaxonomy(ctx context.Context) (*Taxonomy, error)

	// Knowledge graph operations
	InsertEntity(ctx context.Context, e *Entity) error
	GetEntity(ctx context.Context, id string) (*Entity, error)

	// Diary operations
	InsertDiaryEntry(ctx context.Context, d *DiaryEntry) error
	ListDiaryEntries(ctx context.Context, agent string, limit int) ([]*DiaryEntry, error)

	// DB is the underlying database; the knowledge graph runs its
	// transactions on it directly.
	DB() *sql.DB

	Close() error
}

PalaceStore defines the interface for palace persistence operations.

type Patch added in v0.4.4

type Patch struct {
	Object         *Value
	ValidFrom      *time.Time
	ValidTo        *time.Time
	ClearValidFrom bool
	ClearValidTo   bool
}

Patch is a correction applied by Supersede. Nil fields keep the old value.

type Path added in v0.4.4

type Path struct {
	Nodes []Value
	Steps []PathStep
	// Arrival is the instant the walk reached the last node when the search
	// was time-respecting; nil when unbounded.
	Arrival *time.Time
}

Path is one result: Nodes[i] and Nodes[i+1] are joined by Steps[i].

type PathMode added in v0.4.4

type PathMode int

PathMode selects what a path search returns.

const (
	// PathReach returns one path per reachable target: the one that arrives
	// earliest (time-respecting) or is shortest.
	PathReach PathMode = iota
	// PathShortest returns one shortest path per target.
	PathShortest
	// PathAllShortest returns every shortest path per target.
	PathAllShortest
	// PathTrails returns every trail (no repeated statement) within the hop
	// limits, shortest first, up to Limit.
	PathTrails
)

func ParsePathMode added in v0.4.4

func ParsePathMode(s string) (PathMode, error)

ParsePathMode parses "reach", "shortest", "all_shortest" or "trails".

func (PathMode) String added in v0.4.4

func (m PathMode) String() string

String names the mode as ParsePathMode accepts it.

type PathQuery added in v0.4.4

type PathQuery struct {
	// From and To are entity names; at least one is required. With only To
	// the search runs backwards and paths still read From-side first.
	From, To string
	// Predicates restricts the edges; empty is any non-engine predicate.
	Predicates []string
	// Direction is "out" (subject to object, the default), "in" or "both".
	Direction string
	// MinHops and MaxHops bound the path length: default 1..6, MaxHops capped
	// at 16.
	MinHops, MaxHops int
	Mode             PathMode
	// TimeRespecting requires each edge to still be valid when the walk
	// reaches it: it carries the arrival instant and waits when it must.
	TimeRespecting bool
	// Limit bounds the paths returned (default 50); MaxFrontier bounds the
	// search states held (default 100000) and fails with ErrBudget.
	Limit       int
	MaxFrontier int
	Budget      Budget
}

PathQuery describes a path search.

type PathStep added in v0.4.4

type PathStep struct {
	EID       int64
	From, To  Value
	ValidFrom *time.Time
	ValidTo   *time.Time
}

PathStep is one traversed statement, in its own orientation.

type Pattern added in v0.4.4

type Pattern struct {
	Subject, Predicate, Object *Value
	// IncludeEngine keeps engine bookkeeping (supersedes, confirmations,
	// support links, schema) in the result.
	IncludeEngine bool
	Limit         int
}

Pattern selects statements by any of subject, predicate and object.

type PhaseFunc added in v0.0.41

type PhaseFunc func(stage, item string, done, total int)

PhaseFunc reports progress *inside* a long phase, before the work is done.

Embedding dominates a mining run and operates on chunks rather than files, so the old per-file callback went silent for minutes at a time and the run looked hung. PhaseFunc is called with the item about to be processed — the file the next chunk came from — so a slow phase shows where it actually is.

type PredicateSchema added in v0.4.4

type PredicateSchema struct {
	// One: a subject holds at most one object at any valid time. Asserting a
	// new object retracts the overlapping old ones (kind "replaced"); their
	// layers are not carried over, since they described a different fact.
	One bool `json:"one,omitempty"`
	// Unique: at most one live subject holds a given object.
	Unique bool `json:"unique,omitempty"`
	// ValueType restricts objects to one kind: entity, string, int, number,
	// bool, time or statement. Empty allows any.
	ValueType string `json:"value_type,omitempty"`
	// SubjectType restricts subjects to entity or statement. Empty allows both.
	SubjectType string `json:"subject_type,omitempty"`
	// IsEdge is stored and reported; it marks entity-valued predicates as
	// relationships for query front ends. Nothing is checked.
	IsEdge bool `json:"is_edge,omitempty"`
	// Sensitive seals literal objects under their data subject's key, so that
	// erasing the subject destroys them (crypto-shredding). See kg_seal.go.
	Sensitive bool `json:"sensitive,omitempty"`
}

PredicateSchema holds the constraints a predicate can carry, after Tiramemsu's predicate-schema capability. Every flag is an ordinary, versioned statement about the predicate.

type Program added in v0.4.4

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

Program is a compiled set of rules and constraints.

func ParseDatalog added in v0.4.4

func ParseDatalog(text string) (*Program, error)

ParseDatalog parses a Datalog program with denial constraints. Facts (rules without a body) are rejected: facts belong in the graph, where they have transaction and valid time.

func ParseN3 added in v0.4.4

func ParseN3(text string) (*Program, error)

ParseN3 parses the Horn subset of N3 described above.

func ParseRules added in v0.4.4

func ParseRules(syntax, text string) (*Program, error)

ParseRules parses text in the named syntax: "datalog" or "n3".

func (*Program) Constraints added in v0.4.4

func (p *Program) Constraints() int

Constraints is the number of constraints.

func (*Program) HasNegation added in v0.4.4

func (p *Program) HasNegation() bool

HasNegation reports whether any rule body uses negation.

func (*Program) Rules added in v0.4.4

func (p *Program) Rules() int

Rules is the number of rules (constraints excluded).

type ProgressFunc

type ProgressFunc func(file string, added, skipped, errors int)

ProgressFunc is called after each file is processed during mining. file is the relative path, added/skipped/errors are counts for that file.

type QElem added in v0.4.4

type QElem interface {
	// contains filtered or unexported methods
}

QElem is one element of a conjunction.

type QExpr added in v0.4.4

type QExpr struct {
	Op   string
	Args []*QExpr
	Var  string
	Val  Value
	Re   *regexp.Regexp
}

QExpr is a filter expression. Op is one of var, const, = != < <= > >= && || ! bound regex contains strstarts.

type QFilter added in v0.4.4

type QFilter struct{ Expr *QExpr }

QFilter keeps the solutions for which Expr is true.

type QGraph added in v0.4.4

type QGraph struct {
	Name  string
	Group []QElem
}

QGraph evaluates Group inside the named graph.

type QNode added in v0.4.4

type QNode struct{ Var string }

QNode binds Var to every entity of the view (a bare Cypher node pattern); a bound Var is kept when it is an entity. It reads every statement, so a query with a QNode has no known predicate set.

type QNotExists added in v0.4.4

type QNotExists struct{ Group []QElem }

QNotExists keeps the solutions for which Group has no solution.

type QOptional added in v0.4.4

type QOptional struct {
	Group []QElem
	Aux   bool
}

QOptional is a left join. Aux marks property accessors.

type QOrder added in v0.4.4

type QOrder struct {
	Key  string
	Desc bool
}

QOrder sorts by a column name (or, failing that, a variable).

type QProj added in v0.4.4

type QProj struct {
	Name  string
	Var   string
	Count bool
}

QProj is one output column: variable Var shown as Name, or count(*).

type QTerm added in v0.4.4

type QTerm struct {
	Var string
	Val Value
}

QTerm is a variable or a constant.

func QConst added in v0.4.4

func QConst(v Value) QTerm

QConst is the constant v.

func QVar added in v0.4.4

func QVar(n string) QTerm

QVar is the variable named n.

func (QTerm) IsVar added in v0.4.4

func (t QTerm) IsVar() bool

IsVar reports whether t is a variable.

type QTriple added in v0.4.4

type QTriple struct {
	S, P, O QTerm
	EID     string
	Class   ObjClass
	Aux     bool
}

QTriple matches statements (S P O). EID, when set, binds the statement itself (as a StmtRef) to that variable; a bound EID variable restricts the match to that statement. Aux marks a property accessor: it needs its subject bound already and never counts toward negation.

type QUnion added in v0.4.4

type QUnion struct{ Groups [][]QElem }

QUnion concatenates the solutions of its groups.

type Query added in v0.4.4

type Query struct {
	Dialect  Dialect
	Vars     []QProj
	Distinct bool
	Where    []QElem
	OrderBy  []QOrder
	Limit    int
	HasLimit bool
	Offset   int
}

Query is the logical IR both languages compile to.

func ParseCypher added in v0.4.4

func ParseCypher(text string) (*Query, error)

ParseCypher parses the supported Cypher subset into the query IR.

func ParseSPARQL added in v0.4.4

func ParseSPARQL(text string) (*Query, error)

ParseSPARQL parses the supported SPARQL subset into the query IR.

type QueryOptions added in v0.4.4

type QueryOptions struct{ Budget Budget }

QueryOptions bounds a query evaluation.

type QueryResult added in v0.4.4

type QueryResult struct {
	// Vars is the column order.
	Vars []string
	Rows []map[string]Value
	// Deps is the sorted eids of every statement any returned row matched.
	Deps []int64
	// Preds is the predicates the patterns read, or nil when any pattern has
	// a variable predicate.
	Preds []Value
	// Negative reports that the query uses OPTIONAL, NOT EXISTS, negation or
	// COUNT, so asserting a statement can make a row disappear.
	Negative bool
}

QueryResult is the rows of a query and what they stood on.

type RecallHit added in v0.4.4

type RecallHit struct {
	Statement  Statement `json:"statement"`
	TextRank   int       `json:"text_rank"`
	VectorRank int       `json:"vector_rank"`
	RRF        float64   `json:"rrf"`
}

RecallHit is one fused result. TextRank and VectorRank are 1-based ranks in each channel; 0 means the channel did not return the statement. RRF is a reciprocal-rank-fusion score (k=60), not a similarity.

type Resolved added in v0.4.4

type Resolved struct {
	Value Value `json:"value"`
	// EID is the statement that holds it; 0 for a volatile value.
	EID int64 `json:"eid,omitempty"`
	// UpdatedAt is set for a volatile value.
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
}

Resolved is one value of a subject's key and where it came from.

type RetractKind added in v0.4.4

type RetractKind int

RetractKind says why a statement was retracted.

const (
	RetExplicit RetractKind = iota
	RetCascade
	RetSupersede
	RetCardinality
)

Retraction kinds, stored in kg_stmt.ret_kind.

func (RetractKind) String added in v0.4.4

func (k RetractKind) String() string

type Retraction added in v0.4.4

type Retraction struct {
	EID  int64       `json:"eid"`
	Kind RetractKind `json:"kind"`
}

Retraction is one statement a transaction retracted.

type RoomDef

type RoomDef struct {
	Name     string   `yaml:"name"`
	Patterns []string `yaml:"patterns,omitempty"`
	Keywords []string `yaml:"keywords,omitempty"`
}

RoomDef defines a room with glob patterns and optional keywords for content-based room detection.

type RoomSummary

type RoomSummary struct {
	Room        string   `json:"room"`
	Wing        string   `json:"wing"`
	DrawerCount int      `json:"drawer_count"`
	Halls       []string `json:"halls,omitempty"`
}

RoomSummary is an aggregate view of a room.

type RuleOptions added in v0.4.4

type RuleOptions struct {
	// Budget bounds statements read and tuples derived (one meter per call).
	Budget Budget
	// MaxFacts bounds the derived tuples; 0 means DefaultMaxFacts.
	MaxFacts int
	// MaxFragments bounds the non-redundant fragments one tuple may keep; 0
	// means DefaultMaxFragments. Exceeding it fails with ErrBudget: a
	// truncated answer is never returned as complete.
	MaxFragments int
}

RuleOptions bounds one rule evaluation.

type SQLitePalaceStore

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

SQLitePalaceStore implements PalaceStore using a SQLite database.

func NewSQLitePalaceStore

func NewSQLitePalaceStore(db *sql.DB) *SQLitePalaceStore

NewSQLitePalaceStore creates a new store wrapping the given database.

func (*SQLitePalaceStore) BatchInsertDrawers added in v0.0.18

func (s *SQLitePalaceStore) BatchInsertDrawers(ctx context.Context, drawers []*Drawer) (int, error)

BatchInsertDrawers inserts multiple drawers in a single transaction. Returns the number of drawers inserted.

func (*SQLitePalaceStore) Close

func (s *SQLitePalaceStore) Close() error

Close closes the underlying database connection.

func (*SQLitePalaceStore) CountDrawers

func (s *SQLitePalaceStore) CountDrawers(ctx context.Context) (int, error)

CountDrawers returns the total number of drawers.

func (*SQLitePalaceStore) DB added in v0.4.4

func (s *SQLitePalaceStore) DB() *sql.DB

DB returns the underlying database.

func (*SQLitePalaceStore) DeleteDrawer

func (s *SQLitePalaceStore) DeleteDrawer(ctx context.Context, id string) error

DeleteDrawer removes a drawer by ID.

func (*SQLitePalaceStore) DrawerHashes added in v0.0.41

func (s *SQLitePalaceStore) DrawerHashes(ctx context.Context, wing string) (map[string]string, error)

DrawerHashes returns id → content_hash for every drawer in a wing.

This is what makes mining incremental: the miner looks up each chunk's ID, compares the stored hash with the hash of the chunk it just read, and only embeds the ones that differ. Rows written before the content_hash migration carry ” and so never match, which forces exactly one re-embed and records their hash.

func (*SQLitePalaceStore) FindByContentHash added in v0.0.48

func (s *SQLitePalaceStore) FindByContentHash(ctx context.Context, wing, room, hash string) (string, error)

FindByContentHash returns the id of a drawer with identical content in the same wing and room, or "" when there is none.

This is the cheap half of deduplication: an exact match needs no embedding at all, and idx_drawers_content_hash makes it a covering-index lookup rather than a scan of the room.

func (*SQLitePalaceStore) GetAllEmbeddings

func (s *SQLitePalaceStore) GetAllEmbeddings(ctx context.Context, filter DrawerFilter) ([]EmbeddingRow, error)

GetAllEmbeddings returns all embeddings matching the filter.

func (*SQLitePalaceStore) GetDrawer

func (s *SQLitePalaceStore) GetDrawer(ctx context.Context, id string) (*Drawer, error)

GetDrawer fetches a single drawer by ID.

func (*SQLitePalaceStore) GetEmbedding

func (s *SQLitePalaceStore) GetEmbedding(ctx context.Context, id string) (*EmbeddingRow, error)

GetEmbedding returns the embedding for a single drawer.

func (*SQLitePalaceStore) GetEntity

func (s *SQLitePalaceStore) GetEntity(ctx context.Context, id string) (*Entity, error)

GetEntity fetches an entity by ID.

func (*SQLitePalaceStore) GetTaxonomy

func (s *SQLitePalaceStore) GetTaxonomy(ctx context.Context) (*Taxonomy, error)

GetTaxonomy returns the complete wing → room hierarchy.

func (*SQLitePalaceStore) InsertDiaryEntry

func (s *SQLitePalaceStore) InsertDiaryEntry(ctx context.Context, d *DiaryEntry) error

InsertDiaryEntry inserts a new diary entry.

func (*SQLitePalaceStore) InsertDrawer

func (s *SQLitePalaceStore) InsertDrawer(ctx context.Context, d *Drawer) error

InsertDrawer inserts a new drawer record.

func (*SQLitePalaceStore) InsertEntity

func (s *SQLitePalaceStore) InsertEntity(ctx context.Context, e *Entity) error

InsertEntity inserts a new entity record.

func (*SQLitePalaceStore) KeywordSearch

func (s *SQLitePalaceStore) KeywordSearch(ctx context.Context, query string, filter DrawerFilter, limit int) ([]SearchResult, error)

KeywordSearch performs an FTS5 keyword search on the drawers_fts table, falling back to LIKE if FTS5 is unavailable. Results are ordered by FTS5 rank.

func (*SQLitePalaceStore) ListDiaryEntries

func (s *SQLitePalaceStore) ListDiaryEntries(ctx context.Context, agent string, limit int) ([]*DiaryEntry, error)

ListDiaryEntries returns recent diary entries for an agent.

func (*SQLitePalaceStore) ListDrawers

func (s *SQLitePalaceStore) ListDrawers(ctx context.Context, filter DrawerFilter) ([]*Drawer, error)

ListDrawers returns drawers matching the filter, ordered by importance desc then created_at desc.

func (*SQLitePalaceStore) ListRooms

func (s *SQLitePalaceStore) ListRooms(ctx context.Context, wing string) ([]RoomSummary, error)

ListRooms returns rooms within a wing with their halls.

func (*SQLitePalaceStore) ListWings

func (s *SQLitePalaceStore) ListWings(ctx context.Context) ([]WingSummary, error)

ListWings returns aggregate wing summaries.

type SavedAnswer added in v0.4.4

type SavedAnswer struct {
	Name       string             `json:"name"`
	Lang       string             `json:"lang"`
	Query      string             `json:"query"`
	View       string             `json:"view"`
	Vars       []string           `json:"vars,omitempty"`
	Rows       []map[string]Value `json:"rows"`
	Deps       []int64            `json:"deps,omitempty"`
	Checkpoint int64              `json:"checkpoint"`
	// Stale is empty while the answer is fresh, otherwise why it is not.
	Stale string `json:"stale,omitempty"`
}

SavedAnswer is one saved answer and its status.

type Scored added in v0.4.4

type Scored struct {
	Statement Statement `json:"statement"`
	Score     float64   `json:"score"`
	Rank      int       `json:"rank"`
}

Scored is a statement with its cosine score and 1-based rank.

type ScoredResult

type ScoredResult struct {
	DrawerID   string  `json:"drawer_id"`
	Similarity float32 `json:"similarity"`
}

ScoredResult is a drawer ID paired with a similarity score, used for ranking.

func RankBySimilarity

func RankBySimilarity(query []float32, candidates []EmbeddingRow, limit int) []ScoredResult

RankBySimilarity sorts candidates by cosine similarity to query descending and returns the top limit.

type SearchQuery

type SearchQuery struct {
	Query string
	Wing  string
	Room  string
	Limit int
}

SearchQuery describes a palace search request.

type SearchResult

type SearchResult struct {
	Drawer     Drawer  `json:"drawer"`
	Similarity float32 `json:"similarity"`
	Rank       int     `json:"rank,omitempty"` // FTS5 rank (negative = more relevant), 0 if semantic-only
}

SearchResult is a single search match with similarity score and optional FTS5 rank.

type SearchToolInput

type SearchToolInput struct {
	// The search query.
	Query string `json:"query"`
	// Optional wing filter.
	Wing string `json:"wing,omitempty"`
	// Optional room filter.
	Room string `json:"room,omitempty"`
	// Max results (default 5).
	Limit int `json:"limit,omitempty"`
}

SearchToolInput defines parameters for the palace-search tool.

type SearchToolOutput

type SearchToolOutput struct {
	Content string `json:"content"`
	Total   int    `json:"total"`
}

SearchToolOutput contains formatted search results.

type Solution added in v0.4.4

type Solution struct {
	Bindings           map[string]Value
	Support            []int64
	ValidFrom, ValidTo *time.Time
}

Solution is one answer to a goal: the variable bindings, the eids of the stored statements the answer rests on, and the interval over which it holds.

type Statement added in v0.4.4

type Statement struct {
	EID       int64 `json:"eid"`
	Subject   Value `json:"subject"`
	Predicate Value `json:"predicate"`
	Object    Value `json:"object"`
	// TAdd is the transaction that wrote it, AddedAt that transaction's time.
	TAdd    int64     `json:"t_add"`
	AddedAt time.Time `json:"added_at"`
	// TRet, RetractedAt and RetKind are set once it has been retracted.
	TRet        *int64       `json:"t_ret,omitempty"`
	RetractedAt *time.Time   `json:"retracted_at,omitempty"`
	RetKind     *RetractKind `json:"ret_kind,omitempty"`
	// ValidFrom and ValidTo bound when it held, [from, to); nil is unbounded.
	ValidFrom *time.Time `json:"valid_from,omitempty"`
	ValidTo   *time.Time `json:"valid_to,omitempty"`
}

Statement is one statement as a read returns it.

func (Statement) Live added in v0.4.4

func (s Statement) Live() bool

Live reports whether the statement has not been retracted.

type StatusInput

type StatusInput struct{}

StatusInput is intentionally empty — palace-status takes no parameters.

type StatusOutput

type StatusOutput struct {
	Content string `json:"content"`
}

StatusOutput contains the formatted palace status.

type Supersession added in v0.4.4

type Supersession struct {
	Old int64 `json:"old"`
	New int64 `json:"new"`
}

Supersession links a corrected statement to its replacement.

type Taxonomy

type Taxonomy struct {
	Wings []TaxonomyWing `json:"wings"`
}

Taxonomy is the full wing → room hierarchy.

type TaxonomyRoom

type TaxonomyRoom struct {
	Name        string `json:"name"`
	DrawerCount int    `json:"drawer_count"`
}

TaxonomyRoom is a room entry in the taxonomy.

type TaxonomyWing

type TaxonomyWing struct {
	Name  string         `json:"name"`
	Rooms []TaxonomyRoom `json:"rooms"`
}

TaxonomyWing is a wing entry in the taxonomy.

type TraverseResult

type TraverseResult struct {
	Room        string   `json:"room"`
	Wings       []string `json:"wings"`
	DrawerCount int      `json:"drawer_count"`
	Hops        int      `json:"hops"`
}

TraverseResult is a room discovered during BFS graph traversal.

type TraverseToolInput

type TraverseToolInput struct {
	// The room to start BFS traversal from.
	StartRoom string `json:"start_room"`
	// Maximum hops from start room (default 2).
	MaxHops int `json:"max_hops,omitempty"`
}

TraverseToolInput defines parameters for the palace-traverse tool.

type TraverseToolOutput

type TraverseToolOutput struct {
	Content string `json:"content"`
}

TraverseToolOutput contains formatted traversal results.

type Triple

type Triple struct {
	// ID is "e<EID>".
	ID          string `json:"id"`
	EID         int64  `json:"eid"`
	SubjectID   string `json:"subject_id"`
	PredicateID string `json:"predicate_id"`
	ObjectID    string `json:"object_id"`
	// ObjectKind is empty for an entity object, else "string", "number", ...
	ObjectKind string     `json:"object_kind,omitempty"`
	ValidFrom  *time.Time `json:"valid_from,omitempty"`
	ValidTo    *time.Time `json:"valid_to,omitempty"`
	SourceFile string     `json:"source_file,omitempty"`
	// ExtractedAt is when the fact was learned: the legacy extraction time
	// for imported triples, otherwise the writing transaction's time.
	ExtractedAt   time.Time `json:"extracted_at"`
	TAdd          int64     `json:"t_add"`
	Confidence    *float64  `json:"confidence,omitempty"`
	Sources       []string  `json:"sources,omitempty"`
	Confirmations int       `json:"confirmations,omitempty"`
	// Status is "active", "ended", "superseded", "retracted", "cascade" or
	// "replaced"; SupersededBy names the correction of a superseded fact.
	Status       string `json:"status"`
	SupersededBy int64  `json:"superseded_by,omitempty"`
	// New is set by Add when the fact was written rather than already known.
	New bool `json:"new,omitempty"`
}

Triple is a subject-predicate-object fact in the knowledge graph, in the shape the palace API has always returned. It is a view of one statement.

type TripleInput

type TripleInput struct {
	Subject   string
	Predicate string
	Object    string
	ValidFrom *time.Time
	ValidTo   *time.Time
	// Literal stores Object as a string value instead of an entity.
	Literal bool
	// About annotates statement About instead of the Subject entity.
	About int64
	// Support derives the fact from these statements: it is retracted when
	// any of them is retracted or corrected.
	Support []int64
	// Confidence (0-1), Source and SourceFile become layers on the fact.
	Confidence *float64
	Source     string
	SourceFile string
	// ConfirmExisting confirms an identical fact that already exists.
	ConfirmExisting bool
	// Graph puts the fact into this named graph.
	Graph string
	// Author and Session are recorded on the transaction.
	Author  string
	Session string
}

TripleInput is the input for creating a new triple.

type Tunnel

type Tunnel struct {
	Room        string   `json:"room"`
	Wings       []string `json:"wings"`
	DrawerCount int      `json:"drawer_count"`
}

Tunnel is a room that appears in multiple wings, bridging them.

type TxInfo added in v0.4.4

type TxInfo struct {
	T       int64     `json:"t"`
	Instant time.Time `json:"instant"`
	Author  string    `json:"author,omitempty"`
	Source  string    `json:"source,omitempty"`
	Reason  string    `json:"reason,omitempty"`
}

TxInfo describes one transaction.

type TxOptions added in v0.4.4

type TxOptions struct {
	// Author, Source and Reason are recorded on the transaction.
	Author, Source, Reason string
	// DryRun runs the transaction and reports it without committing. The eids
	// in the report are provisional: they may be issued again later.
	DryRun bool
	// MaxCascade bounds a retraction's cascade; 0 means DefaultMaxCascade.
	MaxCascade int
}

TxOptions configures one knowledge-graph transaction.

type TxReport added in v0.4.4

type TxReport struct {
	T          int64          `json:"t"`
	Instant    time.Time      `json:"instant"`
	Asserted   []int64        `json:"asserted,omitempty"`
	Existing   []int64        `json:"existing,omitempty"`
	Retracted  []Retraction   `json:"retracted,omitempty"`
	Superseded []Supersession `json:"superseded,omitempty"`
	Erased     []string       `json:"erased,omitempty"`
	DryRun     bool           `json:"dry_run,omitempty"`
}

TxReport is what one transaction did.

type UnsupportedQueryError added in v0.4.4

type UnsupportedQueryError struct {
	// Pos is the byte offset of the construct in the query text.
	Pos int
	// Construct names it ("property path", "CREATE", ...).
	Construct string
}

UnsupportedQueryError reports a construct outside the supported subset. It is returned before anything executes.

func (*UnsupportedQueryError) Error added in v0.4.4

func (e *UnsupportedQueryError) Error() string

func (*UnsupportedQueryError) Is added in v0.4.4

func (e *UnsupportedQueryError) Is(target error) bool

Is makes errors.Is(err, ErrUnsupportedQuery) hold.

type Valid added in v0.4.4

type Valid struct {
	From, To *time.Time
}

Valid is a valid-time interval [From, To); nil means unbounded.

type Value added in v0.4.4

type Value struct {
	Kind ValueKind `json:"kind"`
	// Text is the normalized entity id or the string value.
	Text string `json:"text,omitempty"`
	// Int is the integer, eid, transaction number, epoch ms (time) or 0/1 (bool).
	Int int64 `json:"int,omitempty"`
	// Num is the number value.
	Num float64 `json:"num,omitempty"`
}

Value is a subject, predicate or object of a statement.

func Bool added in v0.4.4

func Bool(b bool) Value

Bool is a boolean literal.

func Ent added in v0.4.4

func Ent(name string) Value

Ent is the entity with the given name, normalized as entity ids always are.

func Int added in v0.4.4

func Int(i int64) Value

Int is an integer literal.

func Num added in v0.4.4

func Num(f float64) Value

Num is a number literal.

func StmtRef added in v0.4.4

func StmtRef(eid int64) Value

StmtRef refers to the statement with the given eid.

func Str added in v0.4.4

func Str(s string) Value

Str is a string literal.

func TimeVal added in v0.4.4

func TimeVal(t time.Time) Value

TimeVal is a time literal at millisecond precision.

func (Value) IsStatement added in v0.4.4

func (v Value) IsStatement() bool

IsStatement reports whether v refers to a statement.

func (Value) String added in v0.4.4

func (v Value) String() string

String renders v for people: the entity id, "e<eid>", the literal text.

type ValueKind added in v0.4.4

type ValueKind uint8

ValueKind says what a Value holds.

const (
	KindEntity ValueKind = iota + 1
	KindStatement
	KindString
	KindInt
	KindNumber
	KindBool
	KindTime
	KindTx
)

The kinds a Value can hold.

type View added in v0.4.4

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

View is a read-only window on the knowledge graph: a transaction-time selection (now, as of a transaction, or all history), optionally narrowed to the statements valid at one instant. Every scan of a read applies the same predicate, after Tiramemsu's view.rs#scan_predicates.

func (View) About added in v0.4.4

func (v View) About(ctx context.Context, entity, direction string) ([]Statement, error)

About returns the visible statements with the entity as subject ("subject"), object ("object") or either (""/"both"), oldest first.

func (View) Bundle added in v0.4.4

func (v View) Bundle(ctx context.Context, eid int64, opts BundleOptions) (*Bundle, error)

Bundle exports statement eid as seen by v: the root, its visible dependents and the statements they reference, except engine bookkeeping. A past bundle comes from AsOf.

func (View) Check added in v0.4.4

func (v View) Check(ctx context.Context, p *Program, opts RuleOptions) ([]Violation, error)

Check evaluates the program over the view in one snapshot and returns the bindings that satisfy a constraint body, with the eids of the stored statements that witness each. A violation counts only where its witnesses are valid together (pointwise valid time).

func (View) Conflicts added in v0.4.4

func (v View) Conflicts(ctx context.Context, f ConflictFilter) ([]Conflict, error)

Conflicts lists where memory disagrees with itself: visible statements with the same subject and predicate, different objects, and overlapping valid time. Multi-valued predicates (a person knows several people) appear too; the evidence is there to decide, the graph does not. It is not defined on the history view, where a corrected value and its correction were never believed together.

func (View) Dependents added in v0.4.4

func (v View) Dependents(ctx context.Context, eid int64) ([]int64, error)

Dependents returns what retracting eid would take with it in this view: eid first, then every visible statement standing on it, breadth-first. It is the cascade walk as a read, and is never truncated.

func (View) Elpi added in v0.4.4

func (v View) Elpi(ctx context.Context, prog *ElpiProgram, goal string, opts ElpiOptions) (*ElpiResult, error)

Elpi solves goal against prog in v and returns one row per solution. It writes nothing.

func (View) Explain added in v0.4.4

func (v View) Explain(ctx context.Context, eid int64) (*Explanation, error)

Explain gathers statement eid's layers, supports, lineage, confirmations and dependents under v, all from one snapshot. It returns nil when eid does not exist.

func (View) Graphs added in v0.4.4

func (v View) Graphs() []string

Graphs reports the graph restriction of v.

func (View) GraphsOf added in v0.4.4

func (v View) GraphsOf(ctx context.Context, eid int64) ([]string, error)

GraphsOf returns the graphs statement eid is a member of in v.

func (View) InGraph added in v0.4.4

func (v View) InGraph(graphs ...string) View

InGraph restricts v to the members of the named graphs (any of them).

func (View) IsHistory added in v0.4.4

func (v View) IsHistory() bool

IsHistory reports whether v is the history view.

func (View) Layers added in v0.4.4

func (v View) Layers(ctx context.Context, eid int64) ([]Statement, error)

Layers returns the visible statements about statement eid, excluding engine bookkeeping.

func (View) ListGraphs added in v0.4.4

func (v View) ListGraphs(ctx context.Context) ([]GraphInfo, error)

ListGraphs returns the graphs with at least one member visible in v.

func (View) Match added in v0.4.4

func (v View) Match(ctx context.Context, p Pattern) ([]Statement, error)

Match returns the visible statements matching p, oldest first.

func (View) Paths added in v0.4.4

func (v View) Paths(ctx context.Context, pq PathQuery) ([]Path, error)

Paths searches the view for paths per pq.

func (View) Recall added in v0.4.4

func (v View) Recall(ctx context.Context, emb Embedder, model, query string, k int) ([]RecallHit, error)

Recall fuses TextSearch and VectorSearch by reciprocal rank (k=60) on one snapshot. Each hit reports its rank in each channel; RRF is the fused score and is not a similarity. A missing channel fails the call with ErrChannelUnavailable instead of silently degrading.

func (View) Resolve added in v0.4.4

func (v View) Resolve(ctx context.Context, s, key Value) ([]Resolved, error)

Resolve returns the values of s's key in v: the objects of the statements (s key ?) the view selects; if there are none and v is the plain now view, the volatile value. Under time travel volatile values are absent, never wrong.

func (View) RunQuery added in v0.4.4

func (v View) RunQuery(ctx context.Context, lang, text string, opts QueryOptions) (*QueryResult, error)

RunQuery parses text in lang ("sparql" or "cypher") and runs it.

func (View) Select added in v0.4.4

func (v View) Select(ctx context.Context, q *Query, opts QueryOptions) (*QueryResult, error)

Select evaluates q in one snapshot of the view under one budget.

func (View) Solve added in v0.4.4

func (v View) Solve(ctx context.Context, p *Program, goal string, opts RuleOptions) ([]Solution, error)

Solve answers a goal such as "reports(alice, Y)": it evaluates the program over the view in one snapshot and returns one Solution per binding and fragment, in a deterministic order. Negation is evaluated atemporally over the whole view: "not p(X)" holds when no visible statement says p(X), at any valid time, and does not restrict a Solution's interval.

func (View) String added in v0.4.4

func (v View) String() string

String describes the view for people.

func (View) TextSearch added in v0.4.4

func (v View) TextSearch(ctx context.Context, query string, limit int) ([]Statement, error)

TextSearch finds visible statements whose subject or object is an entity or string matching the words of query (all of them), newest first.

func (View) ValidAt added in v0.4.4

func (v View) ValidAt(at time.Time) View

ValidAt narrows v to statements valid at instant at.

func (View) VectorSearch added in v0.4.4

func (v View) VectorSearch(ctx context.Context, emb Embedder, model, query string, k int) ([]Scored, error)

VectorSearch ranks the statements v selects by exact cosine similarity to query, using vectors stored by the view's transaction bound (Now and History: the last committed one; AsOf(t): t). It fails with ErrChannelUnavailable when there is no embedder or no vector for model.

type Violation added in v0.4.4

type Violation struct {
	Rule      string
	Bindings  map[string]Value
	Witnesses []int64
}

Violation is one way a constraint is broken.

type WingSummary

type WingSummary struct {
	Wing        string `json:"wing"`
	DrawerCount int    `json:"drawer_count"`
	RoomCount   int    `json:"room_count"`
}

WingSummary is an aggregate view of a wing.

Jump to

Keyboard shortcuts

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