Files
archie/internal/tools/builtin/read_test.go
T
sam e03cef17c9 feat(tools): lift tau's file and shell tools into the tool registry
The chat agent had two tools -- memory_edit and skill_activate -- so it
could not read a file, search a tree or run a command. ai-sdk's runtime
already drives a tool loop for it (MaxSteps 8, toolExecute wired as the
executor), so the loop was never the missing piece: the registry was empty
of anything useful.

Lifted from tau internal/agent/tools at commit f5289ea, per the recorded
copy-and-mutate strategy: every file carries a provenance header naming its
tau source path, the commit, and the mutations made, so refreshing from
upstream is a diff rather than archaeology.

  internal/tools/builtin/          the lifted tools, ~3.1k lines
  internal/tools/provider/builtin/ the adapter to tools.ToolEntry

Six tools: read, write, edit, shell, grep, find. Tau's own tests came with
them and pass unmodified, which is the evidence that the lift is faithful.

Deliberately not lifted:
  - agent.go (1214 lines): subagent spawning, and the only real coupling in
    the package -- 10 tau packages including chat, sessions, store and
    registry. Nothing the chat agent needs to do work.
  - skill.go: depends on tau's skills package; archie has internal/skill and
    already exposes skill_activate.
  - docs.go: serves tau's own embedded documentation via tau/docs.

Not lifting the coordinator either. It is tau's agent loop (6.4k lines over
ten packages) and archie already has one in the ai-sdk runtime; porting it
would leave two loops competing. Its cancellation and tool events are worth
having, but they are a few hundred lines built against the existing path
rather than six thousand lifted onto a second one.

The adapter bridges two shape differences: archie hands handlers decoded
arguments where tau's executor takes raw JSON, and tau reports tool-level
failure in Result.IsError rather than as an error -- surfaced as a real
error so the runtime and the guardrail engine both see it. Tools are
classified idempotent or mutating for guardrails and budgets; that is
categorisation, not a jail.

chat.workspace roots the tools and defaults to empty, which registers none
of them. They read, write and execute, so the directory has to be a
deliberate choice rather than whatever the daemon started in -- in the
container that is /.

Verified: go build, go vet, gofmt clean; full suite passes.
2026-07-29 15:46:21 +10:00

213 lines
6.8 KiB
Go

