feat(edastore): project tool_call events into the tool_calls collection

The tool_calls collection existed in the event-capture schema but nothing
wrote it. Give it its write path:

- edastore gains InsertToolCall and the minimal TaskToolCalls read, writing
  only the existing collection. No new index: the collection is an
  append-only transcript and the SQLite predecessor had no unique index.
- internal/app/archied composes toolCallProjectingTaskStore, a decorator on
  the task store that persists the event first, then -- only for tool_call
  events -- writes one row. A projection failure is counted and logged but
  never returned from InsertEvent: event persistence is load-bearing,
  tool_calls is observability.
- stateStoreDeps wires the decorator around deps.Tasks when both stores are
  open, and passes Tasks through untouched otherwise.

The event adapts to the existing schema, not the other way round: the tool
name comes from data, a succeeded call's detail is the row's result, a
failed call's detail its error; args and duration_ms stay reserved for a
producer that reports them.
This commit is contained in:
sam committed 2026-09-23 03:26:14 +10:00
1 parent c208a637cb
commit a0d6cfbb28
5 files changed
+488

No files matched your search

@@ -0,0 +1,98 @@
package edastore
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/pocketbase/pocketbase/core"
)
// ToolCall is one completed tool invocation during an agent stage run, as the
// tool_call event projection stores it. The projection adapts the event to the
// existing collection (schema.go): a tool's output summary goes in result, a
// failure's detail in error. The args and duration_ms fields the schema also
// carries are left unwritten -- the tool_call event reports neither -- and a
// future producer that has them can start filling them without a schema
// change.
type ToolCall struct {
ID string
TaskID int64
Attempt int
Tool string
Result string
Error string
CalledAt time.Time
}
// InsertToolCall appends one row to the tool_calls collection. There is no
// idempotency here, deliberately: the collection is an append-only transcript
// and the schema carries no unique index (the SQLite predecessor had none --
// tool calls lived only in the on-disk task log), so one event is one row.
//
// The notify hook stays silent, matching the task-dispatch tables rather than
// the operator-editable ones: tool calls are high-frequency telemetry, not
// dashboard activity.
func (s *Store) InsertToolCall(_ context.Context, tc ToolCall) error {
collection, err := s.app.FindCollectionByNameOrId(CollToolCalls)
if err != nil {
return err
}
r := core.NewRecord(collection)
r.Set("task_id", tc.TaskID)
r.Set("attempt", tc.Attempt)
r.Set("tool", tc.Tool)
if tc.Result != "" {
r.Set("result", tc.Result)
}
if tc.Error != "" {
r.Set("error", tc.Error)
}
if !tc.CalledAt.IsZero() {
// called_at is an autodate field, but an explicitly set date is kept:
// the row carries the time the tool call happened, not the time it
// was projected.
r.Set("called_at", tc.CalledAt)
}
if err := s.app.Save(r); err != nil {
return fmt.Errorf("edastore: insert tool call: %w", err)
}
return nil
}
// TaskToolCalls returns one task's tool calls in call order.
func (s *Store) TaskToolCalls(_ context.Context, taskID int64) ([]ToolCall, error) {
records, err := s.app.FindRecordsByFilter(CollToolCalls, "task_id = {:task}", "+called_at", 0, 0,
map[string]any{"task": taskID})
if err != nil {
return nil, fmt.Errorf("edastore: list tool calls: %w", err)
}
out := make([]ToolCall, 0, len(records))
for _, r := range records {
out = append(out, ToolCall{
ID: r.Id,
TaskID: r.GetInt64("task_id"),
Attempt: r.GetInt("attempt"),
Tool: r.GetString("tool"),
Result: jsonTextToString(r.GetString("result")),
Error: r.GetString("error"),
CalledAt: r.GetDateTime("called_at").Time(),
})
}
return out, nil
}
// jsonTextToString unwraps the JSON string a JSONField stores a plain text
// summary under, and falls back to the raw text for anything that is not a
// JSON string (e.g. an object a future producer stored directly).
func jsonTextToString(raw string) string {
if raw == "" {
return ""
}
var decoded string
if err := json.Unmarshal([]byte(raw), &decoded); err != nil {
return raw
}
return decoded
}
@@ -0,0 +1,102 @@
package edastore_test
import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
)
func insertToolCall(t *testing.T, s *edastore.Store, tc edastore.ToolCall) {
t.Helper()
if err := s.InsertToolCall(t.Context(), tc); err != nil {
t.Fatalf("InsertToolCall() error = %v", err)
}
}
// TestInsertToolCallRoundTrip pins the write/read pair on the tool_calls
// collection: a row written with the fields the tool_call projection provides
// reads back unchanged, and the read filters on task_id so one task's calls
// never surface in another's.
func TestInsertToolCallRoundTrip(t *testing.T) {
s := newStore(t)
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
insertToolCall(t, s, edastore.ToolCall{
TaskID: 42,
Attempt: 2,
Tool: "shell",
Result: "all checks passed",
CalledAt: at,
})
insertToolCall(t, s, edastore.ToolCall{
TaskID: 42,
Attempt: 2,
Tool: "read_file",
Error: "no such file",
CalledAt: at.Add(time.Second),
})
// A different task's call must not leak into the read below.
insertToolCall(t, s, edastore.ToolCall{
TaskID: 7,
Attempt: 1,
Tool: "shell",
Result: "other task's call",
CalledAt: at.Add(2 * time.Second),
})
got, err := s.TaskToolCalls(t.Context(), 42)
if err != nil {
t.Fatalf("TaskToolCalls() error = %v", err)
}
if len(got) != 2 {
t.Fatalf("TaskToolCalls() returned %d rows for task 42, want 2: %+v", len(got), got)
}
first, second := got[0], got[1]
// Chronological order: the earlier call first.
if first.Tool != "shell" || second.Tool != "read_file" {
t.Errorf("order = [%q, %q], want [shell, read_file] by called_at", first.Tool, second.Tool)
}
if first.TaskID != 42 || first.Attempt != 2 {
t.Errorf("first row task/attempt = %d/%d, want 42/2", first.TaskID, first.Attempt)
}
if first.Result != "all checks passed" {
t.Errorf("first row result = %q, want the stored summary without JSON quoting", first.Result)
}
if first.Error != "" {
t.Errorf("first row error = %q, want empty: a succeeded call is not an error", first.Error)
}
if second.Error != "no such file" {
t.Errorf("second row error = %q, want the stored failure detail", second.Error)
}
if second.Result != "" {
t.Errorf("second row result = %q, want empty: a failed call has no result", second.Result)
}
if first.CalledAt.IsZero() {
t.Error("first row called_at is zero; the call time must round-trip")
}
}
// TestInsertToolCallIsAnAppendOnlyTranscript pins that the collection is one
// row per tool call, not an upsert: repeated calls with the same (task,
// attempt, tool) are distinct transcript entries. There is no unique index and
// there must not be one -- the SQLite predecessor had none (tool calls lived
// only in the on-disk task log), so the schema's non-unique (task_id, attempt)
// index stays the only one.
func TestInsertToolCallIsAnAppendOnlyTranscript(t *testing.T) {
s := newStore(t)
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
row := edastore.ToolCall{TaskID: 42, Attempt: 3, Tool: "shell", Result: "ok", CalledAt: at}
insertToolCall(t, s, row)
insertToolCall(t, s, row)
got, err := s.TaskToolCalls(t.Context(), 42)
if err != nil {
t.Fatalf("TaskToolCalls() error = %v", err)
}
if len(got) != 2 {
t.Fatalf("TaskToolCalls() returned %d rows, want 2: the transcript is append-only, not a dedup ledger", len(got))
}
}