diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 99ea95286..9087f0bc9 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -154,3 +154,4 @@ {"id":"int-30b8e857c7ac14ce8bfbac49283d7853","kind":"field_change","created_at":"2026-07-27T02:53:55.882577468Z","actor":"Sam Catlow","issue_id":"archie-core-rqp.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped: authorized /version reports installed gateway and runtime build versions from the composition root; menu/help parity covered; task check and scoped lint clean; fresh review found no blocking issues."}} {"id":"int-21fc57e924a09c3e2cc06dad0b9fc341","kind":"field_change","created_at":"2026-07-27T03:02:11.029169675Z","actor":"Sam Catlow","issue_id":"archie-core-rqp","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped: deployment-neutral /update with configured argv check/install adapters, gateway/runtime release sections, per-user exact-version persisted deferrals, recipient-bound expiring single-use callback actions, global install serialization, callback authorization, and truthful progress/failure. Webhook callback queries enabled. task check and scoped lint clean; adversarial review findings remediated."}} {"id":"int-0515875f328056cbb0888785d35497c9","kind":"field_change","created_at":"2026-07-27T12:11:14.316202683Z","actor":"Sam Catlow","issue_id":"archie-core-5dn","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Investigated local Hermes CLI and current Archie implementation; added the requested parity TODO checklist."}} +{"id":"int-e2b07b5c81dd19cabd9e2a18ff94f7f7","kind":"field_change","created_at":"2026-07-27T12:20:51.572157777Z","actor":"Sam Catlow","issue_id":"archie-core-sc5","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Implemented gateway.BuildSystemPrompt rendering internal/gateway/templates/archie.md.tpl: instruction precedence, core rules, communication rules, and blocks, with PersonaRegistry kept as the style layer on top. Tool inventory is derived from the same core.ToolSet passed to the model (cmd/archied/toolSummaries) so prompt and reality cannot drift; empty toolset renders an explicit 'no tools are available'. Tool metadata is markup-escaped and whitespace-flattened against forged tags and forged list entries. task check clean: vet, full go test ./... , golangci-lint 0 issues on changed packages, gofumpt clean. Commit 7fde716. NOT yet deployed - not pushed."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 2eeb8021c..1ab7d80eb 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -53,7 +53,8 @@ {"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-sc5","title":"Chat: real system prompt template for Archie (identity, tools, env)","description":"The chat agent's system prompt is the four-sentence static string in gateway.DefaultPersonas(). It carries no tool inventory, no environment/date block, and no instruction precedence, so the model invents its own capabilities -- it told Sam it 'only has the memory editing tool' and then offered to walk him through installing software it cannot install.\n\nTake the shape from tau: /work/apps/tau/internal/agent/templates/agent.md.tpl renders an agent body plus \u003ctools\u003e, \u003cguidelines\u003e, \u003cproject_context\u003e and \u003cenv\u003e blocks, and /work/apps/tau/internal/agent/spec/templates/tau.agent.md supplies identity, instruction precedence, core rules, communication rules and confirmation boundaries.\n\nKeep the existing PersonaRegistry as the style layer; the template is the substrate it renders into.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-27T12:14:08Z","created_by":"Sam Catlow","updated_at":"2026-07-27T12:14:08Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-4we","title":"Port tau internal/indexing (codesearch) into archie-core","description":"First slice of the tau cherry-pick strategy. Copy-and-mutate (NOT extract to pkg/ - Sam's decision: exporting would force designing metrics/session/logger seams upfront before archie-core knows which it wants differently).\n\ntau/internal/indexing is the cheapest high-value lift: 512 LoC, one file, and its only tau coupling is 3 calls to config.WorkspaceIndexDir()/WorkspaceIndexDBPath(). Nothing else in tau imports it.\n\nMutations: replace the global config path helpers with explicit constructor params (archie-core passes config, no globals); add the workspace-codesearch helper subcommand to archied since the manager deliberately runs google/codesearch in a child process (upstream fatal exits + mmap leaks must not kill the daemon).\n\nEach lifted file carries a provenance header (source path + tau commit) so a future refresh is a diff, not archaeology.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-27T13:41:58Z","created_by":"Sam Catlow","updated_at":"2026-07-27T13:41:58Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-sc5","title":"Chat: real system prompt template for Archie (identity, tools, env)","description":"The chat agent's system prompt is the four-sentence static string in gateway.DefaultPersonas(). It carries no tool inventory, no environment/date block, and no instruction precedence, so the model invents its own capabilities -- it told Sam it 'only has the memory editing tool' and then offered to walk him through installing software it cannot install.\n\nTake the shape from tau: /work/apps/tau/internal/agent/templates/agent.md.tpl renders an agent body plus \u003ctools\u003e, \u003cguidelines\u003e, \u003cproject_context\u003e and \u003cenv\u003e blocks, and /work/apps/tau/internal/agent/spec/templates/tau.agent.md supplies identity, instruction precedence, core rules, communication rules and confirmation boundaries.\n\nKeep the existing PersonaRegistry as the style layer; the template is the substrate it renders into.","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-27T12:14:08Z","created_by":"Sam Catlow","updated_at":"2026-07-27T12:20:52Z","closed_at":"2026-07-27T12:20:52Z","close_reason":"Implemented gateway.BuildSystemPrompt rendering internal/gateway/templates/archie.md.tpl: instruction precedence, core rules, communication rules, \u003ctools\u003e and \u003cenv\u003e blocks, with PersonaRegistry kept as the style layer on top. Tool inventory is derived from the same core.ToolSet passed to the model (cmd/archied/toolSummaries) so prompt and reality cannot drift; empty toolset renders an explicit 'no tools are available'. Tool metadata is markup-escaped and whitespace-flattened against forged tags and forged list entries. task check clean: vet, full go test ./... , golangci-lint 0 issues on changed packages, gofumpt clean. Commit 7fde716. NOT yet deployed - not pushed.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-qnm","title":"Telegram: remove task approval from the public command surface","description":"Existing /approve [identity=name] \u003ctask-id\u003e was inherited as chat-task lifecycle control, but Sam explicitly states task approvals are not a product requirement. Reserve /approve exclusively for dangerous-command approval. Remove task approval from Telegram command menu/help/router/public UX; retain or remove internal waiting_human task mechanics only after verifying workflow callers. Do not repurpose the command until the dangerous-command approval model (archie-core-alm.6) exists.","acceptance_criteria":"Telegram no longer advertises or accepts task approval via /approve; no documentation/help describes task approvals; task lifecycle code is not broken for existing non-Telegram workflow paths; /approve remains unclaimed or is implemented only for the approved dangerous-command design.","status":"open","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-27T09:00:56Z","created_by":"Sam Catlow","updated_at":"2026-07-27T09:00:56Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-alm.6","title":"Telegram: controlled execution and checkpoint commands","description":"Design /rollback [number] filesystem checkpoints, /stop background process termination, /approve and /deny for dangerous commands. /approve is RESERVED exclusively for dangerous-command approval; it must not be interpreted as task approval. The pending-command UX is inline selection buttons: Approve this time, Approve Permanently, Deny. Define the exact policy scope/lifetime for permanent approval, callback authorization, expiry, audit persistence, and cancellation. Requires a real sandbox/process/checkpoint authority; do not create commands that claim control over host processes or filesystem state Archie does not own.","acceptance_criteria":"For every pending dangerous command, Telegram renders authorized inline buttons exactly representing Approve this time, Approve Permanently, and Deny. Callbacks are recipient-bound, expiring, single-use, auditable, and cannot authorize a changed command. Permanent approval scope/lifetime is explicit. /approve exclusively controls this policy; /deny controls the same policy. Authority boundaries match actual sandbox/process ownership; tests cover authorization, expiry, replay, denial, and failure.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-27T08:59:54Z","created_by":"Sam Catlow","updated_at":"2026-07-27T09:01:52Z","dependencies":[{"issue_id":"archie-core-alm.6","depends_on_id":"archie-core-alm","type":"parent-child","created_at":"2026-07-27T18:59:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-alm.4","title":"Telegram: model scope and personality selection","description":"Extend /model to support Hermes-like /model [model] [--provider name] [--global|--session] [--refresh], with persisted default behaviour. Add /personality [name] for predefined personalities. Design global-versus-session ownership, provider filtering, persistence, refresh semantics, validity when credits are exhausted, and interaction with existing model selector before implementation.","acceptance_criteria":"/model scope and persistence are explicit and tested; provider/model selection cannot be ambiguous; /personality operates on a defined catalog and session scope; existing Telegram selector behaviour remains coherent.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-27T08:59:53Z","created_by":"Sam Catlow","updated_at":"2026-07-27T08:59:53Z","dependencies":[{"issue_id":"archie-core-alm.4","depends_on_id":"archie-core-alm","type":"parent-child","created_at":"2026-07-27T18:59:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/codesearch.go b/cmd/archied/codesearch.go new file mode 100644 index 000000000..cef7433ee --- /dev/null +++ b/cmd/archied/codesearch.go @@ -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...) +} diff --git a/cmd/archied/codesearch_test.go b/cmd/archied/codesearch_test.go new file mode 100644 index 000000000..023469277 --- /dev/null +++ b/cmd/archied/codesearch_test.go @@ -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") + } +} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 11672a6d8..dac87a7c2 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -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()) } diff --git a/go.mod b/go.mod index cba61d087..e07f05bcb 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,7 @@ require ( github.com/go-fed/httpsig v1.1.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/codesearch v1.3.0-rc.1 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/go-tpm v0.9.8 // indirect github.com/google/uuid v1.6.0 // indirect diff --git a/go.sum b/go.sum index 90ed8e105..d2e788d28 100644 --- a/go.sum +++ b/go.sum @@ -41,6 +41,8 @@ github.com/go-telegram/bot v1.18.0 h1:yQzv437DY42SYTPBY48RinAvwbmf1ox5QICskIYWCD github.com/go-telegram/bot v1.18.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= github.com/go-telegram/bot v1.22.0 h1:zK29OoTYMmR5emJrCtGa2SjaGleeZiUB/C1i7kc2lXE= github.com/go-telegram/bot v1.22.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= +github.com/google/codesearch v1.3.0-rc.1 h1:vSFGuF5wS3sjimuLzqPG+PGjWQ9VvEtPFbxdZD7YuuQ= +github.com/google/codesearch v1.3.0-rc.1/go.mod h1:hKdpx7wOsvk2WLT/D6NLPxFeLT8jKCehZu21JpA2rIY= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= diff --git a/internal/indexing/codesearch.go b/internal/indexing/codesearch.go new file mode 100644 index 000000000..b244863e7 --- /dev/null +++ b/internal/indexing/codesearch.go @@ -0,0 +1,564 @@ +// Package indexing provides language-neutral workspace text indexing. +// +// Ported from tau: internal/indexing/codesearch.go @ 4893818d0c76 (2026-07-13). +// Mutations from the original: +// - tau resolved its index paths from process-global config helpers +// (config.WorkspaceIndexDir/WorkspaceIndexDBPath). archied passes config +// explicitly, so paths arrive via [Config] instead. +// - the helper subcommand is archied's rather than tau's +// (cmd/archied/codesearch.go). +// - deferred db.Close calls are explicitly discarded; archie-core runs +// errcheck, tau does not. +// +// Refresh from upstream by diffing against that path and commit. +package indexing + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "regexp/syntax" + "slices" + "strings" + "time" + + "github.com/google/codesearch/index" + "github.com/google/uuid" + + _ "modernc.org/sqlite" +) + +const ( + // MaxCandidateFiles bounds helper output and grep argv construction. + MaxCandidateFiles = 2000 + maxCandidateArgBytes = 24 * 1024 + buildTimeout = 10 * time.Minute + metadataTimeout = 5 * time.Second +) + +// CandidateProvider returns files which may match a grep query. A false +// handled result tells the caller to use its normal unindexed search path. +type CandidateProvider interface { + Candidates(context.Context, string, bool, bool) ([]string, bool) +} + +// Manager owns the workspace index lifecycle. The codesearch implementation +// runs in a child Tau process so upstream fatal exits and mmap lifetime cannot +// terminate or leak inside the interactive agent process. +type Manager struct { + root string + indexPath string + dbPath string + runner helperRunner +} + +type helperRunner interface { + Build(context.Context, string, string) error + Candidates(context.Context, string, string, bool, bool) ([]string, error) +} + +type processRunner struct{} + +// Config locates the index storage for a Manager. +// +// tau derived these from process-global helpers. archied owns its paths in +// daemon config and passes them down, so they are parameters here: two +// daemons on one host (archie and winter) must not share one index. +type Config struct { + // IndexDir holds the mmap-friendly codesearch sidecar files. + IndexDir string + // DBPath is the SQLite database holding index lifecycle metadata. + DBPath string +} + +// DefaultConfig derives index paths from a daemon work directory. +func DefaultConfig(workDir string) Config { + return Config{ + IndexDir: filepath.Join(workDir, "indexes"), + DBPath: filepath.Join(workDir, "workspace-indexes.db"), + } +} + +// NewManager prepares lifecycle storage and starts an asynchronous atomic +// refresh. An existing index remains available while the refresh runs. +func NewManager(ctx context.Context, cfg Config, root string) (*Manager, error) { + if strings.TrimSpace(cfg.IndexDir) == "" { + return nil, fmt.Errorf("indexing: IndexDir is required") + } + if strings.TrimSpace(cfg.DBPath) == "" { + return nil, fmt.Errorf("indexing: DBPath is required") + } + absRoot, err := filepath.Abs(root) + if err != nil { + return nil, fmt.Errorf("resolve workspace root: %w", err) + } + if err := os.MkdirAll(cfg.IndexDir, 0o700); err != nil { + return nil, fmt.Errorf("create workspace index directory: %w", err) + } + m := &Manager{ + root: filepath.Clean(absRoot), + indexPath: filepath.Join(cfg.IndexDir, workspaceKey(absRoot)+".csearch"), + dbPath: cfg.DBPath, + runner: processRunner{}, + } + if err := m.ensureSchema(ctx); err != nil { + return nil, err + } + m.refreshAsync(ctx) + return m, nil +} + +// Candidates implements the tools.GrepIndex contract. +func (m *Manager) Candidates(ctx context.Context, pattern string, literal, caseSensitive bool) ([]string, bool) { + state, err := m.state(ctx) + if err != nil || state.IndexedAt.IsZero() { + return nil, false + } + if _, err := os.Stat(state.IndexPath); err != nil { + return nil, false + } + files, err := m.runner.Candidates(ctx, state.IndexPath, pattern, literal, caseSensitive) + if err != nil { + return nil, false + } + + // The sidecar is a snapshot. Include files changed or created since the + // build began so indexed search cannot miss live workspace edits. + workspaceFiles, err := WorkspaceFiles(ctx, m.root) + if err != nil { + return nil, false + } + changedFiles := changedGitFiles(ctx, m.root) + seen := make(map[string]struct{}, len(files)) + merged := make([]string, 0, len(files)) + argumentBytes := 0 + add := func(path string) { + path, ok := confinedWorkspaceFile(m.root, path) + if !ok { + return + } + if _, ok := seen[path]; ok { + return + } + seen[path] = struct{}{} + merged = append(merged, path) + argumentBytes += len(path) + 1 + } + for _, path := range files { + add(path) + } + for _, path := range workspaceFiles { + info, statErr := os.Stat(path) + _, changed := changedFiles[path] + if statErr == nil && (changed || !info.ModTime().Before(state.IndexedAt)) { + add(path) + } + } + if len(merged) == 0 || len(merged) > MaxCandidateFiles || argumentBytes > maxCandidateArgBytes { + return nil, false + } + slices.Sort(merged) + return merged, true +} + +func changedGitFiles(ctx context.Context, root string) map[string]struct{} { + changed := map[string]struct{}{} + commands := [][]string{ + {"-C", root, "ls-files", "-m", "-o", "--exclude-standard", "-z"}, + {"-C", root, "diff", "--cached", "--name-only", "--diff-filter=ACMR", "-z"}, + } + for _, args := range commands { + out, err := exec.CommandContext(ctx, "git", args...).Output() + if err != nil { + return map[string]struct{}{} + } + for name := range strings.SplitSeq(string(out), "\x00") { + if name != "" { + path := filepath.Join(root, filepath.FromSlash(name)) + if confined, ok := confinedWorkspaceFile(root, path); ok { + changed[confined] = struct{}{} + } + } + } + } + return changed +} + +type indexState struct { + IndexPath string + IndexedAt time.Time +} + +func (m *Manager) refreshAsync(parent context.Context) { + go func() { + ctx, cancel := context.WithTimeout(parent, buildTimeout) + defer cancel() + startedAt := time.Now().UTC() + buildID := uuid.NewString() + previous, _ := m.state(ctx) + claimed, err := m.claimBuild(ctx, startedAt, buildID) + if err != nil || !claimed { + return + } + finalPath := m.indexPath + "." + buildID + tmp := finalPath + ".tmp" + _ = os.Remove(tmp) + if err := m.runner.Build(ctx, m.root, tmp); err != nil { + _ = os.Remove(tmp) + m.finishBuild(parent, buildID, "error", time.Time{}, "", err.Error()) + return + } + if err := os.Rename(tmp, finalPath); err != nil { + _ = os.Remove(tmp) + m.finishBuild(parent, buildID, "error", time.Time{}, "", err.Error()) + return + } + if !m.finishBuild(parent, buildID, "ready", startedAt, finalPath, "") { + _ = os.Remove(finalPath) + return + } + if previous.IndexPath != "" && previous.IndexPath != finalPath && + (previous.IndexPath == m.indexPath || strings.HasPrefix(previous.IndexPath, m.indexPath+".")) { + _ = os.Remove(previous.IndexPath) + } + }() +} + +func (m *Manager) finishBuild(parent context.Context, buildID, status string, indexedAt time.Time, indexPath, lastError string) bool { + ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), metadataTimeout) + defer cancel() + db, err := openIndexDB(m.dbPath) + if err != nil { + return false + } + // Each helper opens its own single-connection handle and the write has + // already been committed by the time this runs, so a Close error carries + // no recoverable information. + defer func() { _ = db.Close() }() + indexed := "" + if !indexedAt.IsZero() { + indexed = indexedAt.Format(time.RFC3339Nano) + } + result, err := db.ExecContext(ctx, `UPDATE workspace_indexes SET + index_path=CASE WHEN ? = 'ready' THEN ? ELSE index_path END, + status=?, indexed_at=CASE WHEN ? = 'ready' THEN ? ELSE indexed_at END, + last_error=?, updated_at=?, generation=generation + CASE WHEN ? = 'ready' THEN 1 ELSE 0 END + WHERE root=? AND build_id=?`, status, indexPath, status, status, indexed, + lastError, time.Now().UTC().Format(time.RFC3339Nano), status, m.root, buildID) + if err != nil { + return false + } + rows, err := result.RowsAffected() + return err == nil && rows == 1 +} + +func (m *Manager) claimBuild(ctx context.Context, startedAt time.Time, buildID string) (bool, error) { + db, err := openIndexDB(m.dbPath) + if err != nil { + return false, err + } + // Each helper opens its own single-connection handle and the write has + // already been committed by the time this runs, so a Close error carries + // no recoverable information. + defer func() { _ = db.Close() }() + cutoff := startedAt.Add(-buildTimeout).Format(time.RFC3339Nano) + result, err := db.ExecContext(ctx, `INSERT INTO workspace_indexes (root, index_path, status, indexed_at, build_started_at, build_id, last_error, updated_at) + VALUES (?, ?, 'building', '', ?, ?, '', ?) + ON CONFLICT(root) DO UPDATE SET status='building', + build_started_at=excluded.build_started_at, build_id=excluded.build_id, last_error='', updated_at=excluded.updated_at + WHERE workspace_indexes.status != 'building' OR workspace_indexes.updated_at < ?`, + m.root, m.indexPath, startedAt.Format(time.RFC3339Nano), buildID, startedAt.Format(time.RFC3339Nano), cutoff) + if err != nil { + return false, fmt.Errorf("claim workspace index build: %w", err) + } + rows, err := result.RowsAffected() + if err != nil { + return false, fmt.Errorf("inspect workspace index build claim: %w", err) + } + return rows > 0, nil +} + +func (m *Manager) ensureSchema(ctx context.Context) error { + db, err := openIndexDB(m.dbPath) + if err != nil { + return err + } + // Each helper opens its own single-connection handle and the write has + // already been committed by the time this runs, so a Close error carries + // no recoverable information. + defer func() { _ = db.Close() }() + _, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS workspace_indexes ( + root TEXT PRIMARY KEY, + index_path TEXT NOT NULL, + status TEXT NOT NULL, + format_version TEXT NOT NULL DEFAULT 'codesearch-v2', + generation INTEGER NOT NULL DEFAULT 0, + indexed_at TEXT NOT NULL DEFAULT '', + build_started_at TEXT NOT NULL DEFAULT '', + build_id TEXT NOT NULL DEFAULT '', + last_error TEXT NOT NULL DEFAULT '', + updated_at TEXT NOT NULL + )`) + if err != nil { + return fmt.Errorf("create workspace index metadata: %w", err) + } + for _, migration := range []string{ + `ALTER TABLE workspace_indexes ADD COLUMN format_version TEXT NOT NULL DEFAULT 'codesearch-v2'`, + `ALTER TABLE workspace_indexes ADD COLUMN generation INTEGER NOT NULL DEFAULT 0`, + `ALTER TABLE workspace_indexes ADD COLUMN build_started_at TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE workspace_indexes ADD COLUMN build_id TEXT NOT NULL DEFAULT ''`, + } { + if _, migrationErr := db.ExecContext(ctx, migration); migrationErr != nil && !strings.Contains(migrationErr.Error(), "duplicate column name") { + return fmt.Errorf("migrate workspace index metadata: %w", migrationErr) + } + } + return nil +} + +func (m *Manager) state(ctx context.Context) (indexState, error) { + db, err := openIndexDB(m.dbPath) + if err != nil { + return indexState{}, err + } + // Each helper opens its own single-connection handle and the write has + // already been committed by the time this runs, so a Close error carries + // no recoverable information. + defer func() { _ = db.Close() }() + var indexed, indexPath string + err = db.QueryRowContext(ctx, `SELECT index_path, indexed_at FROM workspace_indexes WHERE root = ?`, m.root).Scan(&indexPath, &indexed) + if errors.Is(err, sql.ErrNoRows) { + return indexState{}, nil + } + if err != nil { + return indexState{}, fmt.Errorf("read workspace index metadata: %w", err) + } + at, _ := time.Parse(time.RFC3339Nano, indexed) + return indexState{IndexPath: indexPath, IndexedAt: at}, nil +} + +func (m *Manager) setState(ctx context.Context, status string, indexedAt time.Time, lastError string) error { + db, err := openIndexDB(m.dbPath) + if err != nil { + return err + } + // Each helper opens its own single-connection handle and the write has + // already been committed by the time this runs, so a Close error carries + // no recoverable information. + defer func() { _ = db.Close() }() + indexed := "" + if !indexedAt.IsZero() { + indexed = indexedAt.Format(time.RFC3339Nano) + } else if current, stateErr := m.state(ctx); stateErr == nil && !current.IndexedAt.IsZero() { + indexed = current.IndexedAt.Format(time.RFC3339Nano) + } + _, err = db.ExecContext(ctx, `INSERT INTO workspace_indexes (root, index_path, status, indexed_at, last_error, updated_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(root) DO UPDATE SET index_path=excluded.index_path, status=excluded.status, + indexed_at=excluded.indexed_at, last_error=excluded.last_error, updated_at=excluded.updated_at, + generation=workspace_indexes.generation + CASE WHEN excluded.status = 'ready' THEN 1 ELSE 0 END`, + m.root, m.indexPath, status, indexed, lastError, time.Now().UTC().Format(time.RFC3339Nano)) + if err != nil { + return fmt.Errorf("write workspace index metadata: %w", err) + } + return nil +} + +func openIndexDB(path string) (*sql.DB, error) { + // modernc.org/sqlite only applies pragmas passed via repeated _pragma + // params; unrecognized keys like _journal_mode/_busy_timeout are + // silently ignored, which previously left the busy timeout at 0 and + // caused SQLITE_BUSY on any lock contention instead of a bounded wait. + db, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)") + if err != nil { + return nil, fmt.Errorf("open workspace index metadata: %w", err) + } + db.SetMaxOpenConns(1) + return db, nil +} + +func workspaceKey(root string) string { + sum := sha256.Sum256([]byte(filepath.Clean(root))) + return hex.EncodeToString(sum[:12]) +} + +func (processRunner) Build(ctx context.Context, root, target string) error { + _, err := runHelper(ctx, "build", "--root", root, "--index", target) + return err +} + +func (processRunner) Candidates(ctx context.Context, indexPath, pattern string, literal, caseSensitive bool) ([]string, error) { + args := []string{"candidates", "--index", indexPath, "--pattern", pattern} + if literal { + args = append(args, "--literal") + } + if caseSensitive { + args = append(args, "--case-sensitive") + } + out, err := runHelper(ctx, args...) + if err != nil { + return nil, err + } + var files []string + if err := json.Unmarshal(out, &files); err != nil { + return nil, fmt.Errorf("decode codesearch candidates: %w", err) + } + return files, nil +} + +func runHelper(ctx context.Context, args ...string) ([]byte, error) { + executable, err := os.Executable() + if err != nil { + return nil, fmt.Errorf("locate archied executable: %w", err) + } + cmd := exec.CommandContext(ctx, executable, append([]string{"workspace-codesearch"}, args...)...) + out, err := cmd.Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return nil, fmt.Errorf("codesearch helper: %s", strings.TrimSpace(string(exitErr.Stderr))) + } + return nil, fmt.Errorf("run codesearch helper: %w", err) + } + return out, nil +} + +// BuildIndex creates a codesearch sidecar for root. It is called only inside +// the isolated helper process. +func BuildIndex(ctx context.Context, root, target string) error { + files, err := WorkspaceFiles(ctx, root) + if err != nil { + return err + } + w := index.Create(target) + w.AddRoots([]index.Path{index.MakePath(root)}) + for _, path := range files { + if err := w.AddFile(path); err != nil { + continue + } + } + w.Flush() + return nil +} + +// IndexCandidates returns the conservative trigram candidate set. It is +// called only inside the isolated helper process. +func IndexCandidates(indexPath, pattern string, literal, caseSensitive bool) (files []string, err error) { + defer func() { + if recovered := recover(); recovered != nil { + files = nil + err = fmt.Errorf("open codesearch index: %v", recovered) + } + }() + if literal { + pattern = regexp.QuoteMeta(pattern) + } + if !caseSensitive && !hasUppercase(pattern) { + pattern = "(?i:" + pattern + ")" + } + re, err := syntax.Parse(pattern, syntax.Perl) + if err != nil { + return nil, fmt.Errorf("parse search pattern: %w", err) + } + ix := index.Open(indexPath) + ids := ix.PostingQuery(index.RegexpQuery(re)) + files = make([]string, 0, len(ids)) + for _, id := range ids { + files = append(files, ix.Name(id).String()) + } + return files, nil +} + +// WorkspaceFiles lists searchable workspace files, preferring Git's ignore +// semantics and falling back to a conservative filesystem walk. +func WorkspaceFiles(ctx context.Context, root string) ([]string, error) { + cmd := exec.CommandContext(ctx, "git", "-C", root, "ls-files", "-co", "--exclude-standard", "-z") + out, err := cmd.Output() + if err == nil { + parts := strings.Split(string(out), "\x00") + files := make([]string, 0, len(parts)) + for _, part := range parts { + if part != "" { + path := filepath.Join(root, filepath.FromSlash(part)) + if confined, ok := confinedWorkspaceFile(root, path); ok { + files = append(files, confined) + } + } + } + slices.Sort(files) + return files, nil + } + + var files []string + err = filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return nil + } + if path != root && strings.HasPrefix(entry.Name(), ".") { + if entry.IsDir() { + return filepath.SkipDir + } + return nil + } + if !entry.IsDir() && entry.Type().IsRegular() { + if confined, ok := confinedWorkspaceFile(root, path); ok { + files = append(files, confined) + } + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("walk workspace files: %w", err) + } + slices.Sort(files) + return files, nil +} + +func confinedWorkspaceFile(root, path string) (string, bool) { + absRoot, err := filepath.Abs(root) + if err != nil { + return "", false + } + absPath, err := filepath.Abs(path) + if err != nil { + return "", false + } + // Reject a symlink at the final component before resolving parent links. + info, err := os.Lstat(absPath) + if err != nil || !info.Mode().IsRegular() { + return "", false + } + resolvedRoot, err := filepath.EvalSymlinks(absRoot) + if err != nil { + return "", false + } + resolvedPath, err := filepath.EvalSymlinks(absPath) + if err != nil { + return "", false + } + rel, err := filepath.Rel(resolvedRoot, resolvedPath) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + resolvedInfo, err := os.Lstat(resolvedPath) + if err != nil || !resolvedInfo.Mode().IsRegular() { + return "", false + } + return filepath.Clean(resolvedPath), true +} + +func hasUppercase(value string) bool { + for _, r := range value { + if r >= 'A' && r <= 'Z' { + return true + } + } + return false +} diff --git a/internal/indexing/codesearch_test.go b/internal/indexing/codesearch_test.go new file mode 100644 index 000000000..8a2d2b7dc --- /dev/null +++ b/internal/indexing/codesearch_test.go @@ -0,0 +1,250 @@ +// Ported from tau: internal/indexing/codesearch_test.go @ 4893818d0c76 (2026-07-13). +package indexing + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + "time" +) + +func TestBuildIndexAndCandidates(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "a.txt", "alpha needle omega\n") + writeTestFile(t, root, "b.txt", "nothing here\n") + indexPath := filepath.Join(t.TempDir(), "workspace.csearch") + + if err := BuildIndex(context.Background(), root, indexPath); err != nil { + t.Fatalf("BuildIndex() error = %v", err) + } + files, err := IndexCandidates(indexPath, "needle", false, false) + if err != nil { + t.Fatalf("IndexCandidates() error = %v", err) + } + if len(files) != 1 || files[0] != filepath.Join(root, "a.txt") { + t.Fatalf("candidates = %v", files) + } +} + +func TestWorkspaceFilesRespectsGitIgnore(t *testing.T) { + root := t.TempDir() + runGit(t, root, "init", "-q") + writeTestFile(t, root, ".gitignore", "ignored.txt\n") + writeTestFile(t, root, "tracked.txt", "tracked\n") + writeTestFile(t, root, "untracked.txt", "untracked\n") + writeTestFile(t, root, "ignored.txt", "ignored\n") + runGit(t, root, "add", ".gitignore", "tracked.txt") + + files, err := WorkspaceFiles(context.Background(), root) + if err != nil { + t.Fatalf("WorkspaceFiles() error = %v", err) + } + if slices.Contains(files, filepath.Join(root, "ignored.txt")) { + t.Fatalf("ignored file returned: %v", files) + } + for _, name := range []string{"tracked.txt", "untracked.txt"} { + if !slices.Contains(files, filepath.Join(root, name)) { + t.Fatalf("%s missing from %v", name, files) + } + } +} + +func TestWorkspaceFilesRejectsTrackedSymlinkOutsideRoot(t *testing.T) { + root := t.TempDir() + runGit(t, root, "init", "-q") + outside := filepath.Join(t.TempDir(), "secret.txt") + if err := os.WriteFile(outside, []byte("secret"), 0o600); err != nil { + t.Fatal(err) + } + link := filepath.Join(root, "link.txt") + if err := os.Symlink(outside, link); err != nil { + t.Fatal(err) + } + runGit(t, root, "add", "link.txt") + + files, err := WorkspaceFiles(context.Background(), root) + if err != nil { + t.Fatal(err) + } + _, accepted := confinedWorkspaceFile(root, link) + if slices.Contains(files, link) || accepted { + t.Fatalf("outside symlink accepted: %v", files) + } +} + +func TestConfinedWorkspaceFileRejectsIntermediateSymlinkEscape(t *testing.T) { + root := t.TempDir() + outside := t.TempDir() + writeTestFile(t, outside, "secret.txt", "secret") + if err := os.Symlink(outside, filepath.Join(root, "linkdir")); err != nil { + t.Fatal(err) + } + if path, ok := confinedWorkspaceFile(root, filepath.Join(root, "linkdir", "secret.txt")); ok { + t.Fatalf("intermediate symlink escape accepted as %s", path) + } +} + +func TestManagerCandidatesIncludeFilesChangedSinceSnapshot(t *testing.T) { + root := t.TempDir() + runGit(t, root, "init", "-q") + oldPath := filepath.Join(root, "old.txt") + newPath := filepath.Join(root, "new.txt") + writeTestFile(t, root, "old.txt", "old\n") + runGit(t, root, "add", "old.txt") + indexedAt := time.Now().UTC().Add(-time.Second) + writeTestFile(t, root, "new.txt", "new\n") + staleTime := indexedAt.Add(-time.Hour) + if err := os.Chtimes(newPath, staleTime, staleTime); err != nil { + t.Fatal(err) + } + indexPath := filepath.Join(t.TempDir(), "workspace.csearch") + writeTestFile(t, filepath.Dir(indexPath), filepath.Base(indexPath), "placeholder") + outside := filepath.Join(t.TempDir(), "outside.txt") + if err := os.WriteFile(outside, []byte("outside"), 0o600); err != nil { + t.Fatal(err) + } + dbPath := filepath.Join(t.TempDir(), "indexes.db") + m := &Manager{root: root, indexPath: indexPath, dbPath: dbPath, runner: fakeRunner{files: []string{oldPath, outside}}} + if err := m.ensureSchema(context.Background()); err != nil { + t.Fatal(err) + } + if err := m.setState(context.Background(), "ready", indexedAt, ""); err != nil { + t.Fatal(err) + } + + files, ok := m.Candidates(context.Background(), "new", false, false) + if !ok || !slices.Contains(files, oldPath) || !slices.Contains(files, newPath) { + t.Fatalf("Candidates() = %v, %v", files, ok) + } + if slices.Contains(files, outside) { + t.Fatalf("outside candidate accepted: %v", files) + } +} + +func TestManagerRefreshBuildsAtomicallyAndRecordsGeneration(t *testing.T) { + root := t.TempDir() + dir := t.TempDir() + m := &Manager{ + root: root, indexPath: filepath.Join(dir, "workspace.csearch"), + dbPath: filepath.Join(dir, "indexes.db"), runner: writingRunner{}, + } + if err := m.ensureSchema(context.Background()); err != nil { + t.Fatal(err) + } + ctx := t.Context() + m.refreshAsync(ctx) + + // Poll for the async build to complete. Use a deadline longer than SQLite's + // busy timeout (5 s) so a contended CI runner doesn't trigger a false timeout. + deadline := time.Now().Add(8 * time.Second) + var installedPath string + for { + state, stateErr := m.state(context.Background()) + if stateErr == nil && !state.IndexedAt.IsZero() { + if _, err := os.Stat(state.IndexPath); err == nil { + installedPath = state.IndexPath + break + } + } + // If the goroutine errored, fail fast with the last error. + if stateErr == nil && state.IndexedAt.IsZero() { + // Check if status indicates an error. + db, dbErr := openIndexDB(m.dbPath) + if dbErr == nil { + var status, lastErr string + _ = db.QueryRowContext(context.Background(), + `SELECT status, last_error FROM workspace_indexes WHERE root = ?`, m.root).Scan(&status, &lastErr) + _ = db.Close() + if status == "error" { + t.Fatalf("build failed: %s", lastErr) + } + } + } + if time.Now().After(deadline) { + t.Fatal("index was not atomically installed") + } + time.Sleep(10 * time.Millisecond) + } + if installedPath == m.indexPath { + t.Fatalf("build did not install a generation-specific sidecar: %s", installedPath) + } + db, err := openIndexDB(m.dbPath) + if err != nil { + t.Fatal(err) + } + defer func() { _ = db.Close() }() + var status string + var generation int + if err := db.QueryRowContext(context.Background(), `SELECT status, generation FROM workspace_indexes WHERE root = ?`, root).Scan(&status, &generation); err != nil { + t.Fatal(err) + } + if status != "ready" || generation != 1 { + t.Fatalf("state = %q generation %d", status, generation) + } +} + +func TestStaleBuilderCannotCompleteNewerLease(t *testing.T) { + dir := t.TempDir() + m := &Manager{root: t.TempDir(), indexPath: filepath.Join(dir, "workspace.csearch"), dbPath: filepath.Join(dir, "indexes.db")} + if err := m.ensureSchema(context.Background()); err != nil { + t.Fatal(err) + } + oldStart := time.Now().UTC().Add(-2 * buildTimeout) + claimed, err := m.claimBuild(context.Background(), oldStart, "build-a") + if err != nil || !claimed { + t.Fatalf("first claim = %v, %v", claimed, err) + } + newStart := time.Now().UTC() + claimed, err = m.claimBuild(context.Background(), newStart, "build-b") + if err != nil || !claimed { + t.Fatalf("replacement claim = %v, %v", claimed, err) + } + if m.finishBuild(context.Background(), "build-a", "ready", oldStart, filepath.Join(dir, "a"), "") { + t.Fatal("stale builder completed replacement lease") + } + pathB := filepath.Join(dir, "b") + if !m.finishBuild(context.Background(), "build-b", "ready", newStart, pathB, "") { + t.Fatal("current builder could not complete lease") + } + state, err := m.state(context.Background()) + if err != nil || state.IndexPath != pathB { + t.Fatalf("state = %#v, %v", state, err) + } +} + +type fakeRunner struct { + files []string +} + +type writingRunner struct{} + +func (writingRunner) Build(_ context.Context, _, target string) error { + return os.WriteFile(target, []byte("index"), 0o600) +} + +func (writingRunner) Candidates(context.Context, string, string, bool, bool) ([]string, error) { + return nil, nil +} + +func (f fakeRunner) Build(context.Context, string, string) error { return nil } +func (f fakeRunner) Candidates(context.Context, string, string, bool, bool) ([]string, error) { + return slices.Clone(f.files), nil +} + +func writeTestFile(t *testing.T, dir, name, content string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } +} + +func runGit(t *testing.T, dir string, args ...string) { + t.Helper() + cmd := exec.CommandContext(context.Background(), "git", append([]string{"-C", dir}, args...)...) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } +}