refactor: pre-cleanup.

This commit is contained in:
sam committed 2026-08-06 01:40:15 +10:00
1 parent 0ceab9d897
commit e10cbbc92c
53 files changed
+3596 -648

No files matched your search

+17 -1
View File
@@ -32,6 +32,10 @@ type InProcessRunner struct {
log *slog.Logger
run loopFunc
tools *tools.Registry
// Limits bounds the size of tool results fed back into the stage. The
// zero value applies no limits.
Limits ToolLimits
}
func NewInProcessRunner(
@@ -46,6 +50,18 @@ func NewInProcessRunner(
return runner
}
// workspaceToolset names the central-registry toolset a task agent must not
// inherit. Those tools are rooted at the chat workspace, not the task's
// worktree, and they reach the filesystem through their own handlers -- so
// agentloop's ReadOnly and ProtectPaths, which gate only the tools agentloop
// registers itself, do not apply to them. A feasibility stage running
// ReadOnly could otherwise write, and a TDD fix stage could edit the very
// tests it is being graded against.
//
// This is an invariant of task execution rather than a deployment choice, so
// it is not configurable.
const workspaceToolset = "workspace"
func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) {
if err := req.Validate(); err != nil {
return Result{}, err
@@ -59,7 +75,7 @@ func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request
notes := &memoryNotes{initial: req.Notes}
captures := make(map[string][]json.RawMessage)
centralTools, err := BuildToolSet(r.tools)
centralTools, err := BuildToolSet(r.tools, r.Limits.Options(workspaceToolset))
if err != nil {
return Result{}, fmt.Errorf("build central tool set: %w", err)
}
+128 -8
View File
@@ -4,12 +4,94 @@ import (
"context"
"encoding/json"
"fmt"
"os"
"slices"
aicore "github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/tools"
)
// ToolLimits are the configured result limits for one chat turn or agent
// stage. It holds only settings, never accumulated state, so it is safe to
// store on a long-lived runner and share across tasks.
//
// A negative limit means no limit; see config.ToolPolicy for why zero cannot
// carry that meaning.
type ToolLimits struct {
MaxResultChars int
TurnBudgetChars int
SpillDir string
}
// EnsureSpillDir creates the spill directory if one is configured.
//
// Call it once at startup. Without it the directory never exists, and because
// TurnBudget's write failure is silent every oversized result falls back to
// inline truncation -- spilling looks configured and does nothing. An empty
// SpillDir is not an error: it selects inline truncation deliberately.
func (l ToolLimits) EnsureSpillDir() error {
if l.SpillDir == "" {
return nil
}
// 0700: spill files are verbatim tool output and may hold anything the
// tools could read.
if err := os.MkdirAll(l.SpillDir, 0o700); err != nil {
return fmt.Errorf("create tool spill directory %s: %w", l.SpillDir, err)
}
return nil
}
// Options builds the tool-set options for a single turn or stage, minting a
// fresh TurnBudget each time.
//
// The budget must never outlive one turn: a shared counter would let one
// task's tool output exhaust another's allowance, and nothing would reset it.
func (l ToolLimits) Options(excludeToolsets ...string) ToolSetOptions {
opts := ToolSetOptions{
MaxResultChars: l.MaxResultChars,
ExcludeToolsets: excludeToolsets,
}
if l.TurnBudgetChars > 0 {
opts.Budget = tools.NewTurnBudget(l.TurnBudgetChars, l.SpillDir)
}
return opts
}
// ToolSetOptions bounds what a built tool set may do and return.
//
// The zero value builds every available tool with no result limits, which is
// the behaviour this package had before the options existed.
type ToolSetOptions struct {
// Budget accounts for the aggregate size of tool results across one chat
// turn or agent stage, and supplies the spill directory oversized results
// are displaced to. Nil disables budget accounting entirely.
Budget *tools.TurnBudget
// MaxResultChars caps a single tool result. Entries setting
// ToolEntry.MaxResultSizeChars override it. Zero or negative means no cap.
MaxResultChars int
// ExcludeToolsets omits entries whose ToolEntry.Toolset matches. Task
// agents use it to drop the chat workspace's file and shell tools, which
// are rooted at a directory that is not the task's worktree and which
// bypass the agent loop's read-only and protected-path enforcement.
ExcludeToolsets []string
}
// resultLimit returns the cap that applies to one entry.
func (o ToolSetOptions) resultLimit(entry tools.ToolEntry) int {
if entry.MaxResultSizeChars != 0 {
return entry.MaxResultSizeChars
}
return o.MaxResultChars
}
// excludes reports whether an entry's toolset is omitted.
func (o ToolSetOptions) excludes(entry tools.ToolEntry) bool {
return slices.Contains(o.ExcludeToolsets, entry.Toolset)
}
// BuildToolSet converts every currently-available entry in reg into an
// ai-sdk core.ToolSet, ready to pass as core.GenerateOptions.Tools for a
// multi-step chat turn. A nil registry (memory/tools disabled) returns
@@ -20,12 +102,31 @@ import (
// tools.Handler exchanges a decoded map. The returned Execute functions
// do the JSON <-> map translation and surface decode failures as errors
// rather than silently dropping malformed model input.
func BuildToolSet(reg *tools.Registry) (aicore.ToolSet, error) {
set := aicore.ToolSet{}
//
// This is the only path from a registered tools.ToolEntry to a model, so it is
// also where result limits are enforced. The model runtime owns the tool loop
// and decides what to invoke, so archie cannot gate a batch -- but it builds
// every Execute closure here, which makes per-call accounting reachable.
func BuildToolSet(reg *tools.Registry, opts ToolSetOptions) (aicore.ToolSet, error) {
if reg == nil {
return set, nil
return aicore.ToolSet{}, nil
}
for _, entry := range reg.All() {
return BuildToolSetFrom(reg.All(), opts)
}
// BuildToolSetFrom converts a loose slice of entries under the same rules as
// [BuildToolSet].
//
// It exists for tools that are bound per turn rather than registered globally
// -- the task tools carry the calling gateway's identity, so there is one set
// of them per gateway and they cannot live in the process-wide registry. Pass
// the same ToolSetOptions to both calls so a single turn shares one budget.
func BuildToolSetFrom(entries []tools.ToolEntry, opts ToolSetOptions) (aicore.ToolSet, error) {
set := aicore.ToolSet{}
for _, entry := range entries {
if opts.excludes(entry) {
continue
}
available, err := safeToolAvailable(entry)
if err != nil {
return nil, fmt.Errorf("tool %s availability: %w", entry.Name, err)
@@ -47,7 +148,7 @@ func BuildToolSet(reg *tools.Registry) (aicore.ToolSet, error) {
if err != nil {
return nil, fmt.Errorf("tool %s schema: %w", entry.Name, err)
}
set[entry.Name] = aicore.NewTool(entry.Name, entry.Description, params, toolExecute(entry))
set[entry.Name] = aicore.NewTool(entry.Name, entry.Description, params, toolExecute(entry, opts))
}
return set, nil
}
@@ -71,9 +172,23 @@ func safeResolvedSchema(entry tools.ToolEntry) (schema tools.JSONSchema, err err
}
// toolExecute adapts a tools.ToolEntry's Handler to core.Tool's
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape.
func toolExecute(entry tools.ToolEntry) func(context.Context, string) (string, error) {
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape, and
// applies the turn's result accounting.
//
// The cap is applied to the marshalled payload rather than to the handler's
// return value, because the marshalled form is what actually reaches the
// model: JSON escaping can change the length materially, so capping the Go
// value would bound the wrong string.
func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Context, string) (string, error) {
limit := opts.resultLimit(entry)
return func(ctx context.Context, input string) (string, error) {
// A turn that has spent its budget must say so. Returning an error
// tells the model it has run out; returning an empty result would
// read as "the tool found nothing" and invite it to try again.
if opts.Budget != nil && opts.Budget.Exceeded() {
return "", fmt.Errorf("tool %s: turn budget exceeded (%d chars)", entry.Name, opts.Budget.MaxChars)
}
var args map[string]any
if input != "" {
if err := json.Unmarshal([]byte(input), &args); err != nil {
@@ -88,6 +203,11 @@ func toolExecute(entry tools.ToolEntry) func(context.Context, string) (string, e
if err != nil {
return "", fmt.Errorf("tool %s: encode output: %w", entry.Name, err)
}
return string(data), nil
payload := tools.CapPayload(entry.Name, string(data), limit, opts.Budget)
if opts.Budget != nil {
opts.Budget.Consume(len(payload))
}
return payload, nil
}
}
+239 -2
View File
@@ -4,6 +4,9 @@ import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
aicore "github.com/samcharles93/ai-sdk/core"
@@ -214,7 +217,7 @@ func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
)
func() {
defer func() { panicked = recover() }()
_, err = BuildToolSet(registry)
_, err = BuildToolSet(registry, ToolSetOptions{})
}()
if panicked != nil {
t.Fatalf("BuildToolSet() panicked: %v", panicked)
@@ -228,9 +231,243 @@ func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
func mustBuildToolSet(t *testing.T, registry *tools.Registry) map[string]*aicore.Tool {
t.Helper()
set, err := BuildToolSet(registry)
return mustBuildToolSetWith(t, registry, ToolSetOptions{})
}
func mustBuildToolSetWith(t *testing.T, registry *tools.Registry, opts ToolSetOptions) map[string]*aicore.Tool {
t.Helper()
set, err := BuildToolSet(registry, opts)
if err != nil {
t.Fatal(err)
}
return set
}
// registryReturning builds a single-entry registry whose tool returns payload.
func registryReturning(t *testing.T, entry tools.ToolEntry, payload string) *tools.Registry {
t.Helper()
reg := tools.NewRegistry()
entry.Handler = func(context.Context, map[string]any) (any, error) { return payload, nil }
if err := reg.Register(entry); err != nil {
t.Fatal(err)
}
return reg
}
// TestToolSetCapsResults covers the limit that decides how much of a tool
// result reaches the model. The workspace tools truncate themselves, so the
// entries that matter here are the ones that do not: skill bodies and MCP
// results were previously handed over whole.
func TestToolSetCapsResults(t *testing.T) {
const payloadSize = 4000
payload := strings.Repeat("z", payloadSize)
tests := []struct {
name string
entryLimit int // ToolEntry.MaxResultSizeChars
defaultLimit int // ToolSetOptions.MaxResultChars
wantTruncated bool
}{
{name: "under the default passes through", defaultLimit: payloadSize * 2},
{name: "over the default is capped", defaultLimit: 100, wantTruncated: true},
{name: "per-entry limit overrides a larger default", entryLimit: 100, defaultLimit: payloadSize * 2, wantTruncated: true},
{name: "per-entry limit overrides a smaller default", entryLimit: payloadSize * 2, defaultLimit: 100},
{name: "negative default disables capping", defaultLimit: -1},
{name: "zero default disables capping", defaultLimit: 0},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
reg := registryReturning(t, tools.ToolEntry{
Name: "big",
MaxResultSizeChars: tc.entryLimit,
}, payload)
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: tc.defaultLimit})
out, err := set["big"].Execute(context.Background(), "{}")
if err != nil {
t.Fatal(err)
}
truncated := strings.Contains(out, "truncated")
if truncated != tc.wantTruncated {
t.Fatalf("truncated = %v, want %v (result %d bytes)", truncated, tc.wantTruncated, len(out))
}
if !tc.wantTruncated && len(out) < payloadSize {
t.Errorf("result is %d bytes, want the whole %d-byte payload", len(out), payloadSize)
}
})
}
}
// TestToolSetSpillsOversizeResults proves an oversized result is displaced to
// disk rather than lost: the model gets a path it can read back with the read
// tool, which is the whole point of spilling instead of truncating.
func TestToolSetSpillsOversizeResults(t *testing.T) {
dir := t.TempDir()
budget := tools.NewTurnBudget(1_000_000, dir)
payload := strings.Repeat("q", 4000)
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, payload)
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget})
out, err := set["big"].Execute(context.Background(), "{}")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "spilled") {
t.Fatalf("result = %q, want a spill reference", out)
}
spilled := budget.Spilled()
if len(spilled) != 1 || spilled[0].Path == "" {
t.Fatalf("Spilled() = %+v, want one spill with a path", spilled)
}
if !strings.Contains(out, spilled[0].Path) {
t.Errorf("result %q does not name the spill path %q", out, spilled[0].Path)
}
body, err := os.ReadFile(spilled[0].Path)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), payload) {
t.Error("spill file does not hold the full payload")
}
}
// TestToolLimitsCreatesSpillDir covers the gap that made spilling dead code in
// production: the configured directory defaults to <work_dir>/tool-spill and
// nothing ever created it, while TurnBudget.Spill swallows the write error. So
// every oversized result silently fell back to inline truncation and the spill
// path was never exercised outside tests that made their own directory.
func TestToolLimitsCreatesSpillDir(t *testing.T) {
// A nested path proves the whole tree is created, not just a leaf.
dir := filepath.Join(t.TempDir(), "work", "tool-spill")
limits := ToolLimits{MaxResultChars: 100, TurnBudgetChars: 1_000_000, SpillDir: dir}
if err := limits.EnsureSpillDir(); err != nil {
t.Fatal(err)
}
info, err := os.Stat(dir)
if err != nil {
t.Fatalf("spill directory was not created: %v", err)
}
if !info.IsDir() {
t.Fatalf("%s is not a directory", dir)
}
// And a spill actually lands there once it exists.
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("z", 5000))
set := mustBuildToolSetWith(t, reg, limits.Options())
if _, err := set["big"].Execute(context.Background(), "{}"); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if len(entries) == 0 {
t.Error("no spill file was written into the created directory")
}
}
// TestToolLimitsEnsureSpillDirNoop covers the disabled case: no directory
// configured is not an error, it selects inline truncation.
func TestToolLimitsEnsureSpillDirNoop(t *testing.T) {
if err := (ToolLimits{}).EnsureSpillDir(); err != nil {
t.Errorf("EnsureSpillDir() with no directory = %v, want nil", err)
}
}
// TestToolSetChargesBudgetOnce pins the invariant that makes the turn budget
// mean anything: a turn is charged exactly the bytes it was shown.
//
// Displacing an oversized result to disk used to charge the full displaced
// size AND the short reference handed back, so two 60 KB results burned more
// than the 200 K default budget while the model saw about 200 characters.
func TestToolSetChargesBudgetOnce(t *testing.T) {
tests := []struct {
name string
spillDir bool
}{
{name: "results spilled to disk", spillDir: true},
{name: "results truncated inline", spillDir: false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
dir := ""
if tc.spillDir {
dir = t.TempDir()
}
budget := tools.NewTurnBudget(1_000_000, dir)
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("q", 60_000))
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget})
delivered := 0
for range 2 {
out, err := set["big"].Execute(context.Background(), "{}")
if err != nil {
t.Fatal(err)
}
delivered += len(out)
}
if used := budget.Used(); used != delivered {
t.Errorf("budget charged %d for %d delivered characters", used, delivered)
}
})
}
}
// TestToolSetBudgetStopsFurtherCalls checks the aggregate cap: once a turn has
// spent its budget the next tool call must fail loudly, so the model is told it
// has run out rather than silently receiving nothing.
func TestToolSetBudgetStopsFurtherCalls(t *testing.T) {
budget := tools.NewTurnBudget(50, "")
reg := registryReturning(t, tools.ToolEntry{Name: "chatty"}, strings.Repeat("w", 200))
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Budget: budget})
if _, err := set["chatty"].Execute(context.Background(), "{}"); err != nil {
t.Fatalf("first call: %v", err)
}
if !budget.Exceeded() {
t.Fatal("budget should be exceeded after a 200-byte result against a 50-byte cap")
}
_, err := set["chatty"].Execute(context.Background(), "{}")
if err == nil {
t.Fatal("second call succeeded, want a budget-exceeded error")
}
if !strings.Contains(err.Error(), "budget") {
t.Errorf("error = %v, want it to name the budget", err)
}
}
// TestToolSetExcludesToolsets covers the task-agent case: a task runs in its
// own worktree, so the chat workspace's file and shell tools must not follow it
// in and bypass the agent loop's read-only and protected-path enforcement.
func TestToolSetExcludesToolsets(t *testing.T) {
reg := tools.NewRegistry()
for _, e := range []tools.ToolEntry{
{Name: "shell", Toolset: "workspace"},
{Name: "memory_edit", Toolset: "memory"},
} {
e.Handler = func(context.Context, map[string]any) (any, error) { return "ok", nil }
if err := reg.Register(e); err != nil {
t.Fatal(err)
}
}
full := mustBuildToolSetWith(t, reg, ToolSetOptions{})
if len(full) != 2 {
t.Fatalf("with no exclusions the set has %d tools, want 2", len(full))
}
limited := mustBuildToolSetWith(t, reg, ToolSetOptions{ExcludeToolsets: []string{"workspace"}})
if _, ok := limited["shell"]; ok {
t.Error("workspace tool survived the exclusion")
}
if _, ok := limited["memory_edit"]; !ok {
t.Error("memory tool was dropped, want only the workspace toolset excluded")
}
}