Initial commit: Go agentic harness extracted from Felix

This commit is contained in:
sausheong committed 2026-05-07 11:31:42 +08:00
commit 1f2c471ff9
89 files changed
+19388

No files matched your search

+286
View File
@@ -0,0 +1,286 @@
package todo
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/sausheong/harness/tool"
)
// TodoStatus is the status of a todo item.
type TodoStatus string
const (
TodoPending TodoStatus = "pending"
TodoInProgress TodoStatus = "in_progress"
TodoCompleted TodoStatus = "completed"
)
// TodoItem is one entry in the per-workspace todo list.
type TodoItem struct {
ID string `json:"id"`
Content string `json:"content"`
Status TodoStatus `json:"status"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
}
// TodoWriteTool maintains a per-workspace todo list the agent uses to
// track multi-step work. Persisted to <Workspace>/.felix/todos.json so
// it survives across turns within a session and across sessions for
// the same workspace.
//
// State is loaded lazily on first call and re-read from disk before
// each operation — so external edits (a human deleting the file, a
// concurrent agent in another process) are picked up. The mutex only
// serialises calls within this process.
type TodoWriteTool struct {
WorkDir string
mu sync.Mutex
}
func (t *TodoWriteTool) Name() string { return "todo_write" }
func (t *TodoWriteTool) Description() string {
return "Persistent todo list for tracking long, multi-stage work. DO NOT use this as a planning scratchpad before starting a task — start working directly and call your real tools. Reserve todo_write for genuinely long-running work with roughly 5+ independent subtasks that will span many turns. When initializing a list, emit every `add` call as a parallel tool call in the SAME assistant response (the runtime serialises them safely) — never call `add` once per turn, that wastes round trips. Operations: list (default), add, update, complete, remove. The full current list is returned every call."
}
func (t *TodoWriteTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"op": {
"type": "string",
"enum": ["list", "add", "update", "complete", "remove"],
"description": "Operation to perform. Default: list."
},
"id": {
"type": "string",
"description": "Todo id, required for update/complete/remove. Returned by add."
},
"content": {
"type": "string",
"description": "Todo body, required for add and optional for update."
},
"status": {
"type": "string",
"enum": ["pending", "in_progress", "completed"],
"description": "Status, used by update. Add starts items as pending; complete is shorthand for status=completed."
}
}
}`)
}
// IsConcurrencySafe is FALSE: the tool reads-modify-writes a shared
// file and modifies in-process state under a mutex. Marking it safe
// would let the agent loop dispatch parallel todo_write calls, all
// racing the same file. Better to serialise.
func (t *TodoWriteTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
type todoInput struct {
Op string `json:"op"`
ID string `json:"id"`
Content string `json:"content"`
Status TodoStatus `json:"status"`
}
func (t *TodoWriteTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
t.mu.Lock()
defer t.mu.Unlock()
var in todoInput
if len(input) > 0 {
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
}
if in.Op == "" {
in.Op = "list"
}
items, err := t.load()
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("load todos: %v", err)}, nil
}
now := time.Now().Unix()
switch in.Op {
case "list":
// nothing to do
case "add":
if in.Content == "" {
return tool.ToolResult{Error: "content is required for add"}, nil
}
items = append(items, TodoItem{
ID: nextTodoID(items),
Content: in.Content,
Status: TodoPending,
CreatedAt: now,
UpdatedAt: now,
})
case "update":
if in.ID == "" {
return tool.ToolResult{Error: "id is required for update"}, nil
}
idx := findTodo(items, in.ID)
if idx < 0 {
return tool.ToolResult{Error: fmt.Sprintf("todo not found: %q", in.ID)}, nil
}
if in.Content != "" {
items[idx].Content = in.Content
}
if in.Status != "" {
if !validStatus(in.Status) {
return tool.ToolResult{Error: fmt.Sprintf("invalid status: %q", in.Status)}, nil
}
items[idx].Status = in.Status
}
items[idx].UpdatedAt = now
case "complete":
if in.ID == "" {
return tool.ToolResult{Error: "id is required for complete"}, nil
}
idx := findTodo(items, in.ID)
if idx < 0 {
return tool.ToolResult{Error: fmt.Sprintf("todo not found: %q", in.ID)}, nil
}
items[idx].Status = TodoCompleted
items[idx].UpdatedAt = now
case "remove":
if in.ID == "" {
return tool.ToolResult{Error: "id is required for remove"}, nil
}
idx := findTodo(items, in.ID)
if idx < 0 {
return tool.ToolResult{Error: fmt.Sprintf("todo not found: %q", in.ID)}, nil
}
items = append(items[:idx], items[idx+1:]...)
default:
return tool.ToolResult{Error: fmt.Sprintf("unknown op: %q", in.Op)}, nil
}
if in.Op != "list" {
if err := t.save(items); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("save todos: %v", err)}, nil
}
}
return tool.ToolResult{Output: formatTodos(items)}, nil
}
// load reads the persisted todos from <WorkDir>/.felix/todos.json.
// Missing file → empty list (not an error). Corrupt JSON → error so
// the agent knows the file needs manual repair rather than silently
// dropping work.
func (t *TodoWriteTool) load() ([]TodoItem, error) {
if t.WorkDir == "" {
return nil, nil // headless / test mode — no persistence
}
path := t.todosPath()
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var items []TodoItem
if err := json.Unmarshal(data, &items); err != nil {
return nil, fmt.Errorf("corrupt todos.json: %w", err)
}
return items, nil
}
func (t *TodoWriteTool) save(items []TodoItem) error {
if t.WorkDir == "" {
return nil
}
path := t.todosPath()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
data, err := json.MarshalIndent(items, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
func (t *TodoWriteTool) todosPath() string {
return filepath.Join(t.WorkDir, ".felix", "todos.json")
}
// nextTodoID returns the next sequential id (t1, t2, …) — short and
// memorable for the model to reference. Numeric suffix is one past
// the highest existing numeric id; non-numeric ids are ignored when
// computing the next number.
func nextTodoID(items []TodoItem) string {
max := 0
for _, it := range items {
var n int
if _, err := fmt.Sscanf(it.ID, "t%d", &n); err == nil && n > max {
max = n
}
}
return fmt.Sprintf("t%d", max+1)
}
func findTodo(items []TodoItem, id string) int {
for i, it := range items {
if it.ID == id {
return i
}
}
return -1
}
func validStatus(s TodoStatus) bool {
return s == TodoPending || s == TodoInProgress || s == TodoCompleted
}
// formatTodos renders the list as a checklist the model can scan.
// Sorted: in_progress → pending → completed, then by id within each
// bucket, so the model's eye lands on what's currently active first.
func formatTodos(items []TodoItem) string {
if len(items) == 0 {
return "(no todos)"
}
statusOrder := map[TodoStatus]int{
TodoInProgress: 0,
TodoPending: 1,
TodoCompleted: 2,
}
sorted := make([]TodoItem, len(items))
copy(sorted, items)
sort.SliceStable(sorted, func(i, j int) bool {
si, sj := statusOrder[sorted[i].Status], statusOrder[sorted[j].Status]
if si != sj {
return si < sj
}
return sorted[i].ID < sorted[j].ID
})
var b strings.Builder
for _, it := range sorted {
var marker string
switch it.Status {
case TodoCompleted:
marker = "[x]"
case TodoInProgress:
marker = "[~]"
default:
marker = "[ ]"
}
fmt.Fprintf(&b, "%s %s — %s\n", marker, it.ID, it.Content)
}
return strings.TrimRight(b.String(), "\n")
}
+189
View File
@@ -0,0 +1,189 @@
package todo
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// --- single-call ops ---
func TestTodoWriteListEmpty(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, err := tool.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
require.NoError(t, err)
assert.Empty(t, res.Error)
assert.Equal(t, "(no todos)", res.Output)
}
func TestTodoWriteAddReturnsItemAndPersists(t *testing.T) {
dir := t.TempDir()
tool := &TodoWriteTool{WorkDir: dir}
res, err := tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"first task"}`))
require.NoError(t, err)
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[ ] t1 — first task")
// Persisted to disk so a fresh tool instance picks it up.
path := filepath.Join(dir, ".felix", "todos.json")
data, err := os.ReadFile(path)
require.NoError(t, err)
assert.Contains(t, string(data), "first task")
tool2 := &TodoWriteTool{WorkDir: dir}
res2, _ := tool2.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
assert.Contains(t, res2.Output, "first task")
}
func TestTodoWriteAddMissingContentRejected(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"add"}`))
assert.Contains(t, res.Error, "content is required")
}
func TestTodoWriteCompleteShortcut(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"complete","id":"t1"}`))
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[x] t1 — x")
}
func TestTodoWriteUpdateChangesStatusAndContent(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"orig"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"update","id":"t1","content":"revised","status":"in_progress"}`))
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[~] t1 — revised")
}
func TestTodoWriteUpdateInvalidStatusRejected(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"update","id":"t1","status":"frobnicated"}`))
assert.Contains(t, res.Error, "invalid status")
}
func TestTodoWriteRemove(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"y"}`))
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"remove","id":"t1"}`))
assert.Empty(t, res.Error)
assert.NotContains(t, res.Output, "t1")
assert.Contains(t, res.Output, "t2 — y")
}
func TestTodoWriteRemoveUnknownID(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"remove","id":"ghost"}`))
assert.Contains(t, res.Error, "todo not found")
}
func TestTodoWriteUnknownOpRejected(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"frobnicate"}`))
assert.Contains(t, res.Error, "unknown op")
}
func TestTodoWriteEmptyInputDefaultsToList(t *testing.T) {
tool := &TodoWriteTool{WorkDir: t.TempDir()}
res, err := tool.Execute(context.Background(), nil)
require.NoError(t, err)
assert.Empty(t, res.Error)
assert.Equal(t, "(no todos)", res.Output)
}
// --- ID generation ---
func TestNextTodoIDGapsAreSafe(t *testing.T) {
// id allocator must keep monotonically increasing even when items
// have been removed in the middle. Otherwise an old removed id
// could get re-issued and the model's earlier reference would
// silently target a different todo.
items := []TodoItem{
{ID: "t1"},
{ID: "t3"},
}
assert.Equal(t, "t4", nextTodoID(items))
}
func TestNextTodoIDIgnoresNonNumeric(t *testing.T) {
items := []TodoItem{
{ID: "legacy"},
{ID: "t2"},
}
assert.Equal(t, "t3", nextTodoID(items))
}
// --- formatTodos ordering ---
func TestFormatTodosSortsByStatusThenID(t *testing.T) {
items := []TodoItem{
{ID: "t3", Content: "c3", Status: TodoCompleted},
{ID: "t1", Content: "c1", Status: TodoPending},
{ID: "t2", Content: "c2", Status: TodoInProgress},
{ID: "t4", Content: "c4", Status: TodoInProgress},
}
got := formatTodos(items)
// Order: in_progress (t2, t4), then pending (t1), then completed (t3).
t2Idx := indexOf(got, "t2")
t4Idx := indexOf(got, "t4")
t1Idx := indexOf(got, "t1")
t3Idx := indexOf(got, "t3")
require.True(t, t2Idx < t4Idx, "in_progress sorted by id")
require.True(t, t4Idx < t1Idx, "in_progress before pending")
require.True(t, t1Idx < t3Idx, "pending before completed")
}
// --- corrupt store ---
func TestTodoWriteCorruptStoreSurfacesError(t *testing.T) {
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, ".felix"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, ".felix", "todos.json"), []byte("{not valid json"), 0o644))
tool := &TodoWriteTool{WorkDir: dir}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
// Corrupt store must not return "(no todos)" — that would be
// silent data loss. Surface the error so a human can intervene.
assert.Contains(t, res.Error, "load todos")
}
// --- headless mode ---
func TestTodoWriteHeadlessNoWorkDir(t *testing.T) {
// No WorkDir → no persistence. Operations still succeed but
// state lives only in the current call (not even between calls
// on the same tool — that's intentional; the persistence layer
// IS the WorkDir file).
tool := &TodoWriteTool{}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"add","content":"x"}`))
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, "[ ] t1 — x")
res2, _ := tool.Execute(context.Background(), json.RawMessage(`{"op":"list"}`))
// No persistence, so the second list call sees nothing.
assert.Equal(t, "(no todos)", res2.Output)
}
func TestTodoWriteIsConcurrencySafeFalse(t *testing.T) {
tool := &TodoWriteTool{}
assert.False(t, tool.IsConcurrencySafe(nil),
"todo_write is stateful read-modify-write; concurrent dispatch would race")
}
// helper
func indexOf(s, sub string) int {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return i
}
}
return -1
}