memorygraph

package
v0.6.13 Latest Latest
Warning

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

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

Documentation

Overview

Package memorygraph implements a persistent memory graph for interlinked RAG. Nodes represent typed knowledge units; edges are weighted, typed relations. The graph is stored as a single JSON file under rootDir/.supermodel/memory-graph.json and is safe for concurrent reads within a process (writes hold a mutex).

Package memorygraph — MCP tool wrappers. Each exported Tool* function is the Go equivalent of the TypeScript tool functions in tools/memory-tools.ts and follows the same output format so that callers get identical text responses.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatPeek

func FormatPeek(p *NodePeek) string

FormatPeek renders a NodePeek as a human-readable block suitable for display in a terminal or MCP tool response.

func FormatPeekList

func FormatPeekList(peeks []NodePeek) string

FormatPeekList renders a PeekList result as a compact table with one node per line, suitable for scanning before a prune pass.

func ToolAddInterlinkedContext

func ToolAddInterlinkedContext(opts AddInterlinkedContextOptions) (string, error)

ToolAddInterlinkedContext bulk-upserts nodes and optionally auto-links them by content similarity (threshold ≥ 0.72).

func ToolCreateRelation

func ToolCreateRelation(opts *CreateRelationOptions) (string, error)

ToolCreateRelation adds a directed edge between two existing nodes.

func ToolPruneStaleLinks(opts PruneStaleLinksOptions) (string, error)

ToolPruneStaleLinks removes weak edges and orphaned nodes.

func ToolRetrieveWithTraversal

func ToolRetrieveWithTraversal(opts RetrieveWithTraversalOptions) (string, error)

ToolRetrieveWithTraversal starts a BFS from startNodeID and returns all reachable nodes up to maxDepth, formatted with path context and scores.

func ToolSearchMemoryGraph

func ToolSearchMemoryGraph(opts SearchMemoryGraphOptions) (string, error)

ToolSearchMemoryGraph searches the graph and returns direct matches plus one-hop neighbors, formatted identically to the TypeScript version.

func ToolUpsertMemoryNode

func ToolUpsertMemoryNode(opts UpsertMemoryNodeOptions) (string, error)

ToolUpsertMemoryNode creates or updates a memory node and returns a human-readable summary including updated graph stats.

Types

type AddInterlinkedContextOptions

type AddInterlinkedContextOptions struct {
	RootDir  string
	Items    []InterlinkedItem
	AutoLink bool
}

AddInterlinkedContextOptions mirrors AddInterlinkedContextOptions in the TS source.

type CreateRelationOptions

type CreateRelationOptions struct {
	RootDir  string
	SourceID string
	TargetID string
	Relation RelationType
	Weight   float64
	Metadata map[string]string
}

CreateRelationOptions mirrors CreateRelationOptions in the TS source.

type Edge

type Edge struct {
	ID       string            `json:"id"`
	Source   string            `json:"source"`
	Target   string            `json:"target"`
	Relation RelationType      `json:"relation"`
	Weight   float64           `json:"weight"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

Edge is a directed, weighted relation between two nodes.

func CreateRelation

func CreateRelation(rootDir, sourceID, targetID string, relation RelationType, weight float64, metadata map[string]string) (*Edge, error)

CreateRelation adds a directed edge between two existing nodes. Returns nil if either node ID is not found.

type EdgePeek

type EdgePeek struct {
	Edge      Edge
	PeerID    string
	PeerLabel string
	PeerType  NodeType
}

EdgePeek is a human-readable summary of a single edge and its peer node.

type GraphStats

type GraphStats struct {
	Nodes int
	Edges int
}

GraphStats summarises the current state of the graph.

func GetGraphStats

func GetGraphStats(rootDir string) (GraphStats, error)

GetGraphStats returns a snapshot of node and edge counts.

type InterlinkResult

type InterlinkResult struct {
	Nodes []Node
	Edges []Edge
}

InterlinkResult is returned by AddInterlinkedContext.

func AddInterlinkedContext

func AddInterlinkedContext(rootDir string, items []struct {
	Type     NodeType
	Label    string
	Content  string
	Metadata map[string]string
}, autoLink bool) (*InterlinkResult, error)

AddInterlinkedContext bulk-upserts a set of nodes and, when autoLink is true, automatically creates similarity edges between pairs whose content overlaps above a fixed threshold (0.72 cosine-approximated via token Jaccard).

type InterlinkedItem

type InterlinkedItem struct {
	Type     NodeType
	Label    string
	Content  string
	Metadata map[string]string
}

InterlinkedItem is a single entry for AddInterlinkedContext.

type Node

type Node struct {
	ID          string            `json:"id"`
	Type        NodeType          `json:"type"`
	Label       string            `json:"label"`
	Content     string            `json:"content"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	AccessCount int               `json:"accessCount"`
	CreatedAt   time.Time         `json:"createdAt"`
	UpdatedAt   time.Time         `json:"updatedAt"`
}

