Add project OpenCode agent + skills; note core compose topology
release gate / check (push) Failing after 5m49s

- .opencode/agents/superbrain.md: primary project engineer agent
- .opencode/agents/invariant-reviewer.md: read-only diff reviewer subagent
- .opencode/skills/: db-migration, add-endpoint, web-invariants, verify, release
- RUNNING.md: warn that the repo docker-compose.yml is local dev/test only and
  must never be run on a core (cores use the federated render + shared postgresql)
This commit is contained in:
Andrew S Erwin
2026-11-30 10:00:14 -06:00
parent be80baf28e
commit f603bcd2d2
8 changed files with 431 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
---
description: Read-only reviewer that checks diffs against Superbrain's dense invariant set (migrations, netguard, secrets, version/409, plan gates) and reports findings by severity. Use after changes, before a release, or when asked to review a PR/diff.
mode: subagent
model: anthropic/claude-sonnet-5-5#high
permissions:
- action: edit
resource: "*"
effect: deny
- action: shell
resource: "*"
effect: deny
- action: subagent
resource: "*"
effect: deny
---
You are the Superbrain invariant reviewer. You review the current changes
(`git diff`, `git diff --staged`, or a commit/range the user names) and report
findings. You NEVER edit files or run shell commands — you read code and reason.
## What to check
Read the root `AGENTS.md` and `web/AGENTS.md` in full first; they are the
source of truth. Then walk the diff and flag violations of these recurring
invariants (cite file:line for each finding):
1. **Schema convergence** — any DB change must touch BOTH `db/schema.sql` AND a
new `db/migrations/NNN_*.sql`. Migrations must be additive, transaction-safe,
and carry NO `BEGIN`/`COMMIT` (the runner wraps each file). `CREATE INDEX
CONCURRENTLY`/`VACUUM` are unsupported. Flag schema.sql-only or
migration-only changes.
2. **Netguard** — every server-initiated dial must go through
`internal/netguard` (ports pinned, no redirect following). User-supplied
hosts must NEVER get a `NETGUARD_TRUSTED_HOSTS` exemption. Flag raw
`http.Client`/`net.Dial`/default transport for outbound calls.
3. **Write-only secrets** — credentials (IMAP, MCP, WebDAV/CalDAV/CardDAV,
channel secrets, AI keys) are encrypted at rest, masked (`••••••••`) in
EVERY response, and write-only: a PATCH echoing the mask or omitting the
field keeps the stored value. Flag any GET that returns a plaintext secret
or any PATCH that overwrites a stored secret with a mask/blank.
4. **Optimistic concurrency** — every mutating collection PATCH must send the
expected `version`; a 409 reloads server state instead of clobbering. Page
content PATCHes must carry `version` (Go rejects them without it). Flag
last-write-wins writes and 409s that silently overwrite.
5. **Plan gates, never TIER** — features gate on the entitlement catalog
(`entitlements.AllowConnector/AllowChannel/AllowServerAI`, `Limits`), never
on `TIER` directly. Gates apply at creation AND at use/delivery (downgrade ⇒
suppress). Flag `TIER` checks in feature code and single-point gates.
6. **Tenancy** — every user has exactly one tenant; default is the implicit
`tenant-default`. Flag code that special-cases "no tenant".
7. **Identity** — never use an OIDC `sub` as a local Go user ID; the Next proxy
must not forward client `Authorization` headers; browser-supplied user IDs
are never trusted.
8. **API keys** — `sb_...` keys resolve before assertions, ignore
`tokenVersion` bumps, never impersonate; issuance and use gate on `mcp-core`.
9. **Notifications** — exactly-once is solely `UNIQUE("ruleId","dedupeKey")` +
`ON CONFLICT DO NOTHING`; producers are never instrumented. Webhooks go
through netguard + `outbound.Reserve`.
10. **Agent engine** — runs ONLY specs that pass `ValidateSpec` (on write AND
load); the LLM never chooses actions/calls; fetched page content is
untrusted; fire caps enforced.
11. **Page URLs → bookmarks** — every URL added to a page becomes a bookmark
(reuse same-URL, never duplicate); pasting never rewrites the Markdown.
12. **Frontend (web/)** — no local Prisma; data via the proxy + `lib/api.ts`;
keep NextAuth `/api/auth/*` local; fix hydration rather than weakening the
SSR eslint config; shared/narrowed projections keep optional fields
optional; secrets never prefilled.
13. **Release lockstep** — a version change touches `deploy/federated/service`,
the installer image version, `mcp/pyproject.toml`, and
`mcp/superbrain_mcp/__init__.py` together, plus a CHANGELOG entry. Tags
have NO `v` prefix.
## Output format
List findings in severity order (Critical → High → Medium → Low → Nit), each as:
- **[severity] file:line** — one-line violation, then a sentence on why it
breaks the invariant and the minimal fix.
End with a short verdict: APPROVE / APPROVE WITH NITS / REQUEST CHANGES, and a
one-line note on what you could NOT verify (e.g. needed to run the test suite).
Do not restate the whole diff; only report findings and the verdict.
+51
View File
@@ -0,0 +1,51 @@
---
description: Superbrain's project engineer — Go API + Next.js monorepo. Use for any Superbrain work (features, migrations, endpoints, releases, verification). Reads AGENTS.md/web/AGENTS.md first, uses the project skills, and treats maincore as read-only.
mode: primary
color: "#4f8cff"
---
You are the Superbrain engineer. Superbrain is a multi-user, self-hostable
"second brain": Go API (`internal/*`) owns persistence/auth/business logic;
Next.js App Router (`web/*`) owns the UI and browser sessions via NextAuth. Hard
boundary: no local Prisma, all data flows through the proxy + `lib/api.ts`.
## First, every session
1. Read the root `AGENTS.md` and `web/AGENTS.md` in full — they are the source of
truth and are kept current (memory lives there). Follow `web/STYLE_GUIDE.md`
for UI work.
2. Check `git log --oneline -20` and `git status` before changing anything.
3. Load the matching skill before the task (see below); don't restate rules the
skill already covers.
## Skills (load with the `skill` tool)
- `db-migration` — any schema change (schema.sql + new `NNN_*.sql`, `make db-converge`).
- `add-endpoint` — new/changed Go endpoint (handler + route, netguard, entitlement gate, write-only secrets, version/409, tests).
- `web-invariants` — anything under `web/`.
- `verify` — choosing and running the right gate before declaring done.
- `release` — version bumps / CHANGELOG / tags (lockstep files, no `v` prefix).
## Non-negotiable rules
- **Cores:** dev core is `ssh core` (read/write within ops scope). Production
core is `ssh maincore` — **READ-ONLY, for verification/comparison only. Never
mutate it** (no patch/upgrade/restart/probe-writes).
- **Invariants:** schema↔migration convergence; netguard on every server dial;
write-only encrypted secrets (masked, never prefilled); `version`/409 on
mutating PATCHes; plan gates via the entitlement catalog, never `TIER`;
tenancy default `tenant-default`; never use an OIDC `sub` as a local user id.
- **Compose:** the repo `docker-compose.yml` is local dev/test only — never run
it on a core (cores use the federated render against the shared `postgresql`).
- **Verify before done:** run the narrowest gate that covers the change, then the
full gate before a release. Local gates are authoritative (CI `check.yml` has a
known env failure — don't chase it).
## Style
Match the surrounding code's structure, naming, and patterns. Prefer small,
additive, reversible changes. Cite file:line when explaining. When a change is
ambiguous or risky, say so and confirm before mutating anything.
For a read-only second opinion on a diff, launch the `invariant-reviewer`
subagent.
+57
View File
@@ -0,0 +1,57 @@
---
name: Add Endpoint
description: Add a new Go API endpoint the Superbrain way — handler + route registration, effective-user resolution, netguard, entitlement gate, write-only secrets, version/409 contract, and tests. Use when adding or changing an HTTP endpoint in internal/.
---
# Add an endpoint
Data endpoints live in `internal/handlers/*.go` and are registered in
`internal/http/server.go` on the `mux`. Every data endpoint resolves the
effective user, returns 401 if none, checks ownership, returns 404 if not
theirs, then acts. Errors are `{error: string}`; all routes return JSON unless
marked `.md`.
## Steps
1. **Handler** in the right `internal/handlers/<area>.go` file. Use the shared
helpers from `common.go`:
- `user(r)` — effective user id (from the session context).
- `database(r)` — the `*db.DB`.
- `read(w, r)` — decode a JSON object (1 MiB cap, 413 on oversize).
- `writeJSON(w, status, body)` / `Error{...}`.
- `bad(...)` → 400, `conflict(...)` → 409 (optimistic concurrency).
2. **Route** in `internal/http/server.go`, e.g.
`mux.HandleFunc("POST /api/things", authed(handlers.HandleThingsCreate))`.
Use `authed(...)` for session endpoints; `admin(...)` for admin-only.
3. **Identity** — never trust a browser-supplied user id; never use an OIDC
`sub` as a local user id. API keys (`sb_...`) resolve in `AuthMiddleware`
before assertions.
4. **Secrets** (if the endpoint stores credentials) — encrypt at rest
(`internal/crypto`, versioned ciphertext `base64(0x01 || ...)`), mask
(`••••••••`) in EVERY response, write-only: a PATCH echoing the mask or
omitting the field keeps the stored value.
5. **Outbound dials** — go through `internal/netguard`
(`DialContextPorts`/`DialContext`, ports pinned, no redirect following) and
draw from the shared budget via `outbound.Reserve(key, limit, window)`.
User-supplied hosts get NO `NETGUARD_TRUSTED_HOSTS` exemption.
6. **Plan gate** — gate on the entitlement catalog, never `TIER`:
`entitlements.For(plan).AllowConnector(name)` / `AllowChannel(name)` /
`AllowServerAI(plan)`. Gate at creation AND at use (downgrade ⇒ suppress).
Resolve the caller's tenant plan (see `webdavConnectorGate` in
`handlers/webdav.go` for the shape).
7. **Optimistic concurrency** — mutating collection PATCHes take the expected
`version`; return 409 (`conflict(...)`) on stale. Page content PATCHes must
require `version`.
8. **Tests** — add `internal/http/<area>_test.go` (DB-backed; set secrets with
`t.Setenv`, no `t.Parallel()` when using `t.Setenv`). Cover auth (401),
ownership (404), the plan gate, and the version/409 path.
9. **Verify** — `make test`, and `make integration` if it touches the DB (see
the verify skill).
## Reference
- `internal/handlers/webdav.go` — the canonical connector handler (gates,
write-only secrets, netguard, version, per-user limiter).
- `internal/handlers/common.go` — shared helpers.
- `internal/http/server.go` — route registration.
- `API.md` — endpoint documentation (keep it in sync).
+51
View File
@@ -0,0 +1,51 @@
---
name: DB Migration
description: Add a PostgreSQL migration the Superbrain way — schema.sql + ordered additive migration file + convergence/atomicity proof. Use whenever a change alters the database schema.
---
# DB migration workflow
Superbrain has TWO paths to the same schema and both must stay in lockstep:
- `db/schema.sql` — initializes a fresh database.
- `db/migrations/NNN_*.sql` — ordered, additive migrations applied by
`db/migrate.sh` in ONE transaction under a fixed advisory lock.
`make db-converge` proves the two paths are equivalent and that apply/record is
atomic. A change that edits only one path fails convergence.
## Steps
1. **Find the next number.** `ls db/migrations | sort | tail -1` → use the next
zero-padded integer (currently 026, so the next is `027_<snake_name>.sql`).
2. **Edit `db/schema.sql`** so a fresh database gets the final shape (tables,
columns, indexes, constraints).
3. **Add `db/migrations/027_<name>.sql`** with the additive statements that
bring an existing database from the previous shape to the new one.
4. **Run the gate:** `make db-converge` (runs `db/check-convergence.sh` plus
`db/migrate-atomicity.sh` against scratch databases). It must pass.
5. If the change is behavioral, run the DB-backed tests:
`docker compose run --rm tests go test -race -run TestName ./internal/http`
(or `make integration` for the full suite).
## Hard rules (the runner enforces these)
- **No `BEGIN`/`COMMIT`** in a migration file — `migrate.sh` wraps each file in
one transaction. A file that manages its own transaction breaks the ledger.
- **No `CREATE INDEX CONCURRENTLY`, `VACUUM`, or other statements that cannot
run inside a transaction block** — handle those as explicit operator steps
outside the ledger.
- **Additive only.** Prefer `ADD COLUMN IF NOT EXISTS`, `CREATE TABLE IF NOT
EXISTS`, etc. Migrations are checksummed and immutable once applied — never
edit an existing migration file; add a new one.
- **Idempotent by convention** (defense in depth; migration 001 must stay so
for first ledger adoption on legacy-upgraded databases).
- Every user belongs to exactly one tenant; single-tenant deployments use the
implicit `tenant-default` row — do not special-case "no tenant".
## Reference
- `db/migrate.sh` — runner + ledger + preflight rules (read its header).
- `db/migrations/020_webdav_shares.sql`, `021_caldav_calendars.sql`,
`022_carddav_shares.sql` — recent examples of the ledger/tombstone pattern.
- Root `AGENTS.md` → "Database Layer".
+55
View File
@@ -0,0 +1,55 @@
---
name: Release
description: Cut a Superbrain release — lockstep version bump across service/installer/mcp files, CHANGELOG entry, tag (no v prefix), and the separate Docker Hub publish process. Use when asked to bump the version or prepare a release.
---
# Release workflow
Versions correspond to git tags AND the published image set
(`federatedcomputer/superbrain-{app,web,migrate}` on Docker Hub). The
`superbrain-mcp` Python package and the federated suite files move in lockstep.
Superbrain is pre-beta: the line is `0.x`, semver **without a `v` prefix**
(suite `VERSION_RX` is `^[0-9][0-9\.]*$`).
## Steps
1. **Propose the version bump first** and get user approval before editing.
2. **Bump every lockstep file together** (a release commit touches all of them):
- `deploy/federated/service` — the `VERSION` line.
- The installer image version referenced by the federated suite
(`deploy/federated/lib-superbrain.sh` and/or the installer image tag).
- `mcp/pyproject.toml` — `version = "..."`.
- `mcp/superbrain_mcp/__init__.py` — `__version__`.
Confirm with `git log --stat` on a prior "release 0.3.x" commit for the exact
file set at the current head.
3. **Add a CHANGELOG entry** at the top of `CHANGELOG.md`:
`## X.Y.Z — YYYY-MM-DD` with `### Added` / `### Changed` / `### Fixed`
subsections. Match the existing prose style (feature-first, one bullet per
user-visible change). Dates are tag dates.
4. **Commit** with the message pattern `release X.Y.Z: bump federated service
VERSION, installer image version and mcp package version`.
5. **Tag** without a `v` prefix: `git tag X.Y.Z`.
## Publishing (important, do not "fix")
- The Docker Hub image set is published by a **SEPARATE process triggered on
push to `main`** — NOT by this repo's CI.
- The Gitea `release.yml` publish job has **never succeeded** (the repo's
`DOCKERHUB_*` Actions secrets are empty; writing them needs a repo-owner
account the git credential user is not). Do NOT treat that job's failure as a
regression or rework the flow. Its tag-triggered `smoke` job is still a valid
gate.
- **Fallback publisher:** local `docker buildx` with the `multiarch` builder
(amd64 + arm64, `<tag>` + `latest`, web build-arg
`SUPERBRAIN_VERSION=<tag>`). qemu arm64 binfmt registration is lost on reboot
— re-register with
`docker run --privileged --rm tonistiigi/binfmt --install arm64` then
`docker restart buildx_buildkit_multiarch0`.
- Cores consume Docker Hub via the suite upgrade flow (erwin example):
`ssh core 'sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/update.sh)" update.sh <version>'`.
## Reference
- `CHANGELOG.md` (format + recent entries).
- Root `AGENTS.md` → "Release publishing (confirmed by operator 2026-11-21)".
- `RUNNING.md` for deploy/upgrade detail.
+45
View File
@@ -0,0 +1,45 @@
---
name: Verify
description: Pick and run the right Superbrain verification gate for a change — Go unit/integration, schema convergence, web lint/typecheck/build, browser regressions, e2e. Use before declaring work done or before a release.
---
# Verification gates
Run the narrowest gate that covers your change, then the full gate before a
release. Local gates are authoritative (the CI `check.yml` runner has a
pre-existing environment failure — do not chase it as a code regression).
## Choose the gate
| Change | Run |
| --- | --- |
| Go code (any `internal/*`) | `make test` (unit; DB tests skip without `TEST_DATABASE_URL`) |
| Go code touching DB / queries | `make integration` (inside Docker) or `docker compose run --rm tests go test -race -run TestName ./internal/http` |
| Schema / migration | `make db-converge` (see the db-migration skill) |
| `web/*` | from `web/`: `yarn lint`, `yarn build` (includes typecheck), `yarn eslint -c eslint.ssr.config.mjs .` |
| Browser / UI behavior | `npm --prefix scripts run test:regressions` (needs a prior `yarn build` in `web/`) |
| Full stack smoke | `make e2e` against a running composed stack (`BASE_URL` default `http://localhost:3000`) |
| Everything (release) | `make check` |
## Notes
- `make check` sequence: `build → vet → integration → db-converge → yarn lint +
SSR eslint + yarn build → browser regressions`. It fails (by design) when
Docker is unavailable — DB-backed coverage is mandatory for release.
- If `yarn` comes through corepack, use `make check YARN="corepack yarn"`.
- Go tests using `t.Setenv` cannot be parallel; the `tests` container mounts
only `go.mod`, `go.sum`, `internal/`, `db/` (never the repo root or `.env`),
so tests must set their own secrets via `t.Setenv`.
- The Go toolchain is pinned in lockstep in the app `Dockerfile`
(`golang:1.26.1-alpine3.22`) and the `tests` service in `docker-compose.yml` —
upgrade both together.
- Browser suites launch Chromium from `CHROMIUM_PATH` (default
`/usr/bin/chromium`), not the Playwright-bundled browser.
- `make e2e` tests built images; rebuild with `make run` after source changes.
Cleanup requires the local Compose db.
- `make audit` is opt-in (needs network + `govulncheck`).
## Reference
- `Makefile` (all targets).
- Root `AGENTS.md` → "Setup & Commands" and "Testing Quirks".
+82
View File
@@ -0,0 +1,82 @@
---
name: Web Invariants
description: Condensed rules from web/AGENTS.md for frontend work — no Prisma, proxy + lib/api.ts, local NextAuth, write-only secrets, version/409, hydration, narrowed projections. Use before editing anything under web/.
---
# Web invariants (condensed)
Read `web/AGENTS.md` in full for the authoritative version; this is the
quick-reference checklist. Follow `web/STYLE_GUIDE.md` for design tokens and
reusable components.
## Architecture
- Next.js App Router; **Go owns persistence**. All data requests go through
`app/api/[...path]/route.ts` and `lib/api.ts` — **no local Prisma routes**.
- `API_BASE_URL` is server-only Docker DNS (`http://app:8080`); the browser
uses relative `/api/*` URLs.
- Keep NextAuth `/api/auth/*` local. Credentials call Go; the server proxy
signs short-lived assertions (60s) for the session's id. **Never pass a
browser-supplied user id as trusted identity.** The proxy does NOT forward a
client `Authorization` header (so `sb_...` keys only work against Go direct).
## Secrets (write-only discipline)
- Channel / MCP / WebDAV / CalDAV / CardDAV / AI-key secrets are write-only:
render masked values as-is, **never prefill secret inputs from GET
responses**, and send the mask back unchanged on PATCH to keep the stored
value. The plaintext key (`sb_...`) exists only in the POST response — render
once, never persist.
## Concurrency (version / 409)
- Every mutating collection PATCH sends the expected `version`; a **409
reloads server state** instead of clobbering (detail sheet keeps the unsaved
form until the user explicitly reloads; kanban reloads the board).
- Page content saves must carry `version` (Go rejects them without it). Page
autosave treats a conflict as a distinct paused state; only the banner
actions (overwrite / save-as-copy / discard) touch remote content — typing
never resolves a conflict.
## Projections & sharing
- Shared readers get a narrowed projection without contact, recipient list,
alerts, mailbox watches, or board placement (`kanbanColumnId`/
`kanbanPosition`) — keep those fields **optional** in UI code. The legacy
`kanbanStatus` badge IS included.
- Shared collections render read-only — hide mutation controls.
- Tag sharing is group-wide; public bookmark links publish notes/dueDate but
carry NO owner attribution. Keep the tags share panel and the detail sheet's
public-toggle disclosure in sync with these rules.
## Rendering & hydration
- Markdown is `react-markdown` + `remark-gfm` in a Tailwind `prose` wrapper
(`@tailwindcss/typography`). The full-dialect renderer (GFM +
`superbrain:page/<id>` links + `{{collection:…}}` embeds + link previews)
lives in `app/(app)/pages/client.tsx`.
- Remote preview/favicon images always render with
`referrerPolicy="no-referrer"`.
- Fix hydration failures rather than weakening `eslint.ssr.config.mjs`.
`components/client-only.tsx` and `components/safe-format.tsx` are the safe
patterns.
## Page URLs → bookmarks
- Every URL a user adds to a page (links popover "Save & add", editor Link
button, bare-URL paste) becomes a bookmark linked to that page — reuse an
existing same-URL bookmark, never POST a duplicate. Pasting never rewrites
the Markdown text.
## Plan gates & settings
- Plan gating is the server's job: surface its 403 message; the UI must not
guess entitlements. List responses carry `allowed` — hide mutation controls
when false, never recompute entitlements client-side.
- Test/sync results (including 502 dial failures) render verbatim.
## Verify (from `web/`)
`yarn lint`, `yarn build` (includes type checking),
`yarn eslint -c eslint.ssr.config.mjs .`. Browser regressions need a prior
`yarn build` (see the verify skill).
+8
View File
@@ -4,6 +4,14 @@ This guide takes you from cloning the repository to signing in on your own
Superbrain instance. Docker runs the web app, Go API, and PostgreSQL database together.
You do not need to install Go, Node.js, PostgreSQL, Make, or OpenSSL separately.
> **Cores / federated hosts:** the `docker-compose.yml` in this repository is
> for **local development and testing only** — it includes a local `db`
> (PostgreSQL) container. Federated "core" hosts (the suite) do **not** use this
> compose; they run the rendered `app` + `web` + `migrate` stack against the
> shared `postgresql`. Never run this repository's `docker-compose.yml` on a
> core — doing so leaves an orphan `superbrain-db-1` container that is not the
> app's database. See `RUNNING.md`/`AGENTS.md` for the core upgrade flow.
## Before you start
- **Docker with Docker Compose v2 or newer.** Docker Desktop includes Compose