db73a949310daa135257dac4180a0d61da264d4d
30
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
9dbf9fa3ea |
Library sidebar: folders, pinned-top, per-page menus, and an all-pages view
- Page.isFolder (migration 027): folders are content-less pages reusing parentId; folder delete reparents children one level up - Sidebar: Pages group becomes Library; Pinned at top; folder tree; page menu (duplicate/pin/copy link/rename/move/trash); folder menu - /pages index: filterable Library table (all/recent/pinned/untagged) with folder path + last edit (components/library-index.tsx) - Docs: API.md isFolder + folder-delete semantics |
||
|
|
c84d694a03 |
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.
|
||
|
|
060a8115ec |
Automations workspace phase 1: sidebar groups, detail view, recompile-to-edit, named runs
Promotes Automations to a top-level sidebar group (below Bookmarks) with user-defined AgentGroup folders (migration 025, FK SET NULL on delete). The /automations page becomes master-detail: overview (composer + grouped list + named global runs) and per-task detail (original prompt, group assignment, run-now/pause/delete, per-task run timeline with true/false/ error pills). Editing recompiles through /api/agent/compile and confirms the proposal before a versioned PATCH applies spec+prompt — the model never writes. Tasks store prompt+groupId; projections add runCount/ errorCount; runs carry taskName. The engine is untouched: groups/prompt are metadata, the validated spec remains the only thing it executes. Chaining, refinements and dry-run stay phase 2. Verified: full DB integration suite under -race, db-converge + migration atomicity, web lint/SSR/build, and a rewritten browser regression covering the sidebar folder, detail prompt, per-task runs, recompile-to-edit and named global runs. |
||
|
|
5b3dcfdbb7 |
MCP catalog: core-hub suggestion from MCP_HUB_URL (deployment data)
When the deployment sets MCP_HUB_URL (the Core installer now writes https://mcphub.$DOMAIN, the NEXTCLOUD_URL pattern), the MCP list appends a core-hub suggestion: the federated tool hub over SSE with the user's own mhub_ bearer token (DESIGN_MCP_HUB_AUTH.md step 3). Unset/invalid -> no suggestion; never a TIER fork. The UI renders it generically (Use prefills URL/transport/auth + token hint). Go test covers the env gate; regression fixture carries the entry. |
||
|
|
a167e376f7 |
MCP settings: suggestion catalog for GitHub, HubSpot and Make
The connections list now serves a shipped catalog of well-known hosted MCP servers (data in the binary, like the entitlements catalog — never a TIER fork). 'Use' prefills name/url/transport/authKind and shows a secretHint placeholder; the credential stays the user's to paste (write-only discipline unchanged). Verified against vendor docs: GitHub (api.githubcopilot.com/mcp/) and Make (<zone>.make.com/mcp/v2) accept Bearer tokens and are connectable today. HubSpot's remote MCP (mcp.hubspot.com) requires OAuth 2.1 + PKCE with no static-token path — the client speaks none/bearer/header only, so the entry is shown honestly labeled 'OAuth required' with a note and docs link, and NO Use button. Go test asserts the catalog; browser regression covers the prefill and the HubSpot treatment. |
||
|
|
3878dddaa7 |
WebDAV: survive rate limits on large shares
Nextcloud throttles bursty PROPFIND walks (429) and big trees exceeded the 3-minute sync budget — production's 1000+ file share failed intermittently with 'unexpected answer (429)' and 'context deadline exceeded'. propfind now retries 429/503 up to 3 times honoring Retry-After (capped 30s, ctx-bound, linear backoff without the header), the directory walk paces 100ms between PROPFINDs, and the engine sync budget grows to 6 minutes. Unit tests cover recover-after-429 and the bounded attempt count; truncation semantics are unchanged. |
||
|
|
eff81e4d8d |
Settings: remove the Contacts sync tab; the sync API remains
The single-config Nextcloud Contacts sync tab is gone — the unified Nextcloud tab is the UI path for connecting an account. POST /api/contacts/sync is untouched (Contact rows still feed contact-linking; the handler is stateless, so no persisted config orphans). Legacy ?tab=nextcloud deep links map to the unified tab on first render and clean the URL; CardDAV/help wording follows. Regression asserts the tab is gone and the legacy deep link lands on the Nextcloud form. |
||
|
|
084a1167da |
Unified Nextcloud connect: one credential connects files, calendars and contacts
POST /api/nextcloud/connect composes the three per-user DAV roots server-side, verifies the credential against each protocol in parallel (netguard-pinned, sharing the siblings' /test budgets) BEFORE storing anything, and creates one ordinary sibling connection per protocol that passes. Orchestration, not a fourth connector: every sibling plan gate, validation (incl. CardDAV https/443), cap and projection applies; partial success is a 200 with per-connector created|exists|gated|error results; repeat calls are idempotent by composed URL. GET /api/nextcloud/status serves the new Settings -> Nextcloud tab (origin hint + allowed flags + masked connections); the UI fires the existing /sync surfaces right after connect so collections materialize immediately. Contacts sync untouched; no schema change. Tests: unified Nextcloud fake (sibling fakes re-rooted to Nextcloud paths on one origin) covering happy path, idempotency, wrong-password-stores- nothing, owner scoping, partial plan gate + restore; browser regression for the full connect/sync/idempotent/Manage flow. |
||
|
|
f6158f58b5 |
Settings → Profile: editable particulars (name, bio, location, occupation, organization, website)
The Profile tab was a read-only avatar/name/email stub. It is now a real
form, modeled on the profile surfaces of GitHub/Slack/Nextcloud and scoped
to what a knowledge tool uses: display name, bio (280 chars with counter),
location, occupation, organization and website; email stays read-only
(sign-in identity). Copy explains where the name appears (shares) and
that public bookmark links never reveal identity.
Schema: migration 024_user_profile.sql + schema.sql add five nullable
text columns to User (db-converge green, fresh and upgraded paths).
models.User, userFromObject and the auth identity projection carry them,
so GET /api/me serves the stored truth (Go re-reads identity per request).
PATCH /api/me applies partial allowlisted edits: empty string clears to
NULL, rune-based caps (120/280/120/120/120), website <=2048 and http(s)
with a host; the answer is the fresh identity projection. User has no
version column (identity, not a collaborative collection), so this follows
the settings-save shape rather than the 409 contract; view-as writes stay
blocked by the middleware.
Session propagation: the auth.ts jwt callback gains an "update" trigger
that re-syncs name/email/image from Go via the same assertion the data
proxy signs (fail-quiet when Go is unreachable). The component calls
useSession().update({}) after a save — the {} argument is load-bearing:
in next-auth v5 a bare update() only re-fetches the session, it does not
fire the trigger (caught by the new browser regression). The top bar name
refreshes without a re-login.
Verified: full Go integration suite green incl. new TestProfileUpdate
(partial edits, clearing, rune caps, URL validation, auth gate);
db-converge green; web lint/SSR-lint/build 0 errors; full browser
regressions pass incl. the new profile round-trip (save → toast → top-bar
refresh → form values intact → Save re-disables on a clean baseline).
|
||
|
|
7a7e77e039 |
Branded email template + footer pages: help center, token unsubscribe, settings deep links
release gate / check (push) Failing after 6m56s
Transactional mail now goes out as the Superbrain HTML design
(internal/mailer/template.html, embedded verbatim) with a plain-text
alternative: multipart/alternative (plain first per RFC 2046), random
boundary, CRLF normalization and SMTP dot-stuffing. Render() fills the
{{placeholders}} with HTML-escaped values and removes optional sections
(CTA + fallback link, note block, footer links, address) when empty;
anchor drift fails the unit tests and degrades to plain text at send
time, never blocking delivery. Password reset gets the headline,
first-name greeting, "Choose a new password" button (Outlook VML
fallback) and expiry/single-use note; notification and agent emails
render title-as-headline with body paragraphs.
The template's footer links are now real pages:
- /help: public help center (10 topic sections + FAQ accordion), linked
from the login page.
- /unsubscribe?token=...: public confirmation page; the HMAC-signed user
id (notify.UnsubscribeToken, domain-separated, stable, no stored row)
IS the credential. POST /api/notifications/unsubscribe accepts the
RFC 8058 one-click shape (token in query, form body ignored) and the
browser JSON shape; it disables the user's enabled email channels and
pauses enabled agent email tasks addressed to their own email
(idempotent, re-enableable, per-client rate limited, audit logged).
- Email preferences deep-links to /settings?tab=notifications; Settings
now honors ?tab=<section> (unknown values fall back to profile).
notify.FooterLinks is the single eligibility point: preferences + help
whenever NEXTAUTH_URL is set; unsubscribe ONLY when the recipient is the
owner's own account email — third-party channel addresses and agent
recipients never receive a link that changes someone else's settings,
and transactional mail (password reset) never carries unsubscribe.
Owner-addressed mail also carries List-Unsubscribe +
List-Unsubscribe-Post headers.
Verified: Go build/vet/unit green; new TestUnsubscribeFlow integration
test pins footer + headers, blast radius (slack channel and third-party
task survive), one-click + JSON paths, idempotence, tampered tokens and
the third-party/transactional exclusions; notifications, phase-2,
password-reset and agent suites green; web lint/SSR-lint/build 0 errors;
full browser regressions pass; live smoke of /help, /unsubscribe states,
the settings deep-link auth gate and bad-token 400 through the proxy.
|
||
|
|
ef69be6320 |
API.md: document every endpoint (page tags, Next server routes, public/auth aliases)
release gate / check (push) Failing after 6m39s
Cross-checked all 140 registered Go routes against the reference; the only
undocumented ones were the page-tag endpoints. Add POST /api/pages/{id}/tags
and DELETE /api/pages/{id}/tags/{tagId} plus a Page tags subsection (owner-or-
shared tag rule, metadata with no content-version bump, cascade, sidebar
drag-to-tag), and surface tags:[{tag}] in the page list/detail projections.
Clarify two aliases: GET /share/bookmark/{id} on Go is the rate-limited public
JSON projection (Next.js renders the HTML page at the same path), and Go's
/api/auth/ catch-all implements only session+signout (other subpaths 404 on
Go, served by Next).
Add a Next.js server routes subsection: the /api/[...path] proxy (assertion
signing, CSRF + 1 MiB streaming cap, X-Next-Cursor passthrough, no client
Authorization forwarding), NextAuth /api/auth/*, and POST /api/session/revoke
(honest {revoked,reason} global-revocation reporting).
Docs-only; no version bump.
|
||
|
|
298cc4efd6 |
Fix Nextcloud DAV connections on Core: public-IP pin + username-composed prefills
Two bugs made the suggested Nextcloud shares fail on Core: 1. Reachability: nextcloud.$DOMAIN is split-horizon DNS — inside the core network it answers the Nextcloud container's private IP, where nothing listens on 443 (traefik holds TLS on the public address), and netguard refuses private dials anyway. Verified from the core network: the private route refuses connections; the public route answers PROPFIND with 401 (correct credentials-required). The installer's rendered compose now pins nextcloud.$DOMAIN to EXTERNALIP via extra_hosts on the APP service — the exact house pattern the web service already uses for authelia. DNS inside the app container resolves the public address, the dial goes through traefik like any external client, and netguard stays fully strict (no guard relaxation, no trusted-host change). update.sh re-renders compose from the shipped lib, so running cores pick this up on upgrade. 2. Wrong endpoint: Nextcloud's DAV roots are per-user (/remote.php/dav/files/<username>/, /calendars/<username>/), but the WebDAV and CalDAV suggestion prefills handed over the bare /files/ and /calendars/ homes — one level above any valid endpoint. Both now compose the viewer's username into the URL (the URL shown is the URL saved), matching the CardDAV prefill. Dry-rendered the updated compose template and validated it with docker compose config. Regressions updated to assert the composed per-user URLs are what gets POSTed (20/20 PASS incl. the mobile suite); real-stack e2e all PASS; lint/SSR-lint/build clean. API.md and the local AGENTS invariant document the pin and the composition. |
||
|
|
4f919033d1 |
CardDAV address books: each server book a Collection, each contact a URL bookmark
Settings -> CardDAV connects an external CardDAV endpoint (any RFC 6352
service; on Core the deployment's NEXTCLOUD_URL adds a Nextcloud-contacts
one-click prefill, composed visibly with the username so the URL shown is
the URL saved). Each server address book materializes as its own Collection
and every contact becomes a Bookmark carrying the card's DAV .vcf URL — FN
as title, email/phone in the description as display sugar set once.
internal/carddav mirrors the WebDAV/CalDAV siblings:
- client.go — discovery accepts a single book or a home (resourcetype
<card:addressbook/>), addressbook-query REPORT bounded at 50 books /
2000 cards, netguard-pinned, Basic auth in the header only, redirects
refused, folded-vCard parser;
- sync.go — RunLoop/RunOnce under a dedicated carddav-tick advisory lease;
full ledger discipline: idempotent re-runs, etag refreshes never touch
user-edited bookmark fields, vanished cards detach membership but keep
the bookmark, user-deleted bookmarks are tombstones that never
resurrect, a re-deleted Collection is re-created and re-linked, a
truncated listing never reconciles deletions, one unreadable book does
not abort the rest.
CardDAV dials pin to 443 only and require https — CardDAV ships
Basic-auth credentials, and the Contacts sync's review rulings (M-3/CR-01)
stand; the INTEGRATIONS_ALLOW_PRIVATE escape hatch keeps loopback fakes
working. This surface is deliberately separate from the single-config
Contacts sync (Contact rows powering contact-linking): same transport,
different product model, stated in API.md and the UI copy.
Three tables (CardDavConnection/CardDavAddressbook/CardDavItem) via
migration 022 + schema.sql. Handlers expose /api/carddav/connections CRUD
+ /test + /sync with the house credential (encrypted, masked, write-only),
version (409 on stale) and AllowConnector("carddav") plan gate on creation
AND every sync; cap 10; wired as the sixth background loop.
Settings -> CardDAV tab (web/components/carddav-settings.tsx): masked
write-only password, version on PATCH, per-row address-book list,
verbatim test/sync results, Core suggestion prefill, allowed flag drives
the plan notice.
Verification: full Go integration suite green incl. TestCardDavLifecycle
(materialize/URL+title checks, idempotency, etag refresh, detach-but-
survive, tombstone, version contract, 502+lastError, owner scoping) and
TestCardDavSuggestion; carddav unit tests on httptest fakes;
make db-converge passes; browser regressions all 19 PASS incl. the new
CardDAV walkthrough (and a deterministic Sonner-toast drain before the
sign-out assertion, which the added toasts had made racy); web lint/SSR-
lint/build clean. API.md contract section, AGENTS invariant, env docs and
the Core installer wording updated for the three-way DAV prefill.
|
||
|
|
a8bd0ab876 |
CalDAV calendars: each server calendar a Collection, each event a URL bookmark
Settings -> CalDAV connects an external CalDAV endpoint (any RFC 4791
service; on Core the deployment's NEXTCLOUD_URL adds a Nextcloud-calendars
one-click prefill alongside the existing files one). Each server calendar
materializes as its own Collection and every in-window event becomes a
Bookmark carrying the event's DAV .ics URL.
internal/caldav mirrors internal/webdav:
- client.go — PROPFIND discovery (accepts a calendar home via
calendar-home-set or a single calendar), REPORT calendar-query over a
rolling window (last 30d .. next 180d), netguard-pinned 80/443, Basic
auth in the header only, redirects refused, bounded (50 calendars /
500 events);
- ics.go — RFC 5545 unfolding + first-VEVENT parse (UID/SUMMARY/DTSTART);
- sync.go — RunLoop/RunOnce under a dedicated advisory lease, reconciling
each calendar to a Collection and each event to a bookmark via the
CalDavEvent ledger. Same tombstone/detach discipline as WebDAV: a
vanished OR out-of-window event detaches membership but keeps the
bookmark; a user-deleted event never resurrects; a re-deleted collection
is recreated and re-linked; a truncated window never reconciles
deletions; one unreadable calendar does not abort the rest.
Three tables (CalDavConnection/CalDavCalendar/CalDavEvent) via migration 021
+ schema.sql. Handlers expose /api/caldav/connections CRUD + /test + /sync
with the house credential (encrypted, masked, write-only), version (409 on
stale), and AllowConnector("caldav") plan gate on creation AND every sync.
Wired as the fifth background loop in main.go.
Settings -> CalDAV tab (web/components/caldav-settings.tsx): masked
write-only password, version on PATCH, per-row calendar list, verbatim
test/sync results, Core suggestion prefill with the viewer's email
local-part, allowed flag drives the plan notice.
Verification: full Go integration suite green incl. four TestCalDav*
(lifecycle, collection-recreation, plan gate + suggestion) on an httptest
fake CalDAV server; make db-converge passes; browser regressions all 18
PASS incl. the new CalDAV settings walkthrough; web lint/SSR-lint/build
clean. API.md, README, .env.example, Core installer and local AGENTS
documents updated.
|
||
|
|
564bdc87b6 |
WebDAV file shares: connect any RFC 4918 service as a Collection of per-file bookmark URLs
Settings -> WebDAV: a user connects an external WebDAV share (any service; on Core the deployment's NEXTCLOUD_URL offers Nextcloud as a one-click prefill - DATA, never a TIER code fork). The share materializes as a Collection and every file becomes a Bookmark carrying the file's DAV URL, reconciled by the WebDavItem path ledger (migration 020 + schema.sql, db-converge proven): - idempotent syncs; etag changes refresh the ledger only, never user-edited title/notes/tags; same-URL bookmarks are reused (URL-identity invariant); - vanished files detach membership but keep the bookmark (sync never destroys user data); a user-deleted bookmark is a tombstone that is never resurrected; a user-removed membership stays removed - unless the whole collection was deleted, when the next sync re-links every live row; - bounded walks (200 dirs / 1000 files / depth 12) and a truncated listing never reconciles deletions; - netguard-pinned dials (80/443, no trusted exemption for user hosts), Basic auth in a header only, redirects refused outright; - the webdav connector entitlement gates creation AND every sync; a downgrade suppresses instead of deleting; - engine tick per notify/agent discipline (jitter, advisory lease, budget, log-not-fatal); /test proves PROPFIND, /sync reconciles on demand; passwords write-only + masked, PATCH carries version (409 on stale), cap 10 per user. internal/webdav (client+engine), handlers/webdav.go + routes, main.go 4th loop, config.NextcloudSuggestion, Settings tab + webdav-settings.tsx, API.md contract section, env docs, Core installer writes NEXTCLOUD_URL. Client unit tests on an httptest fake DAV server; four integration tests cover lifecycle, recreation, plan gate and suggestion; regressions drive the Settings UI end-to-end (masked rows, prefill, connect/sync/test, no secret echo). All suites green. |
||
|
|
3b11ac83fc |
Notifications phase 2 (Gitea #10): share triggers, targeted people, Signal, managed-by footer
- share_received trigger: scanner fires when a bookmark, tag or collection
is shared with the rule owner (same dedupe discipline; sharer name and
item title in the message)
- config.targetUserIds on rules: same-tenant targets (<=20, validated at
write time); each targeted Notification row carries recipientId and is
delivered through the RECIPIENT's own enabled channel of the rule's kind,
gated by the recipient's tenant plan (no channel => suppressed, visible
in history); history lists rows you own or were targeted on
- signal channel kind: signal-cli REST bridge (POST {restUrl}/v2/send with
account query param and recipients array); account encrypted + masked
like every other credential; netguard-dialed like every webhook
- 'Managed by David's Superbrain.' footer is plan DATA: entitlements
ManagedFooter (free hosted plan only; managed_footer override key),
appended at delivery time - paying plans, core and self-hosted never
carry it
- catalog: signal joins standard/premium/core/selfhosted channel lists
- migration 019 + schema.sql (trigger/kind CHECKs, Notification.recipientId)
- UI: trigger option, same-tenant target picker via /api/users/search,
signal channel fields, targeted-count badge on rules
- tests: share/target/footer/signal legs against fake webhook, fake SMTP
and a fake signal-cli bridge; entitlements footer assertions
|
||
|
|
9cfd6efa38 |
Outbound MCP connections: Notion-style client integrations (Settings -> MCP)
Superbrain dials external MCP servers as a client (official modelcontextprotocol/go-sdk): Streamable HTTP or SSE, none/bearer/header auth. Management surface /api/mcp/connections (CRUD + test) with the house disciplines: - secrets encrypted at rest (internal/crypto), masked in every response, write-only (mask or omission keeps the stored value); authKind none clears them - mutating PATCH carries version (409 on stale); mask-only PATCH is a documented no-op returning the current projection - dials netguard-pinned (public ranges, ports 80/443 outside tests), no redirect following, header names restricted to RFC 7230 tokens - test endpoint: per-user limiter + shared outbound budget; 502 with an error class on dial/auth failure, never a silent ok; returns the tool list for the UI - cap of 10 connections per user under the user lock UI: Settings -> MCP tab (components/mcp-settings.tsx) — list with enable switch, add/edit dialog (secret never prefilled), Test showing the live tool list or the server's error verbatim. Migration 018 + schema.sql; integration test drives a go-sdk fake MCP server (incl. a Bearer-secured one) end to end. Tool USE by the assistant is phase 2. |
||
|
|
e6ab778bd5 |
Add personal API keys, superbrain-mcp, and fix Markdown prose styling
API keys & MCP (the mcpserver-link prerequisite from STRATEGY.md): - ApiKey table (migration 017 + schema.sql): hash-only storage of personal "sb_..." Bearer credentials, unique keyHash, owner cascade. - internal/auth/apikeys.go + AuthMiddleware fork: keys resolve before the assertion/cookie channels; gated on the mcp-core connector at issuance AND at every use (downgrade 403s); independent of tokenVersion so "sign out everywhere" never breaks a gateway link; view-as stays browser-only. - /api/keys GET/POST/DELETE: plaintext shown exactly once, 10-key cap under the user lock, owner-scoped revocation; Settings -> API Keys tab. - mcp/: superbrain-mcp, a pip-installable stdio MCP server (listmonk-mcp pattern) with bookmarks/tags/pages tools, version-safe updates; the federated gateway spawns it via config_mcpserver_superbrain() in deploy/federated/lib-superbrain.sh (mints the gateway key in-db, points it at http://superbrain-app:8080). STRATEGY.md records the remaining suite-side registry work. - Tests: TestAPIKeys (plan gate, cap, revocation, tokenVersion semantics, downgrade-at-use); full DB-backed suite, db-converge, live MCP-client smoke all pass. Markdown (Gitea issue #3): add @tailwindcss/typography and enable it in tailwind.config.ts. The prose wrapper was a no-op without it, so Tailwind Preflight flattened headings/blockquotes to body text while bold/italic survived - exactly the reported symptom. Verified in the built CSS. Gitea: #2 and #3 closed with reference notes; #1 stays open pending the Superpanel core-AI walkthrough. |
||
|
|
09f8a5d933 |
BYO AI settings: custom instructions, model picker, key show/hide
Mirrors the BYOK dialog suggested in issue #2: - UserAiConfig gains an optional instructions column (schema.sql + migration 016); PUT validates (<=4000 chars) and full-replaces it. - Instructions ride along on the assistant chat system prompt only (chatSystemWith); the automation compiler and page-extraction prompts stay server-owned contracts. - Settings -> AI: labeled fields, per-provider suggested-model dropdown with a custom-model escape hatch, API key show/hide toggle, and the instructions textarea. - Tests: projection echo, omission clears, cap validation, and the system-prompt assertion via a recorded fake provider body. |
||
|
|
0848453732 |
Add the Superbrain assistant: ephemeral chat drawer with automation proposals
release gate / check (push) Failing after 6m21s
The A+B slice: one conversation surface for questions AND automations.
Backend: POST /api/ai/chat — ephemeral multi-turn chat through the same
per-user AI resolution as everything else (BYO key -> plan-gated server
key -> 428). The server is stateless per request: the browser owns
history, the handler caps it anyway (40 messages accepted, last 20 used,
8k chars each, last turn must be the user's). Per-user rate limit
(30/hour, keyed on the account not the IP) and a 50-second budget inside
the proxy's 55s window.
The chat system prompt embeds agent.AutomationSchema — the SAME contract
text the compiler uses — so chat proposals and compiled tasks can never
drift. The model answers in a {reply, automation|null} JSON envelope; a
proposal reaches the client only if its spec passes agent.ValidateSpec
(invalid ones are dropped silently, the reply survives), and model-
invented channelIds are scrubbed so the UI always picks from the user's
real channels. A model that ignores the envelope degrades gracefully: raw
text becomes the reply, no proposal.
Web: components/assistant.tsx — floating launcher on every signed-in
screen (mounted once in AppShellWrapper so conversations survive in-app
navigation), Sheet drawer with markdown rendering (house ReactMarkdown +
remarkGfm pattern), proposal cards (channel picker for notify, editable
recipient for email, Create automation -> the regular tasks endpoint),
and Save to page (Markdown transcript into Pages — the only persistence,
by design). Enter sends, Shift+Enter newline.
Tests: envelope parsing, valid proposal + channelId scrub, invalid-spec
drop with reply intact, non-JSON graceful fallback, request validation
(empty/assistant-last/system-role), multi-turn passthrough, 428 path.
Full suite green (-race); web lint/SSR-eslint/build clean.
Docs: API.md chat endpoint, RUNNING.md 'two doors' framing (drawer +
Settings), README feature bullet, plan/notes docs updated.
|
||
|
|
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). |
||
|
|
c432ff57e9 |
Add Authelia identity bridge for NextAuth sessions
release gate / check (push) Failing after 6m40s
Keep NextAuth as the OIDC/session layer and add a trusted Go provisioning endpoint that maps verified Authelia subjects to local users. Existing password accounts require explicit admin linking; new users are provisioned without a password. Enable the Authelia login path and update docs. Also fix test schema search_path so pg_trgm opclasses resolve. |
||
|
|
45aa3c80aa |
Change compurer references to superbrain
release gate / check (push) Failing after 7m39s
|
||
|
|
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
|