Node is a single knowledge unit in the memory graph.

func UpsertNode

func UpsertNode(rootDir string, t NodeType, label, content string, metadata map[string]string) (*Node, error)

UpsertNode creates or updates a node identified by (type, label). If the node already exists its content and metadata are updated in-place.

type NodePeek

type NodePeek struct {
	Node     Node
	EdgesOut []EdgePeek // edges where this node is the source
	EdgesIn  []EdgePeek // edges where this node is the target
}

NodePeek is a full snapshot of a node and all its edges, returned by Peek.

func Peek

func Peek(opts PeekOptions) (*NodePeek, error)

Peek returns a full NodePeek for the requested node: its content, metadata, access stats, and every inbound/outbound edge with peer labels resolved. Returns nil if the node cannot be found.

func PeekList

func PeekList(rootDir string) ([]NodePeek, error)

PeekList returns a lightweight summary of every node in the graph — ID, type, label, access count, age, and edge degree — sorted by access count descending. Useful for scanning the graph before pruning.

type NodeType

type NodeType string

NodeType classifies what kind of knowledge a node represents.

const (
	NodeTypeFact      NodeType = "fact"
	NodeTypeConcept   NodeType = "concept"
	NodeTypeEntity    NodeType = "entity"
	NodeTypeEvent     NodeType = "event"
	NodeTypeProcedure NodeType = "procedure"
	NodeTypeContext   NodeType = "context"
)

Node type constants for classifying knowledge units.

type PeekOptions

type PeekOptions struct {
	RootDir string
	// NodeID takes priority if set.
	NodeID string
	// Label is used for lookup when NodeID is empty (first match wins).
	Label string
}

PeekOptions controls what Peek returns.

type PruneResult

type PruneResult struct {
	Removed   int
	Remaining int
}

PruneResult reports what was removed during a prune pass.

func PruneStaleLinks(rootDir string, threshold float64) (PruneResult, error)

PruneStaleLinks removes edges whose weight falls below threshold and then removes any nodes that have become fully orphaned (no edges in or out).

type PruneStaleLinksOptions

type PruneStaleLinksOptions struct {
	RootDir   string
	Threshold float64
}

PruneStaleLinksOptions mirrors PruneStaleLinksOptions in the TS source.

type RelationType

type RelationType string

RelationType classifies the semantic relationship between two nodes.

const (
	RelationRelatedTo    RelationType = "related_to"
	RelationDependsOn    RelationType = "depends_on"
	RelationPartOf       RelationType = "part_of"
	RelationLeadsTo      RelationType = "leads_to"
	RelationContrasts    RelationType = "contrasts"
	RelationSimilarTo    RelationType = "similar_to"
	RelationInstantiates RelationType = "instantiates"
)

Relation type constants for edge labels.

type RetrieveWithTraversalOptions

type RetrieveWithTraversalOptions struct {
	RootDir     string
	StartNodeID string
	MaxDepth    int
	EdgeFilter  []RelationType
}

RetrieveWithTraversalOptions mirrors RetrieveWithTraversalOptions in the TS source.

type SearchMemoryGraphOptions

type SearchMemoryGraphOptions struct {
	RootDir    string
	Query      string
	MaxDepth   int
	TopK       int
	EdgeFilter []RelationType
}

SearchMemoryGraphOptions mirrors SearchMemoryGraphOptions in the TS source.

type SearchResult

type SearchResult struct {
	Direct     []TraversalResult
	Neighbors  []TraversalResult
	TotalNodes int
	TotalEdges int
}

SearchResult is returned by SearchGraph.

func SearchGraph

func SearchGraph(rootDir, query string, maxDepth, topK int, edgeFilter []RelationType) (*SearchResult, error)

SearchGraph finds nodes whose label or content matches query, then expands one hop to collect linked neighbors. Results are scored by relevance.

type TraversalResult

type TraversalResult struct {
	Node           Node
	Depth          int
	RelevanceScore float64
	PathRelations  []string // relation labels along the path from the start node
}

TraversalResult is a node reached during graph traversal, enriched with path context and a relevance score.

func RetrieveWithTraversal

func RetrieveWithTraversal(rootDir, startNodeID string, maxDepth int, edgeFilter []RelationType) ([]TraversalResult, error)

RetrieveWithTraversal performs a BFS/depth-limited walk starting from startNodeID, returning all reachable nodes up to maxDepth hops away. edgeFilter restricts which relation types are followed; nil follows all.

type UpsertMemoryNodeOptions

type UpsertMemoryNodeOptions struct {
	RootDir  string
	Type     NodeType
	Label    string
	Content  string
	Metadata map[string]string
}

UpsertMemoryNodeOptions mirrors UpsertMemoryNodeOptions in the TS source.

Jump to

Keyboard shortcuts

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