diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index e948776d0..de5326907 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -53,6 +53,7 @@ {"_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":"closed","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:41Z","closed_at":"2026-07-28T17:04:41Z","close_reason":"Superseded by merged work: all 32 children complete (32/32, bd flags it 'eligible for close'). MemoryProvider interface, built-in file-backed memory, MemoryManager, scrubber, drain and threat scanning all landed in internal/memory. Nothing left in scope.","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-qiq","title":"chat: mid-conversation context loss, undiagnosed","description":"Reported from a real Telegram transcript (29 Jul, ~09:47 AEST / 23:47 UTC 28\nJul). Turn 3 of a coherent conversation was answered with a fresh greeting as\nthough no history existed; turn 4 was coherent again.\n\nRuled out by evidence:\n- Not two processes racing the bot token. docker compose ps on carina shows a\n single archied container.\n- Not a restart. That container had 43h uptime spanning the whole exchange.\n- Not history compression. DefaultCompressionConfig protects the first 3 and\n last 20 messages and triggers at 50% of a 128k window; there were three\n messages.\n- Not a canned greeting. No such string exists in the codebase, so the reply\n was model-generated from little or no history.\n- Not the session-key namespace split fixed in 96ab167: the deployed image\n predates the session lifecycle commands entirely.\n\nBlocked on evidence, now unblocked: chat turns were completely unlogged (76\nlog lines covered two days, none a conversation). 96ab167 adds a \"chat turn\"\nlog line carrying session id, channel, thread and history depth.\n\nNext step when it recurs: check the chat turn log for that message. A session\nid differing from neighbouring turns points at key resolution (e.g. ThreadID\nappearing on one message); history_messages of 0 or 1 with a stable session id\npoints at the store read path.\n\nDo not close this by guessing. It needs one reproduction with the new log line.","status":"open","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-29T05:17:39Z","created_by":"Sam Catlow","updated_at":"2026-07-29T05:17:39Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-uxk","title":"gateway: restore /whoami /profile /sessions /resume /agents handlers","description":"These five command handlers were lost during parallel merges of the Telegram\nworkers. The Router fields they need (Identity, Models, Sessions, Agents)\nalready exist; the handlers and their Route cases do not.\n\n18 tests in internal/gateway/gateway_test.go already specify the exact\nbehaviour. They are currently failing. Run them and make them pass:\n\n go test ./internal/gateway/...\n\nFailing: TestRouteWhoami, TestRouteWhoamiNoIdentity, TestRouteWhoamiWithModel,\nTestRouteProfile, TestRouteProfileNoIdentity, TestRouteSessionsEmpty,\nTestRouteSessionsNotConfigured, TestRouteSessionsError, TestRouteResumeNoArg,\nTestRouteResumeNotConfigured, TestRouteResumeNoMatch, TestRouteResumeAmbiguous,\nTestRouteResumeExactMatch, TestRouteAgentsEmpty, TestRouteAgentsNotConfigured,\nTestRouteAgentsWithTasks, TestRouteAgentsError, TestLocalCommandsIncludesNewCommands\n\nScope:\n- ONLY internal/gateway/. Do not touch any other package.\n- Read the tests first; they define the exact reply text fragments expected\n (\"not configured\", \"No sessions\", \"Usage\", etc). Do not invent wording.\n- Follow the shape of the existing handlers in gateway.go and\n session_commands.go: handleX methods on *Router returning (string, error).\n- A nil dependency means \"not configured\" and returns a reply, not an error.\n A dependency that returns an error must propagate it (see TestRouteSessionsError).\n- Add the new commands to the Route switch and to LocalCommands.\n\nConstraints:\n- Do NOT add //nolint or otherwise suppress lint findings. Fix issues properly.\n- Do NOT write architecture docs, ledgers, plans or new beads. Just the code.\n- Do NOT modify the tests to make them pass. The tests are correct.\n\nDone when: go build ./... , go vet ./... , gofmt -l . clean, and\ngo test ./internal/gateway/... passes with zero failures.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T00:58:16Z","created_by":"Sam Catlow","updated_at":"2026-07-29T01:11:44Z","closed_at":"2026-07-29T01:11:44Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-o3l","title":"infrastructure/eventbus/nats: relocate NATS transport","description":"Create internal/infrastructure/eventbus/nats as a properly structured replacement for internal/nats. This is NOT a mechanical move: the existing code has no interfaces, leaks vendor types (Conn() *nats.Conn, PublishMsg(*nats.Msg), Fetch() jetstream.Msg) into all four consumers, uses a 7-positional-parameter publish with stringly-typed comma-separated labels, stores an unused logger, returns (nil, nil) for 'no message', and hardcodes stream/consumer/timeout config. Rebuild it with: separate files per concern; a Message wrapper so jetstream types stop crossing the boundary; Publisher/Consumer interfaces; a Config struct; sentinel errors; consistent %w wrapping; real logging. Then update cmd/archied, cmd/archie-agent, internal/daemon and internal/agentexec to the new API.","acceptance_criteria":"internal/nats no longer exists; internal/infrastructure/eventbus/nats has its contents. All imports updated. task check clean. Container and NATS behaviour unchanged.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T00:02:50Z","created_by":"Sam Catlow","updated_at":"2026-07-29T00:14:19Z","started_at":"2026-07-29T00:04:35Z","closed_at":"2026-07-29T00:06:37Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-vq4","title":"infrastructure/configuration: external input boundary","description":"Read docs/architecture/configuration.md. Create internal/infrastructure/configuration as the external config input boundary. It owns TOML/YAML decoding, env and secret references, base/overlay precedence, compatibility aliases, input validation, and provenance. It must NOT own domain behaviour. Preserve current LoadOverlay behaviour exactly and keep every existing TOML field name working. Translate the decoded input into the current internal/config.Config shape at the composition boundary as an explicitly-marked temporary adapter, so runtime behaviour is unchanged. Do not migrate consumers in this bead.","acceptance_criteria":"internal/infrastructure/configuration exists and is the loader used by cmd/archied. Old config files still load with identical effective values. task check clean. No consumer outside cmd/archied changed. The temporary adapter carries a comment naming its deletion condition.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T00:02:49Z","created_by":"Sam Catlow","updated_at":"2026-07-29T00:13:04Z","started_at":"2026-07-29T00:04:30Z","closed_at":"2026-07-29T00:13:04Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index edfb95477..348f2519b 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -50,6 +50,7 @@ import ( "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools/mcp" toolprovider "github.com/samcharles93/archie-core/internal/tools/provider" + builtintoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/builtin" mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp" memorytoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/memory" "github.com/samcharles93/archie-core/internal/webui" @@ -503,6 +504,18 @@ func run() int { log.Error("memory tool provider registration failed", "err", err) return 1 } + // Workspace file and shell tools. Registered only when a workspace is + // configured: these read, write and execute, so the directory is a + // deliberate choice rather than a default. + if workspace := cfg.Chat.Workspace; workspace != "" { + if err := providerRegistry.Register(builtintoolprovider.New(workspace)); err != nil { + log.Error("workspace tool provider registration failed", "err", err) + return 1 + } + log.Info("workspace tools enabled", "workspace", workspace) + } else { + log.Info("workspace tools disabled (chat.workspace is unset)") + } for _, srv := range cfg.Tools.MCPServers { provider, err := configuredMCPProvider(srv) if err != nil { diff --git a/config.example.toml b/config.example.toml index 0199bd2a5..fa1b0da7d 100644 --- a/config.example.toml +++ b/config.example.toml @@ -50,8 +50,14 @@ class = "ollama" # passed to the chat agent as runtime metadata, which means it is sent to the # configured model provider on every turn -- leave it unset to tell the agent # nothing about who is running it. +# +# `workspace` roots the chat agent's file and shell tools (read, write, edit, +# shell, grep, find). Unset, those tools are not registered at all. Set it and +# the agent can read, modify and execute inside that directory with the same +# reach the daemon process has -- choose it deliberately. # [chat] # operator = "Ada Lovelace" +# workspace = "/var/lib/archie/workspace" # models = [ # "openai/gpt-5.6-sol", # "openrouter/openai/gpt-5.6-sol", diff --git a/internal/config/config.go b/internal/config/config.go index adf4335bf..bad5ec86c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -486,6 +486,11 @@ type ChatConfig struct { // person, and that name was sent to the model provider on every turn // regardless of who was running it. Operator string `toml:"operator" yaml:"operator"` + // Workspace is the directory the chat agent's file and shell tools are + // rooted at. Empty disables those tools entirely, which is the default: + // they read, write and execute, so the directory must be a deliberate + // choice rather than whatever the daemon happens to start in. + Workspace string `toml:"workspace" yaml:"workspace"` // Models is the optional interactive-chat model catalog. When empty, // chat falls back to the distinct model references assigned to workflow // roles in the top-level [models] table. diff --git a/internal/tools/builtin/bridge.go b/internal/tools/builtin/bridge.go new file mode 100644 index 000000000..c8f5bb1e6 --- /dev/null +++ b/internal/tools/builtin/bridge.go @@ -0,0 +1,56 @@ +// Lifted from tau internal/agent/tools/bridge.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "context" + "errors" +) + +var ( + ErrInteractiveUnsupported = errors.New("interactive prompts are not supported in this mode") + ErrInteractiveCanceled = errors.New("interactive prompt was canceled") +) + +// UIBridge allows tools to interact with the user through the TUI. +// This interface is satisfied by the extension/ui bridge implementation. +type UIBridge interface { + Confirm(ctx context.Context, title, description string) (bool, error) + Select(ctx context.Context, title string, options []string) (string, error) + Input(ctx context.Context, title, placeholder string) (string, error) + Notify(title, level string) + Log(chunk string) + // SessionID returns the session this bridge instance is scoped to for + // the current tool call, or "" when there is no session context (e.g. + // NonInteractiveBridge). Tools that need to correlate their own + // forwarded events to the calling session (e.g. the agent tool) read + // this instead of requiring it to be threaded through static config. + SessionID() string +} + +type NonInteractiveBridge struct{} + +func (NonInteractiveBridge) SessionID() string { return "" } + +func (NonInteractiveBridge) Confirm(context.Context, string, string) (bool, error) { + return false, ErrInteractiveUnsupported +} + +func (NonInteractiveBridge) Select(context.Context, string, []string) (string, error) { + return "", ErrInteractiveUnsupported +} + +func (NonInteractiveBridge) Input(context.Context, string, string) (string, error) { + return "", ErrInteractiveUnsupported +} + +func (NonInteractiveBridge) Notify(string, string) {} + +func (NonInteractiveBridge) Log(string) {} diff --git a/internal/tools/builtin/bridge_test.go b/internal/tools/builtin/bridge_test.go new file mode 100644 index 000000000..819ef91bf --- /dev/null +++ b/internal/tools/builtin/bridge_test.go @@ -0,0 +1,11 @@ +package builtin + +import ( + "testing" +) + +func TestNonInteractiveBridgeLog(t *testing.T) { + var bridge UIBridge = NonInteractiveBridge{} + // This will fail to compile until Log is added to UIBridge and NonInteractiveBridge + bridge.Log("test chunk") +} diff --git a/internal/tools/builtin/builtin.go b/internal/tools/builtin/builtin.go new file mode 100644 index 000000000..7516c0d08 --- /dev/null +++ b/internal/tools/builtin/builtin.go @@ -0,0 +1,37 @@ +// Lifted from tau internal/agent/tools/builtin.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// - the docs tool is not registered and docs.go was not lifted. It serves +// tau's own embedded documentation via the tau/docs package, which has +// no meaning here. The pluginDocs parameter went with it. +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +// RegisterBuiltins registers all built-in tools into the given registry. +// The cwd parameter sets the working directory for file and shell operations. +func RegisterBuiltins(reg *Registry, cwd string, indexes ...GrepIndex) error { + mq := NewMutationQueue() + rt := NewReadTracker() + + builtins := []Tool{ + NewReadTool(cwd, rt), + NewWriteTool(cwd, mq, rt), + NewEditTool(cwd, mq, rt), + NewShellTool(cwd, mq), + NewGrepTool(cwd, indexes...), + NewFindTool(cwd), + } + + for _, tool := range builtins { + if err := reg.Register(tool); err != nil { + return err + } + } + + return nil +} diff --git a/internal/tools/builtin/edit.go b/internal/tools/builtin/edit.go new file mode 100644 index 000000000..7bed95330 --- /dev/null +++ b/internal/tools/builtin/edit.go @@ -0,0 +1,411 @@ +// Lifted from tau internal/agent/tools/edit.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "sort" + "strings" +) + +// EditParams are the parameters for the edit tool. +type EditParams struct { + Path string `json:"path"` + Edits []EditAction `json:"edits"` +} + +// EditAction is a single search-and-replace operation. +type EditAction struct { + OldText string `json:"old_text"` + NewText string `json:"new_text"` + ReplaceAll bool `json:"replace_all,omitempty"` +} + +var editSchema = Schema{ + Name: "edit", + Description: "Edit an existing file using exact text replacement. Each edit specifies old_text (must match exactly including whitespace) and new_text. Every old_text is matched against the original file and must be unique in it; set replace_all to true to replace every occurrence instead. Edits must not overlap - merge nearby changes into one edit. All edits are validated first and applied atomically: on any failure the file is left unchanged.", + Parameters: json.RawMessage(`{ + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Absolute or relative file path to edit" + }, + "edits": { + "type": "array", + "description": "One or more search-and-replace operations, each matched against the original file. Keep old_text as small as possible while still unique.", + "items": { + "type": "object", + "properties": { + "old_text": { + "type": "string", + "description": "Exact text to find (must match exactly including whitespace and be unique in the file unless replace_all is set)" + }, + "new_text": { + "type": "string", + "description": "Replacement text" + }, + "replace_all": { + "type": "boolean", + "description": "Replace all occurrences of old_text. Defaults to false (old_text must be unique)." + } + }, + "required": ["old_text", "new_text"] + } + } + }, + "required": ["path", "edits"] + }`), +} + +// NewEditTool creates the built-in edit tool. +func NewEditTool(cwd string, mq *MutationQueue, rt *ReadTracker) Tool { + return Tool{ + Schema: editSchema, + Source: "builtin", + Execute: makeEditExecutor(cwd, mq, rt), + } +} + +// parseEditParams unmarshals edit parameters, tolerating two model quirks +// observed in the wild: sending edits as a JSON-encoded string instead of an +// array, and sending a single flat old_text/new_text pair at the top level +// instead of inside edits[]. +func parseEditParams(params json.RawMessage) (EditParams, error) { + var wire struct { + Path string `json:"path"` + Edits json.RawMessage `json:"edits"` + OldText *string `json:"old_text"` + NewText *string `json:"new_text"` + ReplaceAll bool `json:"replace_all"` + } + if err := json.Unmarshal(params, &wire); err != nil { + return EditParams{}, err + } + + p := EditParams{Path: wire.Path} + + if len(wire.Edits) > 0 { + raw := wire.Edits + // Some models double-encode the array as a JSON string. + var asString string + if err := json.Unmarshal(raw, &asString); err == nil { + raw = json.RawMessage(asString) + } + if err := json.Unmarshal(raw, &p.Edits); err != nil { + return EditParams{}, fmt.Errorf("invalid edits: %w", err) + } + } + + // A flat old_text/new_text pair at the top level becomes a single edit. + if wire.OldText != nil && wire.NewText != nil { + p.Edits = append(p.Edits, EditAction{ + OldText: *wire.OldText, + NewText: *wire.NewText, + ReplaceAll: wire.ReplaceAll, + }) + } + + return p, nil +} + +func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { + return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { + p, err := parseEditParams(params) + if err != nil { + return Result{Content: fmt.Sprintf("invalid parameters: %v", err), IsError: true}, nil + } + + if len(p.Edits) == 0 { + return Result{Content: "at least one edit is required", IsError: true}, nil + } + + _, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + path := resolvePath(cwd, p.Path) + + if !isConfined(cwd, path) { + return Result{Content: "path escapes working directory", IsError: true}, nil + } + + // Enforce read-before-write check. + if rt != nil { + if err := rt.CheckRead(cwd, p.Path); err != nil { + return Result{Content: err.Error(), IsError: true}, nil + } + } + + // Check file size before reading to avoid OOM on large files. + info, err := os.Stat(path) + if err != nil { + return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true}, nil + } + if info.Size() > maxReadBytes { + return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true}, nil + } + + release := mq.Acquire(path) + defer release() + + data, err := os.ReadFile(path) + if err != nil { + return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true}, nil + } + + // Strip a UTF-8 BOM and normalise CRLF to LF before matching - the + // model never includes an invisible BOM or carriage returns in + // old_text. Both are restored on write. + raw := string(data) + bom := "" + if strings.HasPrefix(raw, utf8BOM) { + bom = utf8BOM + raw = strings.TrimPrefix(raw, utf8BOM) + } + hadCRLF := strings.Contains(raw, "\r\n") + content := strings.ReplaceAll(raw, "\r\n", "\n") + + newContent, err := applyEdits(content, p.Edits) + if err != nil { + errorKind := "invalid_arguments" + if strings.Contains(err.Error(), "old_text not found") { + errorKind = "stale_edit" + } + return Result{ + Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying", + IsError: true, + ErrorKind: errorKind, + }, nil + } + if newContent == content { + return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true}, nil + } + + if hadCRLF { + newContent = strings.ReplaceAll(newContent, "\n", "\r\n") + } + + if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil { + return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true}, nil + } + + return Result{ + Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path), + Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent}, + }, nil + } +} + +const utf8BOM = "\ufeff" + +// editSpan is a resolved replacement range in the original content. +type editSpan struct { + start, end int // byte offsets in the original content + repl string // replacement text + editIdx int // index of the edit that produced this span (for errors) +} + +// applyEdits resolves every edit against the ORIGINAL content, validates that +// the resulting replacement spans do not overlap, and applies them in one +// pass. It never partially applies: any error leaves the content untouched. +// +// Matching is exact first; if old_text is not found, a fuzzy pass retries the +// match with trailing whitespace stripped from every line of both the content +// and old_text, which recovers the most common exact-match failure. +func applyEdits(content string, edits []EditAction) (string, error) { + var spans []editSpan + + for i, edit := range edits { + if edit.OldText == "" { + return "", fmt.Errorf("edit %d: old_text must not be empty", i+1) + } + if edit.OldText == edit.NewText { + return "", fmt.Errorf("edit %d: old_text and new_text are identical", i+1) + } + + matches := indexAll(content, edit.OldText) + + if edit.ReplaceAll { + if len(matches) == 0 { + matches = fuzzyIndexAll(content, edit.OldText) + } + if len(matches) == 0 { + return "", editNotFoundError(i, content, edit.OldText) + } + for _, m := range matches { + spans = append(spans, editSpan{start: m[0], end: m[1], repl: edit.NewText, editIdx: i}) + } + continue + } + + switch len(matches) { + case 1: + spans = append(spans, editSpan{start: matches[0][0], end: matches[0][1], repl: edit.NewText, editIdx: i}) + case 0: + fuzzy := fuzzyIndexAll(content, edit.OldText) + switch len(fuzzy) { + case 1: + spans = append(spans, editSpan{start: fuzzy[0][0], end: fuzzy[0][1], repl: edit.NewText, editIdx: i}) + case 0: + return "", editNotFoundError(i, content, edit.OldText) + default: + return "", editAmbiguousError(i, len(fuzzy)) + } + default: + return "", editAmbiguousError(i, len(matches)) + } + } + + sort.Slice(spans, func(a, b int) bool { return spans[a].start < spans[b].start }) + + for i := 1; i < len(spans); i++ { + if spans[i].start < spans[i-1].end { + return "", fmt.Errorf( + "edits %d and %d overlap in the file; merge them into a single edit", + spans[i-1].editIdx+1, spans[i].editIdx+1, + ) + } + } + + var b strings.Builder + cursor := 0 + for _, s := range spans { + b.WriteString(content[cursor:s.start]) + b.WriteString(s.repl) + cursor = s.end + } + b.WriteString(content[cursor:]) + return b.String(), nil +} + +func editNotFoundError(idx int, content, oldText string) error { + base := fmt.Sprintf("edit %d: old_text not found in file; it must match exactly, including whitespace and indentation", idx+1) + if hint := nearestMatchHint(content, oldText); hint != "" { + return fmt.Errorf("%s\n%s", base, hint) + } + return errors.New(base) +} + +// nearestMatchHint locates the most likely intended location for a failed +// old_text and quotes the file's actual text there, so the model can correct +// the edit from the error alone instead of spending a round trip re-reading +// the file. stale_edit was 6.7% of all edit calls across analysed sessions. +// +// The anchor is the first non-blank line of old_text compared with leading and +// trailing whitespace removed, because indentation drift is the dominant cause: +// the model reproduces the right code at the wrong nesting depth. Matching on +// content alone is deliberately loose - a wrong hint costs nothing beyond a few +// lines of output, whereas no hint costs a whole round trip. +func nearestMatchHint(content, oldText string) string { + var anchor string + wantLines := strings.Split(oldText, "\n") + for _, l := range wantLines { + if t := strings.TrimSpace(l); t != "" { + anchor = t + break + } + } + if anchor == "" { + return "" + } + + lines := strings.Split(content, "\n") + for i, l := range lines { + if strings.TrimSpace(l) != anchor { + continue + } + end := min(i+len(wantLines), len(lines)) + return fmt.Sprintf( + "nearest match is at line %d; the file actually contains:\n%s", + i+1, strings.Join(lines[i:end], "\n"), + ) + } + return "" +} + +func editAmbiguousError(idx, occurrences int) error { + return fmt.Errorf("edit %d: old_text appears %d times in file; add surrounding context to make it unique, or set replace_all", idx+1, occurrences) +} + +// indexAll returns the [start, end) offsets of every non-overlapping +// occurrence of needle in content. +func indexAll(content, needle string) [][2]int { + var out [][2]int + for from := 0; ; { + i := strings.Index(content[from:], needle) + if i < 0 { + return out + } + start := from + i + out = append(out, [2]int{start, start + len(needle)}) + from = start + len(needle) + } +} + +// fuzzyIndexAll matches needle against content with trailing whitespace +// stripped from every line of both, returning spans in the ORIGINAL content. +// Only trailing-whitespace differences are forgiven; everything else must +// still match exactly. +func fuzzyIndexAll(content, needle string) [][2]int { + strippedNeedle := stripTrailingWhitespace(needle) + if strippedNeedle == "" { + return nil + } + + strippedContent, offsets := buildStrippedIndex(content) + + var out [][2]int + for _, m := range indexAll(strippedContent, strippedNeedle) { + start := offsets[m[0]] + end := len(content) + if m[1] < len(offsets) { + end = offsets[m[1]] + } + out = append(out, [2]int{start, end}) + } + return out +} + +func stripTrailingWhitespace(s string) string { + lines := strings.Split(s, "\n") + for i, line := range lines { + lines[i] = strings.TrimRight(line, " \t") + } + return strings.Join(lines, "\n") +} + +// buildStrippedIndex returns content with trailing whitespace stripped from +// every line, plus a per-character map from stripped offsets back to offsets +// in the original content. +func buildStrippedIndex(content string) (string, []int) { + var b strings.Builder + b.Grow(len(content)) + offsets := make([]int, 0, len(content)) + + lines := strings.Split(content, "\n") + pos := 0 + for i, line := range lines { + stripped := strings.TrimRight(line, " \t") + for j := range len(stripped) { + offsets = append(offsets, pos+j) + } + b.WriteString(stripped) + if i < len(lines)-1 { + offsets = append(offsets, pos+len(line)) // the newline + b.WriteByte('\n') + } + pos += len(line) + 1 + } + return b.String(), offsets +} diff --git a/internal/tools/builtin/edit_test.go b/internal/tools/builtin/edit_test.go new file mode 100644 index 000000000..36493c100 --- /dev/null +++ b/internal/tools/builtin/edit_test.go @@ -0,0 +1,329 @@ +package builtin + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestApplyEdits(t *testing.T) { + cases := []struct { + name string + content string + edits []EditAction + want string + wantErr string + }{ + { + name: "single edit", + content: "func a() {}\nfunc b() {}\n", + edits: []EditAction{{OldText: "func a()", NewText: "func alpha()"}}, + want: "func alpha() {}\nfunc b() {}\n", + }, + { + name: "multiple disjoint edits applied against original", + content: "one\ntwo\nthree\n", + edits: []EditAction{ + {OldText: "three", NewText: "3"}, + {OldText: "one", NewText: "1"}, + }, + want: "1\ntwo\n3\n", + }, + { + name: "replace all", + content: "x = a; y = a; z = a\n", + edits: []EditAction{{OldText: "a", NewText: "b", ReplaceAll: true}}, + want: "x = b; y = b; z = b\n", + }, + { + name: "not found", + content: "hello\n", + edits: []EditAction{{OldText: "goodbye", NewText: "farewell"}}, + wantErr: "old_text not found", + }, + { + name: "ambiguous without replace_all", + content: "dup\ndup\ndup\n", + edits: []EditAction{{OldText: "dup", NewText: "uniq"}}, + wantErr: "appears 3 times", + }, + { + name: "empty old_text", + content: "hello\n", + edits: []EditAction{{OldText: "", NewText: "x"}}, + wantErr: "must not be empty", + }, + { + name: "identical old and new", + content: "hello\n", + edits: []EditAction{{OldText: "hello", NewText: "hello"}}, + wantErr: "identical", + }, + { + name: "overlapping edits rejected", + content: "abcdef\n", + edits: []EditAction{ + {OldText: "abcd", NewText: "x"}, + {OldText: "cdef", NewText: "y"}, + }, + wantErr: "overlap", + }, + { + name: "fuzzy match forgives trailing whitespace in file", + content: "line one \nline two\n", // trailing spaces on line one + edits: []EditAction{{OldText: "line one\nline two", NewText: "replaced"}}, + want: "replaced\n", + }, + { + name: "fuzzy match forgives trailing whitespace in old_text", + content: "line one\nline two\n", + edits: []EditAction{{OldText: "line one \nline two", NewText: "replaced"}}, + want: "replaced\n", + }, + { + name: "atomic: second edit failing means no content returned", + content: "one\ntwo\n", + edits: []EditAction{ + {OldText: "one", NewText: "1"}, + {OldText: "missing", NewText: "x"}, + }, + wantErr: "edit 2: old_text not found", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := applyEdits(tc.content, tc.edits) + if tc.wantErr != "" { + if err == nil { + t.Fatalf("expected error containing %q, got result:\n%s", tc.wantErr, got) + } + if !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("expected error containing %q, got: %v", tc.wantErr, err) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != tc.want { + t.Fatalf("result mismatch:\ngot: %q\nwant: %q", got, tc.want) + } + }) + } +} + +func TestParseEditParams_Quirks(t *testing.T) { + t.Run("edits as JSON-encoded string", func(t *testing.T) { + params := `{"path": "f.txt", "edits": "[{\"old_text\": \"a\", \"new_text\": \"b\"}]"}` + p, err := parseEditParams(json.RawMessage(params)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(p.Edits) != 1 || p.Edits[0].OldText != "a" || p.Edits[0].NewText != "b" { + t.Fatalf("unexpected edits: %+v", p.Edits) + } + }) + + t.Run("flat old_text and new_text", func(t *testing.T) { + params := `{"path": "f.txt", "old_text": "a", "new_text": "b", "replace_all": true}` + p, err := parseEditParams(json.RawMessage(params)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(p.Edits) != 1 || p.Edits[0].OldText != "a" || !p.Edits[0].ReplaceAll { + t.Fatalf("unexpected edits: %+v", p.Edits) + } + }) + + t.Run("canonical form unchanged", func(t *testing.T) { + params := `{"path": "f.txt", "edits": [{"old_text": "a", "new_text": "b"}, {"old_text": "c", "new_text": "d"}]}` + p, err := parseEditParams(json.RawMessage(params)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(p.Edits) != 2 { + t.Fatalf("expected 2 edits, got %+v", p.Edits) + } + }) + + t.Run("invalid edits payload errors", func(t *testing.T) { + params := `{"path": "f.txt", "edits": "not json"}` + if _, err := parseEditParams(json.RawMessage(params)); err == nil { + t.Fatal("expected error for undecodable edits") + } + }) +} + +func TestEditTool_PreservesCRLFAndBOM(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + if err := os.WriteFile(path, []byte("\ufefffoo\r\nbar\r\n"), 0o644); err != nil { + t.Fatal(err) + } + + tool := NewEditTool(tmp, NewMutationQueue(), nil) + // old_text uses LF: matching must succeed against the CRLF file. + params := `{"path": "f.txt", "edits": [{"old_text": "foo\nbar", "new_text": "baz\nqux"}]}` + res, err := tool.Execute(context.Background(), json.RawMessage(params), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(got) != "\ufeffbaz\r\nqux\r\n" { + t.Fatalf("BOM or CRLF not preserved, got: %q", string(got)) + } +} + +func TestEditTool_AtomicOnDisk(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + original := "one\ntwo\n" + if err := os.WriteFile(path, []byte(original), 0o644); err != nil { + t.Fatal(err) + } + + tool := NewEditTool(tmp, NewMutationQueue(), nil) + // First edit is valid, second fails: the file must be left untouched. + params := `{"path": "f.txt", "edits": [{"old_text": "one", "new_text": "1"}, {"old_text": "missing", "new_text": "x"}]}` + res, err := tool.Execute(context.Background(), json.RawMessage(params), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatalf("expected tool error, got: %s", res.Content) + } + + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(got) != original { + t.Fatalf("file was partially modified on failure: %q", string(got)) + } +} + +func TestEditTool_PopulatesDiffDetails(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + original := "one\ntwo\nthree\n" + if err := os.WriteFile(path, []byte(original), 0o644); err != nil { + t.Fatal(err) + } + + tool := NewEditTool(tmp, NewMutationQueue(), nil) + params := `{"path": "f.txt", "edits": [{"old_text": "two", "new_text": "TWO"}]}` + res, err := tool.Execute(context.Background(), json.RawMessage(params), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + + details, ok := res.Details.(DiffDetails) + if !ok { + t.Fatalf("expected Details to be a DiffDetails, got %T", res.Details) + } + if details.OldContent != original { + t.Fatalf("OldContent mismatch:\ngot: %q\nwant: %q", details.OldContent, original) + } + wantNew := "one\nTWO\nthree\n" + if details.NewContent != wantNew { + t.Fatalf("NewContent mismatch:\ngot: %q\nwant: %q", details.NewContent, wantNew) + } + if details.Path != path { + t.Fatalf("Path mismatch: got %q want %q", details.Path, path) + } +} + +func TestApplyEdits_ExactMatchPreservesTrailingWhitespace(t *testing.T) { + // A single-line old_text is an exact substring match even when the file + // line has trailing whitespace, which is preserved around the edit. + content := "keep\ntarget \nkeep\n" + got, err := applyEdits(content, []EditAction{{OldText: "target", NewText: "T"}}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != "keep\nT \nkeep\n" { + t.Fatalf("result mismatch: %q", got) + } +} + +// The dominant stale_edit cause is indentation drift: the model reproduces the +// right code with the wrong leading whitespace. Naming the line and showing the +// file's actual text lets the retry succeed without re-reading the file. +func TestEdit_NotFoundReportsNearestMatch(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.go") + content := "package p\n\nfunc handleCancel() {\n\t\tdoWork()\n}\n" + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + + rt := NewReadTracker() + rt.MarkRead(tmp, path) + tool := NewEditTool(tmp, NewMutationQueue(), rt) + + // Same code, wrong indentation on the body line. + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"path":"f.go","edits":[{"old_text":"func handleCancel() {\n\tdoWork()\n}","new_text":"func handleCancel() { return }"}]}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatal("expected the edit to fail") + } + if !strings.Contains(res.Content, "line 3") { + t.Fatalf("error should name the nearest line, got:\n%s", res.Content) + } + if !strings.Contains(res.Content, "doWork()") { + t.Fatalf("error should show the file's actual text, got:\n%s", res.Content) + } + + // The file must be untouched. + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(after) != content { + t.Fatalf("a failed edit must not write; file is now:\n%s", after) + } +} + +func TestEdit_NotFoundWithNoPlausibleMatchStaysGeneric(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.go") + if err := os.WriteFile(path, []byte("package p\n"), 0o644); err != nil { + t.Fatal(err) + } + + rt := NewReadTracker() + rt.MarkRead(tmp, path) + tool := NewEditTool(tmp, NewMutationQueue(), rt) + + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"path":"f.go","edits":[{"old_text":"nothing like this exists","new_text":"x"}]}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatal("expected the edit to fail") + } + if strings.Contains(res.Content, "nearest") { + t.Fatalf("no plausible match should mean no nearest-match hint, got:\n%s", res.Content) + } + if !strings.Contains(res.Content, "old_text not found") { + t.Fatalf("expected the generic error, got:\n%s", res.Content) + } +} diff --git a/internal/tools/builtin/find.go b/internal/tools/builtin/find.go new file mode 100644 index 000000000..88aa394cd --- /dev/null +++ b/internal/tools/builtin/find.go @@ -0,0 +1,358 @@ +// Lifted from tau internal/agent/tools/find.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "sort" + "strings" +) + +// FindParams are the parameters for the find tool. +type FindParams struct { + Path string `json:"path,omitempty"` // directory to search in + Pattern string `json:"pattern,omitempty"` // glob pattern for file names + Type string `json:"type,omitempty"` // "file", "directory", or empty for both + MaxDepth int `json:"max_depth,omitempty"` // max directory depth (0 = unlimited) + Exclude string `json:"exclude,omitempty"` // glob pattern to exclude (e.g. 'node_modules', '*.test.*') +} + +var findSchema = Schema{ + Name: "find", + Description: fmt.Sprintf("Find files and directories by name pattern, or list a directory's contents. Respects .gitignore when fd is available. Returns a list of matching paths, truncated to %d results or %s (whichever is hit first). Omit pattern and set max_depth:1 to list a single directory. Use exclude to skip unwanted directories.", DefaultMaxLines, FormatSize(DefaultMaxBytes)), + Parameters: json.RawMessage(`{ + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Directory to search in. Defaults to current directory." + }, + "pattern": { + "type": "string", + "description": "Glob pattern to match file/directory names (e.g. '*.go', 'README*')" + }, + "type": { + "type": "string", + "enum": ["file", "directory"], + "description": "Filter by type: 'file' or 'directory'. Omit for both." + }, + "max_depth": { + "type": "integer", + "description": "Maximum directory depth to descend. 0 means unlimited. Use to limit recursion in large trees." + }, + "exclude": { + "type": "string", + "description": "Glob pattern for directories or files to exclude (e.g. 'node_modules', '*.test.go', 'vendor')." + } + } + }`), +} + +// NewFindTool creates the built-in find tool. +func NewFindTool(cwd string) Tool { + return Tool{ + Schema: findSchema, + Source: "builtin", + Execute: makeFindExecutor(cwd), + } +} + +func makeFindExecutor(cwd string) Executor { + return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { + var p FindParams + if err := json.Unmarshal(params, &p); err != nil { + return Result{Content: fmt.Sprintf("invalid parameters: %v", err), IsError: true}, nil + } + + ctx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + searchPath := cwd + if p.Path != "" { + searchPath = resolvePath(cwd, p.Path) + } + + if !isReadConfined(cwd, searchPath) { + return Result{Content: "error: path escapes working directory", IsError: true}, nil + } + + info, err := os.Stat(searchPath) + if err != nil { + return Result{Content: fmt.Sprintf("error accessing path: %v", err), IsError: true}, nil + } + if !info.IsDir() { + return Result{Content: "path must be a directory", IsError: true}, nil + } + + binary, err := findBinary() + if err != nil { + // No external binary available - use pure-Go fallback. + return runFindGoFallback(ctx, cwd, searchPath, p) + } + args := buildFindArgs(binary, p, searchPath) + + cmd := exec.CommandContext(ctx, binary, args...) + cmd.Dir = cwd + + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + + err = cmd.Run() + + output := strings.TrimSpace(stdout.String()) + if output == "" && err != nil { + errMsg := stderr.String() + if errMsg == "" { + errMsg = err.Error() + } + return Result{Content: fmt.Sprintf("find error: %s", errMsg), IsError: true}, nil + } + + if output == "" { + return Result{Content: "no matches found"}, nil + } + + tr := TruncateHead(output, DefaultMaxLines, DefaultMaxBytes) + return Result{Content: tr.Content, Truncated: tr.Truncated, ResultBytes: tr.OriginalSize}, nil + } +} + +func runFindGoFallback(ctx context.Context, cwd, searchPath string, p FindParams) (Result, error) { + info, err := os.Stat(searchPath) + if err != nil { + return Result{Content: fmt.Sprintf("error accessing path: %v", err), IsError: true}, nil + } + if !info.IsDir() { + return Result{Content: "path must be a directory", IsError: true}, nil + } + + var matches []string + + var patternRe *regexp.Regexp + if p.Pattern != "" { + reStr := globToRegex(p.Pattern) + var err error + patternRe, err = regexp.Compile("^(?:" + reStr + ")$") + if err != nil { + return Result{Content: fmt.Sprintf("invalid pattern: %v", err), IsError: true}, nil + } + } + + var excludeRe *regexp.Regexp + if p.Exclude != "" { + reStr := globToRegex(p.Exclude) + var err error + excludeRe, err = regexp.Compile("(?:" + reStr + ")") + if err != nil { + return Result{Content: fmt.Sprintf("invalid exclude: %v", err), IsError: true}, nil + } + } + + err = filepath.WalkDir(searchPath, func(walkPath string, d os.DirEntry, err error) error { + if err != nil { + return nil // skip inaccessible entries + } + + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + // Calculate depth relative to searchPath. + if p.MaxDepth > 0 && walkPath != searchPath { + relDepth := strings.Count(strings.TrimPrefix(walkPath, searchPath+string(filepath.Separator)), string(filepath.Separator)) + if relDepth >= p.MaxDepth { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + } + + base := d.Name() + // Skip hidden entries like .git, .env, etc. + if strings.HasPrefix(base, ".") && walkPath != searchPath { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + + // Apply exclude filter to both files and directories. + if excludeRe != nil { + if excludeRe.MatchString(base) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + } + + // Skip root directory itself. + if walkPath == searchPath { + return nil + } + + // Type filter. + switch p.Type { + case "file": + if d.IsDir() { + return nil + } + case "directory": + if !d.IsDir() { + return nil + } + } + + // Pattern filter. + if patternRe != nil { + if !patternRe.MatchString(base) { + return nil + } + } + + // Use path relative to cwd for output consistency. + outputPath, err := filepath.Rel(cwd, walkPath) + if err != nil { + outputPath = walkPath + } + matches = append(matches, filepath.ToSlash(outputPath)) + return nil + }) + + if err != nil && err != ctx.Err() { + return Result{Content: fmt.Sprintf("find error: %v", err), IsError: true}, nil + } + + if len(matches) == 0 { + return Result{Content: "no matches found"}, nil + } + + sort.Strings(matches) + output := strings.Join(matches, "\n") + tr := TruncateHead(output, DefaultMaxLines, DefaultMaxBytes) + return Result{Content: tr.Content, Truncated: tr.Truncated, ResultBytes: tr.OriginalSize}, nil +} + +func isFdBinary(binary string) bool { + base := filepath.Base(binary) + base = strings.TrimSuffix(base, filepath.Ext(base)) // strip .exe on Windows + return base == "fd" || base == "fd-find" || base == "fdfind" +} + +func buildFindArgs(binary string, p FindParams, searchPath string) []string { + // fd (fd-find) style + if isFdBinary(binary) { + args := []string{} + if p.Pattern != "" { + args = append(args, "--glob", p.Pattern) + } + switch p.Type { + case "file": + args = append(args, "--type", "f") + case "directory": + args = append(args, "--type", "d") + } + if p.MaxDepth > 0 { + args = append(args, "--max-depth", fmt.Sprintf("%d", p.MaxDepth)) + } + if p.Exclude != "" { + args = append(args, "--exclude", p.Exclude) + } + args = append(args, "--search-path", searchPath) + return args + } + + // POSIX find style + args := []string{searchPath} + switch p.Type { + case "file": + args = append(args, "-type", "f") + case "directory": + args = append(args, "-type", "d") + } + if p.MaxDepth > 0 { + args = append(args, "-maxdepth", fmt.Sprintf("%d", p.MaxDepth)) + } + if p.Exclude != "" { + args = append(args, "-not", "-path", fmt.Sprintf("*/%s/*", p.Exclude)) + } + if p.Pattern != "" { + args = append(args, "-name", p.Pattern) + } + return args +} + +func findBinary() (string, error) { + // Prefer fd; fall back to POSIX find on Unix only. + for _, name := range []string{"fd", "fdfind", "fd-find"} { + if path, err := exec.LookPath(name); err == nil { + return path, nil + } + } + if runtime.GOOS == "windows" { + return "", fmt.Errorf("fd is required on Windows but was not found in PATH") + } + return "find", nil +} + +// globToRegex converts a simple glob pattern to a regex string. +// Supports * (any chars), ? (single char), and character classes [...]. +func globToRegex(pattern string) string { + var sb strings.Builder + inClass := false + for i := 0; i < len(pattern); i++ { + c := pattern[i] + switch c { + case '*': + if inClass { + sb.WriteByte(c) + } else { + sb.WriteString(".*") + } + case '?': + if inClass { + sb.WriteByte(c) + } else { + sb.WriteByte('.') + } + case '[': + inClass = true + sb.WriteByte(c) + case ']': + inClass = false + sb.WriteByte(c) + case '\\': + if i+1 < len(pattern) { + sb.WriteByte(pattern[i+1]) + i++ + } else { + sb.WriteByte(c) + } + case '.', '+', '^', '$', '(', ')', '|': + sb.WriteByte('\\') + sb.WriteByte(c) + default: + sb.WriteByte(c) + } + } + return sb.String() +} diff --git a/internal/tools/builtin/find_test.go b/internal/tools/builtin/find_test.go new file mode 100644 index 000000000..62df32843 --- /dev/null +++ b/internal/tools/builtin/find_test.go @@ -0,0 +1,148 @@ +package builtin + +import ( + "context" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" +) + +func TestFindFallback(t *testing.T) { + // Create a temporary directory tree. + tmp := t.TempDir() + createTestFile(t, tmp, "foo.go", "package main") + createTestFile(t, tmp, "bar.go", "package bar") + createTestFile(t, tmp, "README.md", "# readme") + createTestFile(t, tmp, "subdir/baz.go", "package baz") + createTestFile(t, tmp, "subdir/nested/deep.txt", "deep") + createTestFile(t, tmp, "vendor/mod.go", "package mod") + os.MkdirAll(filepath.Join(tmp, "hiddendir"), 0o755) + createTestFile(t, tmp, "hiddendir/visible.txt", "text") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + cases := []struct { + name string + params FindParams + want []string + wantEmpty bool + }{ + { + name: "glob pattern *.go (matches all depths)", + params: FindParams{Path: tmp, Pattern: "*.go", Type: "file"}, + want: []string{"bar.go", "foo.go", "subdir/baz.go", "vendor/mod.go"}, + }, + { + name: "match directories (nested shown)", + params: FindParams{Path: tmp, Type: "directory"}, + want: []string{"hiddendir", "subdir", "subdir/nested", "vendor"}, + }, + { + name: "max depth 1", + params: FindParams{Path: tmp, Type: "file", MaxDepth: 1}, + want: []string{"bar.go", "foo.go", "README.md"}, + }, + { + name: "max depth 0 unlimited", + params: FindParams{Path: tmp, Type: "file", MaxDepth: 0}, + want: []string{ + "bar.go", "foo.go", "README.md", + "hiddendir/visible.txt", "subdir/baz.go", + "subdir/nested/deep.txt", "vendor/mod.go", + }, + }, + { + name: "exclude vendor", + params: FindParams{Path: tmp, Type: "file", Exclude: "vendor"}, + want: []string{ + "bar.go", "foo.go", "README.md", + "hiddendir/visible.txt", "subdir/baz.go", + "subdir/nested/deep.txt", + }, + }, + { + name: "exclude by glob", + params: FindParams{Path: tmp, Type: "file", Exclude: "*.md"}, + want: []string{ + "bar.go", "foo.go", + "hiddendir/visible.txt", "subdir/baz.go", + "subdir/nested/deep.txt", "vendor/mod.go", + }, + }, + { + name: "no matches", + params: FindParams{Path: tmp, Pattern: "nonexistent*", Type: "file"}, + wantEmpty: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + res, err := runFindGoFallback(ctx, tmp, tmp, tc.params) + if err != nil { + t.Fatalf("runFindGoFallback returned error: %v", err) + } + if tc.wantEmpty { + if res.Content != "no matches found" { + t.Fatalf("expected empty, got:\n%s", res.Content) + } + return + } + gotLines := strings.Split(strings.TrimSpace(res.Content), "\n") + if len(gotLines) == 1 && gotLines[0] == "" { + gotLines = []string{} + } + sort.Strings(gotLines) + sort.Strings(tc.want) + if len(gotLines) != len(tc.want) { + t.Fatalf("got %d results, want %d\ngot: %v\nwant: %v", len(gotLines), len(tc.want), gotLines, tc.want) + } + for i := range tc.want { + if gotLines[i] != tc.want[i] { + t.Fatalf("result mismatch at %d: got %q, want %q", i, gotLines[i], tc.want[i]) + } + } + }) + } +} + +func TestFindFallback_NonExistentPath(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + res, _ := runFindGoFallback(ctx, "/nonexistent/path", "/nonexistent/path", FindParams{}) + if !res.IsError { + t.Fatal("expected error for non-existent path") + } +} + +func TestFindFallback_NotADirectory(t *testing.T) { + tmp := t.TempDir() + f := filepath.Join(tmp, "file.txt") + if err := os.WriteFile(f, []byte("hello"), 0o644); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + res, _ := runFindGoFallback(ctx, tmp, f, FindParams{}) + if !res.IsError { + t.Fatal("expected error when path is a file") + } +} + +func createTestFile(t *testing.T, base, relPath, content string) { + t.Helper() + full := filepath.Join(base, relPath) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/internal/tools/builtin/fsutil.go b/internal/tools/builtin/fsutil.go new file mode 100644 index 000000000..2e63d8412 --- /dev/null +++ b/internal/tools/builtin/fsutil.go @@ -0,0 +1,71 @@ +// Lifted from tau internal/agent/tools/fsutil.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "context" + "os" + "path/filepath" +) + +// runWithContext runs fn in a goroutine and returns its result, or ctx.Err() +// if ctx is done first. Go cannot forcibly cancel a blocked syscall (e.g. a +// hung NFS/FUSE mount), so fn's goroutine is not killed - it keeps running +// in the background and its result is discarded - but the caller stops +// waiting on it, so a hung filesystem can no longer block the tool executor +// (and therefore the coordinator's turn loop) indefinitely. +// +// If the context is already done when runWithContext is called, fn is never +// spawned. This avoids a goroutine leak that can race with test cleanup. +func runWithContext(ctx context.Context, fn func() error) error { + if err := ctx.Err(); err != nil { + return err + } + + done := make(chan error, 1) + go func() { done <- fn() }() + select { + case err := <-done: + return err + case <-ctx.Done(): + return ctx.Err() + } +} + +// writeFileAtomic replaces path atomically using a temp file in the same directory. +func writeFileAtomic(path string, data []byte, mode os.FileMode) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + + tmp, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + tmpPath := tmp.Name() + cleanup := func() { + _ = os.Remove(tmpPath) + } + defer cleanup() + + if err := tmp.Chmod(mode); err != nil { + _ = tmp.Close() + return err + } + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpPath, path) +} diff --git a/internal/tools/builtin/fsutil_test.go b/internal/tools/builtin/fsutil_test.go new file mode 100644 index 000000000..55a5d71e0 --- /dev/null +++ b/internal/tools/builtin/fsutil_test.go @@ -0,0 +1,77 @@ +package builtin + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestRunWithContext_ReturnsFnResult(t *testing.T) { + err := runWithContext(context.Background(), func() error { return nil }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + sentinel := errors.New("boom") + err = runWithContext(context.Background(), func() error { return sentinel }) + if !errors.Is(err, sentinel) { + t.Fatalf("expected sentinel error, got %v", err) + } +} + +// TestRunWithContext_ReturnsCtxErrOnAlreadyExpired verifies that when the +// context is already done before runWithContext is called, no goroutine is +// spawned and the context error is returned immediately. +func TestRunWithContext_ReturnsCtxErrOnAlreadyExpired(t *testing.T) { + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + spawned := make(chan struct{}) + err := runWithContext(ctx, func() error { + close(spawned) + return nil + }) + + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected context.DeadlineExceeded, got %v", err) + } + + // The goroutine must NOT have been spawned because the context + // was already expired. Give it a short grace period to prove the + // negative. + select { + case <-spawned: + t.Fatal("fn was spawned even though the context was already expired — goroutine leak") + case <-time.After(50 * time.Millisecond): + // Expected: fn was never called. + } +} + +// TestRunWithContext_ReturnsCtxErrOnTimeout is the core regression coverage +// for tau-6wa: fn blocks forever (simulating a hung filesystem call); the +// caller must get control back once ctx expires rather than waiting for fn. +func TestRunWithContext_ReturnsCtxErrOnTimeout(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + + fnStarted := make(chan struct{}) + blockForever := make(chan struct{}) // deliberately never closed + + start := time.Now() + err := runWithContext(ctx, func() error { + close(fnStarted) + <-blockForever + return nil + }) + elapsed := time.Since(start) + + <-fnStarted // make sure fn actually started (and is now hung) before checking the result + + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected context.DeadlineExceeded, got %v", err) + } + if elapsed > 500*time.Millisecond { + t.Fatalf("runWithContext took %v to return after the deadline, expected it to return promptly instead of waiting on the hung fn", elapsed) + } +} diff --git a/internal/tools/builtin/grep.go b/internal/tools/builtin/grep.go new file mode 100644 index 000000000..9eeb45b65 --- /dev/null +++ b/internal/tools/builtin/grep.go @@ -0,0 +1,583 @@ +// Lifted from tau internal/agent/tools/grep.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "unicode/utf8" + + "github.com/samcharles93/archie-core/internal/tools/builtin/rg" +) + +const ( + // grepMaxLineChars caps each output line so a single long line (e.g. in + // minified or generated files) cannot blow out the context window. + grepMaxLineChars = 500 + + // grepDefaultLimit is the default maximum number of matches returned. + grepDefaultLimit = 100 + grepMaxBytes = 24 * 1024 + + // grepMaxContext bounds context_before/context_after. Large context values + // spend the whole byte budget on padding: at the default limit of 100 + // matches, every extra context line is 100 extra lines of output, so a + // request for 10 lines either side truncates long before it has shown 100 + // distinct matches. Clamping keeps the budget on matches instead. + grepMaxContext = 5 +) + +// grepMatchLineRe recognises a match line in ripgrep-style output +// (path:line:content). Context lines use '-' separators instead. +var grepMatchLineRe = regexp.MustCompile(`^.+?:\d+:`) + +// GrepParams are the parameters for the grep tool. +type GrepParams struct { + Pattern string `json:"pattern"` + Path string `json:"path,omitempty"` // file or directory + Include string `json:"include,omitempty"` // glob pattern for file names + Literal bool `json:"literal,omitempty"` + CaseSensitive bool `json:"case_sensitive,omitempty"` + ContextBefore int `json:"context_before,omitempty"` // lines before each match (-B) + ContextAfter int `json:"context_after,omitempty"` // lines after each match (-A) + Limit int `json:"limit,omitempty"` // max matches to return +} + +// GrepIndex provides conservative workspace-wide candidate files. The grep +// tool remains responsible for authoritative matching and output formatting. +type GrepIndex interface { + Candidates(context.Context, string, bool, bool) ([]string, bool) +} + +var grepSchema = Schema{ + Name: "grep", + Description: fmt.Sprintf("Search file contents for a regex pattern using ripgrep (rg). Respects .gitignore. Returns matching lines with file paths and line numbers. Supports alternation (e.g. 'foo|bar') and full regex syntax. Use context_before/context_after to show surrounding lines (capped at %d each). Output is capped at %d matches (adjustable via limit) and long lines are truncated to %d chars.", grepMaxContext, grepDefaultLimit, grepMaxLineChars), + Parameters: json.RawMessage(`{ + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regex pattern to search for (e.g. 'handleCancel|CancelChat'). Set literal:true to match the pattern as plain text instead." + }, + "path": { + "type": "string", + "description": "File or directory to search in. Defaults to current directory." + }, + "include": { + "type": "string", + "description": "Glob pattern for file inclusion (e.g. '*.go', '*.ts')" + }, + "literal": { + "type": "boolean", + "description": "Treat pattern as literal text instead of a regex. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum number of matches to return. Defaults to 100." + }, + "case_sensitive": { + "type": "boolean", + "description": "Case-sensitive search. Defaults to false (smart case)." + }, + "context_before": { + "type": "integer", + "description": "Number of lines to show before each match (-B). Useful for seeing context without a follow-up read." + }, + "context_after": { + "type": "integer", + "description": "Number of lines to show after each match (-A). Useful for seeing context without a follow-up read." + } + }, + "required": ["pattern"] + }`), +} + +// NewGrepTool creates the built-in grep tool. + +func NewGrepTool(cwd string, indexes ...GrepIndex) Tool { + var workspaceIndex GrepIndex + if len(indexes) > 0 { + workspaceIndex = indexes[0] + } + return Tool{ + Schema: grepSchema, + Source: "builtin", + Execute: makeGrepExecutor(cwd, workspaceIndex), + } +} + +func makeGrepExecutor(cwd string, workspaceIndex GrepIndex) Executor { + return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { + var p GrepParams + if err := json.Unmarshal(params, &p); err != nil { + return Result{Content: fmt.Sprintf("invalid parameters: %v", err), IsError: true}, nil + } + + if strings.TrimSpace(p.Pattern) == "" { + return Result{Content: "pattern is required", IsError: true}, nil + } + + ctx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + clamped := clampGrepContext(&p) + + searchPath := cwd + if p.Path != "" { + searchPath = resolvePath(cwd, p.Path) + } + + if !isReadConfined(cwd, searchPath) { + return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil + } + + args := buildGrepArgs(p) + searchTargets := []string{searchPath} + searchBackend := "direct" + // The index is workspace-wide, so it can serve any search scoped at or + // below cwd once its candidates are narrowed to the requested subtree. + // Requiring searchPath == cwd meant subdirectory searches silently fell + // back to a full walk, which is why the index served only 5% of + // searches across analysed sessions. + if workspaceIndex != nil && isConfined(cwd, searchPath) { + if candidates, ok := workspaceIndex.Candidates(ctx, p.Pattern, p.Literal, p.CaseSensitive); ok { + if scoped := filterUnder(searchPath, candidates); len(scoped) > 0 { + searchTargets = scoped + searchBackend = "codesearch" + } + // An empty scoped set is NOT evidence of no matches: the index + // may simply be cold or stale for this subtree, so fall through + // to the authoritative direct walk rather than reporting "no + // matches found" from an empty candidate list. + } + } + args = append(args, searchTargets...) + + limit := p.Limit + if limit <= 0 { + limit = grepDefaultLimit + } + + binary, err := grepBinary() + if err != nil { + searchBackend = "direct" + // No external binary available - use pure-Go fallback. + output, err := grepFallback(ctx, p, searchPath, cwd, searchTargets) + if err != nil { + return grepBackendResult(Result{Content: fmt.Sprintf("grep error: %v", err), IsError: true}, searchBackend, clamped), nil + } + if output == "" { + return grepBackendResult(Result{Content: "no matches found"}, searchBackend, clamped), nil + } + return grepBackendResult(capGrepResult(output, limit), searchBackend, clamped), nil + } + + cmd := exec.CommandContext(ctx, binary, args...) + cmd.Dir = cwd + + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + + err = cmd.Run() + + output := stdout.String() + if searchBackend == "codesearch" && err != nil { + // Snapshot candidates can disappear, or an unusually large candidate + // argv can fail to spawn. Retry the authoritative workspace path. + searchBackend = "direct" + args = append(buildGrepArgs(p), searchPath) + cmd = exec.CommandContext(ctx, binary, args...) + cmd.Dir = cwd + stdout.Reset() + stderr.Reset() + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err = cmd.Run() + output = stdout.String() + } + if output == "" && err != nil { + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 { + return grepBackendResult(Result{Content: "no matches found"}, searchBackend, clamped), nil + } + errMsg := stderr.String() + if errMsg == "" { + errMsg = err.Error() + } + return grepBackendResult(Result{Content: fmt.Sprintf("grep error: %s", errMsg), IsError: true}, searchBackend, clamped), nil + } + + return grepBackendResult(capGrepResult(output, limit), searchBackend, clamped), nil + } +} + +// filterUnder returns the candidates at or below root. Paths are compared +// after cleaning so that a candidate is only kept when root is a genuine path +// prefix, not merely a string prefix ("/a/bc" is not under "/a/b"). +func filterUnder(root string, candidates []string) []string { + root = filepath.Clean(root) + + out := make([]string, 0, len(candidates)) + for _, c := range candidates { + if isConfined(root, filepath.Clean(c)) { + out = append(out, c) + } + } + return out +} + +// clampGrepContext bounds the context window in place and returns a notice +// describing what was clamped, or "" if the request was already within limits. +func clampGrepContext(p *GrepParams) string { + var clamped []string + if p.ContextBefore > grepMaxContext { + p.ContextBefore = grepMaxContext + clamped = append(clamped, "context_before") + } + if p.ContextAfter > grepMaxContext { + p.ContextAfter = grepMaxContext + clamped = append(clamped, "context_after") + } + if len(clamped) == 0 { + return "" + } + return fmt.Sprintf( + "[%s clamped to %d; for a wider window, read the file at the reported line numbers]", + strings.Join(clamped, " and "), grepMaxContext, + ) +} + +func grepBackendResult(result Result, backend, clampNotice string) Result { + result.MetricLabels = map[string]string{"search_backend": backend} + if clampNotice != "" && !result.IsError { + result.Content += "\n" + clampNotice + } + return result +} + +func capGrepResult(output string, limit int) Result { + lines := strings.Split(strings.TrimSuffix(output, "\n"), "\n") + kept := make([]string, 0, len(lines)) + matches := 0 + limitHit := false + linesTruncated := false + + for _, line := range lines { + if grepMatchLineRe.MatchString(line) { + if matches >= limit { + limitHit = true + break + } + matches++ + } + if len(line) > grepMaxLineChars { + line = line[:truncationBoundary(line, grepMaxLineChars)] + "... [truncated]" + linesTruncated = true + } + kept = append(kept, line) + } + + tr := TruncateHead(strings.Join(kept, "\n"), DefaultMaxLines, grepMaxBytes) + content := tr.Content + if limitHit { + content += fmt.Sprintf("\n\n[showing first %d matches; refine the pattern or raise limit]", limit) + } + if linesTruncated { + content += fmt.Sprintf("\n[some lines truncated to %d chars]", grepMaxLineChars) + } + if tr.Truncated { + content += fmt.Sprintf("\n[output truncated at %s; refine the pattern, search a narrower path, or use jq for structured JSON]", FormatSize(grepMaxBytes)) + } + return Result{Content: content, Truncated: tr.Truncated || limitHit || linesTruncated, ResultBytes: len(output)} +} + +// truncationBoundary returns the largest cut point <= max that does not split +// a UTF-8 rune. +func truncationBoundary(s string, max int) int { + cut := max + for cut > 0 && !utf8.RuneStart(s[cut]) { + cut-- + } + return cut +} + +// grepFallback performs a pure-Go file scan for when ripgrep is not available. +// Works on all platforms including Windows. When targets has explicit file paths +// (not just the searchPath directory), only those files are searched. +func grepFallback(ctx context.Context, p GrepParams, searchPath, cwd string, targets []string) (string, error) { + matcher, err := buildMatcher(p) + if err != nil { + return "", err + } + + var results []grepResult + + // When explicit files are provided (index candidates), search only those. + if len(targets) > 0 && targets[0] != searchPath { + for _, path := range targets { + select { + case <-ctx.Done(): + return "", ctx.Err() + default: + } + res, fErr := grepFile(ctx, path, matcher, p.ContextBefore, p.ContextAfter) + if fErr != nil { + continue + } + for i := range res { + res[i].relPath, _ = filepath.Rel(cwd, path) + res[i].relPath = filepath.ToSlash(res[i].relPath) + if res[i].relPath == "" || res[i].relPath == "." { + res[i].relPath = filepath.ToSlash(filepath.Base(path)) + } + } + results = append(results, res...) + } + return formatGrepResults(results), nil + } + + info, err := os.Stat(searchPath) + if err != nil { + return "", err + } + + if !info.IsDir() { + res, err := grepFile(ctx, searchPath, matcher, p.ContextBefore, p.ContextAfter) + if err != nil { + return "", err + } + for i := range res { + res[i].relPath, _ = filepath.Rel(cwd, searchPath) + if res[i].relPath == "" || res[i].relPath == "." { + res[i].relPath = filepath.Base(searchPath) + } + } + results = append(results, res...) + } else { + err = filepath.WalkDir(searchPath, func(walkPath string, d os.DirEntry, err error) error { + if err != nil { + return nil // skip inaccessible + } + + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + if d.IsDir() { + // Skip hidden directories. + if d.Name() != "" && d.Name()[0] == '.' && walkPath != searchPath { + return filepath.SkipDir + } + return nil + } + + // Skip hidden files. + if d.Name() != "" && d.Name()[0] == '.' { + return nil + } + + // Include filter. + if p.Include != "" { + if matched, _ := filepath.Match(p.Include, d.Name()); !matched { + return nil + } + } + + res, err := grepFile(ctx, walkPath, matcher, p.ContextBefore, p.ContextAfter) + if err != nil { + return nil // skip files we can't read + } + for i := range res { + res[i].relPath, _ = filepath.Rel(cwd, walkPath) + res[i].relPath = filepath.ToSlash(res[i].relPath) + if res[i].relPath == "" || res[i].relPath == "." { + res[i].relPath = filepath.ToSlash(filepath.Base(walkPath)) + } + } + results = append(results, res...) + return nil + }) + if err != nil && err != ctx.Err() { + return "", err + } + } + + return formatGrepResults(results), nil +} + +// buildMatcher returns a line matcher based on grep parameters. +func buildMatcher(p GrepParams) (func(string) bool, error) { + if !p.Literal { + var re *regexp.Regexp + var err error + if p.CaseSensitive || hasUppercase(p.Pattern) { + re, err = regexp.Compile(p.Pattern) + } else { + re, err = regexp.Compile("(?i:" + p.Pattern + ")") + } + if err != nil { + return nil, fmt.Errorf("invalid regex: %w", err) + } + return func(line string) bool { return re.MatchString(line) }, nil + } + if p.CaseSensitive || hasUppercase(p.Pattern) { + return func(line string) bool { return strings.Contains(line, p.Pattern) }, nil + } + lowerPattern := strings.ToLower(p.Pattern) + return func(line string) bool { return strings.Contains(strings.ToLower(line), lowerPattern) }, nil +} + +// formatGrepResults deduplicates and formats grep results in ripgrep style. +func formatGrepResults(results []grepResult) string { + if len(results) == 0 { + return "" + } + + // Overlapping context windows can emit the same line twice, and a line + // can be both a match and a neighbour's context. Dedup by file+line, + // preferring the match form. + seen := make(map[string]int) + deduped := results[:0] + for _, r := range results { + key := fmt.Sprintf("%s:%d", r.relPath, r.lineNum) + if idx, ok := seen[key]; ok { + if !r.isContext { + deduped[idx].isContext = false + } + continue + } + seen[key] = len(deduped) + deduped = append(deduped, r) + } + + // Format results like ripgrep: path:line:content for matches, + // path-line-content for context lines. + var lines []string + for _, r := range deduped { + if r.isContext { + lines = append(lines, fmt.Sprintf("%s-%d-%s", r.relPath, r.lineNum, r.content)) + } else { + lines = append(lines, fmt.Sprintf("%s:%d:%s", r.relPath, r.lineNum, r.content)) + } + } + + return strings.Join(lines, "\n") +} + +type grepResult struct { + relPath string + lineNum int + content string + isContext bool +} + +func grepFile(ctx context.Context, path string, matcher func(string) bool, ctxBefore, ctxAfter int) ([]grepResult, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + str := string(data) + allLines := strings.Split(str, "\n") + + var results []grepResult + for i, line := range allLines { + select { + case <-ctx.Done(): + return nil, ctx.Err() + default: + } + + if matcher(line) { + // Add context lines before. + start := max(i-ctxBefore, 0) + for j := start; j < i; j++ { + results = append(results, grepResult{ + lineNum: j + 1, + content: allLines[j], + isContext: true, + }) + } + + // Add match line. + results = append(results, grepResult{ + lineNum: i + 1, + content: line, + isContext: false, + }) + + // Add context lines after. + end := i + ctxAfter + if end >= len(allLines) { + end = len(allLines) - 1 + } + for j := i + 1; j <= end; j++ { + results = append(results, grepResult{ + lineNum: j + 1, + content: allLines[j], + isContext: true, + }) + } + } + } + + return results, nil +} + +func buildGrepArgs(p GrepParams) []string { + args := []string{"--line-number", "--with-filename", "--no-heading", "--color=never"} + + if p.Literal { + args = append(args, "--fixed-strings") + } + + if !p.CaseSensitive { + args = append(args, "--smart-case") + } else { + args = append(args, "--case-sensitive") + } + + if p.Include != "" { + args = append(args, "--glob", p.Include) + } + + if p.ContextBefore > 0 { + args = append(args, fmt.Sprintf("-B%d", p.ContextBefore)) + } + if p.ContextAfter > 0 { + args = append(args, fmt.Sprintf("-A%d", p.ContextAfter)) + } + + args = append(args, "--", p.Pattern) + return args +} + +func grepBinary() (string, error) { + // Use the embedded statically-linked ripgrep binary. + return rg.Path() +} + +// hasUppercase reports whether s contains any uppercase ASCII letter. +func hasUppercase(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] >= 'A' && s[i] <= 'Z' { + return true + } + } + return false +} diff --git a/internal/tools/builtin/grep_test.go b/internal/tools/builtin/grep_test.go new file mode 100644 index 000000000..7d185a0f3 --- /dev/null +++ b/internal/tools/builtin/grep_test.go @@ -0,0 +1,409 @@ +package builtin + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +type staticGrepIndex struct{ files []string } + +func (s staticGrepIndex) Candidates(context.Context, string, bool, bool) ([]string, bool) { + return s.files, true +} + +func TestGrepUsesIndexCandidatesAsAdvisoryFileSet(t *testing.T) { + tmp := t.TempDir() + indexed := filepath.Join(tmp, "indexed.txt") + createGrepTestFile(t, tmp, "indexed.txt", "needle\n") + createGrepTestFile(t, tmp, "excluded.txt", "needle\n") + tool := NewGrepTool(tmp, staticGrepIndex{files: []string{indexed}}) + result, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"needle"}`), nil) + if err != nil || result.IsError { + t.Fatalf("grep result = %#v, err = %v", result, err) + } + if !strings.Contains(result.Content, "indexed.txt") || strings.Contains(result.Content, "excluded.txt") { + t.Fatalf("candidate-filtered output = %s", result.Content) + } +} + +func TestGrepRetriesDirectSearchWhenIndexedCandidatesAreStale(t *testing.T) { + tmp := t.TempDir() + createGrepTestFile(t, tmp, "live.txt", "needle\n") + missing := filepath.Join(tmp, "deleted.txt") + tool := NewGrepTool(tmp, staticGrepIndex{files: []string{missing}}) + result, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"needle"}`), nil) + if err != nil || result.IsError { + t.Fatalf("grep result = %#v, err = %v", result, err) + } + if !strings.Contains(result.Content, "live.txt") || result.MetricLabels["search_backend"] != "direct" { + t.Fatalf("fallback output = %s, labels = %v", result.Content, result.MetricLabels) + } +} + +func TestGrepDiscardsPartialIndexedOutputOnCandidateError(t *testing.T) { + tmp := t.TempDir() + live := filepath.Join(tmp, "live.txt") + createGrepTestFile(t, tmp, "live.txt", "needle\n") + createGrepTestFile(t, tmp, "also-live.txt", "needle\n") + missing := filepath.Join(tmp, "deleted.txt") + tool := NewGrepTool(tmp, staticGrepIndex{files: []string{live, missing}}) + result, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"needle"}`), nil) + if err != nil || result.IsError { + t.Fatalf("grep result = %#v, err = %v", result, err) + } + if !strings.Contains(result.Content, "also-live.txt") || result.MetricLabels["search_backend"] != "direct" { + t.Fatalf("partial indexed output was not replaced: %s, labels = %v", result.Content, result.MetricLabels) + } +} + +func TestGrepFallback(t *testing.T) { + // Create a temporary directory with test files. + tmp := t.TempDir() + createGrepTestFile(t, tmp, "alpha.go", "package alpha\nfunc Hello() {}\n") + createGrepTestFile(t, tmp, "beta.go", "package beta\nfunc World() {}\nfunc hello() {}\n") + createGrepTestFile(t, tmp, "gamma.txt", "Hello world\n") + createGrepTestFile(t, tmp, "vendor/mod.go", "package vendor\nfunc Hello() {}\n") + createGrepTestFile(t, tmp, "subdir/nested.go", "package nested\nfunc HelloThere() {}\n") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + cases := []struct { + name string + params GrepParams + want []string + wantEmpty bool + }{ + { + name: "literal match in file", + params: GrepParams{Pattern: "Hello", Path: filepath.Join(tmp, "alpha.go")}, + want: []string{"alpha.go:2:func Hello() {}"}, + }, + { + // Smart case: an uppercase letter in the pattern makes the + // search case-sensitive, matching ripgrep's --smart-case. + name: "match in directory (smart case)", + params: GrepParams{Pattern: "Hello", Path: tmp}, + want: []string{ + "alpha.go:2:func Hello() {}", + "gamma.txt:1:Hello world", + "subdir/nested.go:2:func HelloThere() {}", + "vendor/mod.go:2:func Hello() {}", + }, + }, + { + name: "lowercase pattern matches both cases", + params: GrepParams{Pattern: "hello", Path: tmp}, + want: []string{ + "alpha.go:2:func Hello() {}", + "beta.go:3:func hello() {}", + "gamma.txt:1:Hello world", + "subdir/nested.go:2:func HelloThere() {}", + "vendor/mod.go:2:func Hello() {}", + }, + }, + { + name: "case sensitive literal", + params: GrepParams{Pattern: "Hello", Path: tmp, CaseSensitive: true}, + want: []string{ + "alpha.go:2:func Hello() {}", + "gamma.txt:1:Hello world", + "subdir/nested.go:2:func HelloThere() {}", + "vendor/mod.go:2:func Hello() {}", + }, + }, + { + name: "regex match by default", + params: GrepParams{Pattern: "Hello.*", Path: tmp}, + want: []string{ + "alpha.go:2:func Hello() {}", + "gamma.txt:1:Hello world", + "subdir/nested.go:2:func HelloThere() {}", + "vendor/mod.go:2:func Hello() {}", + }, + }, + { + name: "regex alternation", + params: GrepParams{Pattern: "World|world", Path: tmp}, + want: []string{ + "beta.go:2:func World() {}", + "gamma.txt:1:Hello world", + }, + }, + { + name: "literal match with regex metacharacters", + params: GrepParams{Pattern: "Hello() {}", Path: tmp, Literal: true, CaseSensitive: true}, + want: []string{ + "alpha.go:2:func Hello() {}", + "vendor/mod.go:2:func Hello() {}", + }, + }, + { + name: "include filter", + params: GrepParams{Pattern: "hello", Path: tmp, Include: "*.go"}, + want: []string{ + "alpha.go:2:func Hello() {}", + "beta.go:3:func hello() {}", + "subdir/nested.go:2:func HelloThere() {}", + "vendor/mod.go:2:func Hello() {}", + }, + }, + { + name: "context lines", + params: GrepParams{Pattern: "Hello", Path: filepath.Join(tmp, "alpha.go"), ContextBefore: 1, ContextAfter: 1}, + want: []string{ + "alpha.go-1-package alpha", + "alpha.go:2:func Hello() {}", + "alpha.go-3-", // trailing newline yields empty third line + }, + }, + { + name: "no matches", + params: GrepParams{Pattern: "nonexistentXYZ", Path: tmp}, + wantEmpty: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := grepFallback(ctx, tc.params, tc.params.Path, tmp, nil) + if err != nil { + t.Fatalf("grepFallback error: %v", err) + } + if tc.wantEmpty { + if got != "" { + t.Fatalf("expected empty, got:\n%s", got) + } + return + } + gotLines := strings.Split(strings.TrimSpace(got), "\n") + if len(gotLines) == 1 && gotLines[0] == "" { + gotLines = []string{} + } + if len(gotLines) != len(tc.want) { + t.Fatalf("got %d results, want %d\ngot:\n%s\nwant: %v", len(gotLines), len(tc.want), got, tc.want) + } + for i := range tc.want { + if gotLines[i] != tc.want[i] { + t.Fatalf("result mismatch at %d: got %q, want %q", i, gotLines[i], tc.want[i]) + } + } + }) + } +} + +func TestGrepFallback_ContextDedup(t *testing.T) { + tmp := t.TempDir() + content := "line1\nHello\nline3\nHello\nline5\n" + createGrepTestFile(t, tmp, "test.txt", content) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + params := GrepParams{Pattern: "Hello", Path: tmp, ContextBefore: 1, ContextAfter: 1} + got, err := grepFallback(ctx, params, tmp, tmp, nil) + if err != nil { + t.Fatalf("grepFallback error: %v", err) + } + + lines := strings.Split(strings.TrimSpace(got), "\n") + // Expected: + // line1 (context for first Hello) + // Hello (match 1) + // line3 (context after first Hello + context before second Hello - dedup) + // Hello (match 2) + // line5 (context after second Hello) + // Total unique lines: 5 + if len(lines) != 5 { + t.Fatalf("expected 5 lines, got %d:\n%s", len(lines), got) + } +} + +func TestCapGrepOutput_MatchLimit(t *testing.T) { + var lines []string + for i := 1; i <= 20; i++ { + lines = append(lines, fmt.Sprintf("file.go:%d:match line", i)) + } + output := strings.Join(lines, "\n") + + got := capGrepResult(output, 5).Content + + if !strings.Contains(got, "[showing first 5 matches") { + t.Fatalf("expected match-limit notice, got:\n%s", got) + } + matchCount := strings.Count(got, "match line") + if matchCount != 5 { + t.Fatalf("expected 5 match lines, got %d", matchCount) + } +} + +func TestCapGrepOutput_LongLines(t *testing.T) { + long := "file.js:1:" + strings.Repeat("x", 2000) + got := capGrepResult(long, 100).Content + + if !strings.Contains(got, "... [truncated]") { + t.Fatalf("expected per-line truncation marker, got:\n%s", got) + } + if !strings.Contains(got, "[some lines truncated to 500 chars]") { + t.Fatalf("expected long-line notice, got:\n%s", got) + } + if len(strings.Split(got, "\n")[0]) > 600 { + t.Fatalf("first line not capped: %d chars", len(strings.Split(got, "\n")[0])) + } +} + +func TestCapGrepOutput_ContextLinesNotCounted(t *testing.T) { + // Context lines (dash separators) must not count towards the match limit. + output := strings.Join([]string{ + "file.go-1-context before", + "file.go:2:match one", + "file.go-3-context after", + "file.go:4:match two", + }, "\n") + + got := capGrepResult(output, 2).Content + + if strings.Contains(got, "[showing first") { + t.Fatalf("limit notice should not fire for 2 matches with limit 2, got:\n%s", got) + } + if !strings.Contains(got, "match two") { + t.Fatalf("expected both matches present, got:\n%s", got) + } +} + +func TestGrepFallback_NonExistentPath(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _, err := grepFallback(ctx, GrepParams{Pattern: "foo"}, "/nonexistent/path", "/nonexistent/path", nil) + if err == nil { + t.Fatal("expected error for non-existent path") + } +} + +func createGrepTestFile(t *testing.T, base, relPath, content string) { + t.Helper() + full := filepath.Join(base, relPath) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestGrepClampsContextLines(t *testing.T) { + tmp := t.TempDir() + var lines []string + for i := 1; i <= 200; i++ { + if i == 100 { + lines = append(lines, "the needle") + continue + } + lines = append(lines, fmt.Sprintf("filler %d", i)) + } + createGrepTestFile(t, tmp, "f.txt", strings.Join(lines, "\n")+"\n") + + tool := NewGrepTool(tmp, nil) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"pattern":"needle","context_before":40,"context_after":40}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + + // Context is clamped to grepMaxContext either side, so a line that far + // from the match must not appear. + if strings.Contains(res.Content, "filler 80") || strings.Contains(res.Content, "filler 120") { + t.Fatalf("context lines were not clamped, got:\n%s", res.Content) + } + if !strings.Contains(res.Content, "filler 99") || !strings.Contains(res.Content, "filler 101") { + t.Fatalf("clamped context should still include adjacent lines, got:\n%s", res.Content) + } + if !strings.Contains(res.Content, "context") { + t.Fatalf("expected a notice explaining the clamp, got:\n%s", res.Content) + } +} + +func TestGrepLeavesModestContextAlone(t *testing.T) { + tmp := t.TempDir() + createGrepTestFile(t, tmp, "f.txt", "a\nb\nneedle\nd\ne\n") + + tool := NewGrepTool(tmp, nil) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"pattern":"needle","context_before":2,"context_after":2}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if strings.Contains(res.Content, "clamped") { + t.Fatalf("a within-limit request must not be clamped, got:\n%s", res.Content) + } + for _, want := range []string{"a", "b", "needle", "d", "e"} { + if !strings.Contains(res.Content, want) { + t.Fatalf("missing %q in:\n%s", want, res.Content) + } + } +} + +// The index served only 5% of searches across the analysed sessions +// (codesearch 11, direct 199) because it engaged only when the search path was +// exactly cwd. Any subdirectory-scoped search silently fell back to a walk. +func TestGrepUsesIndexForSubdirectorySearch(t *testing.T) { + tmp := t.TempDir() + createGrepTestFile(t, tmp, "sub/inside.txt", "needle\n") + createGrepTestFile(t, tmp, "other/outside.txt", "needle\n") + + index := staticGrepIndex{files: []string{ + filepath.Join(tmp, "sub", "inside.txt"), + filepath.Join(tmp, "other", "outside.txt"), + }} + + tool := NewGrepTool(tmp, index) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"pattern":"needle","path":"sub"}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + if got := res.MetricLabels["search_backend"]; got != "codesearch" { + t.Fatalf("search_backend = %q, want codesearch", got) + } + if !strings.Contains(res.Content, "inside.txt") { + t.Fatalf("expected the in-scope match, got:\n%s", res.Content) + } + if strings.Contains(res.Content, "outside.txt") { + t.Fatalf("candidates outside the search path must be filtered out, got:\n%s", res.Content) + } +} + +// If the index has no candidates inside the requested subtree we must not +// conclude "no matches" from an empty candidate list - fall back to a walk. +func TestGrepFallsBackToDirectWhenNoCandidatesInSubtree(t *testing.T) { + tmp := t.TempDir() + createGrepTestFile(t, tmp, "sub/inside.txt", "needle\n") + + index := staticGrepIndex{files: []string{filepath.Join(tmp, "elsewhere.txt")}} + + tool := NewGrepTool(tmp, index) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"pattern":"needle","path":"sub"}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got := res.MetricLabels["search_backend"]; got != "direct" { + t.Fatalf("search_backend = %q, want direct", got) + } + if !strings.Contains(res.Content, "inside.txt") { + t.Fatalf("an empty candidate set must not hide real matches, got:\n%s", res.Content) + } +} diff --git a/internal/tools/builtin/mutation.go b/internal/tools/builtin/mutation.go new file mode 100644 index 000000000..bb121c154 --- /dev/null +++ b/internal/tools/builtin/mutation.go @@ -0,0 +1,96 @@ +// Lifted from tau internal/agent/tools/mutation.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "sync" +) + +// MutationQueue serializes write operations to the same file path, +// preventing concurrent edits from clobbering each other during +// parallel tool execution. +// +// A sync.RWMutex coordinates between shell commands and file-mutation +// tools. File mutations (write, edit) take a read lock so they +// can run concurrently with each other. Shell commands take the write +// lock, blocking all file mutations for the duration of the command. +type MutationQueue struct { + mu sync.Mutex + locks map[string]*mutexEntry + + globalMu sync.RWMutex +} + +// mutexEntry tracks a per-file mutex and its active holder count. +type mutexEntry struct { + mu sync.Mutex + holders int +} + +// NewMutationQueue creates a new per-file mutation queue. +func NewMutationQueue() *MutationQueue { + return &MutationQueue{ + locks: make(map[string]*mutexEntry), + } +} + +// GlobalLock blocks until all in-flight per-file mutations complete, then +// prevents new per-file Acquire calls from proceeding until GlobalUnlock +// is called. Used by the shell tool to ensure no race between shell +// commands and file-mutation tools. +func (q *MutationQueue) GlobalLock() { + q.globalMu.Lock() +} + +// GlobalUnlock releases the global lock, allowing per-file mutations to +// proceed again. +func (q *MutationQueue) GlobalUnlock() { + q.globalMu.Unlock() +} + +// Acquire returns a lock for the given file path. The caller must call +// the returned release function when done with the mutation. +// +// Acquire blocks while the global write lock is held (i.e. while a shell +// command is running). +// +// Usage: +// +// release := q.Acquire("/path/to/file.go") +// defer release() +// // ... perform read-modify-write ... +func (q *MutationQueue) Acquire(path string) (release func()) { + // Take a read lock so shell commands (which take the write lock) + // block until we're done, and we block while a shell command runs. + q.globalMu.RLock() + + q.mu.Lock() + entry, ok := q.locks[path] + if !ok { + entry = &mutexEntry{} + q.locks[path] = entry + } + entry.holders++ + q.mu.Unlock() + + entry.mu.Lock() + return func() { + entry.mu.Unlock() + + q.mu.Lock() + entry.holders-- + if entry.holders == 0 { + delete(q.locks, path) + } + q.mu.Unlock() + + q.globalMu.RUnlock() + } +} diff --git a/internal/tools/builtin/mutation_test.go b/internal/tools/builtin/mutation_test.go new file mode 100644 index 000000000..f9af35a5c --- /dev/null +++ b/internal/tools/builtin/mutation_test.go @@ -0,0 +1,68 @@ +package builtin_test + +import ( + "sync" + "sync/atomic" + "testing" + + "github.com/samcharles93/archie-core/internal/tools/builtin" +) + +func TestMutationQueue_Serializes(t *testing.T) { + q := builtin.NewMutationQueue() + path := "/tmp/test.txt" + + var counter atomic.Int64 + var maxConcurrent atomic.Int64 + var wg sync.WaitGroup + + for i := range 50 { + _ = i + wg.Go(func() { + release := q.Acquire(path) + defer release() + + cur := counter.Add(1) + // Track max concurrency for this path. + for { + old := maxConcurrent.Load() + if cur <= old || maxConcurrent.CompareAndSwap(old, cur) { + break + } + } + counter.Add(-1) + }) + } + + wg.Wait() + + if maxConcurrent.Load() > 1 { + t.Fatalf("expected max concurrency of 1, got %d", maxConcurrent.Load()) + } +} + +func TestMutationQueue_DifferentPaths_Parallel(t *testing.T) { + q := builtin.NewMutationQueue() + + var wg sync.WaitGroup + started := make(chan struct{}, 2) + + wg.Add(2) + go func() { + defer wg.Done() + release := q.Acquire("/path/a") + started <- struct{}{} + <-started // wait for both to acquire + release() + }() + go func() { + defer wg.Done() + release := q.Acquire("/path/b") + started <- struct{}{} + <-started // wait for both to acquire + release() + }() + + wg.Wait() + // If we get here without deadlocking, different paths don't block each other. +} diff --git a/internal/tools/builtin/pathutil.go b/internal/tools/builtin/pathutil.go new file mode 100644 index 000000000..32595e1b3 --- /dev/null +++ b/internal/tools/builtin/pathutil.go @@ -0,0 +1,93 @@ +// Lifted from tau internal/agent/tools/pathutil.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "os" + "path/filepath" + "strings" + "sync" +) + +const ( + // maxReadBytes is the maximum file size the read tool will load into memory. + maxReadBytes = 5 * 1024 * 1024 // 5MB + + // maxWriteBytes is the maximum content size the write tool will accept. + maxWriteBytes = 5 * 1024 * 1024 // 5MB +) + +// resolvePath resolves a potentially relative path against the working directory. +// It also strips a leading @ (some LLMs include this). +func resolvePath(cwd, path string) string { + path = strings.TrimPrefix(path, "@") + if filepath.IsAbs(path) { + return filepath.Clean(path) + } + return filepath.Clean(filepath.Join(cwd, path)) +} + +// goModCacheDir returns the Go module cache root, or "" if it cannot be +// determined. It mirrors cmd/go's own resolution order rather than shelling +// out to `go env GOMODCACHE`, so path checks stay allocation-cheap and do not +// depend on a Go toolchain being installed. It is a var so tests can point it +// at a temp dir instead of the host's real cache. +var goModCacheDir = sync.OnceValue(func() string { + if v := os.Getenv("GOMODCACHE"); v != "" { + return filepath.Clean(v) + } + if v := os.Getenv("GOPATH"); v != "" { + // GOPATH may be a list; cmd/go uses the first entry. + if first, _, _ := strings.Cut(v, string(os.PathListSeparator)); first != "" { + return filepath.Join(filepath.Clean(first), "pkg", "mod") + } + } + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, "go", "pkg", "mod") +}) + +// isReadConfined reports whether a read-only tool may touch target. It permits +// the workspace plus the Go module cache: sandbox_escape on module-cache paths +// was the largest avoidable error class across analysed sessions, and every +// occurrence was a legitimate attempt to read dependency source. The cache is +// deliberately NOT extended to the mutating tools (edit, write), which stay +// confined to the workspace so the agent cannot corrupt shared dependencies. +func isReadConfined(base, target string) bool { + if isConfined(base, target) { + return true + } + cache := goModCacheDir() + return cache != "" && isConfined(cache, target) +} + +// isConfined checks whether target is within (or equal to) the base directory. +// Returns false if target escapes via ../ or is an unrelated absolute path. +func isConfined(base, target string) bool { + if base == "" { + return true // no confinement if cwd is unset + } + baseAbs, err := filepath.Abs(base) + if err != nil { + return false + } + targetAbs, err := filepath.Abs(target) + if err != nil { + return false + } + + rel, err := filepath.Rel(baseAbs, targetAbs) + if err != nil { + return false + } + return !strings.HasPrefix(rel, "..") && rel != ".." +} diff --git a/internal/tools/builtin/pathutil_test.go b/internal/tools/builtin/pathutil_test.go new file mode 100644 index 000000000..d708a17e3 --- /dev/null +++ b/internal/tools/builtin/pathutil_test.go @@ -0,0 +1,131 @@ +package builtin + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +// withGoModCache points the module-cache lookup at a temp dir for the duration +// of a test, so these tests never depend on the host's real GOMODCACHE. +func withGoModCache(t *testing.T, dir string) { + t.Helper() + prev := goModCacheDir + goModCacheDir = func() string { return dir } + t.Cleanup(func() { goModCacheDir = prev }) +} + +func TestReadAllowsGoModCache(t *testing.T) { + cwd := t.TempDir() + cache := t.TempDir() + withGoModCache(t, cache) + + dep := filepath.Join(cache, "example.com", "dep@v1.0.0") + if err := os.MkdirAll(dep, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dep, "dep.go"), []byte("package dep\n"), 0o644); err != nil { + t.Fatal(err) + } + + res := execRead(t, cwd, `{"path":`+quote(filepath.Join(dep, "dep.go"))+`}`) + if res.IsError { + t.Fatalf("expected read of a module-cache file to succeed, got: %s", res.Content) + } + if !strings.Contains(res.Content, "package dep") { + t.Fatalf("unexpected content: %s", res.Content) + } +} + +func TestGrepAllowsGoModCache(t *testing.T) { + cwd := t.TempDir() + cache := t.TempDir() + withGoModCache(t, cache) + + if err := os.WriteFile(filepath.Join(cache, "dep.go"), []byte("package dep\nfunc Needle() {}\n"), 0o644); err != nil { + t.Fatal(err) + } + + tool := NewGrepTool(cwd, nil) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"pattern":"Needle","path":`+quote(cache)+`}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("expected grep of the module cache to succeed, got: %s", res.Content) + } + if !strings.Contains(res.Content, "Needle") { + t.Fatalf("unexpected content: %s", res.Content) + } +} + +// The module cache is a read-only escape hatch. Mutating tools must still be +// confined to the workspace, or the agent could corrupt shared dependencies. +func TestWriteRejectsGoModCache(t *testing.T) { + cwd := t.TempDir() + cache := t.TempDir() + withGoModCache(t, cache) + + tool := NewWriteTool(cwd, nil, NewReadTracker()) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"path":`+quote(filepath.Join(cache, "evil.go"))+`,"content":"package evil\n"}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError || !strings.Contains(res.Content, "escapes working directory") { + t.Fatalf("expected write to the module cache to be rejected, got: %#v", res) + } +} + +func TestEditRejectsGoModCache(t *testing.T) { + cwd := t.TempDir() + cache := t.TempDir() + withGoModCache(t, cache) + + target := filepath.Join(cache, "dep.go") + if err := os.WriteFile(target, []byte("package dep\n"), 0o644); err != nil { + t.Fatal(err) + } + + rt := NewReadTracker() + rt.MarkRead(cwd, target) + tool := NewEditTool(cwd, nil, rt) + res, err := tool.Execute(context.Background(), json.RawMessage( + `{"path":`+quote(target)+`,"edits":[{"old_text":"package dep","new_text":"package hacked"}]}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError || !strings.Contains(res.Content, "escapes working directory") { + t.Fatalf("expected edit of the module cache to be rejected, got: %#v", res) + } +} + +// A path in neither the workspace nor the module cache stays rejected. +func TestReadRejectsUnrelatedAbsolutePath(t *testing.T) { + cwd := t.TempDir() + cache := t.TempDir() + other := t.TempDir() + withGoModCache(t, cache) + + target := filepath.Join(other, "secret.txt") + if err := os.WriteFile(target, []byte("secret\n"), 0o644); err != nil { + t.Fatal(err) + } + + res := execRead(t, cwd, `{"path":`+quote(target)+`}`) + if !res.IsError || !strings.Contains(res.Content, "escapes working directory") { + t.Fatalf("expected an unrelated absolute path to be rejected, got: %#v", res) + } +} + +func quote(s string) string { + b, err := json.Marshal(s) + if err != nil { + panic(err) + } + return string(b) +} diff --git a/internal/tools/builtin/procgroup_unix.go b/internal/tools/builtin/procgroup_unix.go new file mode 100644 index 000000000..bbc45ea36 --- /dev/null +++ b/internal/tools/builtin/procgroup_unix.go @@ -0,0 +1,43 @@ +// Lifted from tau internal/agent/tools/procgroup_unix.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +//go:build !windows + +package builtin + +import ( + "os/exec" + "syscall" +) + +// setProcessGroup configures cmd to start as the leader of a new process +// group, so the parent can signal the whole tree (see +// docs/specs/agents/02-spawning-and-lifecycle.md, Process group +// management). Must be called before cmd.Start(). +func setProcessGroup(cmd *exec.Cmd) { + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + cmd.SysProcAttr.Setpgid = true +} + +// signalProcessGroup sends sig to cmd's entire process group (shells, +// tools, provider subprocesses, grandchild agents - everything that +// inherited the group from setProcessGroup). Must be called after +// cmd.Start(). ESRCH (group already gone) is not an error worth surfacing. +func signalProcessGroup(cmd *exec.Cmd, sig syscall.Signal) error { + if cmd.Process == nil { + return nil + } + // A negative pid targets the whole process group (see kill(2)). + if err := syscall.Kill(-cmd.Process.Pid, sig); err != nil && err != syscall.ESRCH { + return err + } + return nil +} diff --git a/internal/tools/builtin/procgroup_windows.go b/internal/tools/builtin/procgroup_windows.go new file mode 100644 index 000000000..7b79f0e36 --- /dev/null +++ b/internal/tools/builtin/procgroup_windows.go @@ -0,0 +1,40 @@ +// Lifted from tau internal/agent/tools/procgroup_windows.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +//go:build windows + +package builtin + +import ( + "os/exec" + "syscall" +) + +// setProcessGroup configures cmd to start in a new process group on +// Windows (see docs/specs/agents/02-spawning-and-lifecycle.md, Process +// group management / Platform behavior). +func setProcessGroup(cmd *exec.Cmd) { + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + cmd.SysProcAttr.CreationFlags |= syscall.CREATE_NEW_PROCESS_GROUP +} + +// signalProcessGroup best-effort terminates cmd's direct process on +// Windows. Windows has no POSIX-style negative-pid group signal; the spec's +// documented fallback is TerminateProcess (GenerateConsoleCtrlEvent would +// require additional job-object/console plumbing this doesn't set up), so +// descendants spawned by the child are not guaranteed to receive this - +// a known platform limitation, not an oversight. +func signalProcessGroup(cmd *exec.Cmd, _ syscall.Signal) error { + if cmd.Process == nil { + return nil + } + return cmd.Process.Kill() +} diff --git a/internal/tools/builtin/read.go b/internal/tools/builtin/read.go new file mode 100644 index 000000000..982bd67fe --- /dev/null +++ b/internal/tools/builtin/read.go @@ -0,0 +1,355 @@ +// Lifted from tau internal/agent/tools/read.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "context" + "encoding/json" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "unicode/utf8" +) + +// ReadParams are the parameters for the read tool. +type ReadParams struct { + Path string `json:"path"` + File string `json:"file,omitempty"` // compatibility alias used by some providers + Offset int `json:"offset,omitempty"` // start line (1-based) + Limit int `json:"limit,omitempty"` // max lines to read + Full bool `json:"full,omitempty"` // explicitly allow a full-file response +} + +// DefaultReadLines is the bounded line count used when no explicit read limit +// or full-file request is supplied. +const DefaultReadLines = 400 + +var readSchema = Schema{ + Name: "read", + Description: fmt.Sprintf("Read file contents; pointed at a directory it returns a listing. Omitted limits return at most %d lines; set full:true only when the complete file is genuinely needed. Output is always capped at %d lines or %s and includes a continuation offset.", DefaultReadLines, DefaultMaxLines, FormatSize(DefaultMaxBytes)), + // NOTE: file is a compatibility alias for path; the executor + // handles the fallback (file → path) and returns a clear error + // when both are empty. We intentionally do NOT use anyOf here + // because the OpenAI Responses API rejects schemas with + // anyOf/oneOf/allOf at the top level of the parameters object. + Parameters: json.RawMessage(`{ + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Absolute or relative file path to read" + }, + "file": { + "type": "string", + "description": "Compatibility alias for path. Prefer path." + }, + "offset": { + "type": "integer", + "description": "Start reading from this line number (1-based). Defaults to 1." + }, + "limit": { + "type": "integer", + "description": "Maximum number of lines to read. Defaults to 400 unless full is true." + }, + "full": { + "type": "boolean", + "description": "Return the whole file up to the global safety cap, and resend lines you have already been shown. Defaults to false. Lines already read from an unchanged file are skipped unless this is set." + } + } + }`), +} + +const ( + // maxPathSuggestions bounds how many alternatives a not-found read offers. + maxPathSuggestions = 5 + + // maxSuggestionScan bounds the walk behind those suggestions. A miss is + // already an error path, so it must stay cheap on a large workspace. + maxSuggestionScan = 20000 +) + +// suggestPaths looks for files sharing the missing path's basename. Reads that +// fail on a plausible-but-wrong path cost a round trip plus a follow-up find; +// naming the real location lets the model correct itself immediately. +// +// The match is on basename alone, which is loose, but a wrong suggestion costs +// one line of output while no suggestion costs a whole round trip. +func suggestPaths(cwd, missing string) string { + if cwd == "" { + return "" + } + want := filepath.Base(missing) + if want == "" || want == "." || want == string(filepath.Separator) { + return "" + } + + // If the directory exists, its contents are the most useful answer: the + // model had the location right and only the filename wrong. This is the + // shape of the real misses (internal/theme/theme.go, where the directory + // exists but holds colors.go), and it avoids the walk entirely. + if dir := filepath.Dir(missing); dir != "" { + if entries, err := os.ReadDir(dir); err == nil { + names := make([]string, 0, maxPathSuggestions) + for _, e := range entries { + if len(names) >= maxPathSuggestions { + names = append(names, "...") + break + } + names = append(names, e.Name()) + } + if len(names) > 0 { + rel, relErr := filepath.Rel(cwd, dir) + if relErr != nil { + rel = dir + } + return fmt.Sprintf("%s exists and contains: %s", rel, strings.Join(names, ", ")) + } + } + } + + var found []string + scanned := 0 + + _ = filepath.WalkDir(cwd, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return nil //nolint:nilerr // an unreadable subtree just yields no suggestions + } + if scanned++; scanned > maxSuggestionScan { + return fs.SkipAll + } + if d.IsDir() { + if skipSuggestionDir(d.Name()) { + return fs.SkipDir + } + return nil + } + if d.Name() != want { + return nil + } + if rel, relErr := filepath.Rel(cwd, path); relErr == nil { + found = append(found, rel) + } + if len(found) >= maxPathSuggestions { + return fs.SkipAll + } + return nil + }) + + if len(found) == 0 { + return "" + } + return "did you mean: " + strings.Join(found, ", ") +} + +// skipSuggestionDir keeps the suggestion walk out of directories that are large +// and never the answer. +func skipSuggestionDir(name string) bool { + switch name { + case ".git", "node_modules", "vendor", "dist", "build", ".cache": + return true + } + return false +} + +// maxDirEntries bounds the listing returned when read is pointed at a +// directory. Large directories are truncated rather than refused. +const maxDirEntries = 200 + +// listDirResult renders a bounded directory listing. display is the path as +// the caller wrote it, so the notice echoes their own spelling. +func listDirResult(path, display string) (Result, error) { + entries, err := os.ReadDir(path) + if err != nil { + return Result{Content: fmt.Sprintf("error reading directory: %v", err), IsError: true}, nil + } + + var b strings.Builder + fmt.Fprintf(&b, "%s is a directory, not a file. Listing:\n", display) + for i, e := range entries { + if i >= maxDirEntries { + fmt.Fprintf(&b, "\n[%d more entries; use find for a filtered search]", len(entries)-maxDirEntries) + break + } + if e.IsDir() { + fmt.Fprintf(&b, "%s/\n", e.Name()) + continue + } + fmt.Fprintf(&b, "%s\n", e.Name()) + } + + return Result{Content: strings.TrimRight(b.String(), "\n"), Truncated: len(entries) > maxDirEntries}, nil +} + +// NewReadTool creates the built-in read tool. +func NewReadTool(cwd string, rt *ReadTracker) Tool { + return Tool{ + Schema: readSchema, + Source: "builtin", + Execute: makeReadExecutor(cwd, rt), + } +} + +func makeReadExecutor(cwd string, rt *ReadTracker) Executor { + return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { + var p ReadParams + if err := json.Unmarshal(params, &p); err != nil { + return Result{Content: fmt.Sprintf("invalid parameters: %v", err), IsError: true}, nil + } + + if p.Offset < 0 { + return Result{Content: "offset must be >= 0", IsError: true}, nil + } + if p.Limit < 0 { + return Result{Content: "limit must be >= 0", IsError: true}, nil + } + if strings.TrimSpace(p.Path) == "" { + p.Path = p.File + } + if strings.TrimSpace(p.Path) == "" { + return Result{Content: "path is required (file is accepted as an alias)", IsError: true, ErrorKind: "invalid_arguments"}, nil + } + // Record whether the caller asked for a specific slice before the + // default is applied. An explicit limit that happens to equal the + // default is still an explicit content request, so it must not be + // mistaken for "unspecified" by the outline check below. + rangeRequested := p.Offset > 0 || p.Limit > 0 + + if p.Limit == 0 && !p.Full { + p.Limit = DefaultReadLines + } + + _, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + path := resolvePath(cwd, p.Path) + + if !isReadConfined(cwd, path) { + return Result{Content: "path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil + } + + info, err := os.Stat(path) + if err != nil { + msg := fmt.Sprintf("error stating file: %v", err) + if hint := suggestPaths(cwd, path); hint != "" { + msg += "\n" + hint + } + return Result{Content: msg, IsError: true, ErrorKind: "not_found"}, nil + } + if info.IsDir() { + // The intent is unambiguous, so answer it rather than spending a + // round trip on an error. Deliberately returned before MarkRead: + // a directory must never satisfy the read-before-write check. + return listDirResult(path, p.Path) + } + if info.Size() > maxReadBytes { + return Result{Content: fmt.Sprintf("file too large (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true}, nil + } + + data, err := os.ReadFile(path) + if err != nil { + return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true}, nil + } + + // Record the read so mutation tools can enforce read-before-write. + // Only record after a successful ReadFile so we don't mark files + // that couldn't actually be read. + if rt != nil { + rt.MarkRead(cwd, p.Path) + } + + if !utf8.Valid(data) { + return Result{Content: "file appears to be binary", IsError: true}, nil + } + + content := string(data) + lines := strings.Split(content, "\n") + totalLines := len(lines) + + // For a large source file with no explicit range requested, an index of + // the whole file beats its first page. Returned before the served-range + // bookkeeping below, because the model has not been shown any of these + // lines and a later read of them must not be suppressed. + if !rangeRequested && !p.Full { + if outline := outlineFor(path, lines); outline != "" { + return Result{Content: outline, Truncated: true, ResultBytes: len(data)}, nil + } + } + + // Apply offset (1-based). + startLine := 1 + if p.Offset > 0 { + startLine = p.Offset + } + if startLine > totalLines { + return Result{Content: fmt.Sprintf("offset %d exceeds file length (%d lines)", startLine, totalLines), IsError: true}, nil + } + + // Apply limit. + endLine := totalLines + if p.Limit > 0 && startLine+p.Limit-1 < endLine { + endLine = startLine + p.Limit - 1 + } + + // Skip lines this session has already been shown from an unchanged + // file. Repeated reads were 23.6% of all tool result tokens across + // analysed sessions - one file was read 58 times in a single session. + // full:true is the deliberate escape hatch for a model that has lost + // the earlier content (compaction, handoff) and needs it resent. + requestedStart := startLine + if rt != nil && !p.Full { + novelStart, novelEnd, hasNovel := rt.Novel(cwd, p.Path, FileIdentity(info), startLine, endLine) + if !hasNovel { + return Result{Content: fmt.Sprintf( + "[lines %d-%d of %s are unchanged since you last read them; nothing new to show. Set full:true to have the content resent.]", + startLine, endLine, p.Path, + )}, nil + } + startLine, endLine = novelStart, novelEnd + } + + selected := strings.Join(lines[startLine-1:endLine], "\n") + tr := TruncateHeadRaw(selected, DefaultMaxLines, DefaultMaxBytes) + output := tr.Content + + if startLine > requestedStart { + output = fmt.Sprintf( + "[lines %d-%d unchanged since you last read them; showing from line %d.]\n\n", + requestedStart, startLine-1, startLine, + ) + output + } + + switch { + case tr.Truncated && tr.OutputLines == 0: + // The first requested line alone exceeds the byte limit. Point the + // model at a shell fallback that can slice within the line. + lineSize := FormatSize(len(lines[startLine-1])) + output = fmt.Sprintf( + "[line %d is %s, exceeding the %s output limit. Use shell: sed -n '%dp' %s | head -c %d]", + startLine, lineSize, FormatSize(DefaultMaxBytes), startLine, p.Path, DefaultMaxBytes, + ) + case tr.Truncated: + shownEnd := startLine + tr.OutputLines - 1 + output += fmt.Sprintf( + "\n\n[showing lines %d-%d of %d. Use offset=%d to continue.]", + startLine, shownEnd, totalLines, shownEnd+1, + ) + case endLine < totalLines: + // A user-specified limit stopped early, but the file has more content. + output += fmt.Sprintf( + "\n\n[%d more lines in file. Use offset=%d to continue.]", + totalLines-endLine, endLine+1, + ) + } + + return Result{Content: output, Truncated: tr.Truncated || endLine < totalLines, ResultBytes: tr.OriginalSize}, nil + } +} diff --git a/internal/tools/builtin/read_outline.go b/internal/tools/builtin/read_outline.go new file mode 100644 index 000000000..fccb0d623 --- /dev/null +++ b/internal/tools/builtin/read_outline.go @@ -0,0 +1,85 @@ +// Lifted from tau internal/agent/tools/read_outline.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "fmt" + "path/filepath" + "regexp" + "strings" +) + +// outlineThresholdLines is how much larger than the normal read budget a file +// must be before an outline replaces its first page. Files near the budget are +// better served raw: the outline saves little and costs a round trip to then +// fetch the body. +const outlineThresholdLines = 2 * DefaultReadLines + +// minOutlineEntries guards against a "structural" summary that is really just +// a handful of arbitrary lines. Below this the raw head is more honest. +const minOutlineEntries = 3 + +// outlinePatterns maps a file extension to the pattern matching its top-level +// declarations. Only languages with a reliable, anchored declaration syntax are +// listed: for anything else an outline would be a guess presented as structure, +// so read falls back to raw content. +var outlinePatterns = map[string]*regexp.Regexp{ + ".go": regexp.MustCompile(`^(func|type|const|var|package)\s`), + ".ts": tsOutlineRe(), + ".js": tsOutlineRe(), + ".mjs": tsOutlineRe(), + ".tsx": tsOutlineRe(), + ".jsx": tsOutlineRe(), + ".py": regexp.MustCompile(`^\s{0,4}(def|class|async def)\s`), +} + +func tsOutlineRe() *regexp.Regexp { + return regexp.MustCompile(`^(export\s|async\s+function\s|function\s|class\s|interface\s|type\s|const\s|enum\s)`) +} + +// outlineFor renders a line-numbered index of a large source file's top-level +// declarations, or "" when an outline is not appropriate. +// +// 15 reads in the analysed corpus landed in the 4k-16k token buckets, roughly +// 18% of all read tokens. DefaultReadLines bounds the line count but not the +// value: the first 400 lines of a 1,500-line file are mostly imports and +// whichever declarations happen to sort first, which is rarely what the model +// was looking for. An index of the whole file plus a targeted follow-up read is +// both cheaper and more likely to land on the right code. +func outlineFor(path string, lines []string) string { + pattern, ok := outlinePatterns[strings.ToLower(filepath.Ext(path))] + if !ok { + return "" + } + if len(lines) < outlineThresholdLines { + return "" + } + + var b strings.Builder + entries := 0 + for i, l := range lines { + if !pattern.MatchString(l) { + continue + } + entries++ + fmt.Fprintf(&b, "%d: %s\n", i+1, strings.TrimRight(l, " \t{")) + } + + // Generated tables and embedded data can be large with no declarations at + // all; an almost-empty outline would hide the file rather than describe it. + if entries < minOutlineEntries { + return "" + } + + return fmt.Sprintf( + "[outline of %s (%d lines, %d declarations). Bodies omitted - read a range with offset/limit, or set full:true.]\n\n%s", + filepath.Base(path), len(lines), entries, strings.TrimRight(b.String(), "\n"), + ) +} diff --git a/internal/tools/builtin/read_outline_test.go b/internal/tools/builtin/read_outline_test.go new file mode 100644 index 000000000..544991478 --- /dev/null +++ b/internal/tools/builtin/read_outline_test.go @@ -0,0 +1,140 @@ +package builtin + +import ( + "fmt" + "strings" + "testing" +) + +// bigGoFile builds a Go file well past the outline threshold, with each +// function body padded so bodies dominate the byte count. +func bigGoFile(t *testing.T, dir, name string, funcs int) { + t.Helper() + var b strings.Builder + b.WriteString("package big\n\nimport \"fmt\"\n\n") + for i := range funcs { + fmt.Fprintf(&b, "// Doc for Fn%d.\nfunc Fn%d() {\n", i, i) + for j := range 20 { + fmt.Fprintf(&b, "\tfmt.Println(\"body %d line %d\")\n", i, j) + } + b.WriteString("}\n\n") + } + writeReadTestFile(t, dir, name, b.String()) +} + +func TestRead_LargeGoFileReturnsOutline(t *testing.T) { + tmp := t.TempDir() + bigGoFile(t, tmp, "big.go", 60) + + res := execRead(t, tmp, `{"path":"big.go"}`) + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + if !strings.Contains(res.Content, "func Fn0()") || !strings.Contains(res.Content, "func Fn59()") { + t.Fatalf("outline should span the whole file, got:\n%s", truncateForMsg(res.Content)) + } + if strings.Contains(res.Content, "body 0 line 0") { + t.Fatalf("outline must not include function bodies, got:\n%s", truncateForMsg(res.Content)) + } + if !strings.Contains(res.Content, "offset") { + t.Fatalf("outline must tell the model how to read a range, got:\n%s", truncateForMsg(res.Content)) + } +} + +// Line numbers are the whole point: without them the outline is not actionable. +func TestRead_OutlineCarriesLineNumbers(t *testing.T) { + tmp := t.TempDir() + bigGoFile(t, tmp, "big.go", 60) + + res := execRead(t, tmp, `{"path":"big.go"}`) + // Each Fn is preceded by a doc comment, so blocks are 24 lines apart + // starting at line 6. Assert the mapping is real rather than just present. + for _, want := range []string{"6: func Fn0()", "30: func Fn1()"} { + if !strings.Contains(res.Content, want) { + t.Fatalf("expected outline entry %q, got:\n%s", want, truncateForMsg(res.Content)) + } + } +} + +func TestRead_ExplicitRangeBypassesOutline(t *testing.T) { + tmp := t.TempDir() + bigGoFile(t, tmp, "big.go", 60) + + res := execRead(t, tmp, `{"path":"big.go","offset":6,"limit":3}`) + if !strings.Contains(res.Content, "body 0 line 0") { + t.Fatalf("an explicit range must return raw content, got:\n%s", truncateForMsg(res.Content)) + } +} + +func TestRead_FullBypassesOutline(t *testing.T) { + tmp := t.TempDir() + bigGoFile(t, tmp, "big.go", 60) + + res := execRead(t, tmp, `{"path":"big.go","full":true}`) + if !strings.Contains(res.Content, "body 0 line 0") { + t.Fatalf("full:true must return raw content, got:\n%s", truncateForMsg(res.Content)) + } +} + +// Files at or below the normal read budget must behave exactly as before. +func TestRead_SmallGoFileIsUnaffected(t *testing.T) { + tmp := t.TempDir() + bigGoFile(t, tmp, "small.go", 3) + + res := execRead(t, tmp, `{"path":"small.go"}`) + if !strings.Contains(res.Content, "body 0 line 0") { + t.Fatalf("a small file must return raw content, got:\n%s", truncateForMsg(res.Content)) + } +} + +// An unrecognised language has no reliable declaration pattern, so outlining +// would risk returning an arbitrary subset of lines as if it were structure. +func TestRead_LargeUnknownFileTypeIsUnaffected(t *testing.T) { + tmp := t.TempDir() + var b strings.Builder + for i := range 2000 { + fmt.Fprintf(&b, "arbitrary line %d\n", i) + } + writeReadTestFile(t, tmp, "data.unknownext", b.String()) + + res := execRead(t, tmp, `{"path":"data.unknownext"}`) + if !strings.Contains(res.Content, "arbitrary line 0") { + t.Fatalf("an unknown file type must fall back to raw content, got:\n%s", truncateForMsg(res.Content)) + } +} + +// A large source file with no recognisable declarations (generated tables, +// embedded data) must not collapse to an empty outline. +func TestRead_LargeGoFileWithoutDeclarationsIsUnaffected(t *testing.T) { + tmp := t.TempDir() + var b strings.Builder + b.WriteString("package gen\n") + for i := range 2000 { + fmt.Fprintf(&b, "\t\"key%d\": %d,\n", i, i) + } + writeReadTestFile(t, tmp, "table.go", b.String()) + + res := execRead(t, tmp, `{"path":"table.go"}`) + if !strings.Contains(res.Content, `"key0"`) { + t.Fatalf("a file with no declarations must fall back to raw content, got:\n%s", truncateForMsg(res.Content)) + } +} + +func truncateForMsg(s string) string { + if len(s) > 600 { + return s[:600] + "..." + } + return s +} + +// An explicit limit that happens to equal the default is still explicit, and +// must be honoured as a content request rather than read as "unspecified". +func TestRead_ExplicitDefaultSizedLimitBypassesOutline(t *testing.T) { + tmp := t.TempDir() + bigGoFile(t, tmp, "big.go", 60) + + res := execRead(t, tmp, fmt.Sprintf(`{"path":"big.go","limit":%d}`, DefaultReadLines)) + if !strings.Contains(res.Content, "body 0 line 0") { + t.Fatalf("an explicit limit must return raw content, got:\n%s", truncateForMsg(res.Content)) + } +} diff --git a/internal/tools/builtin/read_range_test.go b/internal/tools/builtin/read_range_test.go new file mode 100644 index 000000000..abeefa0c3 --- /dev/null +++ b/internal/tools/builtin/read_range_test.go @@ -0,0 +1,158 @@ +package builtin + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func numberedFile(t *testing.T, dir, name string, n int) string { + t.Helper() + lines := make([]string, n) + for i := range lines { + lines[i] = fmt.Sprintf("line %d", i+1) + } + writeReadTestFile(t, dir, name, strings.Join(lines, "\n")) + return filepath.Join(dir, name) +} + +// readTwice runs the read tool twice through one tracker, as a session would. +func readTwice(t *testing.T, cwd, first, second string) (Result, Result) { + t.Helper() + tool := NewReadTool(cwd, NewReadTracker()) + r1, err := tool.Execute(context.Background(), json.RawMessage(first), nil) + if err != nil { + t.Fatalf("first read: %v", err) + } + r2, err := tool.Execute(context.Background(), json.RawMessage(second), nil) + if err != nil { + t.Fatalf("second read: %v", err) + } + return r1, r2 +} + +func TestRead_UnchangedRepeatIsSuppressed(t *testing.T) { + tmp := t.TempDir() + numberedFile(t, tmp, "f.txt", 50) + + r1, r2 := readTwice(t, tmp, `{"path":"f.txt"}`, `{"path":"f.txt"}`) + if r1.IsError || !strings.Contains(r1.Content, "line 50") { + t.Fatalf("first read should return the body, got: %s", r1.Content) + } + if r2.IsError { + t.Fatalf("second read errored: %s", r2.Content) + } + if strings.Contains(r2.Content, "line 50") { + t.Fatalf("second read should not resend the body, got:\n%s", r2.Content) + } + if !strings.Contains(r2.Content, "unchanged") { + t.Fatalf("second read should say the file is unchanged, got:\n%s", r2.Content) + } +} + +func TestRead_ChangedFileIsResent(t *testing.T) { + tmp := t.TempDir() + path := numberedFile(t, tmp, "f.txt", 20) + + tool := NewReadTool(tmp, NewReadTracker()) + if _, err := tool.Execute(context.Background(), json.RawMessage(`{"path":"f.txt"}`), nil); err != nil { + t.Fatal(err) + } + + // Rewrite with different content and a distinct mtime. + if err := os.WriteFile(path, []byte("totally different\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + + res, err := tool.Execute(context.Background(), json.RawMessage(`{"path":"f.txt"}`), nil) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(res.Content, "totally different") { + t.Fatalf("a changed file must be resent in full, got:\n%s", res.Content) + } +} + +func TestRead_OverlappingRangeReturnsOnlyNovelLines(t *testing.T) { + tmp := t.TempDir() + numberedFile(t, tmp, "f.txt", 300) + + _, r2 := readTwice(t, tmp, + `{"path":"f.txt","offset":1,"limit":100}`, + `{"path":"f.txt","offset":1,"limit":200}`) + + if r2.IsError { + t.Fatalf("second read errored: %s", r2.Content) + } + if strings.Contains(r2.Content, "line 50\n") { + t.Fatalf("already-served lines were resent, got:\n%s", r2.Content) + } + if !strings.Contains(r2.Content, "line 101") || !strings.Contains(r2.Content, "line 200") { + t.Fatalf("novel lines 101-200 missing, got:\n%s", r2.Content) + } +} + +func TestRead_DisjointRangeIsServedNormally(t *testing.T) { + tmp := t.TempDir() + numberedFile(t, tmp, "f.txt", 300) + + _, r2 := readTwice(t, tmp, + `{"path":"f.txt","offset":1,"limit":50}`, + `{"path":"f.txt","offset":200,"limit":50}`) + + if r2.IsError { + t.Fatalf("second read errored: %s", r2.Content) + } + if !strings.Contains(r2.Content, "line 200") || !strings.Contains(r2.Content, "line 249") { + t.Fatalf("a disjoint range must be served in full, got:\n%s", r2.Content) + } +} + +// full:true is the documented escape hatch: if the model has lost the earlier +// content (compaction, handoff) it must still be able to force a re-read. +func TestRead_FullBypassesSuppression(t *testing.T) { + tmp := t.TempDir() + numberedFile(t, tmp, "f.txt", 50) + + _, r2 := readTwice(t, tmp, `{"path":"f.txt"}`, `{"path":"f.txt","full":true}`) + if !strings.Contains(r2.Content, "line 50") { + t.Fatalf("full:true must bypass suppression, got:\n%s", r2.Content) + } +} + +// The suppression notice has to tell the model how to force a re-read, +// otherwise a model that has lost the content has no recovery path. +func TestRead_SuppressionNoticeNamesTheEscapeHatch(t *testing.T) { + tmp := t.TempDir() + numberedFile(t, tmp, "f.txt", 50) + + _, r2 := readTwice(t, tmp, `{"path":"f.txt"}`, `{"path":"f.txt"}`) + if !strings.Contains(r2.Content, "full") { + t.Fatalf("notice must mention full:true as the escape hatch, got:\n%s", r2.Content) + } +} + +// Suppression must not weaken the read-before-write guard. +func TestRead_SuppressedReadStillCountsAsRead(t *testing.T) { + tmp := t.TempDir() + numberedFile(t, tmp, "f.txt", 20) + + rt := NewReadTracker() + tool := NewReadTool(tmp, rt) + for range 2 { + if _, err := tool.Execute(context.Background(), json.RawMessage(`{"path":"f.txt"}`), nil); err != nil { + t.Fatal(err) + } + } + if err := rt.CheckRead(tmp, "f.txt"); err != nil { + t.Fatalf("a suppressed re-read must still satisfy read-before-write: %v", err) + } +} diff --git a/internal/tools/builtin/read_test.go b/internal/tools/builtin/read_test.go new file mode 100644 index 000000000..0f3dd2e61 --- /dev/null +++ b/internal/tools/builtin/read_test.go @@ -0,0 +1,212 @@ +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) + } +} diff --git a/internal/tools/builtin/read_tracker.go b/internal/tools/builtin/read_tracker.go new file mode 100644 index 000000000..b6053b2e0 --- /dev/null +++ b/internal/tools/builtin/read_tracker.go @@ -0,0 +1,167 @@ +// Lifted from tau internal/agent/tools/read_tracker.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "sync" +) + +// lineRange is an inclusive 1-based line interval. +type lineRange struct{ start, end int } + +// fileReads is what a session has already been shown of one file. identity is +// a cheap stat fingerprint; when it changes, served is discarded because the +// previously shown lines no longer describe the file. +type fileReads struct { + identity string + served []lineRange // sorted, non-overlapping, non-adjacent +} + +// ReadTracker records which files the model has read so that mutation +// tools (write, edit) can enforce a read-before-write safety check, and which +// line ranges of each file it has already been shown so read can avoid +// re-sending content the model already has. +type ReadTracker struct { + mu sync.Mutex + reads map[string]bool // absolute paths that have been read + seen map[string]*fileReads // absolute path -> already-served ranges +} + +// NewReadTracker creates a new ReadTracker. +func NewReadTracker() *ReadTracker { + return &ReadTracker{ + reads: make(map[string]bool), + seen: make(map[string]*fileReads), + } +} + +// FileIdentity is a cheap fingerprint of a file's current state. Size plus +// modification time is enough here: a rewrite that preserves both is +// indistinguishable from no change, and the cost of being wrong is a stale +// suppression notice the model can override with full:true. Hashing every +// re-read would be strictly more accurate and materially more expensive. +func FileIdentity(info os.FileInfo) string { + return fmt.Sprintf("%d:%d", info.Size(), info.ModTime().UnixNano()) +} + +// Novel reports which part of [start,end] the model has not already been shown +// for this file, and records the whole request as served. +// +// It returns ok=false when the request is entirely covered, meaning read should +// suppress the body. When only part is new AND that part is contiguous, the +// narrowed range is returned. A request whose novel portion is fragmented is +// served whole, because stitching disjoint fragments into one response is more +// confusing to the model than simply repeating some lines. +func (rt *ReadTracker) Novel(cwd, path, identity string, start, end int) (ns, ne int, ok bool) { + abs := resolvePath(cwd, path) + + rt.mu.Lock() + defer rt.mu.Unlock() + + st := rt.seen[abs] + if st == nil || st.identity != identity { + st = &fileReads{identity: identity} + rt.seen[abs] = st + } + + gaps := subtract(lineRange{start, end}, st.served) + st.served = merge(append(st.served, lineRange{start, end})) + + switch len(gaps) { + case 0: + return 0, 0, false + case 1: + return gaps[0].start, gaps[0].end, true + default: + return start, end, true + } +} + +// subtract returns the parts of want not covered by served (sorted, disjoint). +func subtract(want lineRange, served []lineRange) []lineRange { + var gaps []lineRange + cursor := want.start + for _, s := range served { + if s.end < cursor { + continue + } + if s.start > want.end { + break + } + if s.start > cursor { + gaps = append(gaps, lineRange{cursor, min(s.start-1, want.end)}) + } + cursor = max(cursor, s.end+1) + if cursor > want.end { + return gaps + } + } + if cursor <= want.end { + gaps = append(gaps, lineRange{cursor, want.end}) + } + return gaps +} + +// merge normalises ranges into a sorted, non-overlapping, non-adjacent set. +// Adjacent ranges are coalesced so that [1,100] and [101,200] become [1,200], +// keeping the served set compact across many small reads. +func merge(ranges []lineRange) []lineRange { + if len(ranges) < 2 { + return ranges + } + slices.SortFunc(ranges, func(a, b lineRange) int { return a.start - b.start }) + + out := ranges[:1] + for _, r := range ranges[1:] { + last := &out[len(out)-1] + if r.start <= last.end+1 { + last.end = max(last.end, r.end) + continue + } + out = append(out, r) + } + return out +} + +// MarkRead records that a file at the given path has been read by the +// model. The path is normalised to absolute form before recording. +func (rt *ReadTracker) MarkRead(cwd, path string) { + abs := resolvePath(cwd, path) + rt.mu.Lock() + rt.reads[abs] = true + rt.mu.Unlock() +} + +// CheckRead returns an error if the file at the given path has not been +// read by the model in this session. The path is normalised to absolute +// form. A file must be read (via the read tool) before it can be written, +// edited. +func (rt *ReadTracker) CheckRead(cwd, path string) error { + abs := resolvePath(cwd, path) + rt.mu.Lock() + read := rt.reads[abs] + rt.mu.Unlock() + + if !read { + rel, _ := filepath.Rel(cwd, abs) + if rel == "" { + rel = abs + } + return fmt.Errorf( + "file %q has not been read in this session - use the read tool first to read the file before writing or editing it", + rel, + ) + } + return nil +} diff --git a/internal/tools/builtin/registry.go b/internal/tools/builtin/registry.go new file mode 100644 index 000000000..d1b0cbf64 --- /dev/null +++ b/internal/tools/builtin/registry.go @@ -0,0 +1,299 @@ +// Lifted from tau internal/agent/tools/registry.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +// Package tools provides the tool registry and built-in tool implementations +// for the Tau agent coordinator. +package builtin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "time" +) + +// Schema describes a tool's interface for LLM function-calling. +type Schema struct { + Name string `json:"name"` + Description string `json:"description"` + Parameters json.RawMessage `json:"parameters"` // JSON Schema object +} + +// Result is the output of a tool execution. +type Result struct { + Content string `json:"content"` + Details any `json:"details,omitempty"` + IsError bool `json:"is_error,omitempty"` + ErrorKind string `json:"error_kind,omitempty"` + // MetricLabels adds tool-specific low-cardinality dimensions to the + // coordinator's authoritative completion metric. + MetricLabels map[string]string `json:"-"` + + // Execution fields are populated by the coordinator after execution so + // the same facts drive events, metrics, and persisted tool messages. + Duration time.Duration `json:"duration,omitempty"` + ResultBytes int `json:"result_bytes,omitempty"` + Truncated bool `json:"truncated,omitempty"` + StartedAt time.Time `json:"started_at,omitzero"` + CompletedAt time.Time `json:"completed_at,omitzero"` +} + +// DiffDetails is carried in Result.Details by tools that replace file +// content (edit, write), so callers such as the TUI can render a +// before/after diff instead of just a summary string. +type DiffDetails struct { + Path string `json:"path"` + OldContent string `json:"old_content"` + NewContent string `json:"new_content"` +} + +// Executor is a function that executes a tool with the given parameters. +type Executor func(ctx context.Context, params json.RawMessage, ui UIBridge) (Result, error) + +// Tool is a registered tool comprising its schema and executor. +type Tool struct { + Schema Schema + Execute Executor + Source string // "builtin", "extension:" +} + +// Registry holds all registered tools and provides thread-safe access. +type Registry struct { + mu sync.RWMutex + tools map[string]Tool + order []string // insertion order for deterministic iteration + pluginToolExecutor PluginToolExecutor +} + +// NewRegistry creates an empty tool registry. +func NewRegistry() *Registry { + return &Registry{ + tools: make(map[string]Tool), + } +} + +// Register adds a tool to the registry. Returns an error if a tool with +// the same name is already registered (use Replace for overrides). +func (r *Registry) Register(tool Tool) error { + if tool.Schema.Name == "" { + return errors.New("tool name is required") + } + if tool.Execute == nil { + return errors.New("tool executor is required") + } + + r.mu.Lock() + defer r.mu.Unlock() + + if _, exists := r.tools[tool.Schema.Name]; exists { + return fmt.Errorf("tool %q is already registered", tool.Schema.Name) + } + + r.tools[tool.Schema.Name] = tool + r.order = append(r.order, tool.Schema.Name) + return nil +} + +// Replace registers a tool, overriding any existing tool with the same name. +func (r *Registry) Replace(tool Tool) error { + if tool.Schema.Name == "" { + return errors.New("tool name is required") + } + if tool.Execute == nil { + return errors.New("tool executor is required") + } + + r.mu.Lock() + defer r.mu.Unlock() + + if _, exists := r.tools[tool.Schema.Name]; !exists { + r.order = append(r.order, tool.Schema.Name) + } + r.tools[tool.Schema.Name] = tool + return nil +} + +// Unregister removes a tool from the registry. +func (r *Registry) Unregister(name string) { + r.mu.Lock() + defer r.mu.Unlock() + + delete(r.tools, name) + for i, n := range r.order { + if n == name { + r.order = append(r.order[:i], r.order[i+1:]...) + break + } + } +} + +// Get retrieves a tool by name. +func (r *Registry) Get(name string) (Tool, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + + tool, ok := r.tools[name] + return tool, ok +} + +// All returns all registered tools in insertion order. +func (r *Registry) All() []Tool { + r.mu.RLock() + defer r.mu.RUnlock() + + result := make([]Tool, 0, len(r.order)) + for _, name := range r.order { + if tool, ok := r.tools[name]; ok { + result = append(result, tool) + } + } + return result +} + +// Schemas returns the schemas of all registered tools in insertion order. +// This is the slice sent to the LLM in the tools[] field. +func (r *Registry) Schemas() []Schema { + r.mu.RLock() + defer r.mu.RUnlock() + + result := make([]Schema, 0, len(r.order)) + for _, name := range r.order { + if tool, ok := r.tools[name]; ok { + result = append(result, tool.Schema) + } + } + return result +} + +// Names returns the names of all registered tools. +func (r *Registry) Names() []string { + r.mu.RLock() + defer r.mu.RUnlock() + + out := make([]string, len(r.order)) + copy(out, r.order) + return out +} + +// Count returns the number of registered tools. +func (r *Registry) Count() int { + r.mu.RLock() + defer r.mu.RUnlock() + + return len(r.tools) +} + +// PluginToolDef describes a tool provided by a plugin. +type PluginToolDef struct { + Name string + Description string + InputSchema string // JSON Schema as string +} + +// PluginToolExecutor is called by the registry when a plugin tool is executed. +type PluginToolExecutor func(ctx context.Context, pluginName, toolName string, args json.RawMessage) (Result, error) + +// SetPluginToolExecutor sets the executor for plugin tools. The executor is +// called whenever a plugin-registered tool is invoked by the agent. +func (r *Registry) SetPluginToolExecutor(executor PluginToolExecutor) { + r.mu.Lock() + defer r.mu.Unlock() + r.pluginToolExecutor = executor +} + +// pluginToolSep joins a plugin name and its tool name into the registry's +// public tool identifier. It must satisfy the function-name pattern that +// OpenAI-compatible providers enforce (^[a-zA-Z0-9_-]+$), so it cannot be ".". +const pluginToolSep = "__" + +// sanitizePluginToolName maps an arbitrary name to the ^[a-zA-Z0-9_-]+$ +// character set that OpenAI-compatible providers require for function names, +// replacing any other character with '_'. This is applied centrally to every +// plugin tool so plugin authors can return natural names (the MCP spec, for +// one, places no character constraints on tool names) without each plugin +// re-implementing provider name rules. +func sanitizePluginToolName(s string) string { + var b strings.Builder + b.Grow(len(s)) + for _, r := range s { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-': + b.WriteRune(r) + default: + b.WriteByte('_') + } + } + if b.Len() == 0 { + return "tool" + } + return b.String() +} + +// RegisterPluginTool registers a tool from a plugin in the registry. +// +// The public, LLM-facing name is the plugin name and tool name, sanitised to the +// provider-safe character set and joined with pluginToolSep. Sanitising here - +// once, for every plugin - means plugin authors can return whatever names their +// upstream uses. Execution routes back to the plugin with its ORIGINAL, unmodified +// tool name (captured in the closure below), so the plugin never sees the +// sanitised form and needs no name translation of its own. +// +// Returns an error if the resulting name is already registered. +func (r *Registry) RegisterPluginTool(pluginName string, def PluginToolDef) error { + toolName := sanitizePluginToolName(pluginName) + pluginToolSep + sanitizePluginToolName(def.Name) + reg := r // capture for closure + tool := Tool{ + Schema: Schema{ + Name: toolName, + Description: "[" + pluginName + "] " + def.Description, + }, + Execute: func(ctx context.Context, params json.RawMessage, ui UIBridge) (Result, error) { + reg.mu.RLock() + exec := reg.pluginToolExecutor + reg.mu.RUnlock() + if exec == nil { + return Result{IsError: true, Content: "plugin executor not available"}, nil + } + return exec(ctx, pluginName, def.Name, params) + }, + Source: "plugin:" + pluginName, + } + if def.InputSchema != "" { + tool.Schema.Parameters = json.RawMessage(def.InputSchema) + } + return r.Replace(tool) +} + +// UnregisterPluginTools removes all tools belonging to a plugin. +// Plugin tools are identified by the sanitised "pluginName__" prefix in their +// names (see RegisterPluginTool). +func (r *Registry) UnregisterPluginTools(pluginName string) { + prefix := sanitizePluginToolName(pluginName) + pluginToolSep + r.mu.Lock() + defer r.mu.Unlock() + + for name := range r.tools { + if strings.HasPrefix(name, prefix) { + delete(r.tools, name) + r.order = removeFromOrder(r.order, name) + } + } +} + +func removeFromOrder(order []string, name string) []string { + for i, n := range order { + if n == name { + return append(order[:i], order[i+1:]...) + } + } + return order +} diff --git a/internal/tools/builtin/registry_test.go b/internal/tools/builtin/registry_test.go new file mode 100644 index 000000000..1322a94ac --- /dev/null +++ b/internal/tools/builtin/registry_test.go @@ -0,0 +1,189 @@ +package builtin_test + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/tools/builtin" +) + +func dummyExecutor(_ context.Context, _ json.RawMessage, _ builtin.UIBridge) (builtin.Result, error) { + return builtin.Result{Content: "ok"}, nil +} + +func TestRegistry_Register(t *testing.T) { + r := builtin.NewRegistry() + + tool := builtin.Tool{ + Schema: builtin.Schema{Name: "test", Description: "a test tool"}, + Execute: dummyExecutor, + Source: "builtin", + } + + if err := r.Register(tool); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if r.Count() != 1 { + t.Fatalf("expected 1 tool, got %d", r.Count()) + } + + // Duplicate registration should fail. + if err := r.Register(tool); err == nil { + t.Fatal("expected error on duplicate registration") + } +} + +func TestRegistry_Replace(t *testing.T) { + r := builtin.NewRegistry() + + tool := builtin.Tool{ + Schema: builtin.Schema{Name: "test", Description: "v1"}, + Execute: dummyExecutor, + Source: "builtin", + } + _ = r.Register(tool) + + tool.Schema.Description = "v2" + if err := r.Replace(tool); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + got, ok := r.Get("test") + if !ok { + t.Fatal("tool not found after replace") + } + if got.Schema.Description != "v2" { + t.Fatalf("expected description v2, got %q", got.Schema.Description) + } + if r.Count() != 1 { + t.Fatalf("replace should not duplicate; got count %d", r.Count()) + } +} + +func TestRegistry_Unregister(t *testing.T) { + r := builtin.NewRegistry() + + _ = r.Register(builtin.Tool{ + Schema: builtin.Schema{Name: "a", Description: "tool a"}, + Execute: dummyExecutor, + Source: "builtin", + }) + _ = r.Register(builtin.Tool{ + Schema: builtin.Schema{Name: "b", Description: "tool b"}, + Execute: dummyExecutor, + Source: "builtin", + }) + + r.Unregister("a") + + if r.Count() != 1 { + t.Fatalf("expected 1 tool after unregister, got %d", r.Count()) + } + if _, ok := r.Get("a"); ok { + t.Fatal("tool 'a' should be gone") + } +} + +func TestRegistry_All_PreservesOrder(t *testing.T) { + r := builtin.NewRegistry() + + names := []string{"alpha", "beta", "gamma"} + for _, name := range names { + _ = r.Register(builtin.Tool{ + Schema: builtin.Schema{Name: name, Description: name}, + Execute: dummyExecutor, + Source: "builtin", + }) + } + + all := r.All() + if len(all) != 3 { + t.Fatalf("expected 3 tools, got %d", len(all)) + } + for i, tool := range all { + if tool.Schema.Name != names[i] { + t.Fatalf("order mismatch at %d: got %q, want %q", i, tool.Schema.Name, names[i]) + } + } +} + +func TestRegistry_Schemas(t *testing.T) { + r := builtin.NewRegistry() + + _ = r.Register(builtin.Tool{ + Schema: builtin.Schema{ + Name: "read", + Description: "Read a file", + Parameters: json.RawMessage(`{"type":"object","properties":{"path":{"type":"string"}}}`), + }, + Execute: dummyExecutor, + Source: "builtin", + }) + + schemas := r.Schemas() + if len(schemas) != 1 { + t.Fatalf("expected 1 schema, got %d", len(schemas)) + } + if schemas[0].Name != "read" { + t.Fatalf("expected schema name 'read', got %q", schemas[0].Name) + } +} + +func TestRegistry_Validation(t *testing.T) { + r := builtin.NewRegistry() + + // Empty name. + err := r.Register(builtin.Tool{ + Schema: builtin.Schema{Name: "", Description: "no name"}, + Execute: dummyExecutor, + }) + if err == nil { + t.Fatal("expected error for empty name") + } + + // Nil executor. + err = r.Register(builtin.Tool{ + Schema: builtin.Schema{Name: "test", Description: "no exec"}, + }) + if err == nil { + t.Fatal("expected error for nil executor") + } +} + +// TestRegistry_PluginToolSanitizesName verifies that the registry (not each +// plugin) makes plugin tool names safe for OpenAI-compatible providers, while +// routing execution back to the plugin with its ORIGINAL, unmodified names. +func TestRegistry_PluginToolSanitizesName(t *testing.T) { + r := builtin.NewRegistry() + var gotPlugin, gotTool string + r.SetPluginToolExecutor(func(_ context.Context, pluginName, toolName string, _ json.RawMessage) (builtin.Result, error) { + gotPlugin, gotTool = pluginName, toolName + return builtin.Result{Content: "ok"}, nil + }) + + // A plugin returns a natural name containing a '.' - invalid for the provider. + if err := r.RegisterPluginTool("mcp-plugin", builtin.PluginToolDef{Name: "spawn.list_issues"}); err != nil { + t.Fatal(err) + } + + // The public, LLM-facing name is sanitised. + const want = "mcp-plugin__spawn_list_issues" + tool, ok := r.Get(want) + if !ok { + t.Fatalf("expected registered tool %q; got names %v", want, r.Names()) + } + if strings.ContainsRune(tool.Schema.Name, '.') { + t.Fatalf("registered name %q still contains '.'", tool.Schema.Name) + } + + // Execution routes back to the plugin with the ORIGINAL plugin and tool names. + if _, err := tool.Execute(context.Background(), nil, nil); err != nil { + t.Fatal(err) + } + if gotPlugin != "mcp-plugin" || gotTool != "spawn.list_issues" { + t.Fatalf("executor received %q/%q, want mcp-plugin/spawn.list_issues", gotPlugin, gotTool) + } +} diff --git a/internal/tools/builtin/rg/rg-darwin-amd64 b/internal/tools/builtin/rg/rg-darwin-amd64 new file mode 100644 index 000000000..4fdb58b25 Binary files /dev/null and b/internal/tools/builtin/rg/rg-darwin-amd64 differ diff --git a/internal/tools/builtin/rg/rg-linux-amd64 b/internal/tools/builtin/rg/rg-linux-amd64 new file mode 100644 index 000000000..477c4756e Binary files /dev/null and b/internal/tools/builtin/rg/rg-linux-amd64 differ diff --git a/internal/tools/builtin/rg/rg-windows-amd64.exe b/internal/tools/builtin/rg/rg-windows-amd64.exe new file mode 100644 index 000000000..1c6cc8cb5 Binary files /dev/null and b/internal/tools/builtin/rg/rg-windows-amd64.exe differ diff --git a/internal/tools/builtin/rg/rg.go b/internal/tools/builtin/rg/rg.go new file mode 100644 index 000000000..6985c3b9a --- /dev/null +++ b/internal/tools/builtin/rg/rg.go @@ -0,0 +1,45 @@ +//go:build (darwin && amd64) || (linux && amd64) || (windows && amd64) + +// Package rg embeds a statically-linked ripgrep binary and exposes a single +// entry point so the grep tool can always use authoritative rg matching. +package rg + +import ( + "fmt" + "os" + "path/filepath" + "sync" +) + +var ( + extractOnce sync.Once + extractPath string + extractErr error +) + +// Path returns the filesystem path to the embedded rg binary, extracting it +// to a temporary file on first call. The caller must not remove the file. +func Path() (string, error) { + extractOnce.Do(func() { + extractPath, extractErr = extract() + }) + if extractErr != nil { + return "", extractErr + } + return extractPath, nil +} + +func extract() (string, error) { + dir, err := os.MkdirTemp("", "tau-rg-*") + if err != nil { + return "", fmt.Errorf("create rg temp dir: %w", err) + } + exe := filepath.Join(dir, "rg") + if isWindows { + exe += ".exe" + } + if err := os.WriteFile(exe, binary, 0o755); err != nil { + return "", fmt.Errorf("write embedded rg: %w", err) + } + return exe, nil +} diff --git a/internal/tools/builtin/rg/rg_darwin_amd64.go b/internal/tools/builtin/rg/rg_darwin_amd64.go new file mode 100644 index 000000000..74bcc7973 --- /dev/null +++ b/internal/tools/builtin/rg/rg_darwin_amd64.go @@ -0,0 +1,10 @@ +//go:build darwin && amd64 + +package rg + +import _ "embed" + +const isWindows = false + +//go:embed rg-darwin-amd64 +var binary []byte diff --git a/internal/tools/builtin/rg/rg_linux_amd64.go b/internal/tools/builtin/rg/rg_linux_amd64.go new file mode 100644 index 000000000..86ebd6f9b --- /dev/null +++ b/internal/tools/builtin/rg/rg_linux_amd64.go @@ -0,0 +1,10 @@ +//go:build linux && amd64 + +package rg + +import _ "embed" + +const isWindows = false + +//go:embed rg-linux-amd64 +var binary []byte diff --git a/internal/tools/builtin/rg/rg_unsupported.go b/internal/tools/builtin/rg/rg_unsupported.go new file mode 100644 index 000000000..216e8ce01 --- /dev/null +++ b/internal/tools/builtin/rg/rg_unsupported.go @@ -0,0 +1,13 @@ +//go:build !((darwin && amd64) || (linux && amd64) || (windows && amd64)) + +// Package rg embeds a statically-linked ripgrep binary and exposes a single +// entry point so the grep tool can always use authoritative rg matching. +package rg + +import "errors" + +// Path reports that no ripgrep binary is bundled for this platform/arch. +// Callers fall back to the pure-Go grep implementation. +func Path() (string, error) { + return "", errors.New("no embedded ripgrep binary for this platform") +} diff --git a/internal/tools/builtin/rg/rg_windows_amd64.go b/internal/tools/builtin/rg/rg_windows_amd64.go new file mode 100644 index 000000000..8b277b2c0 --- /dev/null +++ b/internal/tools/builtin/rg/rg_windows_amd64.go @@ -0,0 +1,10 @@ +//go:build windows && amd64 + +package rg + +import _ "embed" + +const isWindows = true + +//go:embed rg-windows-amd64.exe +var binary []byte diff --git a/internal/tools/builtin/shell.go b/internal/tools/builtin/shell.go new file mode 100644 index 000000000..15c6a96fe --- /dev/null +++ b/internal/tools/builtin/shell.go @@ -0,0 +1,256 @@ +// Lifted from tau internal/agent/tools/shell.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "regexp" + "runtime" + "strings" + "time" +) + +const ( + defaultShellTimeout = 120 * time.Second + maxShellTimeout = 10 * time.Minute +) + +// ShellParams are the parameters for the shell tool. +type ShellParams struct { + Command string `json:"command"` + Timeout int `json:"timeout,omitempty"` // seconds, defaults to 120 +} + +var shellSchema = Schema{ + Name: "shell", + Description: fmt.Sprintf("Execute a shell command. Uses PowerShell on Windows, bash on Linux/macOS. Returns stdout and stderr, truncated to the last %d lines or %s (whichever is hit first); when truncated, the full output is saved to a temp file whose path is included in the notice. Use for builds, tests, git, and other commands - prefer the dedicated grep, find, and read tools for searching and reading files.", DefaultMaxLines, FormatSize(DefaultMaxBytes)), + Parameters: json.RawMessage(`{ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The shell command to execute" + }, + "timeout": { + "type": "integer", + "description": "Timeout in seconds. Defaults to 120." + } + }, + "required": ["command"] + }`), +} + +// NewShellTool creates the built-in shell execution tool. +func NewShellTool(cwd string, mq *MutationQueue) Tool { + return Tool{ + Schema: shellSchema, + Source: "builtin", + Execute: makeShellExecutor(cwd, mq), + } +} + +type bridgeWriter struct { + bridge UIBridge +} + +func (w *bridgeWriter) Write(p []byte) (n int, err error) { + w.bridge.Log(string(p)) + return len(p), nil +} + +func makeShellExecutor(cwd string, mq *MutationQueue) Executor { + return func(ctx context.Context, params json.RawMessage, bridge UIBridge) (Result, error) { + var p ShellParams + if err := json.Unmarshal(params, &p); err != nil { + return Result{Content: fmt.Sprintf("invalid parameters: %v", err), IsError: true}, nil + } + + p.Command = strings.TrimSpace(p.Command) + if p.Command == "" { + return Result{Content: "command is required", IsError: true}, nil + } + + timeout := defaultShellTimeout + if p.Timeout > 0 { + timeout = time.Duration(p.Timeout) * time.Second + } + if timeout > maxShellTimeout { + timeout = maxShellTimeout + } + + if cwd != "" { + info, err := os.Stat(cwd) + if err != nil || !info.IsDir() { + return Result{Content: fmt.Sprintf("invalid cwd %q", cwd), IsError: true}, nil + } + } + + // Serialize with file-mutation tools: shell commands may modify + // files that write/edit are working on. + if mq != nil { + mq.GlobalLock() + defer mq.GlobalUnlock() + } + + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + shell, args := shellCommand(p.Command) + cmd := exec.CommandContext(ctx, shell, args...) + if cwd != "" { + cmd.Dir = cwd + } + + var stdout, stderr bytes.Buffer + bw := &bridgeWriter{bridge: bridge} + cmd.Stdout = io.MultiWriter(&stdout, bw) + cmd.Stderr = io.MultiWriter(&stderr, bw) + + err := cmd.Run() + + var b strings.Builder + if stdout.Len() > 0 { + b.WriteString(stdout.String()) + } + if stderr.Len() > 0 { + if b.Len() > 0 { + b.WriteString("\n") + } + b.WriteString("[stderr]\n") + b.WriteString(stderr.String()) + } + + output := b.String() + if output == "" { + output = "(no output)" + } + + // Collapse before truncation, so a long passing test run is reduced to + // its summaries rather than tail-truncated into a partial log. + output, _ = collapseGoTestOutput(p.Command, output, err == nil) + + tr := TruncateTail(output, DefaultMaxLines, DefaultMaxBytes) + content := tr.Content + if tr.Truncated { + // Save the full output so the model can grep/tail it instead of + // re-running an expensive command. + if path, saveErr := saveFullOutput(output); saveErr == nil { + content += "\n[full output saved to: " + path + "]" + } + } + + if err != nil { + // Check context cancellation first - a process may exit with + // a non-zero code after the deadline, and we want to report + // timeout rather than a misleading exit code. + if ctx.Err() != nil { + return Result{ + Content: fmt.Sprintf("[timeout after: %s]\n%s", timeout, content), IsError: true, + ErrorKind: "timeout", Truncated: tr.Truncated, ResultBytes: len(output), + }, nil + } + + if exitErr, ok := err.(*exec.ExitError); ok { + return Result{ + Content: fmt.Sprintf("[exit code: %d]\n%s", exitErr.ExitCode(), content), IsError: true, + ErrorKind: "command_exit", Truncated: tr.Truncated, ResultBytes: len(output), + }, nil + } + + return Result{Content: fmt.Sprintf("error executing command: %v", err), IsError: true}, nil + } + + return Result{Content: content, Truncated: tr.Truncated, ResultBytes: len(output)}, nil + } +} + +// goTestSummaryRe matches cmd/go's per-package result lines: "ok", "FAIL" and +// "?" (no test files). Note it must NOT match "---", which prefixes per-test +// result lines ("--- PASS: TestX") - exactly the noise being collapsed. A +// package that fails to build reports as "FAIL [build failed]", so the +// package-level failure case is already covered by the FAIL alternative. +var goTestSummaryRe = regexp.MustCompile(`^(ok|FAIL|\?)\s`) + +// goTestInvocationRe matches a `go test` invocation, allowing for a leading +// `cd ... &&` and for flags between `go` and `test`. It deliberately does not +// match wrappers like gotestsum, whose output format differs. +var goTestInvocationRe = regexp.MustCompile(`(^|[;&|]\s*)go\s+test\b`) + +// collapseGoTestOutput reduces a PASSING `go test` run to its per-package +// summary lines. A single `go test ./internal/tui2/... -v` in the analysed +// sessions took 14.2s and returned 11,044 tokens - 11% of all shell result +// tokens in one call - despite every test having passed, where the only +// information the model needed was "they passed". +// +// Failing runs are returned verbatim: on failure the per-test detail is the +// entire point, and collapsing it would force a re-run to recover it. +func collapseGoTestOutput(command, output string, succeeded bool) (string, bool) { + if !succeeded || !goTestInvocationRe.MatchString(command) { + return output, false + } + + lines := strings.Split(strings.TrimRight(output, "\n"), "\n") + kept := make([]string, 0, len(lines)) + for _, l := range lines { + if goTestSummaryRe.MatchString(l) { + kept = append(kept, l) + } + } + + // Nothing recognisable to keep, or nothing to gain: leave it alone rather + // than returning an empty result or appending a pointless notice. + if len(kept) == 0 || len(kept) == len(lines) { + return output, false + } + + return fmt.Sprintf( + "%s\n\n[%d lines of passing per-test output collapsed; re-run with -v and a narrower package to see it]", + strings.Join(kept, "\n"), len(lines)-len(kept), + ), true +} + +// saveFullOutput writes the complete, untruncated command output to a temp +// file and returns its path. +func saveFullOutput(output string) (string, error) { + f, err := os.CreateTemp("", "tau-shell-*.log") + if err != nil { + return "", err + } + defer f.Close() + if _, err := f.WriteString(output); err != nil { + _ = os.Remove(f.Name()) + return "", err + } + return f.Name(), nil +} + +// shellCommand returns the shell binary and arguments for the current platform. +func shellCommand(command string) (string, []string) { + if runtime.GOOS == "windows" { + // Prefer PowerShell 7 (pwsh), fall back to Windows PowerShell. + shell := "powershell.exe" + if _, err := exec.LookPath("pwsh"); err == nil { + shell = "pwsh" + } + return shell, []string{ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", "Bypass", + "-Command", command, + } + } + return "bash", []string{"-c", command} +} diff --git a/internal/tools/builtin/shell_gotest_test.go b/internal/tools/builtin/shell_gotest_test.go new file mode 100644 index 000000000..9a5372c59 --- /dev/null +++ b/internal/tools/builtin/shell_gotest_test.go @@ -0,0 +1,79 @@ +package builtin + +import ( + "strings" + "testing" +) + +const verboseGoTestOutput = `=== RUN TestAlpha +--- PASS: TestAlpha (0.00s) +=== RUN TestBeta + beta_test.go:12: some chatty log line +--- PASS: TestBeta (0.01s) +PASS +ok github.com/example/pkg 0.014s +? github.com/example/pkg/empty [no test files] +ok github.com/example/other (cached) +` + +func TestCollapseGoTest_KeepsOnlyPackageSummaries(t *testing.T) { + got, collapsed := collapseGoTestOutput("go test ./... -v", verboseGoTestOutput, true) + if !collapsed { + t.Fatal("expected a passing go test run to be collapsed") + } + for _, want := range []string{ + "ok \tgithub.com/example/pkg\t0.014s", + "? \tgithub.com/example/pkg/empty\t[no test files]", + "ok \tgithub.com/example/other\t(cached)", + } { + if !strings.Contains(got, want) { + t.Errorf("summary line missing: %q\ngot:\n%s", want, got) + } + } + for _, unwanted := range []string{"=== RUN", "--- PASS", "chatty log line"} { + if strings.Contains(got, unwanted) { + t.Errorf("per-test noise %q survived:\n%s", unwanted, got) + } + } + if !strings.Contains(got, "collapsed") { + t.Errorf("expected a notice explaining the collapse, got:\n%s", got) + } +} + +// A failing run is the case where the detail is the whole point. +func TestCollapseGoTest_LeavesFailingRunsAlone(t *testing.T) { + failing := verboseGoTestOutput + "--- FAIL: TestGamma (0.00s)\nFAIL\n" + got, collapsed := collapseGoTestOutput("go test ./...", failing, false) + if collapsed { + t.Fatal("a failing run must not be collapsed") + } + if got != failing { + t.Fatal("a failing run's output must be returned verbatim") + } +} + +func TestCollapseGoTest_IgnoresOtherCommands(t *testing.T) { + for _, cmd := range []string{"git status", "go build ./...", "gotestsum --format short"} { + if _, collapsed := collapseGoTestOutput(cmd, verboseGoTestOutput, true); collapsed { + t.Errorf("%q must not be treated as a go test invocation", cmd) + } + } +} + +// Nothing to gain from collapsing output that is already just summaries, and +// doing so would append a confusing notice. +func TestCollapseGoTest_SkipsAlreadyTerseOutput(t *testing.T) { + terse := "ok \tgithub.com/example/pkg\t0.014s\n" + if _, collapsed := collapseGoTestOutput("go test ./...", terse, true); collapsed { + t.Error("already-terse output should be left alone") + } +} + +// Guard against collapsing a run that produced no recognisable summary at all, +// which would leave the model with nothing. +func TestCollapseGoTest_SkipsWhenNoSummaryLines(t *testing.T) { + odd := "=== RUN TestAlpha\n--- PASS: TestAlpha (0.00s)\nPASS\n" + if _, collapsed := collapseGoTestOutput("go test ./...", odd, true); collapsed { + t.Error("output with no package summary lines should be left alone") + } +} diff --git a/internal/tools/builtin/stderr_redact.go b/internal/tools/builtin/stderr_redact.go new file mode 100644 index 000000000..45abbcb2f --- /dev/null +++ b/internal/tools/builtin/stderr_redact.go @@ -0,0 +1,111 @@ +// Lifted from tau internal/agent/tools/stderr_redact.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "bufio" + "io" + "log/slog" + "regexp" + "time" +) + +// Redaction patterns per docs/specs/agents/03-wire-protocol.md (stderr +// handling: Redaction) and 02-spawning-and-lifecycle.md (Redaction +// contract). reBearerToken has no minimum length - the spec's own +// redaction test requirement uses a 10-character example token +// ("tok_abc123"), shorter than the {20,} it documents elsewhere for the +// sk- pattern, so this errs toward redacting too much rather than missing +// the documented test case. +var ( + reBearerToken = regexp.MustCompile(`Bearer\s+[a-zA-Z0-9_\-.]+`) + reSkKey = regexp.MustCompile(`sk-[a-zA-Z0-9]{20,}`) + reEnvSecret = regexp.MustCompile(`(?i)\b([A-Za-z_]*(?:KEY|TOKEN|SECRET|PASSWORD)[A-Za-z_]*)=\S+`) +) + +// redactSecrets replaces known secret patterns in a single stderr line with +// [REDACTED]. Order matters only for overlap avoidance; re-matching an +// already-redacted "[REDACTED]" value is harmless (idempotent). +func redactSecrets(line string) string { + line = reBearerToken.ReplaceAllString(line, "Bearer [REDACTED]") + line = reSkKey.ReplaceAllString(line, "[REDACTED]") + line = reEnvSecret.ReplaceAllString(line, "$1=[REDACTED]") + return line +} + +const ( + // stderrRateLimitBytesPerSec and stderrRateLimitWindow implement "4096 + // bytes per second, averaged over a 5-second window" - bursts within + // the window are allowed (a full panic trace is captured), sustained + // high-volume output past the window budget is truncated. + stderrRateLimitBytesPerSec = 4096 + stderrRateLimitWindow = 5 * time.Second + // stderrMaxCaptureBytes is the total per-instance capture cap; excess + // is discarded (the pipe is still drained so a chatty child never + // blocks on a full stderr pipe buffer). + stderrMaxCaptureBytes = 64 * 1024 +) + +// drainChildStderr reads r line-by-line, redacts known secret patterns, +// rate-limits and caps total capture, and logs surviving lines at ERROR +// level tagged with the child's instance ID. Never parsed for protocol +// messages - stderr is diagnostic-only (see docs/specs/agents/ +// 03-wire-protocol.md). Blocks until r is exhausted (EOF on process exit); +// callers run it in its own goroutine. +func drainChildStderr(r io.Reader, instanceID string) { + drainChildStderrWithClock(r, instanceID, time.Now) +} + +// drainChildStderrWithClock is drainChildStderr with an injectable clock, +// so tests can advance the rate-limit window deterministically instead of +// depending on real wall-clock time passing between reads. +func drainChildStderrWithClock(r io.Reader, instanceID string, now func() time.Time) { + scanner := bufio.NewScanner(r) + scanner.Buffer(make([]byte, 4096), 1024*1024) // tolerate long lines without unbounded growth + + windowBudget := stderrRateLimitBytesPerSec * int(stderrRateLimitWindow/time.Second) + var ( + totalCaptured int + capReported bool + windowStart = now() + windowBytes int + rateLimitedThisWindow bool + ) + + for scanner.Scan() { + line := scanner.Text() + lineBytes := len(line) + 1 // + newline, matching the byte-budget the spec describes + + if totalCaptured >= stderrMaxCaptureBytes { + if !capReported { + slog.Error("[... stderr truncated: capture limit exceeded ...]", "instance_id", instanceID) + capReported = true + } + continue + } + + if t := now(); t.Sub(windowStart) >= stderrRateLimitWindow { + windowStart = t + windowBytes = 0 + rateLimitedThisWindow = false + } + windowBytes += lineBytes + if windowBytes > windowBudget { + if !rateLimitedThisWindow { + slog.Error("[... stderr truncated: rate limit exceeded ...]", "instance_id", instanceID) + rateLimitedThisWindow = true + } + continue + } + + totalCaptured += lineBytes + slog.Error(redactSecrets(line), "instance_id", instanceID) + } +} diff --git a/internal/tools/builtin/stderr_redact_test.go b/internal/tools/builtin/stderr_redact_test.go new file mode 100644 index 000000000..891bdf62b --- /dev/null +++ b/internal/tools/builtin/stderr_redact_test.go @@ -0,0 +1,171 @@ +package builtin + +import ( + "context" + "log/slog" + "strings" + "testing" + "time" +) + +// --- G16: stderr redaction, rate limiting, capture cap --- + +func TestRedactSecrets(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + { + name: "api key env pattern", + in: "TAU_API_KEY=sk-abc123testtesttesttest", + want: "TAU_API_KEY=[REDACTED]", + }, + { + name: "bearer token, spec's exact example", + in: "Authorization: Bearer tok_abc123", + want: "Authorization: Bearer [REDACTED]", + }, + { + name: "bare sk- key", + in: "leaked key: sk-abcdefghijklmnopqrstuvwxyz", + want: "leaked key: [REDACTED]", + }, + { + name: "generic secret env var", + in: "DATABASE_PASSWORD=hunter2", + want: "DATABASE_PASSWORD=[REDACTED]", + }, + { + name: "generic token env var", + in: "GITHUB_TOKEN=ghp_abcdefghijklmnop", + want: "GITHUB_TOKEN=[REDACTED]", + }, + { + name: "no secret present", + in: "starting build in /home/user/project", + want: "starting build in /home/user/project", + }, + { + name: "ordinary key=value that is not sensitive", + in: "BUILD_MODE=release", + want: "BUILD_MODE=release", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := redactSecrets(tc.in) + if got != tc.want { + t.Errorf("redactSecrets(%q) = %q, want %q", tc.in, got, tc.want) + } + }) + } +} + +func TestDrainChildStderr_RedactsBeforeLogging(t *testing.T) { + var records []slog.Record + orig := slog.Default() + defer slog.SetDefault(orig) + slog.SetDefault(slog.New(captureHandler{records: &records})) + + r := strings.NewReader("TAU_API_KEY=sk-abc123testtesttesttest\n") + drainChildStderr(r, "tau#test01") + + if len(records) != 1 { + t.Fatalf("expected 1 log record, got %d", len(records)) + } + if strings.Contains(records[0].Message, "sk-abc123") { + t.Errorf("secret leaked into log: %q", records[0].Message) + } + if !strings.Contains(records[0].Message, "[REDACTED]") { + t.Errorf("expected redacted message, got %q", records[0].Message) + } +} + +func TestDrainChildStderr_CapsTotalCapture(t *testing.T) { + var records []slog.Record + orig := slog.Default() + defer slog.SetDefault(orig) + slog.SetDefault(slog.New(captureHandler{records: &records})) + + // Each line is 100 bytes; write enough lines to exceed the 64KiB cap. + // Uses a fake clock that jumps a full rate-limit window forward per + // line, so the rate limiter never engages and only the capture cap is + // under test - isolating it from TestDrainChildStderr_RateLimitsBurstInOneWindow. + line := strings.Repeat("x", 99) + var sb strings.Builder + lineCount := (stderrMaxCaptureBytes / 100) + 50 + for range lineCount { + sb.WriteString(line) + sb.WriteByte('\n') + } + + fakeNow := time.Now() + clock := func() time.Time { + fakeNow = fakeNow.Add(stderrRateLimitWindow) + return fakeNow + } + drainChildStderrWithClock(strings.NewReader(sb.String()), "tau#test02", clock) + + var truncationMarkers int + for _, rec := range records { + if strings.Contains(rec.Message, "capture limit exceeded") { + truncationMarkers++ + } + } + if truncationMarkers != 1 { + t.Errorf("expected exactly 1 capture-limit truncation marker, got %d", truncationMarkers) + } + if len(records) >= lineCount { + t.Errorf("expected fewer log records than input lines (cap should stop logging), got %d records for %d lines", len(records), lineCount) + } +} + +func TestDrainChildStderr_RateLimitsBurstInOneWindow(t *testing.T) { + var records []slog.Record + orig := slog.Default() + defer slog.SetDefault(orig) + slog.SetDefault(slog.New(captureHandler{records: &records})) + + // Well over the 4096*5=20480 byte per-window budget, all within the + // same instant (no real time passes reading from a strings.Reader). + line := strings.Repeat("y", 999) + var sb strings.Builder + for range 50 { // ~50KB total, comfortably over the 20480 budget + sb.WriteString(line) + sb.WriteByte('\n') + } + + drainChildStderr(strings.NewReader(sb.String()), "tau#test03") + + var rateLimitMarkers int + for _, rec := range records { + if strings.Contains(rec.Message, "rate limit exceeded") { + rateLimitMarkers++ + } + } + if rateLimitMarkers != 1 { + t.Errorf("expected exactly 1 rate-limit truncation marker, got %d", rateLimitMarkers) + } + if len(records) >= 50 { + t.Errorf("expected rate limiting to suppress most of the 50 lines, got %d records", len(records)) + } +} + +// captureHandler is a minimal slog.Handler that records every Record it +// receives, for asserting on log content without depending on slog's text +// formatting. +type captureHandler struct { + records *[]slog.Record +} + +func (captureHandler) Enabled(context.Context, slog.Level) bool { return true } + +func (h captureHandler) Handle(_ context.Context, r slog.Record) error { + *h.records = append(*h.records, r) + return nil +} + +func (h captureHandler) WithAttrs(_ []slog.Attr) slog.Handler { return h } + +func (h captureHandler) WithGroup(_ string) slog.Handler { return h } diff --git a/internal/tools/builtin/truncate.go b/internal/tools/builtin/truncate.go new file mode 100644 index 000000000..fca379fb9 --- /dev/null +++ b/internal/tools/builtin/truncate.go @@ -0,0 +1,156 @@ +// Lifted from tau internal/agent/tools/truncate.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "fmt" + "strings" + "time" +) + +const ( + // DefaultMaxBytes is the maximum byte size for tool output sent to the LLM. + DefaultMaxBytes = 50 * 1024 // 50KB + + // DefaultMaxLines is the maximum line count for tool output sent to the LLM. + DefaultMaxLines = 2000 + + // DefaultToolTimeout is the per-tool execution deadline. Tools that exceed + // this are cancelled. The shell tool uses its own configurable timeout. + DefaultToolTimeout = 60 * time.Second +) + +// TruncationResult holds the potentially truncated content and metadata. +type TruncationResult struct { + Content string + Truncated bool + OriginalSize int + OriginalLine int + OutputLines int // number of complete lines kept in Content +} + +// TruncateHeadRaw keeps the first N lines/bytes, dropping the tail, without +// appending a truncation notice. Callers append their own context-specific +// notice (e.g. read's "Use offset=N to continue"). Never returns partial lines: +// if the first line alone exceeds maxBytes, Content is empty with OutputLines 0. +func TruncateHeadRaw(content string, maxLines, maxBytes int) TruncationResult { + originalSize := len(content) + originalLines := 0 + if content != "" { + originalLines = strings.Count(content, "\n") + 1 + } + + result := TruncationResult{ + Content: content, + OriginalSize: originalSize, + OriginalLine: originalLines, + OutputLines: originalLines, + } + + if originalSize <= maxBytes && originalLines <= maxLines { + return result + } + + lines := strings.SplitAfter(content, "\n") + var b strings.Builder + lineCount := 0 + + for _, line := range lines { + if lineCount >= maxLines || b.Len()+len(line) > maxBytes { + result.Truncated = true + break + } + b.WriteString(line) + lineCount++ + } + + result.Content = strings.TrimSuffix(b.String(), "\n") + result.OutputLines = lineCount + return result +} + +// TruncateHead keeps the first N lines/bytes, dropping the tail, and appends +// a generic truncation notice. Good for search results and listings. +func TruncateHead(content string, maxLines, maxBytes int) TruncationResult { + result := TruncateHeadRaw(content, maxLines, maxBytes) + if result.Truncated { + result.Content += fmt.Sprintf( + "\n\n[truncated: showing %d/%d lines, %s/%s]", + result.OutputLines, result.OriginalLine, + FormatSize(len(result.Content)), FormatSize(result.OriginalSize), + ) + } + return result +} + +// TruncateTail keeps the last N lines/bytes, dropping the head. +// Good for logs, command output. +func TruncateTail(content string, maxLines, maxBytes int) TruncationResult { + originalSize := len(content) + originalLines := 0 + if content != "" { + originalLines = strings.Count(content, "\n") + 1 + } + + result := TruncationResult{ + Content: content, + OriginalSize: originalSize, + OriginalLine: originalLines, + } + + if originalSize <= maxBytes && originalLines <= maxLines { + return result + } + + lines := strings.Split(content, "\n") + + // Work backwards to find start index. + startIdx := len(lines) + byteCount := 0 + lineCount := 0 + + for i := len(lines) - 1; i >= 0; i-- { + lineLen := len(lines[i]) + if i < len(lines)-1 { + lineLen++ // account for the \n + } + if lineCount >= maxLines || byteCount+lineLen > maxBytes { + break + } + byteCount += lineLen + lineCount++ + startIdx = i + } + + if startIdx > 0 { + result.Truncated = true + kept := strings.Join(lines[startIdx:], "\n") + result.Content = fmt.Sprintf( + "[truncated: showing last %d/%d lines, %s/%s]\n\n%s", + lineCount, originalLines, + FormatSize(len(kept)), FormatSize(originalSize), + kept, + ) + } + + return result +} + +// FormatSize returns a human-readable size string. +func FormatSize(bytes int) string { + switch { + case bytes >= 1024*1024: + return fmt.Sprintf("%.1fMB", float64(bytes)/(1024*1024)) + case bytes >= 1024: + return fmt.Sprintf("%.1fKB", float64(bytes)/1024) + default: + return fmt.Sprintf("%dB", bytes) + } +} diff --git a/internal/tools/builtin/truncate_test.go b/internal/tools/builtin/truncate_test.go new file mode 100644 index 000000000..51028cd99 --- /dev/null +++ b/internal/tools/builtin/truncate_test.go @@ -0,0 +1,109 @@ +package builtin_test + +import ( + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/tools/builtin" +) + +func TestTruncateHead_NoTruncation(t *testing.T) { + content := "line1\nline2\nline3" + result := builtin.TruncateHead(content, 100, 100000) + + if result.Truncated { + t.Fatal("should not be truncated") + } + if result.Content != content { + t.Fatalf("content mismatch: got %q", result.Content) + } +} + +func TestTruncateHead_ByLines(t *testing.T) { + lines := make([]string, 100) + for i := range lines { + lines[i] = "x" + } + content := strings.Join(lines, "\n") + + result := builtin.TruncateHead(content, 10, 100000) + + if !result.Truncated { + t.Fatal("should be truncated") + } + if result.OriginalLine != 100 { + t.Fatalf("expected 100 original lines, got %d", result.OriginalLine) + } + if !strings.Contains(result.Content, "[truncated:") { + t.Fatal("should contain truncation notice") + } + if !strings.Contains(result.Content, "10/100 lines") { + t.Fatalf("truncation notice should mention line counts, got: %s", result.Content) + } +} + +func TestTruncateHead_ByBytes(t *testing.T) { + content := strings.Repeat("a", 1000) + + result := builtin.TruncateHead(content, 10000, 100) + + if !result.Truncated { + t.Fatal("should be truncated by bytes") + } + if result.OriginalSize != 1000 { + t.Fatalf("expected 1000 original bytes, got %d", result.OriginalSize) + } +} + +func TestTruncateTail_NoTruncation(t *testing.T) { + content := "line1\nline2\nline3" + result := builtin.TruncateTail(content, 100, 100000) + + if result.Truncated { + t.Fatal("should not be truncated") + } + if result.Content != content { + t.Fatalf("content mismatch") + } +} + +func TestTruncateTail_ByLines(t *testing.T) { + lines := make([]string, 100) + for i := range lines { + lines[i] = "x" + } + content := strings.Join(lines, "\n") + + result := builtin.TruncateTail(content, 10, 100000) + + if !result.Truncated { + t.Fatal("should be truncated") + } + if !strings.Contains(result.Content, "last 10/100 lines") { + t.Fatalf("truncation notice should mention line counts, got: %s", result.Content) + } + // The kept content should be the last 10 lines (all "x"). + kept := strings.Split(strings.TrimSpace(result.Content), "\n") + // Last 10 lines + truncation notice line + blank line = 12. + if len(kept) < 10 { + t.Fatalf("expected at least 10 kept lines, got %d", len(kept)) + } +} + +func TestFormatSize(t *testing.T) { + cases := []struct { + input int + expected string + }{ + {500, "500B"}, + {1024, "1.0KB"}, + {51200, "50.0KB"}, + {1048576, "1.0MB"}, + } + for _, tc := range cases { + got := builtin.FormatSize(tc.input) + if got != tc.expected { + t.Errorf("FormatSize(%d) = %q, want %q", tc.input, got, tc.expected) + } + } +} diff --git a/internal/tools/builtin/write.go b/internal/tools/builtin/write.go new file mode 100644 index 000000000..3b2eb4a63 --- /dev/null +++ b/internal/tools/builtin/write.go @@ -0,0 +1,139 @@ +// Lifted from tau internal/agent/tools/write.go +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// +// Mutations from upstream: +// - package renamed tools -> builtin (archie-core already has an +// internal/tools package holding the registry these are registered into). +// +// Refresh by diffing against that path at a newer tau commit. Do not +// edit without recording the change above. +package builtin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" +) + +// WriteParams are the parameters for the write tool. +type WriteParams struct { + Path string `json:"path"` + Content string `json:"content"` + Overwrite bool `json:"overwrite,omitempty"` +} + +var writeSchema = Schema{ + Name: "write", + Description: "Create or overwrite a file with the given content. Creates parent directories as needed. Set overwrite to true to replace an existing file; otherwise the tool will refuse to overwrite.", + Parameters: json.RawMessage(`{ + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Absolute or relative file path to write" + }, + "content": { + "type": "string", + "description": "The full file content to write" + }, + "overwrite": { + "type": "boolean", + "description": "Allow overwriting an existing file. Defaults to false - the tool will error if the file already exists unless this is true." + } + }, + "required": ["path", "content"] + }`), +} + +// NewWriteTool creates the built-in write tool. +func NewWriteTool(cwd string, mq *MutationQueue, rt *ReadTracker) Tool { + return Tool{ + Schema: writeSchema, + Source: "builtin", + Execute: makeWriteExecutor(cwd, mq, rt), + } +} + +func makeWriteExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { + return func(ctx context.Context, params json.RawMessage, _ UIBridge) (Result, error) { + var p WriteParams + if err := json.Unmarshal(params, &p); err != nil { + return Result{Content: fmt.Sprintf("invalid parameters: %v", err), IsError: true}, nil + } + + if len(p.Content) > maxWriteBytes { + return Result{Content: fmt.Sprintf("content too large (%s > %s)", FormatSize(len(p.Content)), FormatSize(maxWriteBytes)), IsError: true}, nil + } + + path := resolvePath(cwd, p.Path) + + if !isConfined(cwd, path) { + return Result{Content: "path escapes working directory", IsError: true}, nil + } + + writeCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + var result Result + err := runWithContext(writeCtx, func() error { + // Check for accidental overwrite and enforce read-before-write. + // Both checks only apply when the file already exists; new files + // are always allowed. + var oldContent string + if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() { + // Read-before-write: model must have read the file before mutating it. + if rt != nil { + if err := rt.CheckRead(cwd, p.Path); err != nil { + result = Result{Content: err.Error(), IsError: true} + return nil + } + } + // Overwrite protection: require explicit opt-in. + if !p.Overwrite { + result = Result{ + Content: fmt.Sprintf( + "file %q already exists - set overwrite to true to replace it, or use the edit tool for partial changes", + path, + ), + IsError: true, + } + return nil + } + if data, err := os.ReadFile(path); err == nil { + oldContent = string(data) + } + } + + release := mq.Acquire(path) + defer release() + + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o755); err != nil { + result = Result{Content: fmt.Sprintf("error creating directory: %v", err), IsError: true} + return nil + } + + if err := writeFileAtomic(path, []byte(p.Content), 0o644); err != nil { + result = Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true} + return nil + } + + result = Result{ + Content: fmt.Sprintf("wrote %d bytes to %s", len(p.Content), path), + Details: DiffDetails{Path: path, OldContent: oldContent, NewContent: p.Content}, + } + return nil + }) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + return Result{Content: fmt.Sprintf("write timed out after %v", DefaultToolTimeout), IsError: true}, nil + } + return Result{Content: fmt.Sprintf("write failed: %v", err), IsError: true}, nil + } + + return result, nil + } +} diff --git a/internal/tools/builtin/write_test.go b/internal/tools/builtin/write_test.go new file mode 100644 index 000000000..9339ff850 --- /dev/null +++ b/internal/tools/builtin/write_test.go @@ -0,0 +1,98 @@ +package builtin + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +func TestWriteTool_PopulatesDiffDetails_NewFile(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + + tool := NewWriteTool(tmp, NewMutationQueue(), nil) + params := `{"path": "f.txt", "content": "hello\n"}` + res, err := tool.Execute(context.Background(), json.RawMessage(params), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + + details, ok := res.Details.(DiffDetails) + if !ok { + t.Fatalf("expected Details to be a DiffDetails, got %T", res.Details) + } + if details.OldContent != "" { + t.Fatalf("expected empty OldContent for a new file, got %q", details.OldContent) + } + if details.NewContent != "hello\n" { + t.Fatalf("NewContent mismatch: got %q", details.NewContent) + } + if details.Path != path { + t.Fatalf("Path mismatch: got %q want %q", details.Path, path) + } +} + +func TestWriteTool_PopulatesDiffDetails_Overwrite(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + original := "old content\n" + if err := os.WriteFile(path, []byte(original), 0o644); err != nil { + t.Fatal(err) + } + + tool := NewWriteTool(tmp, NewMutationQueue(), nil) + params := `{"path": "f.txt", "content": "new content\n", "overwrite": true}` + res, err := tool.Execute(context.Background(), json.RawMessage(params), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.IsError { + t.Fatalf("unexpected tool error: %s", res.Content) + } + + details, ok := res.Details.(DiffDetails) + if !ok { + t.Fatalf("expected Details to be a DiffDetails, got %T", res.Details) + } + if details.OldContent != original { + t.Fatalf("OldContent mismatch: got %q want %q", details.OldContent, original) + } + if details.NewContent != "new content\n" { + t.Fatalf("NewContent mismatch: got %q", details.NewContent) + } +} + +// TestWriteTool_RespectsParentContextDeadline is the regression test for +// tau-6wa: the executor used to create a timeout-derived context and then +// discard it, passing the original (unbounded) ctx to every downstream I/O +// call. With that bug, an already-expired parent context would have no +// effect on the write. Here the parent's deadline has already passed when +// Execute is called, so the executor must surface a timeout error instead +// of proceeding to write the file. +func TestWriteTool_RespectsParentContextDeadline(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + tool := NewWriteTool(tmp, NewMutationQueue(), nil) + params := `{"path": "f.txt", "content": "hello\n"}` + res, err := tool.Execute(ctx, json.RawMessage(params), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatalf("expected a timeout error result for an already-expired context, got success: %+v", res) + } + + if _, statErr := os.Stat(path); statErr == nil { + t.Fatal("expected no file to be written when the context had already expired") + } +} diff --git a/internal/tools/provider/builtin/provider.go b/internal/tools/provider/builtin/provider.go new file mode 100644 index 000000000..ef5863a6e --- /dev/null +++ b/internal/tools/provider/builtin/provider.go @@ -0,0 +1,181 @@ +// Package builtin adapts the lifted tau file and shell tools to the typed +// tool-provider family. +// +// The tools themselves live in internal/tools/builtin, copied from tau with +// provenance headers. This package is the seam: it translates tau's tool +// shape (a JSON-schema struct plus an Executor taking raw JSON and a UI +// bridge) into archie's tools.ToolEntry, so the ai-sdk runtime's existing +// tool loop can call them without either side knowing about the other. +package builtin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/samcharles93/archie-core/internal/plugin" + "github.com/samcharles93/archie-core/internal/tools" + toolsbuiltin "github.com/samcharles93/archie-core/internal/tools/builtin" +) + +// toolset groups these tools for progressive disclosure and guardrails. +const toolset = "workspace" + +// Provider exposes the built-in file and shell tools. +type Provider struct { + // workspace is the directory file and shell operations are rooted at. + workspace string + + // registry holds the constructed tools. Built once in Start so + // Discover cannot partially fail. + registry *toolsbuiltin.Registry +} + +// New creates a provider rooted at workspace. An empty workspace is a +// configuration error, reported by Start rather than silently defaulting to +// the daemon's own working directory. +func New(workspace string) *Provider { + return &Provider{workspace: workspace} +} + +// Manifest declares the adapter's tool capability. +func (p *Provider) Manifest() plugin.Manifest { + return plugin.Manifest{ + ID: "workspace.tools", + Name: "Workspace tools", + Version: "1.0.0", + APIVersion: plugin.HostAPIVersion, + Capabilities: []plugin.CapabilityKind{"tools"}, + } +} + +// Start constructs the tools against the configured workspace. +func (p *Provider) Start(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + if p.workspace == "" { + return errors.New("workspace tool provider: workspace directory is not configured") + } + registry := toolsbuiltin.NewRegistry() + if err := toolsbuiltin.RegisterBuiltins(registry, p.workspace); err != nil { + return fmt.Errorf("workspace tool provider: register builtins: %w", err) + } + p.registry = registry + return nil +} + +// Discover returns the built-in tools as executable entries. +func (p *Provider) Discover(ctx context.Context) ([]tools.ToolEntry, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if p.registry == nil { + return nil, errors.New("workspace tool provider: not started") + } + + all := p.registry.All() + entries := make([]tools.ToolEntry, 0, len(all)) + for _, tool := range all { + entry, err := toEntry(tool) + if err != nil { + return nil, err + } + entries = append(entries, entry) + } + return entries, nil +} + +// Health reports whether the tools were constructed. +func (p *Provider) Health(context.Context) plugin.Health { + if p.workspace == "" { + return plugin.Health{ + Status: plugin.HealthUnhealthy, + Message: "workspace directory is not configured", + } + } + if p.registry == nil { + return plugin.Health{ + Status: plugin.HealthUnhealthy, + Message: "workspace tools are not started", + } + } + return plugin.Health{Status: plugin.HealthHealthy} +} + +// Stop releases the constructed tools. +func (p *Provider) Stop(context.Context) error { + p.registry = nil + return nil +} + +// toEntry converts one tau tool into an archie tool entry. +func toEntry(tool toolsbuiltin.Tool) (tools.ToolEntry, error) { + var schema tools.JSONSchema + if len(tool.Schema.Parameters) > 0 { + if err := json.Unmarshal(tool.Schema.Parameters, &schema); err != nil { + return tools.ToolEntry{}, fmt.Errorf("workspace tool %s: decode schema: %w", tool.Schema.Name, err) + } + } + return tools.ToolEntry{ + Name: tool.Schema.Name, + Description: tool.Schema.Description, + Toolset: toolset, + Schema: schema, + Classification: classify(tool.Schema.Name), + Handler: handlerFor(tool), + }, nil +} + +// handlerFor adapts a tau Executor to an archie Handler. +// +// Two shape differences are bridged here. Archie hands the handler decoded +// arguments while tau's executor takes raw JSON, and tau's executor reports +// a tool-level failure in Result.IsError rather than as an error. The +// latter is surfaced as a real error so the runtime's own failure handling +// and the guardrail engine both see it. +func handlerFor(tool toolsbuiltin.Tool) tools.Handler { + return func(ctx context.Context, input map[string]any) (any, error) { + params := json.RawMessage("{}") + if len(input) > 0 { + encoded, err := json.Marshal(input) + if err != nil { + return nil, fmt.Errorf("tool %s: encode input: %w", tool.Schema.Name, err) + } + params = encoded + } + + // NonInteractiveBridge refuses prompts rather than blocking. None + // of the lifted tools prompt; a future one that does will fail + // loudly here instead of hanging a chat turn forever. + result, err := tool.Execute(ctx, params, toolsbuiltin.NonInteractiveBridge{}) + if err != nil { + return nil, fmt.Errorf("tool %s: %w", tool.Schema.Name, err) + } + if result.IsError { + if result.ErrorKind != "" { + return nil, fmt.Errorf("tool %s: %s: %s", tool.Schema.Name, result.ErrorKind, result.Content) + } + return nil, fmt.Errorf("tool %s: %s", tool.Schema.Name, result.Content) + } + return result.Content, nil + } +} + +// classify tags each tool so the guardrail engine and budget enforcement +// can reason about it. This is categorisation, not a jail: it describes +// what a tool does and does not gate whether it may run. +// +// shell is classified mutating because it can be, not because it always +// is -- the classification cannot inspect the command. +func classify(name string) tools.ToolClassification { + switch name { + case "read", "grep", "find": + return tools.ClassIdempotent + case "write", "edit", "shell": + return tools.ClassMutating + default: + return 0 + } +} diff --git a/internal/tools/provider/builtin/provider_test.go b/internal/tools/provider/builtin/provider_test.go new file mode 100644 index 000000000..6c1d96e3d --- /dev/null +++ b/internal/tools/provider/builtin/provider_test.go @@ -0,0 +1,112 @@ +package builtin_test + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + provider "github.com/samcharles93/archie-core/internal/tools/provider/builtin" +) + +func startedProvider(t *testing.T, workspace string) *provider.Provider { + t.Helper() + p := provider.New(workspace) + if err := p.Start(context.Background()); err != nil { + t.Fatalf("Start: %v", err) + } + t.Cleanup(func() { _ = p.Stop(context.Background()) }) + return p +} + +func TestDiscoverExposesWorkspaceTools(t *testing.T) { + t.Parallel() + + entries, err := startedProvider(t, t.TempDir()).Discover(context.Background()) + if err != nil { + t.Fatalf("Discover: %v", err) + } + + got := make(map[string]bool, len(entries)) + for _, e := range entries { + got[e.Name] = true + if e.Handler == nil { + t.Errorf("tool %q has no handler, so the model could call something that does nothing", e.Name) + } + if e.Description == "" { + t.Errorf("tool %q has no description", e.Name) + } + } + for _, want := range []string{"read", "write", "edit", "shell", "grep", "find"} { + if !got[want] { + t.Errorf("tool %q missing from discovery; got %v", want, got) + } + } +} + +// TestHandlerRoundTripsThroughTauExecutor covers the seam this package +// exists for: archie hands the handler decoded arguments, tau's executor +// wants raw JSON, and the result comes back as content. +func TestHandlerRoundTripsThroughTauExecutor(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("g'day\n"), 0o600); err != nil { + t.Fatal(err) + } + + entries, err := startedProvider(t, dir).Discover(context.Background()) + if err != nil { + t.Fatalf("Discover: %v", err) + } + var read func(context.Context, map[string]any) (any, error) + for _, e := range entries { + if e.Name == "read" { + read = e.Handler + } + } + if read == nil { + t.Fatal("no read tool discovered") + } + + out, err := read(context.Background(), map[string]any{"path": "hello.txt"}) + if err != nil { + t.Fatalf("read handler: %v", err) + } + if text, ok := out.(string); !ok || !strings.Contains(text, "g'day") { + t.Errorf("read returned %#v, want content containing the file text", out) + } +} + +// TestHandlerSurfacesToolFailureAsError guards the second half of the seam: +// tau reports a tool-level failure in Result.IsError rather than as an +// error, and swallowing that would show the model a successful call. +func TestHandlerSurfacesToolFailureAsError(t *testing.T) { + t.Parallel() + + entries, err := startedProvider(t, t.TempDir()).Discover(context.Background()) + if err != nil { + t.Fatalf("Discover: %v", err) + } + for _, e := range entries { + if e.Name != "read" { + continue + } + if _, err := e.Handler(context.Background(), map[string]any{"path": "absent.txt"}); err == nil { + t.Error("reading a missing file reported success") + } + return + } + t.Fatal("no read tool discovered") +} + +// TestUnconfiguredWorkspaceIsRejected keeps the tools from silently rooting +// at the daemon's own working directory, which in the container is /. +func TestUnconfiguredWorkspaceIsRejected(t *testing.T) { + t.Parallel() + + if err := provider.New("").Start(context.Background()); err == nil { + t.Error("a provider with no workspace started successfully") + } +}