graph

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package graph provides a knowledge graph layer for instinct relationships, dependency tracking, and graph-based queries using in-memory structures. It replaces the shell's jq-based graph layer (graph.sh) with O(1) lookups via adjacency lists, supporting 5 node types and 16 edge types.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Edge

type Edge struct {
	ID           string   `json:"edge_id"`
	Source       string   `json:"source"`
	Target       string   `json:"target"`
	Relationship EdgeType `json:"relationship"`
	Weight       float64  `json:"weight"`
	CreatedAt    string   `json:"created_at"`
}

Edge represents a directed relationship between two nodes. JSON field names match the shell graph.sh format exactly.

type EdgeType

type EdgeType string

EdgeType represents the kind of relationship between two nodes.

const (
	// Learning-to-Instinct edges
	EdgePromotedFrom EdgeType = "promoted_from"
	EdgeDerivedFrom  EdgeType = "derived_from"
	// Instinct-to-Instinct edges (matching shell graph.sh)
	EdgeReinforces  EdgeType = "reinforces"
	EdgeContradicts EdgeType = "contradicts"
	EdgeExtends     EdgeType = "extends"
	EdgeSupersedes  EdgeType = "supersedes"
	EdgeRelated     EdgeType = "related"
	// Instinct-to-Queen edges
	EdgePromotedTo EdgeType = "promoted_to"
	// Phase-to-Learning/Instinct edges
	EdgeProduced   EdgeType = "produced"
	EdgeOriginated EdgeType = "originated"
	// Colony-to-Phase edges
	EdgeContains       EdgeType = "contains"
	EdgeColonyInstinct EdgeType = "colony_instinct"
	// Cross-type edges
	EdgeDependsOn       EdgeType = "depends_on"
	EdgeInfluenced      EdgeType = "influenced"
	EdgeConflictsWith   EdgeType = "conflicts_with"
	EdgeSupersedesPhase EdgeType = "supersedes_phase"
)

type Graph

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

Graph is an in-memory directed graph with typed nodes and edges. All operations are goroutine-safe via sync.RWMutex.

func NewGraph

func NewGraph() *Graph

NewGraph creates an empty graph.

func (*Graph) AddEdge

func (g *Graph) AddEdge(source, target string, relType EdgeType, weight float64, createdAt string) (*Edge, string, error)

AddEdge creates a directed edge between source and target nodes. If source or target nodes do not exist, they are auto-created with inferred types. If an edge with the same source+target+relationship already exists, the weight is updated. Returns the edge, a status string ("created" or "updated"), and any error.

func (*Graph) AddNode

func (g *Graph) AddNode(node Node) error

AddNode adds a node to the graph. Returns an error if a node with the same ID but different type exists. Adding a node with the same ID and same type is idempotent (no error).

func (*Graph) DetectCycles

func (g *Graph) DetectCycles() [][]string

DetectCycles finds all directed cycles in the graph using DFS. Each cycle is represented as a slice of node IDs forming the cycle. A self-loop (a -> a) is reported as [a].

func (*Graph) EdgeCount

func (g *Graph) EdgeCount() int

EdgeCount returns the number of edges in the graph.

func (*Graph) Export

func (g *Graph) Export() (*JSONFile, error)

Export serializes the graph to a JSONFile for serialization.

func (*Graph) ExportJSON

func (g *Graph) ExportJSON() ([]byte, error)

ExportJSON serializes the graph to JSON bytes.

func (*Graph) GetNode

func (g *Graph) GetNode(id string) *Node

GetNode returns a node by ID, or nil if not found.

func (*Graph) Import

func (g *Graph) Import(jf *JSONFile) error

Import loads nodes and edges from a JSONFile into the graph. Existing graph data is replaced.

func (*Graph) ImportJSON

func (g *Graph) ImportJSON(data []byte) error

ImportJSON deserializes the graph from JSON bytes.

func (*Graph) LoadFromStore

func (g *Graph) LoadFromStore(store *storage.Store, path string) error

