mirror of
https://github.com/lukaszraczylo/claude-mnemonic.git
synced 2026-06-05 23:03:55 +00:00
5c2685c7b6
* feat(leann-phase2): implement hybrid vector storage and graph-based search
- [x] Add AST-aware code chunking for Go, Python, and TypeScript using tree-sitter
- [x] Implement LEANN-inspired hybrid vector storage with hub detection and selective embedding storage (60-80% savings)
- [x] Add observation relationship graph with CSR format and edge detection (file overlap, semantic similarity, temporal, concept)
- [x] Implement graph-aware search with two-level traversal and relationship-based ranking
- [x] Add auto-tuning system for dynamic hub threshold adjustment based on query performance
- [x] Add comprehensive metrics tracking for vector storage, queries, latency, and graph traversals
- [x] Update configuration system with graph and hybrid storage settings
- [x] Add graph stats and vector metrics endpoints to worker service
- [x] Enhance UI sidebar with advanced metrics display and graph visualization
- [x] Optimize struct field alignment throughout codebase for memory efficiency
- [x] Update documentation with LEANN Phase 2 features and performance benefits
- [x] Add tree-sitter dependency for AST parsing
* fix: add fts5 build tag to CI workflow
Pass build-tags: "fts5" to shared workflow to properly compile
sqlite-vec-go-bindings with SQLite FTS5 support.
This fixes test failures in hybrid vector storage tests that require
CGO and FTS5 build tags.
Requires shared-actions@8f7f235 or later.
* docs: add testing documentation and macOS ARM64 known issue
Document the macOS ARM64 CGO linking issue with sqlite-vec-go-bindings
that prevents hybrid package tests from compiling locally.
Added:
- .github/TESTING.md: Comprehensive testing guide with platform-specific
issues, workarounds, and CI configuration details
- internal/vector/hybrid/README.md: Package-specific documentation
explaining the macOS limitation
- .github/CI_FIX_SUMMARY.md: Technical details of the CI fix
Key points:
- 41 out of 42 packages test successfully on all platforms
- hybrid package tests fail only on macOS ARM64 (local dev issue)
- Linux CI tests pass with proper build-tags: "fts5" configuration
- Production builds and runtime functionality unaffected
This is a known limitation of sqlite-vec-go-bindings on macOS ARM64
and does not impact CI/CD or production deployments.
* fix: add SQLite busy_timeout to prevent database locked errors
Set PRAGMA busy_timeout=5000 (5 seconds) to allow SQLite to retry
when the database is locked instead of failing immediately.
This fixes race conditions when multiple goroutines try to write
simultaneously, particularly in tests where StoreObservation spawns
async cleanup goroutines.
Root cause:
- StoreObservation launches goroutine -> CleanupOldObservations
- Multiple concurrent cleanups caused "database is locked" errors
- Without busy_timeout, SQLite fails immediately on lock contention
Solution:
- Add 5-second busy timeout for automatic retry on lock
- Standard practice for concurrent SQLite usage
- Works with existing WAL mode configuration
Fixes TestObservationStore_CleanupOldObservations in CI.
* docs: complete summary of all CI test fixes
Comprehensive documentation of all fixes applied:
1. Missing build tags (fts5)
2. Database locked errors (busy_timeout)
All 41/42 packages now pass tests. The hybrid package has a known
macOS ARM64 limitation that doesn't affect CI or production.
No functionality was removed - all fixes are additive only.
* fix: add SQLite driver import to hybrid tests for CGO linking
Add blank import of mattn/go-sqlite3 to hybrid test files to ensure
the SQLite driver is linked into the test binary. This provides the
SQLite symbols that sqlite-vec-go-bindings requires.
Root cause:
- hybrid package imports sqlitevec (transitively depends on sqlite-vec CGO)
- Test binary needs SQLite symbols for linking
- sqlitevec tests already had this import, but hybrid tests didn't
- Without the driver import, linker fails with "undefined symbols"
This fix enables hybrid tests to run with -race flag on all platforms.
Before: 41/42 packages pass (hybrid failed to link)
After: 42/42 packages pass ✅
Fixes hybrid test compilation on macOS ARM64, Linux, and Windows.
* docs: remove outdated macOS limitation documentation
The hybrid test linking issue has been fixed by adding the SQLite
driver import. All tests now pass on all platforms including macOS.
Removed:
- internal/vector/hybrid/README.md (documented workaround no longer needed)
- .github/TESTING.md (macOS limitation section obsolete)
All 42/42 packages now test successfully with -race flag.
* docs: final comprehensive summary of all CI fixes
All three issues now resolved:
1. Missing fts5 build tags
2. Database busy_timeout for concurrent writes
3. Missing SQLite driver import in hybrid tests
Result: 42/42 packages pass with -race on all platforms.
Credit to reviewer for identifying the race detector concern.
418 lines
10 KiB
Go
418 lines
10 KiB
Go
package graph
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"math"
|
|
|
|
"github.com/lukaszraczylo/claude-mnemonic/pkg/models"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
const (
|
|
// SemanticSimilarityThreshold for creating semantic edges
|
|
SemanticSimilarityThreshold = 0.85
|
|
|
|
// MinFileOverlapForEdge minimum file overlap ratio to create edge
|
|
MinFileOverlapForEdge = 0.3
|
|
|
|
// MaxEdgesPerNode prevents creating too many edges
|
|
MaxEdgesPerNode = 20
|
|
)
|
|
|
|
// DetectEdges identifies relationships between observations
|
|
func DetectEdges(ctx context.Context, observations []*models.Observation) ([]Edge, error) {
|
|
if len(observations) < 2 {
|
|
return nil, nil
|
|
}
|
|
|
|
edges := make([]Edge, 0)
|
|
|
|
// Build lookup maps for efficient detection
|
|
sessionMap := buildSessionMap(observations)
|
|
conceptMap := buildConceptMap(observations)
|
|
fileMap := buildFileMap(observations)
|
|
|
|
log.Info().
|
|
Int("observations", len(observations)).
|
|
Int("sessions", len(sessionMap)).
|
|
Int("concepts", len(conceptMap)).
|
|
Msg("Starting edge detection")
|
|
|
|
// Detect temporal edges (same session)
|
|
temporalEdges := detectTemporalEdges(sessionMap)
|
|
edges = append(edges, temporalEdges...)
|
|
|
|
// Detect concept edges (shared tags)
|
|
conceptEdges := detectConceptEdges(conceptMap)
|
|
edges = append(edges, conceptEdges...)
|
|
|
|
// Detect file overlap edges
|
|
fileEdges := detectFileOverlapEdges(fileMap, observations)
|
|
edges = append(edges, fileEdges...)
|
|
|
|
// Prune excessive edges per node
|
|
edges = pruneEdges(edges, MaxEdgesPerNode)
|
|
|
|
log.Info().
|
|
Int("temporal_edges", len(temporalEdges)).
|
|
Int("concept_edges", len(conceptEdges)).
|
|
Int("file_edges", len(fileEdges)).
|
|
Int("total_edges", len(edges)).
|
|
Msg("Edge detection complete")
|
|
|
|
return edges, nil
|
|
}
|
|
|
|
// buildSessionMap groups observations by SDK session
|
|
func buildSessionMap(observations []*models.Observation) map[string][]int64 {
|
|
sessionMap := make(map[string][]int64)
|
|
|
|
for _, obs := range observations {
|
|
if obs.SDKSessionID != "" {
|
|
sessionMap[obs.SDKSessionID] = append(sessionMap[obs.SDKSessionID], obs.ID)
|
|
}
|
|
}
|
|
|
|
return sessionMap
|
|
}
|
|
|
|
// buildConceptMap groups observations by concept tags
|
|
func buildConceptMap(observations []*models.Observation) map[string][]int64 {
|
|
conceptMap := make(map[string][]int64)
|
|
|
|
for _, obs := range observations {
|
|
for _, concept := range obs.Concepts {
|
|
conceptMap[concept] = append(conceptMap[concept], obs.ID)
|
|
}
|
|
}
|
|
|
|
return conceptMap
|
|
}
|
|
|
|
// buildFileMap maps files to observations (from both FilesRead and FilesModified)
|
|
func buildFileMap(observations []*models.Observation) map[string][]int64 {
|
|
fileMap := make(map[string][]int64)
|
|
|
|
for _, obs := range observations {
|
|
// Add files from FilesRead
|
|
for _, file := range obs.FilesRead {
|
|
fileMap[file] = append(fileMap[file], obs.ID)
|
|
}
|
|
// Add files from FilesModified
|
|
for _, file := range obs.FilesModified {
|
|
fileMap[file] = append(fileMap[file], obs.ID)
|
|
}
|
|
}
|
|
|
|
return fileMap
|
|
}
|
|
|
|
// detectTemporalEdges creates edges between observations in the same session
|
|
func detectTemporalEdges(sessionMap map[string][]int64) []Edge {
|
|
edges := make([]Edge, 0)
|
|
|
|
for _, obsIDs := range sessionMap {
|
|
if len(obsIDs) < 2 {
|
|
continue
|
|
}
|
|
|
|
// Create edges between consecutive observations in session
|
|
for i := 0; i < len(obsIDs)-1; i++ {
|
|
edges = append(edges, Edge{
|
|
FromID: obsIDs[i],
|
|
ToID: obsIDs[i+1],
|
|
Relation: RelationTemporal,
|
|
Weight: 0.8, // High weight for temporal proximity
|
|
})
|
|
}
|
|
}
|
|
|
|
return edges
|
|
}
|
|
|
|
// detectConceptEdges creates edges between observations sharing concepts
|
|
func detectConceptEdges(conceptMap map[string][]int64) []Edge {
|
|
edges := make([]Edge, 0)
|
|
seen := make(map[string]bool)
|
|
|
|
for concept, obsIDs := range conceptMap {
|
|
if len(obsIDs) < 2 {
|
|
continue
|
|
}
|
|
|
|
// Create edges between all observations sharing this concept
|
|
for i := 0; i < len(obsIDs); i++ {
|
|
for j := i + 1; j < len(obsIDs); j++ {
|
|
// Use sorted pair as key to avoid duplicates
|
|
pairKey := edgeKey(obsIDs[i], obsIDs[j])
|
|
if seen[pairKey] {
|
|
continue
|
|
}
|
|
seen[pairKey] = true
|
|
|
|
// Weight based on concept specificity (longer = more specific)
|
|
weight := float32(0.5 + 0.3*math.Min(1.0, float64(len(concept))/20.0))
|
|
|
|
edges = append(edges, Edge{
|
|
FromID: obsIDs[i],
|
|
ToID: obsIDs[j],
|
|
Relation: RelationConcept,
|
|
Weight: weight,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
return edges
|
|
}
|
|
|
|
// detectFileOverlapEdges creates edges based on file references
|
|
func detectFileOverlapEdges(fileMap map[string][]int64, observations []*models.Observation) []Edge {
|
|
edges := make([]Edge, 0)
|
|
seen := make(map[string]bool)
|
|
|
|
// Build observation ID to observation map for quick lookup
|
|
obsMap := make(map[int64]*models.Observation)
|
|
for _, obs := range observations {
|
|
obsMap[obs.ID] = obs
|
|
}
|
|
|
|
for _, obsIDs := range fileMap {
|
|
if len(obsIDs) < 2 {
|
|
continue
|
|
}
|
|
|
|
// Create edges between observations referencing same files
|
|
for i := 0; i < len(obsIDs); i++ {
|
|
for j := i + 1; j < len(obsIDs); j++ {
|
|
pairKey := edgeKey(obsIDs[i], obsIDs[j])
|
|
if seen[pairKey] {
|
|
continue
|
|
}
|
|
seen[pairKey] = true
|
|
|
|
// Calculate file overlap ratio
|
|
obs1, ok1 := obsMap[obsIDs[i]]
|
|
obs2, ok2 := obsMap[obsIDs[j]]
|
|
|
|
if !ok1 || !ok2 {
|
|
continue
|
|
}
|
|
|
|
// Merge FilesRead and FilesModified for both observations
|
|
files1 := append([]string{}, obs1.FilesRead...)
|
|
files1 = append(files1, obs1.FilesModified...)
|
|
files2 := append([]string{}, obs2.FilesRead...)
|
|
files2 = append(files2, obs2.FilesModified...)
|
|
|
|
overlap := calculateFileOverlap(files1, files2)
|
|
if overlap < MinFileOverlapForEdge {
|
|
continue
|
|
}
|
|
|
|
edges = append(edges, Edge{
|
|
FromID: obsIDs[i],
|
|
ToID: obsIDs[j],
|
|
Relation: RelationFileOverlap,
|
|
Weight: overlap,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
return edges
|
|
}
|
|
|
|
// calculateFileOverlap computes Jaccard similarity of file sets
|
|
func calculateFileOverlap(files1, files2 []string) float32 {
|
|
if len(files1) == 0 || len(files2) == 0 {
|
|
return 0.0
|
|
}
|
|
|
|
// Convert to sets
|
|
set1 := make(map[string]bool)
|
|
for _, f := range files1 {
|
|
set1[f] = true
|
|
}
|
|
|
|
set2 := make(map[string]bool)
|
|
for _, f := range files2 {
|
|
set2[f] = true
|
|
}
|
|
|
|
// Count intersection
|
|
intersection := 0
|
|
for f := range set1 {
|
|
if set2[f] {
|
|
intersection++
|
|
}
|
|
}
|
|
|
|
// Jaccard similarity = intersection / union
|
|
union := len(set1) + len(set2) - intersection
|
|
if union == 0 {
|
|
return 0.0
|
|
}
|
|
|
|
return float32(intersection) / float32(union)
|
|
}
|
|
|
|
// pruneEdges limits edges per node to prevent graph explosion
|
|
func pruneEdges(edges []Edge, maxPerNode int) []Edge {
|
|
if maxPerNode <= 0 {
|
|
return edges
|
|
}
|
|
|
|
// Count edges per node
|
|
outEdges := make(map[int64][]Edge)
|
|
inEdges := make(map[int64][]Edge)
|
|
|
|
for _, edge := range edges {
|
|
outEdges[edge.FromID] = append(outEdges[edge.FromID], edge)
|
|
inEdges[edge.ToID] = append(inEdges[edge.ToID], edge)
|
|
}
|
|
|
|
// Prune low-weight edges if node has too many
|
|
pruned := make([]Edge, 0, len(edges))
|
|
processed := make(map[string]bool)
|
|
|
|
for _, edge := range edges {
|
|
pairKey := edgeKey(edge.FromID, edge.ToID)
|
|
if processed[pairKey] {
|
|
continue
|
|
}
|
|
processed[pairKey] = true
|
|
|
|
// Check if either node has too many edges
|
|
fromCount := len(outEdges[edge.FromID])
|
|
toCount := len(inEdges[edge.ToID])
|
|
|
|
if fromCount <= maxPerNode && toCount <= maxPerNode {
|
|
pruned = append(pruned, edge)
|
|
continue
|
|
}
|
|
|
|
// Keep edge if it's high-weight (top edges for this node)
|
|
if shouldKeepEdge(edge, outEdges[edge.FromID], maxPerNode) {
|
|
pruned = append(pruned, edge)
|
|
}
|
|
}
|
|
|
|
if len(pruned) < len(edges) {
|
|
log.Debug().
|
|
Int("original", len(edges)).
|
|
Int("pruned", len(pruned)).
|
|
Int("removed", len(edges)-len(pruned)).
|
|
Msg("Pruned excessive edges")
|
|
}
|
|
|
|
return pruned
|
|
}
|
|
|
|
// shouldKeepEdge determines if edge should be kept during pruning
|
|
func shouldKeepEdge(edge Edge, nodeEdges []Edge, maxPerNode int) bool {
|
|
// Sort node's edges by weight descending
|
|
sortedEdges := make([]Edge, len(nodeEdges))
|
|
copy(sortedEdges, nodeEdges)
|
|
|
|
sortEdgesByWeight(sortedEdges)
|
|
|
|
// Keep edge if it's in top maxPerNode
|
|
for i := 0; i < maxPerNode && i < len(sortedEdges); i++ {
|
|
if sortedEdges[i].FromID == edge.FromID && sortedEdges[i].ToID == edge.ToID {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// sortEdgesByWeight sorts edges by weight descending
|
|
func sortEdgesByWeight(edges []Edge) {
|
|
// Simple bubble sort (edges are typically small per node)
|
|
n := len(edges)
|
|
for i := 0; i < n-1; i++ {
|
|
for j := 0; j < n-i-1; j++ {
|
|
if edges[j].Weight < edges[j+1].Weight {
|
|
edges[j], edges[j+1] = edges[j+1], edges[j]
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// edgeKey creates a unique key for an edge pair (sorted)
|
|
func edgeKey(id1, id2 int64) string {
|
|
if id1 < id2 {
|
|
return fmt.Sprintf("%d-%d", id1, id2)
|
|
}
|
|
return fmt.Sprintf("%d-%d", id2, id1)
|
|
}
|
|
|
|
// DetectSemanticEdges creates edges based on semantic similarity
|
|
// This requires embeddings and is called separately when available
|
|
func DetectSemanticEdges(ctx context.Context, observations []*models.Observation, embeddings map[int64][]float32) []Edge {
|
|
edges := make([]Edge, 0)
|
|
seen := make(map[string]bool)
|
|
|
|
// Compare all pairs (expensive, but necessary for semantic similarity)
|
|
for i := 0; i < len(observations); i++ {
|
|
emb1, ok1 := embeddings[observations[i].ID]
|
|
if !ok1 {
|
|
continue
|
|
}
|
|
|
|
for j := i + 1; j < len(observations); j++ {
|
|
emb2, ok2 := embeddings[observations[j].ID]
|
|
if !ok2 {
|
|
continue
|
|
}
|
|
|
|
similarity := cosineSimilarity(emb1, emb2)
|
|
if similarity < SemanticSimilarityThreshold {
|
|
continue
|
|
}
|
|
|
|
pairKey := edgeKey(observations[i].ID, observations[j].ID)
|
|
if seen[pairKey] {
|
|
continue
|
|
}
|
|
seen[pairKey] = true
|
|
|
|
edges = append(edges, Edge{
|
|
FromID: observations[i].ID,
|
|
ToID: observations[j].ID,
|
|
Relation: RelationSemantic,
|
|
Weight: similarity,
|
|
})
|
|
}
|
|
}
|
|
|
|
log.Info().
|
|
Int("semantic_edges", len(edges)).
|
|
Float32("threshold", SemanticSimilarityThreshold).
|
|
Msg("Detected semantic edges")
|
|
|
|
return edges
|
|
}
|
|
|
|
// cosineSimilarity computes cosine similarity between two vectors
|
|
func cosineSimilarity(a, b []float32) float32 {
|
|
if len(a) != len(b) {
|
|
return 0.0
|
|
}
|
|
|
|
var dotProduct, normA, normB float32
|
|
for i := range a {
|
|
dotProduct += a[i] * b[i]
|
|
normA += a[i] * a[i]
|
|
normB += b[i] * b[i]
|
|
}
|
|
|
|
if normA == 0 || normB == 0 {
|
|
return 0.0
|
|
}
|
|
|
|
return dotProduct / float32(math.Sqrt(float64(normA))*math.Sqrt(float64(normB)))
|
|
}
|