release gate / check (push) Failing after 6m37s
The first real-agent slice (PLAN_PRICING_TIERS step 5, partial): describe
an automation in plain language — 'when the round trip on <url> drops
below $400, email david@…' — and Superbrain compiles it into a task the
user reviews and confirms before anything is stored.
Trust model (the point of the whole design): the LLM only ever PROPOSES.
Compile output and hand-built specs pass the same server-side
agent.ValidateSpec on every write AND on every engine load (a spec that
stops validating is paused, never executed). Actions are a closed set —
notify an owned channel, email one recipient, save one bookmark — with no
destructive or cross-user capability. Fetched page content is untrusted:
delimited in the extraction prompt, schema-checked reply ({found,value,
text,summary}), and no action can be chosen or retargeted by page text.
Multi-step requests (flights AND hotels bundled) are explicitly refused by
the compiler until chaining exists.
internal/ai: OpenAI-compatible gateway (OpenRouter default via AI_API_KEY/
AI_MODEL/AI_BASE_URL; any compatible endpoint works — house Core gateway or
Ollama later). Netguard-dialed, outbound-budgeted, balanced-brace JSON
extraction, provider bodies never echoed wholesale (they can reflect keys).
internal/agent: url_watch (scheduled fetch + one extracted fact + numeric/
text comparison) and signal (new mailbox signals, keyword filter)
conditions; poll floor 15min, once-semantics, per-task email cap 5,
per-owner daily email cap 20, global advisory tick lease, bounded run
history (pruned tail + age horizon). Engine loop joins signals/notify in
main's shutdown contract.
Schema: AgentTask + AgentRun (migration 014, converge-verified).
Entitlements: AITasks cap per plan (free 2 / standard 10 / premium 50 /
core+selfhosted unlimited) + ai_tasks override key — stored-task count is
plan data, never TIER checks.
API: /api/agent/compile (rate-limited, 422 surfaces the model's refusal,
503 when AI unconfigured), task CRUD with the version contract, manual
/run, bounded /runs history. Web: Settings -> Automations with the
composer, human-readable proposal + raw-spec review, channel picker for
notify actions, task list with Run now, and the runs strip (SafeTime for
hydration-safe timestamps).
Tests: loopback fake OpenAI-compatible server + watch target + the SMTP
fake — compile success/refusal/invalid-spec, create-time validation
(javascript: URLs rejected), version contract, url_watch fire with
once-completion, signal fire + no-refire without new signals, plan cap via
ai_tasks override, 503 without a key. Full suite green (-race); converge
green; web lint/SSR-eslint/build clean.
Docs: API.md agent section, RUNNING.md, .env.example (key stays in .env
only), compose passthrough.
99 lines
2.9 KiB
Go
99 lines
2.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"github.com/andrew/superbrain/internal/agent"
|
|
"github.com/andrew/superbrain/internal/config"
|
|
"github.com/andrew/superbrain/internal/db"
|
|
"github.com/andrew/superbrain/internal/http"
|
|
"github.com/andrew/superbrain/internal/notify"
|
|
"github.com/andrew/superbrain/internal/scripts"
|
|
"github.com/andrew/superbrain/internal/signals"
|
|
"log"
|
|
stdhttp "net/http"
|
|
"os"
|
|
"os/signal"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
if len(os.Args) > 1 && os.Args[1] == "--healthcheck" {
|
|
client := stdhttp.Client{Timeout: 3 * time.Second}
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
res, err := client.Get("http://127.0.0.1:" + port + "/readyz")
|
|
if err != nil {
|
|
os.Exit(1)
|
|
}
|
|
res.Body.Close()
|
|
if res.StatusCode != 200 {
|
|
os.Exit(1)
|
|
}
|
|
return
|
|
}
|
|
cfg := config.Load()
|
|
if err := cfg.Validate(); err != nil {
|
|
log.Fatalf("config: %v", err)
|
|
}
|
|
d, err := db.New(cfg)
|
|
if err != nil {
|
|
log.Fatalf("db: %v", err)
|
|
}
|
|
defer d.Close()
|
|
// Tenancy phase 1: make sure the implicit tenant exists with the
|
|
// tier-derived plan and adopt any tenantless users (self-heal twin of
|
|
// migration 012). Best-effort: user creation re-ensures per transaction,
|
|
// so a failure here must not keep the API down.
|
|
if err := db.NewTenantRepo(d).Bootstrap(context.Background()); err != nil {
|
|
log.Printf("tenancy bootstrap: %v", err)
|
|
}
|
|
if len(os.Args) > 1 && os.Args[1] == "--seed" {
|
|
if err := scripts.Seed(context.Background(), d); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
return
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
// Shutdown order is owned by main (review OPS-01): drain in-flight HTTP
|
|
// requests first, then await the background loops, and only afterwards let
|
|
// the deferred db close run. Previously Shutdown raced ListenAndServe's
|
|
// return and the process exited mid-drain.
|
|
workersDone := make(chan struct{})
|
|
go func() {
|
|
defer close(workersDone)
|
|
var wg sync.WaitGroup
|
|
wg.Add(3)
|
|
go func() { defer wg.Done(); signals.RunLoop(ctx, d) }()
|
|
// Notification engine (DESIGN_NOTIFICATIONS.md): scans rules and
|
|
// delivers through channels; shares the shutdown contract with
|
|
// signals — drain HTTP first, then the loops, then close the db.
|
|
go func() { defer wg.Done(); notify.RunLoop(ctx, d) }()
|
|
// Agent automations ("hey superbrain"): evaluates compiled tasks on
|
|
// their own poll schedules under a global advisory lease.
|
|
go func() { defer wg.Done(); agent.RunLoop(ctx, d) }()
|
|
wg.Wait()
|
|
}()
|
|
srv := http.NewServer(cfg, d)
|
|
go func() {
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, stdhttp.ErrServerClosed) {
|
|
log.Fatalf("server failed: %v", err)
|
|
}
|
|
}()
|
|
log.Printf("superbrain API listening on %s", srv.Addr)
|
|
<-ctx.Done()
|
|
stop()
|
|
shutdown, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdown); err != nil {
|
|
log.Printf("shutdown: %v", err)
|
|
}
|
|
<-workersDone
|
|
}
|