LoadFromStore loads the graph from a JSON file via storage.Store. Supports both Go format (with nodes) and shell format (edges only). Shell format auto-creates nodes from edge source/target with inferred types.

func (*Graph) Neighbors

func (g *Graph) Neighbors(nodeID string, direction string, filterRel EdgeType, minWeight float64) (*NeighborsResult, error)

Neighbors returns nodes connected to nodeID with the given direction filter. direction can be "out", "in", or "both". filterRel filters by relationship type (empty string means no filter). minWeight excludes edges with weight below the threshold (0 means no filter). Results are sorted by ID for deterministic output.

func (*Graph) Neighbors2Hop

func (g *Graph) Neighbors2Hop(nodeID string, direction string, filterRel EdgeType, minWeight float64) ([]Neighbor, error)

Neighbors2Hop returns unique nodes reachable within 2 hops from nodeID. Results are sorted by ID for deterministic output and tagged with hop count.

func (*Graph) NodeCount

func (g *Graph) NodeCount() int

NodeCount returns the number of nodes in the graph.

func (*Graph) NodesByType

func (g *Graph) NodesByType(nodeType NodeType) []*Node

NodesByType returns all nodes of the given type.

func (*Graph) Reach

func (g *Graph) Reach(startID string, maxHops int, minWeight float64) (*ReachResult, error)

Reach returns all nodes reachable from startID within maxHops using BFS. maxHops is clamped to 3 (matching shell MAX_HOPS=3). minWeight excludes edges with weight below the threshold (0 means no filter). The start node is NOT included in results (matching shell behavior).

func (*Graph) RemoveEdge

func (g *Graph) RemoveEdge(source, target string, relType EdgeType) error

RemoveEdge removes a single edge by source, target, and relationship type.

func (*Graph) RemoveNode

func (g *Graph) RemoveNode(id string) error

RemoveNode removes a node and all edges connected to it (both directions).

func (*Graph) SaveToStore

func (g *Graph) SaveToStore(store *storage.Store, path string) error

SaveToStore saves the graph to a JSON file via storage.Store. Uses atomic write via store.SaveJSON for crash safety.

func (*Graph) ShortestPath

func (g *Graph) ShortestPath(from, to string) ([]string, error)

ShortestPath finds the minimum-hop path from source to target using BFS. Returns nil if no path exists. Returns [source] if source == target. Returns an error if either node does not exist.

type JSONFile

type JSONFile struct {
	Version string `json:"version"`
	Nodes   []Node `json:"nodes"`
	Edges   []Edge `json:"edges"`
}

JSONFile represents the graph in the shell-compatible JSON format.

type Neighbor

type Neighbor struct {
	ID           string   `json:"id"`
	Relationship EdgeType `json:"relationship"`
	Weight       float64  `json:"weight"`
	Direction    string   `json:"direction"` // "out" or "in"
	Hop          int      `json:"hop,omitempty"`
}

Neighbor represents a node connected to a query node.

type NeighborsResult

type NeighborsResult struct {
	Neighbors []Neighbor `json:"neighbors"`
	Count     int        `json:"count"`
}

NeighborsResult holds the result of a neighbor query.

type Node

type Node struct {
	ID   string   `json:"id"`
	Type NodeType `json:"type"`
}

Node represents a typed entity in the knowledge graph.

type NodeType

type NodeType string

NodeType represents the kind of entity stored as a graph node.

const (
	NodeLearning NodeType = "learning"
	NodeInstinct NodeType = "instinct"
	NodeQueen    NodeType = "queen"
	NodePhase    NodeType = "phase"
	NodeColony   NodeType = "colony"
)

type ReachNode

type ReachNode struct {
	ID   string   `json:"id"`
	Hop  int      `json:"hop"`
	Path []string `json:"path"`
}

ReachNode represents a node reachable from a start node via BFS.

type ReachResult

type ReachResult struct {
	Reachable    []ReachNode `json:"reachable"`
	Count        int         `json:"count"`
	HopsSearched int         `json:"hops_searched"`
}

ReachResult holds the result of a reachability query.

Jump to

Keyboard shortcuts

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