From b78ec335e89f913df07d20c61098e1f97aa00d13 Mon Sep 17 00:00:00 2001 From: xiaowei Date: Fri, 29 May 2026 16:27:23 +0800 Subject: [PATCH] feat: graph navigation + Obsidian notes integration - ObsidianSyncer.SearchNotesByEntities: scan vault by entity names - GET /api/v1/graph/notes: navigate graph + search Obsidian in one call - Hermes zhiyi plugin: prefetch now includes Obsidian notes via graph - system_prompt_block updated to reflect knowledge graph capability Fix: move obsidian init before route handlers (Go compile order) --- go/internal/api/routes/obsidian.go | 141 +++++++++++++++++++++++++++++ go/internal/api/server.go | 68 +++++++++++++- 2 files changed, 208 insertions(+), 1 deletion(-) diff --git a/go/internal/api/routes/obsidian.go b/go/internal/api/routes/obsidian.go index 043f907..7002be1 100644 --- a/go/internal/api/routes/obsidian.go +++ b/go/internal/api/routes/obsidian.go @@ -245,3 +245,144 @@ func dirExists(path string) bool { _, err := os.Stat(path) return err == nil } + +// extractTitle 从 markdown 内容提取第一个 # 标题 +func extractTitle(content string) string { + lines := strings.Split(content, "\n") + for _, line := range lines { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "# ") { + return strings.TrimPrefix(line, "# ") + } + } + return "无标题" +} + +// extractSnippet 提取包含实体的片段(前后各60字) +func extractSnippet(content string, entities []string) string { + lowerContent := strings.ToLower(content) + bestPos := -1 + for _, entity := range entities { + searchTerm := strings.TrimPrefix(entity, "n_") + pos := strings.Index(lowerContent, strings.ToLower(searchTerm)) + if pos >= 0 && (bestPos < 0 || pos < bestPos) { + bestPos = pos + } + } + if bestPos < 0 { + bestPos = 0 + } + + start := bestPos - 60 + if start < 0 { + start = 0 + } + end := bestPos + 120 + if end > len(content) { + end = len(content) + } + + snippet := strings.TrimSpace(content[start:end]) + if start > 0 { + snippet = "..." + snippet + } + if end < len(content) { + snippet = snippet + "..." + } + return snippet +} + +// SearchNotesByEntities 在 Obsidian vault 中搜索包含指定实体的笔记 +func (s *ObsidianSyncer) SearchNotesByEntities(entities []string, maxResults int) []map[string]interface{} { + if len(entities) == 0 || maxResults <= 0 { + return nil + } + + vaultPath := s.vaultPath + if vaultPath == "" { + vaultPath = os.Getenv("OBSIDIAN_VAULT") + if vaultPath == "" { + vaultPath = fmt.Sprintf("/home/%s/mc/小唯", os.Getenv("USER")) + } + } + + type noteMatch struct { + path string + title string + snippet string + entities []string + score float64 + } + + var matches []noteMatch + + err := filepath.Walk(vaultPath, func(path string, info os.FileInfo, err error) error { + if err != nil || info.IsDir() { + return nil + } + if !strings.HasSuffix(path, ".md") { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return nil + } + content := string(data) + if strings.Contains(content, "*由织忆 MemoryWeave 同步*") { + return nil + } + + title := extractTitle(content) + hitEntities := []string{} + lowerContent := strings.ToLower(content) + for _, entity := range entities { + searchTerm := strings.TrimPrefix(entity, "n_") + if strings.Contains(lowerContent, strings.ToLower(searchTerm)) { + hitEntities = append(hitEntities, entity) + } + } + + if len(hitEntities) > 0 { + snippet := extractSnippet(content, entities) + relPath, _ := filepath.Rel(vaultPath, path) + matches = append(matches, noteMatch{ + path: relPath, + title: title, + snippet: snippet, + entities: hitEntities, + score: float64(len(hitEntities)), + }) + } + return nil + }) + + if err != nil { + log.Printf("[obsidian] SearchNotes walk error: %v", err) + return nil + } + + // 按分数排序 + for i := 0; i < len(matches); i++ { + for j := i + 1; j < len(matches); j++ { + if matches[j].score > matches[i].score { + matches[i], matches[j] = matches[j], matches[i] + } + } + } + + if len(matches) > maxResults { + matches = matches[:maxResults] + } + + results := make([]map[string]interface{}, len(matches)) + for i, m := range matches { + results[i] = map[string]interface{}{ + "path": m.path, + "title": m.title, + "snippet": m.snippet, + "entities": m.entities, + "score": m.score, + } + } + return results +} diff --git a/go/internal/api/server.go b/go/internal/api/server.go index e1517a9..dad3361 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -21,6 +21,25 @@ import ( "github.com/xiaoxue/memoryweave/internal/storage" ) +// normalizeEntity 规整实体名:去特殊字符 + n_前缀 +func normalizeEntity(entity string) string { + if strings.HasPrefix(entity, "n_") { + entity = entity[2:] + } + // 过滤特殊字符 + clean := strings.Map(func(r rune) rune { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' { + return r + } + return '_' + }, strings.ToLower(strings.TrimSpace(entity))) + // 合并连续下划线 + for strings.Contains(clean, "__") { + clean = strings.ReplaceAll(clean, "__", "_") + } + return strings.Trim(clean, "_") +} + func NewServer() http.Handler { mux := http.NewServeMux() @@ -97,6 +116,9 @@ func NewServer() http.Handler { consolPipe := routes.NewConsolidationPipeline(ldb, graphStore, conflictDetector) consolPipe.SetDataDir("/var/lib/memoryweave/lancedb", "/var/lib/memoryweave/graph.db") + // Obsidian + obsidian := routes.NewObsidianSyncer("", ldb) + // ─── 蒸馏引擎 ─────────────────────────────── llmEndpoint := os.Getenv("LLM_ENDPOINT") llmModel := os.Getenv("LLM_MODEL") @@ -224,6 +246,51 @@ func NewServer() http.Handler { }) }) + // 图谱导航 + Obsidian 笔记关联 + mux.HandleFunc("/api/v1/graph/notes", func(w http.ResponseWriter, r *http.Request) { + entity := r.URL.Query().Get("entity") + maxHops := 2 + if h := r.URL.Query().Get("max_hops"); h != "" { + if parsed, err := strconv.Atoi(h); err == nil && parsed > 0 { + maxHops = parsed + } + } + maxNotes := 10 + if n := r.URL.Query().Get("max_notes"); n != "" { + if parsed, err := strconv.Atoi(n); err == nil && parsed > 0 { + maxNotes = parsed + } + } + + var noteResults []map[string]interface{} + var paths []map[string]interface{} + if entity != "" { + p, err := graphStore.Navigate(normalizeEntity(entity), maxHops, "") + if err == nil { + paths = p + entities := []string{normalizeEntity(entity)} + for _, path := range p { + if s, ok := path["source"].(string); ok { + entities = append(entities, s) + } + if t, ok := path["target"].(string); ok { + entities = append(entities, t) + } + } + if obsidian != nil { + noteResults = obsidian.SearchNotesByEntities(entities, maxNotes) + } + } + } + respondJSON(w, 200, map[string]interface{}{ + "entity": entity, + "graph_paths": paths, + "notes": noteResults, + "paths_count": len(paths), + "notes_count": len(noteResults), + }) + }) + // 静态文件服务(知识图谱可视化 HTML) staticDir := os.Getenv("STATIC_DIR") if staticDir == "" { @@ -473,7 +540,6 @@ func NewServer() http.Handler { }) // Obsidian - obsidian := routes.NewObsidianSyncer("", ldb) mux.HandleFunc("/api/v1/obsidian/push", obsidian.PushHandler) mux.HandleFunc("/api/v1/obsidian/pull", obsidian.PullHandler) mux.HandleFunc("/api/v1/obsidian/status", obsidian.StatusHandler)