Automations phase 2: chaining, refinements, dry run
Chaining: spec gains calls:[ids] + calledOnly. On fire, a task calls its
same-owner callees in order; each callee evaluates its OWN condition and
may call onward. Safety: write-time cycle rejection (owner-graph DFS) plus
a runtime visited-set + depth cap (5); calledOnly tasks skip the schedule;
existing per-task fire caps and the owner daily email cap still apply
across the chain. The LLM never chooses calls — the user wires the graph.
Refinements: AgentTask.refinements jsonb (migration 026) stores added
constraints; the UI composes prompt+refinements into the compile text and
shows removable chips. Dry run: condition-check is split from fire() so
POST /api/agent/dry-run evaluates a spec without acting or recording —
the 'Extend → Try it' preview ('result would be false right now').
UI: detail view gains the 'If true, call' card (picker disables
loop-creating options), refinement chips + Extend/Try it/Add flow, called-by
breadcrumb, and a 'when called' frequency label.
Verified: full DB integration suite under -race (chaining fires callees,
cycle rejected at write + runtime guard terminates a DB-injected cycle,
calledOnly skips schedule, dry run records nothing, refinements capped),
db-converge + atomicity, web lint/SSR/build, browser regression extended
for chaining + refinement + dry run.
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.federated.computer/Federated_Computer/superbrain/internal/agent"
|
||||
"gitea.federated.computer/Federated_Computer/superbrain/internal/db"
|
||||
)
|
||||
|
||||
func phase2Setup(t *testing.T) (apiClient, *db.DB, string) {
|
||||
t.Helper()
|
||||
srv, d := testServerDB(t)
|
||||
fake := newFakeOpenAI(t)
|
||||
host, port, _ := net.SplitHostPort(fake.ln.Addr().String())
|
||||
t.Setenv("AI_API_KEY", "test-key")
|
||||
t.Setenv("AI_BASE_URL", "http://"+host+":"+port+"/v1")
|
||||
t.Setenv("AI_MODEL", "test-model")
|
||||
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
|
||||
c, _ := accountClient(t, srv.URL, "p2@superbrain.test")
|
||||
return c, d, fakeWatchTarget(t)
|
||||
}
|
||||
|
||||
func watchSpec(url string, thr float64, action map[string]any) map[string]any {
|
||||
return map[string]any{
|
||||
"condition": map[string]any{"type": "url_watch", "url": url, "question": "price in USD", "op": "lt", "threshold": thr},
|
||||
"action": action,
|
||||
"pollMinutes": 60, "once": false,
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentChaining(t *testing.T) {
|
||||
c, d, watchURL := phase2Setup(t)
|
||||
bookmark := map[string]any{"type": "bookmark", "url": "https://example.test/deal", "title": "Deal"}
|
||||
|
||||
// Callee B (calledOnly) and caller A that calls B.
|
||||
b := c.request("POST", "/api/agent/tasks", map[string]any{
|
||||
"name": "Hotel check", "spec": watchSpec(watchURL, 400, bookmark), "calledOnly": true,
|
||||
}, 201)
|
||||
_ = b
|
||||
bid := b["id"].(string)
|
||||
// calledOnly is part of the spec, not a top-level field — set it via spec.
|
||||
bSpec := watchSpec(watchURL, 400, bookmark)
|
||||
bSpec["calledOnly"] = true
|
||||
c.request("PATCH", "/api/agent/tasks/"+bid, map[string]any{"spec": bSpec, "version": 1}, 200)
|
||||
|
||||
a := c.request("POST", "/api/agent/tasks", map[string]any{
|
||||
"name": "Flight check", "spec": func() map[string]any { s := watchSpec(watchURL, 400, bookmark); s["calls"] = []string{bid}; return s }(),
|
||||
}, 201)
|
||||
aid := a["id"].(string)
|
||||
|
||||
// Self-call and foreign callee rejected.
|
||||
c.request("PATCH", "/api/agent/tasks/"+aid, map[string]any{"spec": func() map[string]any { s := watchSpec(watchURL, 400, bookmark); s["calls"] = []string{aid}; return s }(), "version": 1}, 400)
|
||||
c.request("PATCH", "/api/agent/tasks/"+aid, map[string]any{"spec": func() map[string]any { s := watchSpec(watchURL, 400, bookmark); s["calls"] = []string{"nope"}; return s }(), "version": 1}, 400)
|
||||
|
||||
// Cycle: C calls A; then A calls C would loop A→C→A.
|
||||
cc := c.request("POST", "/api/agent/tasks", map[string]any{
|
||||
"name": "PTO draft", "spec": func() map[string]any { s := watchSpec(watchURL, 400, bookmark); s["calls"] = []string{aid}; return s }(),
|
||||
}, 201)
|
||||
cid := cc["id"].(string)
|
||||
c.request("PATCH", "/api/agent/tasks/"+aid, map[string]any{"spec": func() map[string]any { s := watchSpec(watchURL, 400, bookmark); s["calls"] = []string{cid}; return s }(), "version": 1}, 400)
|
||||
|
||||
// Run A: it fires (350 < 400) and calls B, which also fires.
|
||||
out := c.request("POST", "/api/agent/tasks/"+aid+"/run", map[string]any{}, 200)
|
||||
if out["outcome"] != "fired" {
|
||||
t.Fatalf("caller outcome: %v", out)
|
||||
}
|
||||
runs := c.getJSON("/api/agent/runs?taskId="+aid, 200)
|
||||
if len(runs) == 0 || !strings.Contains(runs[0]["detail"].(string), "called 1") {
|
||||
t.Fatalf("caller run should note the call: %v", runs)
|
||||
}
|
||||
bRuns := c.getJSON("/api/agent/runs?taskId="+bid, 200)
|
||||
if len(bRuns) == 0 || bRuns[0]["outcome"] != "fired" {
|
||||
t.Fatalf("callee should have fired: %v", bRuns)
|
||||
}
|
||||
|
||||
// calledOnly tasks skip the schedule: a fresh calledOnly task E is never
|
||||
// evaluated by RunOnce, while a normal task D is.
|
||||
eSpec := watchSpec(watchURL, 400, bookmark)
|
||||
eSpec["calledOnly"] = true
|
||||
eTask := c.request("POST", "/api/agent/tasks", map[string]any{"name": "Called only", "spec": eSpec}, 201)
|
||||
eid := eTask["id"].(string)
|
||||
normal := c.request("POST", "/api/agent/tasks", map[string]any{"name": "Normal", "spec": watchSpec(watchURL, 400, bookmark)}, 201)
|
||||
nid := normal["id"].(string)
|
||||
if e := agent.RunOnce(context.Background(), d); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var eChecked, nChecked bool
|
||||
_ = d.QueryRowContext(context.Background(), `SELECT "lastCheckedAt" IS NOT NULL FROM "AgentTask" WHERE id=$1`, eid).Scan(&eChecked)
|
||||
_ = d.QueryRowContext(context.Background(), `SELECT "lastCheckedAt" IS NOT NULL FROM "AgentTask" WHERE id=$1`, nid).Scan(&nChecked)
|
||||
if eChecked {
|
||||
t.Fatal("calledOnly task must not be scheduled")
|
||||
}
|
||||
if !nChecked {
|
||||
t.Fatal("normal task should have been evaluated")
|
||||
}
|
||||
}
|
||||
|
||||
// The runtime visited-set must stop a cycle even if one is written directly
|
||||
// to the DB (bypassing the handler's write-time check) — defense in depth.
|
||||
func TestAgentRuntimeCycleGuard(t *testing.T) {
|
||||
c, d, watchURL := phase2Setup(t)
|
||||
owner := meID(c)
|
||||
mk := func(id, callee string) {
|
||||
spec := `{"condition":{"type":"url_watch","url":"` + watchURL + `","question":"price","op":"lt","threshold":400},"action":{"type":"bookmark","url":"https://example.test/x","title":"X"},"pollMinutes":60,"calls":["` + callee + `"]}`
|
||||
if _, e := d.ExecContext(context.Background(),
|
||||
`INSERT INTO "AgentTask" (id,"ownerId",name,spec) VALUES ($1,$2,$3,$4)`, id, owner, id, spec); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
mk("cyc-a", "cyc-b")
|
||||
mk("cyc-b", "cyc-a")
|
||||
var raw string
|
||||
_ = d.QueryRowContext(context.Background(), `SELECT spec::text FROM "AgentTask" WHERE id='cyc-a'`).Scan(&raw)
|
||||
var sp agent.Spec
|
||||
_ = json.Unmarshal([]byte(raw), &sp)
|
||||
tk := agent.Task{ID: "cyc-a", OwnerID: owner, Name: "A", Spec: sp, Status: "active", Enabled: true}
|
||||
// Must terminate (no infinite recursion) and fire.
|
||||
if out := agent.RunTask(context.Background(), d, tk); out != "fired" {
|
||||
t.Fatalf("cycle root outcome: %s", out)
|
||||
}
|
||||
var n int
|
||||
_ = d.QueryRowContext(context.Background(), `SELECT count(*) FROM "AgentRun" WHERE "ownerId"=$1`, owner).Scan(&n)
|
||||
if n != 2 {
|
||||
t.Fatalf("expected exactly 2 runs (A and B, cycle stopped), got %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentDryRunAndRefinements(t *testing.T) {
|
||||
c, _, watchURL := phase2Setup(t)
|
||||
bookmark := map[string]any{"type": "bookmark", "url": "https://example.test/deal", "title": "Deal"}
|
||||
|
||||
// Dry run: matched true (350 < 400), no run recorded.
|
||||
dr := c.request("POST", "/api/agent/dry-run", map[string]any{"spec": watchSpec(watchURL, 400, bookmark)}, 200)
|
||||
if dr["matched"] != true {
|
||||
t.Fatalf("dry run should match: %v", dr)
|
||||
}
|
||||
drFalse := c.request("POST", "/api/agent/dry-run", map[string]any{"spec": watchSpec(watchURL, 100, bookmark)}, 200)
|
||||
if drFalse["matched"] != false {
|
||||
t.Fatalf("dry run should not match: %v", drFalse)
|
||||
}
|
||||
c.request("POST", "/api/agent/dry-run", map[string]any{"spec": map[string]any{"condition": map[string]any{"type": "bogus"}}}, 400)
|
||||
if n := len(c.getJSON("/api/agent/runs", 200)); n != 0 {
|
||||
t.Fatalf("dry run must not record runs: %d", n)
|
||||
}
|
||||
|
||||
// Refinements stored + projected + capped.
|
||||
task := c.request("POST", "/api/agent/tasks", map[string]any{
|
||||
"name": "Refined", "spec": watchSpec(watchURL, 400, bookmark),
|
||||
"prompt": "watch the price", "refinements": []string{"nonstop only", "include bags"},
|
||||
}, 201)
|
||||
tid := task["id"].(string)
|
||||
if refs := task["refinements"].([]any); len(refs) != 2 {
|
||||
t.Fatalf("refinements: %v", task["refinements"])
|
||||
}
|
||||
c.request("PATCH", "/api/agent/tasks/"+tid, map[string]any{"refinements": []string{"nonstop only"}, "version": 1}, 200)
|
||||
big := make([]string, 21)
|
||||
for i := range big {
|
||||
big[i] = "x"
|
||||
}
|
||||
c.request("PATCH", "/api/agent/tasks/"+tid, map[string]any{"refinements": big, "version": 2}, 400)
|
||||
}
|
||||
@@ -139,6 +139,7 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
||||
// 4.7c Agent automations ("hey superbrain"): compile NL into a validated
|
||||
// proposal (never writes), then owner-confirmed task CRUD + runs.
|
||||
mux.HandleFunc("POST /api/agent/compile", authed(handlers.CompileLimiter(handlers.HandleAgentCompile)))
|
||||
mux.HandleFunc("POST /api/agent/dry-run", authed(handlers.DryRunLimiter(handlers.HandleAgentDryRun)))
|
||||
mux.HandleFunc("GET /api/agent/tasks", authed(handlers.HandleAgentTasksList))
|
||||
mux.HandleFunc("POST /api/agent/tasks", authed(handlers.HandleAgentTasksCreate))
|
||||
mux.HandleFunc("PATCH /api/agent/tasks/{id}", authed(handlers.HandleAgentTasksUpdate))
|
||||
|
||||
Reference in New Issue
Block a user