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:
+110
-31
@@ -118,6 +118,7 @@ type Task struct {
|
||||
Name string
|
||||
Spec Spec
|
||||
Status string
|
||||
Enabled bool
|
||||
FireCount int
|
||||
LastChecked sql.NullTime
|
||||
CreatedAt time.Time
|
||||
@@ -125,9 +126,10 @@ type Task struct {
|
||||
|
||||
func dueTasks(ctx context.Context, d *db.DB) ([]Task, error) {
|
||||
rows, err := d.QueryContext(ctx, `
|
||||
SELECT id, "ownerId", name, spec::text, status, "fireCount", "lastCheckedAt", "createdAt"
|
||||
SELECT id, "ownerId", name, spec::text, status, enabled, "fireCount", "lastCheckedAt", "createdAt"
|
||||
FROM "AgentTask"
|
||||
WHERE enabled AND status='active'
|
||||
AND COALESCE((spec->>'calledOnly')::boolean, false) = false
|
||||
AND ("lastCheckedAt" IS NULL
|
||||
OR "lastCheckedAt" < now() - make_interval(mins => GREATEST((spec->>'pollMinutes')::int, 15)))
|
||||
ORDER BY "lastCheckedAt" NULLS FIRST
|
||||
@@ -138,15 +140,10 @@ func dueTasks(ctx context.Context, d *db.DB) ([]Task, error) {
|
||||
defer rows.Close()
|
||||
var out []Task
|
||||
for rows.Next() {
|
||||
var t Task
|
||||
var raw string
|
||||
if err := rows.Scan(&t.ID, &t.OwnerID, &t.Name, &raw, &t.Status, &t.FireCount, &t.LastChecked, &t.CreatedAt); err != nil {
|
||||
t, err := scanTask(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &t.Spec); err != nil {
|
||||
log.Printf("agent: task %s has an unreadable spec: %v", t.ID, err)
|
||||
continue
|
||||
}
|
||||
// Re-validate on load: a spec that no longer passes (e.g. after a
|
||||
// tightening release) is paused, never executed.
|
||||
if err := ValidateSpec(&t.Spec); err != nil {
|
||||
@@ -159,11 +156,73 @@ func dueTasks(ctx context.Context, d *db.DB) ([]Task, error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// rowScanner is the subset of *sql.Rows / *sql.Row used by scanTask.
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanTask(r rowScanner) (Task, error) {
|
||||
var t Task
|
||||
var raw string
|
||||
if err := r.Scan(&t.ID, &t.OwnerID, &t.Name, &raw, &t.Status, &t.Enabled, &t.FireCount, &t.LastChecked, &t.CreatedAt); err != nil {
|
||||
return t, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &t.Spec); err != nil {
|
||||
return t, fmt.Errorf("unreadable spec: %w", err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// loadTask fetches one owned task for chaining (re-validated). The caller
|
||||
// checks Enabled/Status before running it.
|
||||
func loadTask(ctx context.Context, d *db.DB, id, owner string) (Task, error) {
|
||||
row := d.QueryRowContext(ctx, `
|
||||
SELECT id, "ownerId", name, spec::text, status, enabled, "fireCount", "lastCheckedAt", "createdAt"
|
||||
FROM "AgentTask" WHERE id=$1 AND "ownerId"=$2`, id, owner)
|
||||
t, err := scanTask(row)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
if err := ValidateSpec(&t.Spec); err != nil {
|
||||
return t, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// RunTask evaluates one task once and records the outcome. Exported for the
|
||||
// manual "Run now" endpoint and tests. The returned string is the run
|
||||
// outcome (checked|fired|failed|skipped).
|
||||
// outcome (checked|fired|failed|skipped). When the task fires and lists
|
||||
// calls, it runs them in order (each callee evaluates its OWN condition),
|
||||
// bounded by a runtime visited-set and depth cap.
|
||||
func RunTask(ctx context.Context, d *db.DB, t Task) string {
|
||||
return runChain(ctx, d, t, 0, map[string]bool{})
|
||||
}
|
||||
|
||||
func runChain(ctx context.Context, d *db.DB, t Task, depth int, visited map[string]bool) string {
|
||||
if visited[t.ID] {
|
||||
return "skipped" // cycle guard (write-time check is the primary gate)
|
||||
}
|
||||
visited[t.ID] = true
|
||||
if depth > MaxChainDepth {
|
||||
recordRun(ctx, d, t, "skipped", "chain depth cap reached")
|
||||
return "skipped"
|
||||
}
|
||||
outcome, detail := evaluate(ctx, d, t)
|
||||
if outcome == "fired" && len(t.Spec.Calls) > 0 {
|
||||
called := 0
|
||||
for _, cid := range t.Spec.Calls {
|
||||
callee, err := loadTask(ctx, d, cid, t.OwnerID)
|
||||
if err != nil || !callee.Enabled || callee.Status != "active" {
|
||||
continue // missing, foreign, paused or invalid callee: skip quietly
|
||||
}
|
||||
if runChain(ctx, d, callee, depth+1, visited) == "fired" {
|
||||
called++
|
||||
}
|
||||
}
|
||||
if called > 0 {
|
||||
detail = fmt.Sprintf("%s · called %d", detail, called)
|
||||
}
|
||||
}
|
||||
recordRun(ctx, d, t, outcome, detail)
|
||||
if _, err := d.ExecContext(ctx,
|
||||
`UPDATE "AgentTask" SET "lastCheckedAt"=now(),"updatedAt"=now() WHERE id=$1`, t.ID); err != nil {
|
||||
@@ -172,46 +231,66 @@ func RunTask(ctx context.Context, d *db.DB, t Task) string {
|
||||
return outcome
|
||||
}
|
||||
|
||||
func evaluate(ctx context.Context, d *db.DB, t Task) (outcome, detail string) {
|
||||
switch t.Spec.Condition.Type {
|
||||
case "url_watch":
|
||||
return evalURLWatch(ctx, d, t)
|
||||
case "signal":
|
||||
return evalSignal(ctx, d, t)
|
||||
}
|
||||
return "failed", "unknown condition type"
|
||||
// DryRun evaluates the condition WITHOUT firing actions, calling callees,
|
||||
// recording a run, or touching bookkeeping — the "Try it" preview. It
|
||||
// returns whether the condition would be true and a human-readable reason.
|
||||
func DryRun(ctx context.Context, d *db.DB, t Task) (bool, string) {
|
||||
matched, _, detail := check(ctx, d, t)
|
||||
return matched, detail
|
||||
}
|
||||
|
||||
func evalURLWatch(ctx context.Context, d *db.DB, t Task) (string, string) {
|
||||
func evaluate(ctx context.Context, d *db.DB, t Task) (outcome, detail string) {
|
||||
matched, outcome, detail := check(ctx, d, t)
|
||||
if matched {
|
||||
return fire(ctx, d, t, detail)
|
||||
}
|
||||
return outcome, detail
|
||||
}
|
||||
|
||||
// check evaluates the condition only. When matched, outcome is "fired" and
|
||||
// detail is the summary fire() should use; otherwise outcome/detail describe
|
||||
// the checked/failed/skipped result. Splitting this from fire() is what makes
|
||||
// DryRun possible without duplicating the fetch/extract logic.
|
||||
func check(ctx context.Context, d *db.DB, t Task) (matched bool, outcome, detail string) {
|
||||
switch t.Spec.Condition.Type {
|
||||
case "url_watch":
|
||||
return checkURLWatch(ctx, d, t)
|
||||
case "signal":
|
||||
return checkSignal(ctx, d, t)
|
||||
}
|
||||
return false, "failed", "unknown condition type"
|
||||
}
|
||||
|
||||
func checkURLWatch(ctx context.Context, d *db.DB, t Task) (bool, string, string) {
|
||||
resolved, err := ai.ResolveForUser(ctx, d, t.OwnerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ai.ErrNoAI) {
|
||||
return "skipped", "AI is not configured (add your own key in Settings → AI)"
|
||||
return false, "skipped", "AI is not configured (add your own key in Settings → AI)"
|
||||
}
|
||||
return "failed", "ai config: " + err.Error()
|
||||
return false, "failed", "ai config: " + err.Error()
|
||||
}
|
||||
release, _, ok := outbound.Reserve("agent-fetch:"+t.OwnerID, 10, time.Minute)
|
||||
if !ok {
|
||||
return "skipped", "fetch budget exhausted"
|
||||
return false, "skipped", "fetch budget exhausted"
|
||||
}
|
||||
defer release()
|
||||
|
||||
text, err := fetchText(ctx, t.Spec.Condition.URL)
|
||||
if err != nil {
|
||||
return "failed", "fetch: " + err.Error()
|
||||
return false, "failed", "fetch: " + err.Error()
|
||||
}
|
||||
fact, err := extractFact(ctx, resolved, t.Spec.Condition.Question, text)
|
||||
f, err := extractFact(ctx, resolved, t.Spec.Condition.Question, text)
|
||||
if err != nil {
|
||||
return "failed", "extract: " + err.Error()
|
||||
return false, "failed", "extract: " + err.Error()
|
||||
}
|
||||
matched, why := conditionMet(t.Spec.Condition, fact)
|
||||
matched, why := conditionMet(t.Spec.Condition, f)
|
||||
if !matched {
|
||||
return "checked", why
|
||||
return false, "checked", why
|
||||
}
|
||||
return fire(ctx, d, t, fmt.Sprintf("%s — %s", t.Name, fact.Summary))
|
||||
return true, "fired", fmt.Sprintf("%s — %s", t.Name, f.Summary)
|
||||
}
|
||||
|
||||
func evalSignal(ctx context.Context, d *db.DB, t Task) (string, string) {
|
||||
func checkSignal(ctx context.Context, d *db.DB, t Task) (bool, string, string) {
|
||||
since := t.CreatedAt
|
||||
if t.LastChecked.Valid {
|
||||
since = t.LastChecked.Time
|
||||
@@ -227,12 +306,12 @@ func evalSignal(ctx context.Context, d *db.DB, t Task) (string, string) {
|
||||
}
|
||||
q += ` LIMIT 10) s`
|
||||
if err := d.QueryRowContext(ctx, q, args...).Scan(&titles); err != nil {
|
||||
return "failed", "signal scan: " + err.Error()
|
||||
return false, "failed", "signal scan: " + err.Error()
|
||||
}
|
||||
if titles == "" {
|
||||
return "checked", "no new matching signals"
|
||||
return false, "checked", "no new matching signals"
|
||||
}
|
||||
return fire(ctx, d, t, "new signal(s): "+titles)
|
||||
return true, "fired", "new signal(s): " + titles
|
||||
}
|
||||
|
||||
// fact is the ONLY shape the extractor may return; anything else is a
|
||||
|
||||
@@ -31,8 +31,22 @@ type Spec struct {
|
||||
Action Action `json:"action"`
|
||||
PollMinutes int `json:"pollMinutes"`
|
||||
Once bool `json:"once"`
|
||||
// Phase 2 chaining: when this task's condition is true and its action
|
||||
// fires, it calls these tasks (by id, same owner) in order. Each callee
|
||||
// evaluates its OWN condition. CalledOnly tasks skip the schedule and
|
||||
// run only when called (or via manual Run now). Cycles are rejected at
|
||||
// write time AND guarded at runtime (visited set + depth cap).
|
||||
Calls []string `json:"calls,omitempty"`
|
||||
CalledOnly bool `json:"calledOnly,omitempty"`
|
||||
}
|
||||
|
||||
// MaxChainDepth bounds how deep a call chain may recurse at runtime; the
|
||||
// write-time cycle check is the primary gate, this is defense in depth.
|
||||
const MaxChainDepth = 5
|
||||
|
||||
// MaxCalls bounds the callees one task may list.
|
||||
const MaxCalls = 10
|
||||
|
||||
// Condition types:
|
||||
//
|
||||
// url_watch — periodically fetch a public URL and answer a question about
|
||||
@@ -137,6 +151,25 @@ func ValidateSpec(s *Spec) error {
|
||||
if s.PollMinutes < 15 || s.PollMinutes > 7*24*60 {
|
||||
return errors.New("pollMinutes must be between 15 and 10080")
|
||||
}
|
||||
|
||||
// Chaining local rules: non-empty ids, no self-call, no duplicates,
|
||||
// bounded count. Cross-task ownership and cycle checks live in the
|
||||
// handler (they need the owner's whole graph); the engine adds a
|
||||
// runtime visited-set + depth cap as defense in depth.
|
||||
if len(s.Calls) > MaxCalls {
|
||||
return fmt.Errorf("calls may list at most %d automations", MaxCalls)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range s.Calls {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
return errors.New("calls entries must be non-empty task ids")
|
||||
}
|
||||
if seen[id] {
|
||||
return errors.New("calls contains a duplicate automation")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user