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.
272 lines
9.4 KiB
Go
272 lines
9.4 KiB
Go
// Package entitlements is the plan catalog and limit-resolution logic for
|
|
// the tenancy model (DESIGN_TENANCY_ENTITLEMENTS.md, phase 1).
|
|
//
|
|
// Governing rule: plans are DATA, never code forks. The catalog lives in
|
|
// code because plans ship with the binary; per-tenant overrides
|
|
// (TenantEntitlement rows) adjust individual limits for grandfathering and
|
|
// exceptions. No feature may check TIER directly for gating — tiers decide
|
|
// the auth shape of a deployment, plans decide what a tenant may do.
|
|
//
|
|
// This package is pure logic (no database access) so the catalog and merge
|
|
// rules stay unit-testable; storage lives in internal/db (TenantRepo).
|
|
package entitlements
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Plan identifies a pricing plan (mirrors the Tenant.plan CHECK).
|
|
type Plan string
|
|
|
|
const (
|
|
PlanFree Plan = "free" // hosted multi tier, pre-billing default
|
|
PlanStandard Plan = "standard" // paid $8/user/mo
|
|
PlanPremium Plan = "premium" // paid $15/user/mo
|
|
PlanCore Plan = "core" // federated core install (included)
|
|
PlanSelfHosted Plan = "selfhosted" // open-source self-hosted
|
|
)
|
|
|
|
// Unlimited is the sentinel for count/byte limits without a cap.
|
|
const Unlimited int64 = -1
|
|
|
|
// Limits is the resolved entitlement set for one tenant. Feature areas that
|
|
// do not exist yet (brain links, notification channels, AI) are carried from
|
|
// day one so gate points can be added without catalog churn.
|
|
type Limits struct {
|
|
// StorageBytes caps tenant-attributable storage. NOTE: nothing meters
|
|
// storage yet (no attachments feature); the limit is declarative until
|
|
// the metering workstream lands.
|
|
StorageBytes int64
|
|
// BrainLinks caps outbound+inbound brain-to-brain links (-1 unlimited).
|
|
BrainLinks int64
|
|
// Seats caps tenant members (-1 unlimited).
|
|
Seats int64
|
|
// NotificationChannels is the allowlist of channel kinds
|
|
// (email, slack, matrix, telegram, talk, signal).
|
|
NotificationChannels []string
|
|
// Connectors is the allowlist of connector classes
|
|
// (url, file, google, office365, nextcloud, webdav, caldav, carddav,
|
|
// gmail, oidc, mcp-core).
|
|
Connectors []string
|
|
// AIMode: byo (bring your own key) | credits (built-in, metered) |
|
|
// core (house Core AI settings).
|
|
AIMode string
|
|
// AITasks caps concurrently stored agent automations per tenant
|
|
// (-1 unlimited). Evaluation rate limits live in the engine; this is
|
|
// the storage-side plan differentiator.
|
|
AITasks int64
|
|
}
|
|
|
|
// catalog is the shipped plan matrix (PLAN_PRICING_TIERS.md). Editing a
|
|
// value here changes every tenant on that plan — per-tenant deviations go
|
|
// through TenantEntitlement overrides, never by inventing new plans.
|
|
var catalog = map[Plan]Limits{
|
|
PlanFree: {
|
|
StorageBytes: 5 * 1024 * 1024 * 1024,
|
|
BrainLinks: 2,
|
|
Seats: Unlimited,
|
|
NotificationChannels: []string{"email"},
|
|
Connectors: []string{"url", "file", "carddav"},
|
|
AIMode: "byo",
|
|
AITasks: 2,
|
|
},
|
|
PlanStandard: {
|
|
StorageBytes: 25 * 1024 * 1024 * 1024,
|
|
BrainLinks: 10,
|
|
Seats: Unlimited,
|
|
NotificationChannels: []string{"email", "slack", "matrix"},
|
|
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail"},
|
|
AIMode: "byo",
|
|
AITasks: 10,
|
|
},
|
|
PlanPremium: {
|
|
StorageBytes: 100 * 1024 * 1024 * 1024,
|
|
BrainLinks: Unlimited,
|
|
Seats: Unlimited,
|
|
NotificationChannels: []string{"email", "slack", "matrix", "telegram"},
|
|
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail", "oidc"},
|
|
AIMode: "credits",
|
|
AITasks: 50,
|
|
},
|
|
PlanCore: {
|
|
StorageBytes: Unlimited, // storage on Core
|
|
BrainLinks: Unlimited,
|
|
Seats: Unlimited,
|
|
NotificationChannels: []string{"email", "slack", "matrix", "telegram", "talk"},
|
|
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail", "oidc", "mcp-core"},
|
|
AIMode: "core",
|
|
AITasks: Unlimited,
|
|
},
|
|
PlanSelfHosted: {
|
|
StorageBytes: Unlimited, // limits are the operator's hardware
|
|
BrainLinks: Unlimited,
|
|
Seats: Unlimited,
|
|
NotificationChannels: []string{"email", "slack", "matrix", "telegram"},
|
|
Connectors: []string{"url", "file", "carddav", "google", "office365", "nextcloud", "webdav", "caldav", "gmail", "oidc"},
|
|
AIMode: "byo",
|
|
AITasks: Unlimited,
|
|
},
|
|
}
|
|
|
|
// ValidPlan reports whether p is in the shipped catalog (the DB CHECK and
|
|
// API validation share this list).
|
|
func ValidPlan(p string) bool {
|
|
_, ok := catalog[Plan(p)]
|
|
return ok
|
|
}
|
|
|
|
// For returns the catalog limits of a plan. Unknown plans resolve to the
|
|
// free tier — fail closed, never open.
|
|
func For(plan Plan) Limits {
|
|
l, ok := catalog[plan]
|
|
if !ok {
|
|
return catalog[PlanFree]
|
|
}
|
|
// Copy slices so callers cannot mutate the catalog.
|
|
l.NotificationChannels = append([]string(nil), l.NotificationChannels...)
|
|
l.Connectors = append([]string(nil), l.Connectors...)
|
|
return l
|
|
}
|
|
|
|
// DefaultPlanForTier maps the deployment tier (config.Tier) to the plan the
|
|
// implicit default tenant is created with: core installs run the 'core'
|
|
// plan, hosted multi starts on 'free' (billing upgrades tenants later),
|
|
// and everything else is 'selfhosted'.
|
|
func DefaultPlanForTier(tier string) Plan {
|
|
switch tier {
|
|
case "core":
|
|
return PlanCore
|
|
case "multi":
|
|
return PlanFree
|
|
default:
|
|
return PlanSelfHosted
|
|
}
|
|
}
|
|
|
|
// AutoPlan reports whether p is a deployment-derived plan the startup
|
|
// reconciliation may adjust when TIER changes. Sold plans ('standard',
|
|
// 'premium') and 'free' (which billing owns once introduced) are NEVER
|
|
// touched automatically.
|
|
func AutoPlan(p Plan) bool { return p == PlanCore || p == PlanSelfHosted }
|
|
|
|
// Override keys (TenantEntitlement.key). Kept as constants so typos fail
|
|
// at compile time on the writing side; unknown keys in the database are
|
|
// ignored by ApplyOverrides (forward compatibility).
|
|
const (
|
|
KeyStorageBytes = "storage_bytes"
|
|
KeyBrainLinks = "brain_links"
|
|
KeySeats = "seats"
|
|
KeyNotificationChannels = "notification_channels"
|
|
KeyConnectors = "connectors"
|
|
KeyAIMode = "ai_mode"
|
|
KeyAITasks = "ai_tasks"
|
|
)
|
|
|
|
// ValidOverrideKey reports whether k is a known TenantEntitlement key.
|
|
// Writing an unknown key is a programmer error and refused by the db layer;
|
|
// READING ignores unknown keys so rows from a newer version stay harmless.
|
|
func ValidOverrideKey(k string) bool {
|
|
switch k {
|
|
case KeyStorageBytes, KeyBrainLinks, KeySeats, KeyNotificationChannels, KeyConnectors, KeyAIMode, KeyAITasks:
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ApplyOverrides merges per-tenant override rows onto catalog limits.
|
|
// Numeric keys parse as int64 (Unlimited = -1); list keys are
|
|
// comma-separated; unparsable values are ignored (the catalog value stays)
|
|
// so a bad row can never widen or crash entitlement resolution.
|
|
func ApplyOverrides(l Limits, overrides map[string]string) Limits {
|
|
for k, v := range overrides {
|
|
v = strings.TrimSpace(v)
|
|
switch k {
|
|
case KeyStorageBytes:
|
|
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
|
|
l.StorageBytes = n
|
|
}
|
|
case KeyBrainLinks:
|
|
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
|
|
l.BrainLinks = n
|
|
}
|
|
case KeySeats:
|
|
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
|
|
l.Seats = n
|
|
}
|
|
case KeyAITasks:
|
|
if n, err := strconv.ParseInt(v, 10, 64); err == nil && (n >= 0 || n == Unlimited) {
|
|
l.AITasks = n
|
|
}
|
|
case KeyNotificationChannels:
|
|
l.NotificationChannels = splitList(v)
|
|
case KeyConnectors:
|
|
l.Connectors = splitList(v)
|
|
case KeyAIMode:
|
|
switch v {
|
|
case "byo", "credits", "core":
|
|
l.AIMode = v
|
|
}
|
|
}
|
|
}
|
|
return l
|
|
}
|
|
|
|
func splitList(v string) []string {
|
|
if v == "" {
|
|
return nil
|
|
}
|
|
parts := strings.Split(v, ",")
|
|
out := make([]string, 0, len(parts))
|
|
for _, p := range parts {
|
|
if p = strings.ToLower(strings.TrimSpace(p)); p != "" {
|
|
out = append(out, p)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// AllowConnector / AllowChannel report whether a plan's allowlist contains
|
|
// the named item. Gate points call these BEFORE creating resources so the
|
|
// list of enforcement sites stays greppable.
|
|
func (l Limits) AllowConnector(name string) bool { return contains(l.Connectors, name) }
|
|
func (l Limits) AllowChannel(name string) bool { return contains(l.NotificationChannels, name) }
|
|
|
|
// WithinQuota reports whether growing a used counter by delta stays within
|
|
// limit (Unlimited always passes; negative used is treated as 0).
|
|
func WithinQuota(used, delta, limit int64) bool {
|
|
if limit == Unlimited {
|
|
return true
|
|
}
|
|
if used < 0 {
|
|
used = 0
|
|
}
|
|
return used+delta <= limit
|
|
}
|
|
|
|
func contains(list []string, s string) bool {
|
|
s = strings.ToLower(strings.TrimSpace(s))
|
|
for _, v := range list {
|
|
if v == s {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// String renders the plan for logs/APIs (never secrets — the catalog is
|
|
// public product information).
|
|
func (p Plan) String() string { return string(p) }
|
|
|
|
// Ensure catalog sanity at init: every plan resolves, slices non-nil where
|
|
// the UI would render them. A panic here is a build-time-class error.
|
|
func init() {
|
|
for p := range catalog {
|
|
l := For(p)
|
|
if l.AIMode == "" {
|
|
panic(fmt.Sprintf("entitlements: plan %s has no ai_mode", p))
|
|
}
|
|
}
|
|
}
|