feat(indexing): port tau's codesearch workspace index (4we)
First slice of the tau cherry-pick strategy: copy-and-mutate rather than
extracting tau to pkg/. Exporting would force designing metrics, session
and logger seams upfront, before archie-core knows which of them it wants
differently — a cost paid for reuse not yet proven. ai-sdk earned library
status by stabilising across two consumers; nothing in tau/internal has.
indexing is the cheapest high-value lift: 512 LoC, one file, and its only
coupling to tau was three calls to process-global config path helpers.
Nothing else in tau imports it.
Mutations from upstream:
- path helpers become an explicit indexing.Config. Two archied instances
share a host (archie and winter), so they must not share one index.
- the child-process helper is archied's own workspace-codesearch
subcommand, dispatched before flag parsing so it touches no config,
store or NATS.
- deferred db.Close calls explicitly discarded; archie-core runs errcheck.
The child process is not incidental: google/codesearch calls fatal exits on
a corrupt index and leaks mmapped regions. Verified end to end against this
repo — 2.2MB indexed, correct hits for BuildSystemPrompt, [] for no match,
and a deliberately corrupted index returns "corrupt index" with exit 1
instead of taking the process down.
Every lifted file carries a provenance header naming its tau path and
commit (4893818d0c76), so refreshing from upstream is a diff rather than
archaeology.
This commit is contained in:
1 parent
c79c623e9c
commit
446dc6b3de
9 files changed
+1027
-1
No files matched your search
@@ -0,0 +1,116 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/indexing"
|
||||
)
|
||||
|
||||
// flagErrorOutput receives helper diagnostics. It is a variable so tests can
|
||||
// capture them, and it is deliberately not stdout: the parent parses stdout
|
||||
// as JSON, so a stray usage message there would corrupt the result.
|
||||
var flagErrorOutput io.Writer = os.Stderr
|
||||
|
||||
// codesearchHelperCommand is the argv[1] token that switches archied out of
|
||||
// daemon mode and into the codesearch helper.
|
||||
//
|
||||
// indexing.Manager deliberately runs the google/codesearch library in a child
|
||||
// process: upstream calls fatal exits on a corrupt index and leaks mmapped
|
||||
// regions, neither of which may be allowed to take down a long-lived daemon.
|
||||
// The child it spawns is this binary, so this name is a contract with
|
||||
// internal/indexing -- renaming either side silently disables indexed search
|
||||
// and falls the agent back to unindexed grep.
|
||||
const codesearchHelperCommand = "workspace-codesearch"
|
||||
|
||||
// isCodesearchHelperArgs reports whether args (os.Args[1:]) selects the
|
||||
// helper rather than the daemon.
|
||||
func isCodesearchHelperArgs(args []string) bool {
|
||||
return len(args) > 0 && args[0] == codesearchHelperCommand
|
||||
}
|
||||
|
||||
// runCodesearchHelper executes one helper subcommand and returns a process
|
||||
// exit code. Output is the machine-readable result the parent decodes; all
|
||||
// diagnostics go to stderr so they cannot corrupt it.
|
||||
func runCodesearchHelper(args []string, out io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
helperErrorf("%s: expected a subcommand (build|candidates)\n", codesearchHelperCommand)
|
||||
return 2
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
switch args[0] {
|
||||
case "build":
|
||||
fs := newHelperFlagSet("build")
|
||||
root := fs.String("root", "", "workspace root to index")
|
||||
index := fs.String("index", "", "path of the index sidecar to write")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return 2
|
||||
}
|
||||
if *root == "" || *index == "" {
|
||||
helperErrorf("build: --root and --index are required\n")
|
||||
return 2
|
||||
}
|
||||
if err := indexing.BuildIndex(ctx, *root, *index); err != nil {
|
||||
helperErrorf("build: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
|
||||
case "candidates":
|
||||
fs := newHelperFlagSet("candidates")
|
||||
index := fs.String("index", "", "path of the index sidecar to query")
|
||||
pattern := fs.String("pattern", "", "search pattern")
|
||||
literal := fs.Bool("literal", false, "treat the pattern as a literal string")
|
||||
caseSensitive := fs.Bool("case-sensitive", false, "match case sensitively")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return 2
|
||||
}
|
||||
if *index == "" || *pattern == "" {
|
||||
helperErrorf("candidates: --index and --pattern are required\n")
|
||||
return 2
|
||||
}
|
||||
files, err := indexing.IndexCandidates(*index, *pattern, *literal, *caseSensitive)
|
||||
if err != nil {
|
||||
helperErrorf("candidates: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
// The parent decodes a JSON array and treats any decode failure as
|
||||
// "no index", so a nil slice must still marshal as [] rather than
|
||||
// null.
|
||||
if files == nil {
|
||||
files = []string{}
|
||||
}
|
||||
encoded, err := json.Marshal(files)
|
||||
if err != nil {
|
||||
helperErrorf("candidates: encode result: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
if _, err := out.Write(encoded); err != nil {
|
||||
helperErrorf("candidates: write result: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
|
||||
default:
|
||||
helperErrorf("%s: unknown subcommand %q\n", codesearchHelperCommand, args[0])
|
||||
return 2
|
||||
}
|
||||
}
|
||||
|
||||
func newHelperFlagSet(name string) *flag.FlagSet {
|
||||
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
fs.SetOutput(flagErrorOutput)
|
||||
return fs
|
||||
}
|
||||
|
||||
// helperErrorf writes a diagnostic to stderr. The write result is ignored
|
||||
// deliberately: if stderr is gone there is nowhere left to report it, and the
|
||||
// exit code already carries the outcome the parent acts on.
|
||||
func helperErrorf(format string, args ...any) {
|
||||
_, _ = fmt.Fprintf(flagErrorOutput, format, args...)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunCodesearchHelper(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, "a.txt"), []byte("alpha needle omega\n"), 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "b.txt"), []byte("nothing here\n"), 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
indexPath := filepath.Join(t.TempDir(), "workspace.csearch")
|
||||
|
||||
t.Run("build writes an index sidecar", func(t *testing.T) {
|
||||
var out strings.Builder
|
||||
code := runCodesearchHelper([]string{"build", "--root", root, "--index", indexPath}, &out)
|
||||
if code != 0 {
|
||||
t.Fatalf("build exit code = %d, want 0", code)
|
||||
}
|
||||
if _, err := os.Stat(indexPath); err != nil {
|
||||
t.Fatalf("index sidecar not written: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("candidates emits the JSON contract the manager decodes", func(t *testing.T) {
|
||||
var out strings.Builder
|
||||
code := runCodesearchHelper([]string{
|
||||
"candidates", "--index", indexPath, "--pattern", "needle",
|
||||
}, &out)
|
||||
if code != 0 {
|
||||
t.Fatalf("candidates exit code = %d, want 0", code)
|
||||
}
|
||||
var files []string
|
||||
if err := json.Unmarshal([]byte(out.String()), &files); err != nil {
|
||||
t.Fatalf("decode candidates output %q: %v", out.String(), err)
|
||||
}
|
||||
if !slices.ContainsFunc(files, func(p string) bool {
|
||||
return strings.HasSuffix(p, "a.txt")
|
||||
}) {
|
||||
t.Errorf("candidates = %v, want the file containing the needle", files)
|
||||
}
|
||||
})
|
||||
|
||||
invalid := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{name: "no subcommand", args: nil},
|
||||
{name: "unknown subcommand", args: []string{"frobnicate"}},
|
||||
{name: "build without root", args: []string{"build", "--index", indexPath}},
|
||||
{name: "build without index", args: []string{"build", "--root", root}},
|
||||
{name: "candidates without index", args: []string{"candidates", "--pattern", "x"}},
|
||||
{name: "candidates without pattern", args: []string{"candidates", "--index", indexPath}},
|
||||
}
|
||||
for _, tc := range invalid {
|
||||
t.Run(tc.name+" is rejected", func(t *testing.T) {
|
||||
var out strings.Builder
|
||||
if code := runCodesearchHelper(tc.args, &out); code == 0 {
|
||||
t.Errorf("exit code = 0, want non-zero for %v", tc.args)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The manager shells out to argv[0] with this exact subcommand name, so a
|
||||
// rename on either side silently disables indexed search.
|
||||
func TestCodesearchHelperSubcommandIsRecognised(t *testing.T) {
|
||||
if !isCodesearchHelperArgs([]string{codesearchHelperCommand, "build"}) {
|
||||
t.Errorf("isCodesearchHelperArgs() did not recognise %q", codesearchHelperCommand)
|
||||
}
|
||||
if isCodesearchHelperArgs([]string{"-once"}) {
|
||||
t.Error("isCodesearchHelperArgs() claimed a normal daemon flag")
|
||||
}
|
||||
if isCodesearchHelperArgs(nil) {
|
||||
t.Error("isCodesearchHelperArgs() claimed an empty argument list")
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,12 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
// The codesearch helper is dispatched before the daemon's flags are
|
||||
// parsed: it is this same binary re-invoked as a short-lived child by
|
||||
// internal/indexing, and it must not touch config, the store or NATS.
|
||||
if args := os.Args[1:]; isCodesearchHelperArgs(args) {
|
||||
os.Exit(runCodesearchHelper(args[1:], os.Stdout))
|
||||
}
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user