Files
Andrew S Erwin 2037a04817
release gate / check (push) Failing after 6m37s
Add agent automations: 'hey superbrain' NL-compiled watch-and-act tasks
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.
2026-10-27 22:54:25 -05:00

39 lines
1.7 KiB
SQL

-- 014_agent.sql — "hey superbrain" agent automations (internal/agent).
--
-- Additive and idempotent; schema.sql carries identical structures, so this
-- is a structural no-op on a fresh database (db-converge proves both paths
-- land the same). No existing table gains a constraint here, so the
-- converge pass-2 CASCADE-drop simulation has nothing external to repair.
--
-- Invariants encoded in the DDL:
-- * AgentTask.spec is validated by code on every write and every engine
-- load (internal/agent.ValidateSpec); the engine executes nothing else.
-- * AgentRun is a bounded audit trail (the engine prunes to a per-task
-- tail and an age horizon).
CREATE TABLE IF NOT EXISTS "AgentTask" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
spec jsonb NOT NULL,
enabled boolean NOT NULL DEFAULT true,
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','done','paused')),
"lastCheckedAt" timestamptz,
"lastFiredAt" timestamptz,
"fireCount" integer NOT NULL DEFAULT 0,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS "AgentTask_ownerId_idx" ON "AgentTask"("ownerId");
CREATE TABLE IF NOT EXISTS "AgentRun" (
id text PRIMARY KEY,
"taskId" text NOT NULL REFERENCES "AgentTask"(id) ON DELETE CASCADE,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
outcome text NOT NULL CHECK (outcome IN ('checked','fired','failed','skipped')),
detail text,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS "AgentRun_taskId_createdAt_idx" ON "AgentRun"("taskId", "createdAt" DESC);