package builtin
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func execRead(t *testing.T, cwd string, params string) Result {
t.Helper()
tool := NewReadTool(cwd, nil)
res, err := tool.Execute(context.Background(), json.RawMessage(params), nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return res
}
func TestReadTool_RawContentNoGutter(t *testing.T) {
tmp := t.TempDir()
writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\ngamma\n")
res := execRead(t, tmp, `{"path": "f.txt"}`)
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Content)
}
if strings.Contains(res.Content, "│") {
t.Fatalf("expected raw content without line-number gutter, got:\n%s", res.Content)
}
if !strings.HasPrefix(res.Content, "alpha\nbeta\ngamma") {
t.Fatalf("unexpected content:\n%s", res.Content)
}
}
func TestReadToolAcceptsFileAlias(t *testing.T) {
tmp := t.TempDir()
writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\n")
res := execRead(t, tmp, `{"file":"f.txt"}`)
if res.IsError || !strings.HasPrefix(res.Content, "alpha\nbeta") {
t.Fatalf("file alias result = %#v", res)
}
}
func TestReadToolDefaultsToBoundedOutput(t *testing.T) {
tmp := t.TempDir()
lines := make([]string, DefaultReadLines+10)
for i := range lines {
lines[i] = fmt.Sprintf("line %d", i+1)
}
writeReadTestFile(t, tmp, "f.txt", strings.Join(lines, "\n"))
res := execRead(t, tmp, `{"path":"f.txt"}`)
if res.IsError || !strings.Contains(res.Content, fmt.Sprintf("Use offset=%d to continue", DefaultReadLines+1)) {
t.Fatalf("bounded read result = %s", res.Content)
}
}
func TestReadTool_UserLimitContinuationNotice(t *testing.T) {
tmp := t.TempDir()
var lines []string
for i := 1; i <= 50; i++ {
lines = append(lines, fmt.Sprintf("line %d", i))
}
writeReadTestFile(t, tmp, "f.txt", strings.Join(lines, "\n"))
res := execRead(t, tmp, `{"path": "f.txt", "offset": 10, "limit": 5}`)
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Content)
}
if !strings.HasPrefix(res.Content, "line 10") {
t.Fatalf("expected content to start at line 10, got:\n%s", res.Content)
}
if !strings.Contains(res.Content, "Use offset=15 to continue") {
t.Fatalf("expected continuation notice with offset=15, got:\n%s", res.Content)
}
if !strings.Contains(res.Content, "more lines in file") {
t.Fatalf("expected remaining-lines notice, got:\n%s", res.Content)
}
}
func TestReadTool_TruncationContinuationNotice(t *testing.T) {
tmp := t.TempDir()
var lines []string
for i := 1; i <= DefaultMaxLines+500; i++ {
lines = append(lines, fmt.Sprintf("line %d", i))
}
writeReadTestFile(t, tmp, "f.txt", strings.Join(lines, "\n"))
res := execRead(t, tmp, `{"path": "f.txt", "full": true}`)
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Content)
}
notice := fmt.Sprintf("[showing lines 1-%d of %d. Use offset=%d to continue.]", DefaultMaxLines, DefaultMaxLines+500, DefaultMaxLines+1)
if !strings.Contains(res.Content, notice) {
t.Fatalf("expected notice %q, got tail:\n%s", notice, res.Content[len(res.Content)-200:])
}
}
func TestReadTool_FirstLineExceedsByteLimit(t *testing.T) {
tmp := t.TempDir()
writeReadTestFile(t, tmp, "big.min.js", strings.Repeat("x", DefaultMaxBytes+100))
res := execRead(t, tmp, `{"path": "big.min.js"}`)
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Content)
}
if !strings.Contains(res.Content, "Use shell: sed -n '1p'") {
t.Fatalf("expected shell fallback hint, got:\n%s", res.Content)
}
}
func writeReadTestFile(t *testing.T, dir, name, content string) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func TestReadTool_DirectoryReturnsListing(t *testing.T) {
tmp := t.TempDir()
writeReadTestFile(t, tmp, "alpha.go", "package a\n")
writeReadTestFile(t, tmp, "beta.go", "package b\n")
if err := os.Mkdir(filepath.Join(tmp, "sub"), 0o755); err != nil {
t.Fatal(err)
}
res := execRead(t, tmp, `{"path": "."}`)
if res.IsError {
t.Fatalf("expected a listing, not an error: %s", res.Content)
}
for _, want := range []string{"alpha.go", "beta.go", "sub/"} {
if !strings.Contains(res.Content, want) {
t.Fatalf("listing missing %q, got:\n%s", want, res.Content)
}
}
if !strings.Contains(res.Content, "is a directory") {
t.Fatalf("expected the listing to say the path is a directory, got:\n%s", res.Content)
}
}
// A directory must not satisfy the read-before-write check: marking it read
// would let a later write to a same-named file bypass the guard.
func TestReadTool_DirectoryDoesNotMarkRead(t *testing.T) {
tmp := t.TempDir()
rt := NewReadTracker()
tool := NewReadTool(tmp, rt)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"path": "."}`), nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Content)
}
if err := rt.CheckRead(tmp, "."); err == nil {
t.Fatal("reading a directory must not mark it as read")
}
}
// 5 reads in the analysed corpus failed on plausible-but-wrong paths, each
// costing a round trip plus a follow-up find.
func TestReadTool_NotFoundSuggestsNearestPaths(t *testing.T) {
tmp := t.TempDir()
if err := os.MkdirAll(filepath.Join(tmp, "internal", "ui", "theme"), 0o755); err != nil {
t.Fatal(err)
}
writeReadTestFile(t, filepath.Join(tmp, "internal", "ui", "theme"), "theme.go", "package theme\n")
res := execRead(t, tmp, `{"path":"internal/theme/theme.go"}`)
if !res.IsError {
t.Fatal("expected a not-found error")
}
if !strings.Contains(res.Content, filepath.Join("internal", "ui", "theme", "theme.go")) {
t.Fatalf("expected the real path to be suggested, got:\n%s", res.Content)
}
}
func TestReadTool_NotFoundWithNoCandidateStaysPlain(t *testing.T) {
tmp := t.TempDir()
writeReadTestFile(t, tmp, "other.go", "package other\n")
res := execRead(t, tmp, `{"path":"internal/nothing/absent.go"}`)
if !res.IsError {
t.Fatal("expected a not-found error")
}
if strings.Contains(res.Content, "did you mean") {
t.Fatalf("no candidate should mean no suggestion, got:\n%s", res.Content)
}
}
// The real-world miss was internal/theme/theme.go: the directory exists but
// holds differently-named files, so a basename search finds nothing. Listing
// the directory that does exist is the useful answer.
func TestReadTool_NotFoundListsExistingParentDir(t *testing.T) {
tmp := t.TempDir()
if err := os.MkdirAll(filepath.Join(tmp, "internal", "theme"), 0o755); err != nil {
t.Fatal(err)
}
writeReadTestFile(t, filepath.Join(tmp, "internal", "theme"), "colors.go", "package theme\n")
res := execRead(t, tmp, `{"path":"internal/theme/theme.go"}`)
if !res.IsError {
t.Fatal("expected a not-found error")
}
if !strings.Contains(res.Content, "colors.go") {
t.Fatalf("expected the existing directory to be listed, got:\n%s", res.Content)
}
}