Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(agfs): add ripgrep-based grep acceleration and fix vimgrep line parser (#432)

yangxinxin-742cced0f953a
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 5b5afbb62..36a5f7f4a 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -434,7 +434,7 @@ class VikingFS:
real_ctx = self._ctx_or_default(ctx)
async def _walk(current_path: str, current_rel: str, current_depth: int):
- if len(all_entries) >= node_limit or current_depth > level_limit:
+ if len(all_entries) >= node_limit or current_depth >= level_limit:
return
for entry in self._ls_entries(current_path):
if len(all_entries) >= node_limit:
@@ -475,7 +475,7 @@ class VikingFS:
real_ctx = self._ctx_or_default(ctx)
async def _walk(current_path: str, current_rel: str, current_depth: int):
- if len(all_entries) >= node_limit or current_depth > level_limit:
+ if len(all_entries) >= node_limit or current_depth >= level_limit:
return
for entry in self._ls_entries(current_path):
if len(all_entries) >= node_limit:
diff --git a/third_party/agfs/agfs-server/pkg/handlers/handlers.go b/third_party/agfs/agfs-server/pkg/handlers/handlers.go
index c83257909..99f570e8c 100644
--- a/third_party/agfs/agfs-server/pkg/handlers/handlers.go
+++ b/third_party/agfs/agfs-server/pkg/handlers/handlers.go
@@ -10,12 +10,16 @@ import (
"fmt"
"io"
"net/http"
+ "os/exec"
"path"
+ "path/filepath"
"regexp"
"strconv"
+ "strings"
"time"
"github.com/c4pt0r/agfs/agfs-server/pkg/filesystem"
+ "github.com/c4pt0r/agfs/agfs-server/pkg/mountablefs"
log "github.com/sirupsen/logrus"
"github.com/zeebo/xxh3"
)
@@ -830,6 +834,12 @@ type GrepResponse struct {
Count int `json:"count"` // Total number of matches
}
+type localPathResolver interface {
+ ResolvePath(path string) string
+}
+
+var rgVimgrepSepRe = regexp.MustCompile(`:(\d+):(\d+):`)
+
// Grep searches for a pattern in files
func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {
var req GrepRequest
@@ -861,6 +871,8 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {
return
}
+ localPath, basePath, mountPath, useRipgrep := h.resolveRipgrepPath(req.Path)
+
// Check if path exists and get file info
info, err := h.fs.Stat(req.Path)
if err != nil {
@@ -871,7 +883,11 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {
// Handle stream mode
if req.Stream {
- h.grepStream(w, req.Path, re, info.IsDir, req.Recursive, req.NodeLimit)
+ if useRipgrep {
+ h.grepStreamRipgrep(w, localPath, basePath, mountPath, req.Pattern, info.IsDir, req.Recursive, req.CaseInsensitive, req.NodeLimit)
+ } else {
+ h.grepStream(w, req.Path, re, info.IsDir, req.Recursive, req.NodeLimit)
+ }
return
}
@@ -881,13 +897,21 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {
// Search in file or directory
if info.IsDir {
if req.Recursive {
- matches, err = h.grepDirectory(req.Path, re, req.NodeLimit)
+ if useRipgrep {
+ matches, err = h.grepWithRipgrep(localPath, basePath, mountPath, req.Pattern, req.CaseInsensitive, req.NodeLimit)
+ } else {
+ matches, err = h.grepDirectory(req.Path, re, req.NodeLimit)
+ }
} else {
writeError(w, http.StatusBadRequest, "path is a directory, use recursive=true to search")
return
}
} else {
- matches, err = h.grepFile(req.Path, re, req.NodeLimit)
+ if useRipgrep {
+ matches, err = h.grepWithRipgrep(localPath, basePath, mountPath, req.Pattern, req.CaseInsensitive, req.NodeLimit)
+ } else {
+ matches, err = h.grepFile(req.Path, re, req.NodeLimit)
+ }
}
response := GrepResponse{
@@ -898,6 +922,237 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, response)
}
+func (h *Handler) resolveRipgrepPath(vfsPath string) (string, string, string, bool) {
+ if _, err := exec.LookPath("rg"); err != nil {
+ return "", "", "", false
+ }
+
+ if mfs, ok := h.fs.(*mountablefs.MountableFS); ok {
+ mount, relPath, found := findMountForPath(mfs.GetMounts(), vfsPath)
+ if !found {
+ return "", "", "", false
+ }
+ resolver, ok := mount.Plugin.GetFileSystem().(localPathResolver)
+ if !ok {
+ return "", "", "", false
+ }
+ localPath := resolver.ResolvePath(relPath)
+ basePath := resolver.ResolvePath("/")
+ return localPath, basePath, mount.Path, true
+ }
+
+ resolver, ok := h.fs.(localPathResolver)
+ if !ok {
+ return "", "", "", false
+ }
+ localPath := resolver.ResolvePath(vfsPath)
+ basePath := resolver.ResolvePath("/")
+ return localPath, basePath, "/", true
+}
+
+func (h *Handler) grepStreamRipgrep(w http.ResponseWriter, localPath string, basePath string, mountPath string, pattern string, isDir bool, recursive bool, caseInsensitive bool, nodeLimit int) {
+ w.Header().Set("Content-Type", "application/x-ndjson")
+ w.Header().Set("Transfer-Encoding", "chunked")
+ w.WriteHeader(http.StatusOK)
+
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ log.Error("Streaming not supported")
+ return
+ }
+
+ matchCount := 0
+ encoder := json.NewEncoder(w)
+
+ sendMatch := func(match GrepMatch) error {
+ matchCount++
+ if err := encoder.Encode(match); err != nil {
+ return err
+ }
+ flusher.Flush()
+ return nil
+ }
+
+ var err error
+ if isDir {
+ if !recursive {
+ errMatch := map[string]interface{}{
+ "error": "path is a directory, use recursive=true to search",
+ }
+ encoder.Encode(errMatch)
+ flusher.Flush()
+ return
+ }
+ _, err = h.grepWithRipgrepStream(localPath, basePath, mountPath, pattern, caseInsensitive, nodeLimit, sendMatch)
+ } else {
+ _, err = h.grepWithRipgrepStream(localPath, basePath, mountPath, pattern, caseInsensitive, nodeLimit, sendMatch)
+ }
+
+ summary := map[string]interface{}{
+ "type": "summary",
+ "count": matchCount,
+ }
+ if err != nil {
+ summary["error"] = err.Error()
+ }
+ encoder.Encode(summary)
+ flusher.Flush()
+}
+
+func (h *Handler) grepWithRipgrep(localPath string, basePath string, mountPath string, pattern string, caseInsensitive bool, nodeLimit int) ([]GrepMatch, error) {
+ matches := make([]GrepMatch, 0)
+ _, err := h.grepWithRipgrepStream(localPath, basePath, mountPath, pattern, caseInsensitive, nodeLimit, func(match GrepMatch) error {
+ matches = append(matches, match)
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return matches, nil
+}
+
+func (h *Handler) grepWithRipgrepStream(localPath string, basePath string, mountPath string, pattern string, caseInsensitive bool, nodeLimit int, callback func(GrepMatch) error) (int, error) {
+ args := []string{"--vimgrep", "--no-heading", "--color=never"}
+ if caseInsensitive {
+ args = append(args, "-i")
+ }
+ if nodeLimit > 0 {
+ args = append(args, "--max-count", strconv.Itoa(nodeLimit))
+ }
+ args = append(args, "--", pattern, localPath)
+
+ cmd := exec.Command("rg", args...)
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return 0, err
+ }
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ if err := cmd.Start(); err != nil {
+ return 0, err
+ }
+
+ count := 0
+ scanner := bufio.NewScanner(stdout)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ filePath, lineNum, content, ok := parseRipgrepLine(scanner.Text())
+ if !ok {
+ continue
+ }
+ vfsPath := vfsPathFromLocal(basePath, mountPath, filePath)
+ match := GrepMatch{
+ File: vfsPath,
+ Line: lineNum,
+ Content: content,
+ }
+ if err := callback(match); err != nil {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ return count, err
+ }
+ count++
+ if nodeLimit > 0 && count >= nodeLimit {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ return count, nil
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ return count, err
+ }
+ if err := cmd.Wait(); err != nil {
+ if exitErr, ok := err.(*exec.ExitError); ok {
+ if exitErr.ExitCode() == 1 {
+ return count, nil
+ }
+ if stderr.Len() > 0 {
+ return count, errors.New(strings.TrimSpace(stderr.String()))
+ }
+ }
+ return count, err
+ }
+ return count, nil
+}
+
+func parseRipgrepLine(line string) (string, int, string, bool) {
+ matches := rgVimgrepSepRe.FindAllStringSubmatchIndex(line, -1)
+ if len(matches) == 0 {
+ return "", 0, "", false
+ }
+ m := matches[0]
+ if len(m) < 6 {
+ return "", 0, "", false
+ }
+ filePath := line[:m[0]]
+ lineStr := line[m[2]:m[3]]
+ content := line[m[1]:]
+ lineNum, err := strconv.Atoi(lineStr)
+ if err != nil {
+ return "", 0, "", false
+ }
+ return filePath, lineNum, content, true
+}
+
+func vfsPathFromLocal(basePath string, mountPath string, localPath string) string {
+ rel, err := filepath.Rel(basePath, localPath)
+ if err != nil {
+ return localPath
+ }
+ rel = filepath.ToSlash(rel)
+ if rel == "." {
+ return mountPath
+ }
+ if strings.HasPrefix(rel, "..") {
+ return localPath
+ }
+ mountPath = path.Clean("/" + strings.TrimPrefix(mountPath, "/"))
+ if mountPath == "/" {
+ return "/" + rel
+ }
+ return mountPath + "/" + rel
+}
+
+func findMountForPath(mounts []*mountablefs.MountPoint, targetPath string) (*mountablefs.MountPoint, string, bool) {
+ targetPath = filesystem.NormalizePath(targetPath)
+ var best *mountablefs.MountPoint
+ bestLen := -1
+ bestRel := ""
+
+ for _, m := range mounts {
+ mountPath := filesystem.NormalizePath(m.Path)
+ rel, ok := matchMountPath(mountPath, targetPath)
+ if !ok {
+ continue
+ }
+ if len(mountPath) > bestLen {
+ best = m
+ bestLen = len(mountPath)
+ bestRel = rel
+ }
+ }
+
+ if best == nil {
+ return nil, "", false
+ }
+ return best, bestRel, true
+}
+
+func matchMountPath(mountPath string, targetPath string) (string, bool) {
+ if mountPath == "/" {
+ return targetPath, true
+ }
+ if targetPath == mountPath {
+ return "/", true
+ }
+ if strings.HasPrefix(targetPath, mountPath) && len(targetPath) > len(mountPath) && targetPath[len(mountPath)] == '/' {
+ return targetPath[len(mountPath):], true
+ }
+ return "", false
+}
+
// grepStream handles streaming grep results as NDJSON
func (h *Handler) grepStream(w http.ResponseWriter, path string, re *regexp.Regexp, isDir bool, recursive bool, nodeLimit int) {
// Set headers for NDJSON streaming
diff --git a/third_party/agfs/agfs-server/pkg/handlers/handlers_test.go b/third_party/agfs/agfs-server/pkg/handlers/handlers_test.go
new file mode 100644
index 000000000..30eb88e0f
--- /dev/null
+++ b/third_party/agfs/agfs-server/pkg/handlers/handlers_test.go
@@ -0,0 +1,80 @@
+package handlers
+
+import (
+ "testing"
+)
+
+func TestParseRipgrepLine(t *testing.T) {
+ tests := []struct {
+ name string
+ line string
+ wantFile string
+ wantLine int
+ wantContent string
+ wantOk bool
+ }{
+ {
+ name: "normal line",
+ line: "/path/to/file.go:10:5:some content",
+ wantFile: "/path/to/file.go",
+ wantLine: 10,
+ wantContent: "some content",
+ wantOk: true,
+ },
+ {
+ name: "content contains :digit:digit: pattern",
+ line: "/path/to/file.go:10:5:error at position 20:3: invalid token",
+ wantFile: "/path/to/file.go",
+ wantLine: 10,
+ wantContent: "error at position 20:3: invalid token",
+ wantOk: true,
+ },
+ {
+ name: "content contains multiple :digit:digit: patterns",
+ line: "/path/to/file.go:42:1:fmt.Sprintf(\"%d:%d:\", 1, 2)",
+ wantFile: "/path/to/file.go",
+ wantLine: 42,
+ wantContent: "fmt.Sprintf(\"%d:%d:\", 1, 2)",
+ wantOk: true,
+ },
+ {
+ name: "no separator",
+ line: "just some text",
+ wantOk: false,
+ },
+ {
+ name: "empty line",
+ line: "",
+ wantOk: false,
+ },
+ {
+ name: "col is zero",
+ line: "/src/main.go:1:0:package main",
+ wantFile: "/src/main.go",
+ wantLine: 1,
+ wantContent: "package main",
+ wantOk: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ file, line, content, ok := parseRipgrepLine(tt.line)
+ if ok != tt.wantOk {
+ t.Fatalf("ok = %v, want %v", ok, tt.wantOk)
+ }
+ if !ok {
+ return
+ }
+ if file != tt.wantFile {
+ t.Errorf("file = %q, want %q", file, tt.wantFile)
+ }
+ if line != tt.wantLine {
+ t.Errorf("line = %d, want %d", line, tt.wantLine)
+ }
+ if content != tt.wantContent {
+ t.Errorf("content = %q, want %q", content, tt.wantContent)
+ }
+ })
+ }
+}
diff --git a/third_party/agfs/agfs-server/pkg/plugins/localfs/localfs.go b/third_party/agfs/agfs-server/pkg/plugins/localfs/localfs.go
index c34b44f60..1facb7bf9 100644
--- a/third_party/agfs/agfs-server/pkg/plugins/localfs/localfs.go
+++ b/third_party/agfs/agfs-server/pkg/plugins/localfs/localfs.go
@@ -71,6 +71,10 @@ func (fs *LocalFS) resolvePath(path string) string {
return filepath.Join(fs.basePath, relativePath)
}
+func (fs *LocalFS) ResolvePath(path string) string {
+ return fs.resolvePath(path)
+}
+
func (fs *LocalFS) Create(path string) error {
localPath := fs.resolvePath(path)