palace

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

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 recommended ONNX file for the current platform.

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 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 HasFTS5

func HasFTS5(db *sql.DB) bool

HasFTS5 checks whether the database supports FTS5 for drawers.

func MarshalEmbedding

func MarshalEmbedding(v []float32) []byte

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

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 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"`
}

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 Embedder

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

Embedder wraps a hugot session for in-process text embedding.

func NewEmbedder

func NewEmbedder(modelPath string) (*Embedder, error)

NewEmbedder creates an Embedder backed by hugot's pure-Go (GoMLX) runtime.

func (*Embedder) Close

func (e *Embedder) Close()

Close destroys the hugot session and releases resources.

func (*Embedder) Embed

func (e *Embedder) Embed(texts []string) ([][]float32, error)

Embed returns embedding vectors for the given texts. Inputs exceeding maxTokenLength (128) tokens are truncated to stay within GoMLX sequence bucket limits and prevent bucket mismatch panics during graph compilation.

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 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 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.
	Subject string `json:"subject"`
	// The predicate (relationship type).
	Predicate string `json:"predicate"`
	// The object entity name.
	Object string `json:"object"`
	// Optional validity start date (RFC3339 or YYYY-MM-DD).
	ValidFrom string `json:"valid_from,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 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 KGQueryToolInput

type KGQueryToolInput struct {
	// The entity name to query.
	Entity string `json:"entity"`
	// Optional point-in-time filter (RFC3339 or YYYY-MM-DD).
	AsOf string `json:"as_of,omitempty"`
	// Direction: "subject", "object", or "both" (default "both").
	Direction string `json:"direction,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 KGStats

type KGStats struct {
	EntityCount   int      `json:"entity_count"`
	TripleCount   int      `json:"triple_count"`
	ActiveTriples int      `json:"active_triples"`
	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 KnowledgeGraph

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

KnowledgeGraph provides a high-level API for the temporal knowledge graph.

func NewKnowledgeGraph

func NewKnowledgeGraph(store PalaceStore) *KnowledgeGraph

NewKnowledgeGraph creates a KnowledgeGraph wrapping the given store.

func (*KnowledgeGraph) Add

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

Add creates a triple, auto-creating entities if they don't exist. If an identical active triple already exists (same subj/pred/obj with valid_to IS NULL), it returns the existing triple rather than inserting a duplicate.

func (*KnowledgeGraph) Invalidate

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

Invalidate sets valid_to = now() on the active triple matching subject/predicate/object.

func (*KnowledgeGraph) Query

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

Query returns triples involving the named entity. If asOf is non-empty, it filters to triples valid at that point in time. Direction can be "subject", "object", or "" (both).

func (*KnowledgeGraph) Stats

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

Stats returns aggregate KG statistics.

func (*KnowledgeGraph) Timeline

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

Timeline returns all triples for the named entity ordered chronologically.

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:"-"`
}

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 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 WithModelPath

func WithModelPath(path string) Option

WithModelPath sets the path to the embedding model directory.

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) 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 sets valid_to on an active triple.

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
}

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)

	// Embedding operations
	GetEmbedding(ctx context.Context, id string) (*EmbeddingRow, error)
	GetAllEmbeddings(ctx context.Context, filter DrawerFilter) ([]EmbeddingRow, 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)
	InsertTriple(ctx context.Context, t *Triple) error
	QueryTriples(ctx context.Context, entityID, asOf, direction string) ([]*Triple, error)
	InvalidateTriple(ctx context.Context, subjectID, predicateID, objectID string) error
	TimelineTriples(ctx context.Context, entityID string) ([]*Triple, error)
	KGStats(ctx context.Context) (*KGStats, error)

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

	Close() error
}

PalaceStore defines the interface for palace persistence operations.

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 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 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) DeleteDrawer

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

DeleteDrawer removes a drawer by ID.

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) InsertTriple

func (s *SQLitePalaceStore) InsertTriple(ctx context.Context, t *Triple) error

InsertTriple inserts a new triple record.

func (*SQLitePalaceStore) InvalidateTriple

func (s *SQLitePalaceStore) InvalidateTriple(ctx context.Context, subjectID, predicateID, objectID string) error

InvalidateTriple sets valid_to = now() on matching active triples.

func (*SQLitePalaceStore) KGStats

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

KGStats returns aggregate statistics about the knowledge graph.

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.

func (*SQLitePalaceStore) QueryTriples

func (s *SQLitePalaceStore) QueryTriples(ctx context.Context, entityID, asOf, direction string) ([]*Triple, error)

QueryTriples returns triples involving the entity, optionally filtered by time.

func (*SQLitePalaceStore) TimelineTriples

func (s *SQLitePalaceStore) TimelineTriples(ctx context.Context, entityID string) ([]*Triple, error)

TimelineTriples returns all triples for an entity ordered by extracted_at.

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 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 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          string     `json:"id"`
	SubjectID   string     `json:"subject_id"`
	PredicateID string     `json:"predicate_id"`
	ObjectID    string     `json:"object_id"`
	ValidFrom   *time.Time `json:"valid_from,omitempty"`
	ValidTo     *time.Time `json:"valid_to,omitempty"`
	SourceFile  string     `json:"source_file,omitempty"`
	ExtractedAt time.Time  `json:"extracted_at"`
}

Triple is a subject-predicate-object fact in the knowledge graph.

type TripleInput

type TripleInput struct {
	Subject   string
	Predicate string
	Object    string
	ValidFrom *time.Time
}

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 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