341cdce0269f06dfa97c8e8ae926369c928f3257
9
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
167f74c6b4 |
Separate AI config from implementation: BYO provider, model and key per user
release gate / check (push) Failing after 6m42s
The plan matrix's 'use your own AI' rows, made real. internal/ai is now pure implementation: three provider adapters — openai-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, any house gateway), native Anthropic (/v1/messages, x-api-key) and native Gemini (generateContent; the key travels in the x-goog-api-key HEADER, never the URL, because Go's HTTP error strings include URLs and errors get logged). One netguard-dialed client, per-source outbound budgets (ai:user:<id> vs ai:server). Configuration is data: UserAiConfig (migration 015) — one row per user with provider, base URL, model and an API key encrypted at rest via internal/crypto (the IMAP-password format), masked in every response; a PUT echoing the mask or leaving the key blank keeps the stored value; version contract on updates. New endpoints: GET/PUT/DELETE /api/ai/config, POST /api/ai/test (one probe completion through the resolved config), GET /api/ai/status (plan-gated availability, no secrets). Resolution chain (ai.ResolveForUser): the user's enabled BYO config first on EVERY plan; else the server env key (AI_API_KEY/AI_MODEL/AI_BASE_URL/ AI_PROVIDER) only when the tenant's plan may spend it — new entitlements.AllowServerAI: premium (credits), core (house gateway) and selfhosted (operator IS the user); free/standard are BYO-only, exactly the matrix. No AI available => 428 with a pointer to Settings -> AI (was a global 503): the precondition is per-user now. Agent compile and url_watch extraction resolve per owner, so different users' tasks can run on different providers. Web: Settings -> AI tab (provider picker with per-provider defaults and model hints, write-only key input, Test button, effective-source badge with plan context, enable switch, remove). The Automations tab reads /api/ai/status for a proactive banner and treats 428 as 'not configured'. Preparatory refactors (behavior-preserving): agent.AutomationSchema extracted as the single spec text shared by the compiler prompt (and the upcoming chat assistant), and ai.CompleteMessages for multi-turn conversations with per-provider role mapping (assistant -> model on Gemini). Tests: all three adapters against one loopback fake (asserting each provider's auth-header shape), masked-key lifecycle incl. mask-echo preservation across a provider switch, encrypted-at-rest verification, plan gate both directions (free refuses the server key, premium/core/ selfhosted allow it), BYO precedence over the server key, validation rejects, 428 paths, and compile resolution through a BYO config. Full suite green (-race), converge green (015), web lint/SSR/build clean. Docs: API.md AI section, RUNNING.md setup rewritten around BYO-first + plan-gated server fallback, .env.example (AI_PROVIDER + the precedence story), compose passthrough, AGENTS.md invariant (config vs implementation, Gemini key-in-header rule). |
||
|
|
2037a04817 |
Add agent automations: 'hey superbrain' NL-compiled watch-and-act tasks
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.
|
||
|
|
451312c3cf |
Add notification engine phase 1: channels, rules, plan-gated delivery
release gate / check (push) Failing after 6m54s
When something happens in the brain, tell the user (PLAN_PRICING_TIERS step 3). The engine is a SCANNER, not a hook system: producers are never instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) + ON CONFLICT DO NOTHING, so rescans are free and restarts are safe. Schema (migration 013 + schema.sql, converge-verified): NotificationChannel (secrets encrypted at rest via internal/crypto, the IMAP-password format), NotificationRule (one channel per rule in phase 1, cooldown, version column), Notification (dedupe ledger + delivery state: pending/sent/failed/suppressed, attempts, backoff timestamp). internal/notify: two triggers — signal_created (fires only for signals newer than the rule, never retro-notifying history) and bookmark_due (lead-hours window, dedupe key carries the UTC due date so moving a dueDate re-notifies and same-day rescans do not). Delivery claims rows in one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app instances never double-send; exponential backoff to 5 attempts; per-rule cooldown; per-owner pending cap. Channels: email (internal/mailer, falls back to the account email), Slack webhook, Matrix room, Telegram bot — webhooks dial through netguard inside outbound.Reserve budgets. The plan gate re-checks at delivery: a downgraded tenant's rows become 'suppressed' instead of sending. Signal-app delivery deliberately absent (needs a daemon; see plan doc hard truths). API: channel/rule CRUD with the house version contract (409 on stale base), write-only secrets (masked in every response; a PATCH echoing the mask keeps the stored value), test-send endpoint with its own budget, owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT CATALOG (403 'Not available on your plan') — never on TIER, per the tenancy invariant. Web: Settings -> Notifications tab (channels with per-kind forms and Test button, rule builder, recent-delivery strip). Data loading uses the house promise-chain shape; setState only in async callbacks (SSR lint). Fixes along the way: mailer send budget raised 5->20/min (shared by resets and notifications; 5/min would throttle a hosted instance) and outbound gains ResetBudget() wired into the test harness — the global 'smtp' window made password-reset and notification tests collide when the package ran as a whole. Tests: full channel/rule/engine integration pass (masking + encryption round-trip, masked-PATCH preservation, version contract, plan gating via a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and webhook delivery via loopback fakes, backoff recording, downgrade suppression, history). Full suite green with -race; web lint/SSR-eslint/ build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md invariants, DESIGN_NOTIFICATIONS.md (local). |
||
|
|
1f38c4d56c |
Add tenancy phase 1: implicit tenants, plan entitlements, quota counters
release gate / check (push) Failing after 7m7s
Foundation for the priced plans (PLAN_PRICING_TIERS.md): every user now belongs to exactly one tenant, and single-tenant deployments (self-hosted, core) use an implicit 'tenant-default' row so no code path special-cases 'no tenant'. Plans are per-tenant DATA, never code forks — the open-source promise depends on the free version being the same binary. Schema (migration 012 + schema.sql, converge- and atomicity-verified): Tenant, TenantMember (1:1 per user in phase 1), TenantEntitlement (per-tenant overrides), QuotaUsage (maintained counters), User.tenantId. The backfill adopts every existing user into the implicit tenant (ADMIN -> owner, others -> member). The User.tenantId FK is re-added by name under a guard so converge pass 2 (CASCADE-drop + chain re-run) stays clean. internal/entitlements: the shipped plan catalog (free/standard/premium/ core/selfhosted: storage, brain links, seats, notification channels, connectors, AI mode), tier -> default-plan derivation, override merging that fails CLOSED (unknown plan resolves to free limits; malformed override rows are ignored so a bad row can never widen access), and WithinQuota boundary logic. internal/db/tenants.go: EnsureDefault reconciles the implicit tenant's plan with TIER but only ever touches auto plans (core/selfhosted) — sold plans are billing data, not deployment config. AdoptOrphans is the runtime self-heal twin of the migration backfill (restored dumps); main runs Bootstrap once at startup, best-effort. QuotaAdd moves counters under an advisory lock and refuses growth past the plan limit with ErrQuotaExceeded; counters floor at 0. Wiring: createUserTx attaches tenant + membership atomically for EVERY creation path (signup, OIDC provisioning, seed CLI); the identity projection carries tenantId, so /api/me and the bridge response expose it. models.User gains TenantID. No behavior changes for existing installs: default limits are declarative until gate points land (connectors, brain links, notifications, storage metering are later steps). API.md documents tenantId and the password- reset endpoints; AGENTS.md records the invariant that features gate on PLAN, never on TIER directly. Tests: entitlements unit tests (catalog, fail-closed resolution, override normalization, quota boundaries) and integration tests (attach-on-create across all three paths with owner/member roles, bootstrap + plan reconcile including 'sold plans never overwritten', limits resolution, quota consume/refuse/release/floor). |
||
|
|
f372936894 |
Add deployment tiers, self-service password reset, and Authelia SSO fixes
release gate / check (push) Failing after 7m28s
Product tiers (decided 2026-10-26): TIER=core|multi is the deployment knob. core (federated install, paying customers) derives AUTH_MODE=oidc with signup/bootstrap off - Authelia is the only way in and accounts are provisioned upstream (Superpanel -> LDAP -> Authelia). multi (hosted self-service) derives AUTH_MODE=password: signup, password login and SMTP-backed self-reset, with the OIDC bridge refused even when variables are set. Explicit AUTH_MODE/SIGNUP_ENABLED/ALLOW_BOOTSTRAP_SIGNUP always override the tier; invalid values fail startup instead of falling back. Go enforces every gate at the API; the web UI mirrors it (conditional credentials provider, SSO-only login page, signup/reset redirects). Authelia-only bootstrap: ProvisionExternal grants ADMIN to ADMIN_EMAILS addresses at first SSO login, and --seed accepts SEED_SUBJECT to link a pre-existing password account offline - the only path when 409 'account link required' meets a deployment where nobody can password-login to call oidc-link. Self-service password reset (multi tier): POST /api/password/forgot and /api/password/reset with hashed single-use 30-minute tokens (PasswordResetToken, migration 011 + schema.sql), enumeration-safe identical 200s, per-IP rate limits, tokenVersion bump on success (all prior sessions revoked), OIDC-only accounts excluded by design. New internal/mailer sends via netguard+outbound budget; NETGUARD_TRUSTED_HOSTS pins operator-chosen relays that resolve privately (split-horizon DNS) without the blanket INTEGRATIONS_ALLOW_PRIVATE switch. Web gains /forgot-password and /reset-password pages and a login-page link. Federated install fixes: the Authelia client now registers a claims_policy putting email in the ID token (production AccessDenied - Auth.js builds OIDC profiles exclusively from ID-token claims), config is validated before restarting the shared Authelia, uninstall removes the claims block marker-safely, and generated .env switches to TIER=core with a password-less admin seed. Tests: tier derivation/override unit tests, mode and tier integration tests (403 gates, bridge refusal, ADMIN_EMAILS promotion, offline link), reset-flow integration tests against a loopback SMTP fake, netguard trusted-host tests. Docs: RUNNING.md, web/docs/AUTHELIA.md section 7, .env.example, STRATEGY.md. |
||
|
|
4e421f6ea2 |
Address code review findings across API, web and deployment
release gate / check (push) Failing after 6m43s
High severity: - wire TRUSTED_PROXY through Compose/deploy/docs and warn at web startup - bucket public rate limits on effective client IP, add per-bookmark budget, and forward the signed browser identity from the share page - disable first-run bootstrap in server deployments and document seeding - serialize last-admin demotion in one advisory-locked transaction Medium/low: - cap and batch share recipient inserts - add a shared outbound budget for preview/CardDAV/IMAP/signal work - pin CardDAV dials to 443 and bound IMAP logout - fix rightward kanban column drags and normalize cards on column delete - classify backend outages in auth guards, add request timeouts and an error boundary, remove the dead login route, surface throttling - enforce pinned/unpinned page reorder grouping server-side - avoid preview work for stale bookmark versions; drop duplicate dialog fetch - sequence-guard collection/tag/calendar/quick-find loads - validate property config and fix MULTI_SELECT/DATE filter inputs - document index maintenance; apply same-origin check to sign-out - trim signup names, unique shared dates and kanban keys (migration 010), reset reference cache on identity changes, hide OIDC issuer, return 413 for oversized direct bodies, escape Markdown link destinations - remove dead template files and duplicate test helper Verified with go build/vet, full PostgreSQL race suite, db convergence, tsc, both ESLint configs and a Next production build. |
||
|
|
5eab58f99c |
Add trust features: history, trash, export, and collection sharing
release gate / check (push) Failing after 6m36s
Implement Notion-like upgrade phase 4: append-only page revisions with restore-as-a-new-version; recoverable bookmark/page/collection deletions whose restores never resurrect public flags or shares; owner-scoped JSON export; and explicit, revocable read-only collection sharing with owner-only mutations and no transitive third-party bookmark leaks. Add migration 009, API/docs, integration coverage, and page/collections/trash UI. |
||
|
|
9db69efe4b |
Add connected pages: hierarchy, backlinks, and live embeds
release gate / check (push) Failing after 7m7s
Implement Notion-like upgrade phase 3: owner-scoped nested pages with cycle rejection and child promotion on delete; Markdown-derived internal links and backlinks; live collection embeds resolved in the content-save transaction. Add migration 008, API/docs, integration coverage, and page/sidebar UI. |
||
|
|
b9721ff13f |
initial commit on Federted servers
release gate / check (push) Failing after 8m35s
|