Files
Docwell/docs/PLAN.md
T
tajniak81andClaude Opus 5.5 4903bb12dd Scaffold Docwell monorepo with PocketBase authentication
Phase 0 foundation for Docwell, an open-source knowledge base:

- Database: PocketBase v0.40.6 with initial schema migrations; users is
  the built-in auth collection, plus a hook for token checks and
  env-driven app URL/SMTP settings
- Server: Go API (health, version, auth endpoints forwarded to
  PocketBase, admin user list) with an embedded Vue admin panel
- Web-App: Go static server and Vue/Tailwind app with Tiptap editor,
  sign-in, sign-up, password reset and email verification (EN/PL)
- Desktop-App: Wails v3 host reusing the web app
- Phone-App: Flutter app with sign-in
- Shared packages (editor, ui, api-client), OpenAPI spec, Docker
  compose (separate services and all-in-one), GitHub Actions CI
- Docs: feature inventory and architecture/build plan

Licensed under AGPL-3.0-or-later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 22:18:25 +01:00

224 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Docwell — Architecture and Build Plan
Companion to [FEATURES.md](FEATURES.md), which defines the feature priorities (MVP / v1 / v2) used below.
## 1. Product statement
Docwell is an open-source, self-hostable knowledge base and collaborative document editor. It is wiki-first like Docmost and Outline, and grows into Notion-style databases later, like AppFlowy and AFFiNE. It ships as three standalone services plus native desktop and mobile clients.
## 2. System architecture
```
┌──────────────────────┐ ┌───────────────────┐ ┌───────────────────┐
Clients │ Web App (browser) │ │ Desktop (Wails) │ │ Mobile (Flutter) │
└──────────┬───────────┘ └─────────┬─────────┘ └─────────┬─────────┘
│ HTTPS: REST + WebSocket (all clients use the same API)
─────────────────────────┼──────────────────────────────────────────────────────────
Standalone ┌──────────▼───────────┐ ┌────────────────────────────────────────┐
services │ docwell-web (Go) │ │ docwell-server (Go) │
│ • serves Vue SPA │──▶│ • REST API /api/v1 │
│ • runtime config │ │ • WebSocket collab /collab (Yjs relay) │
│ • optional /api proxy│ │ • auth, permissions, search index │
└──────────────────────┘ │ • jobs: import/export, email, webhooks │
│ • Admin panel (Vue SPA) /admin │
└──────────────────┬─────────────────────┘
│ private network only
┌──────────────────▼─────────────────────┐
│ docwell-db (PocketBase) │
│ • SQLite + collections + migrations │
│ • file storage (local or S3) │
│ • realtime SSE (server subscribes) │
└────────────────────────────────────────┘
```
### 2.1 Responsibilities
| Service | Owns | Does NOT do |
|---|---|---|
| **docwell-db** (PocketBase, unmodified official binary + `pb_migrations/` + optional `pb_hooks/`) | Persistence, schema migrations, file blobs, backups, low-level realtime events | Business rules. Its collection API rules allow **only the server's superuser token**, so it is never exposed publicly. |
| **docwell-server** (Go) | Single public API, authentication and sessions, authorization (workspace/space/page ACLs), Yjs collaboration relay and persistence, search index, background jobs, email, webhooks, API tokens. Hosts the **admin panel** (embedded Vue build). | Rendering the end-user UI |
| **docwell-web** (Go) | Serves the end-user Vue SPA (embedded via `embed.FS`), injects runtime config (`/config.json` with API URL, branding, enabled auth providers), sets security headers and caching, can optionally reverse-proxy `/api` + `/collab` for single-origin deployments | Business logic. It is a thin delivery service, so the SPA can also be hosted on any CDN. |
**Why the server is the only gateway to PocketBase:** permission rules in a wiki depend on space membership, group membership and page-level overrides. Those rules are awkward to express as PocketBase API-rule strings, and splitting auth logic across two places is a security risk. Keeping PocketBase private also lets us swap it for Postgres later behind a Go `Store` interface.
### 2.2 Key technical decisions (ADR summaries)
| # | Decision | Rationale / alternatives |
|---|---|---|
| ADR-1 | **Editor = Tiptap 2/3 (ProseMirror) for web and desktop**, with `@tiptap/vue-3` | This is the stack Docmost uses and close to what Outline uses. It has a large extension ecosystem (tables, math, mentions, collaboration) and is MIT licensed. |
| ADR-2 | **CRDT = Yjs** (`y-prosemirror`, `y-indexeddb`, Awareness for cursors) | Industry standard, and both Docmost and Outline use it. |
| ADR-3 | **The Go server relays the y-websocket / Hocuspocus-compatible protocol** and stores incremental updates. Compaction (merging updates into a snapshot, and extracting plain text and JSON for search and exports) runs **Yrs compiled to WASM inside Go via `wazero`**, so there is no cgo and no Node sidecar. | There is no mature pure-Go Yjs port. Options considered: (a) a Node Hocuspocus sidecar, which breaks the "Go only" goal; (b) cgo + yffi, which complicates cross-compiling; (c) client-side compaction, which you can't trust. **(d) wazero + yrs.wasm** was chosen. Spike it in Phase 0. |
| ADR-4 | **Mobile editor = the same Tiptap editor bundle running inside a Flutter WebView** (`webview_flutter` or `flutter_inappwebview`), bridged over JS channels. Navigation, lists, search, settings and comments are native Flutter. | Writing a second rich-text engine in Dart with identical schema and Yjs semantics is months of work and a constant source of divergence. AppFlowy built its own Flutter editor, but its data model is native to that editor. Revisit a native Dart editor in v2+. |
| ADR-5 | **Search = Bleve** (pure Go, embedded in the server) with an optional **Meilisearch** adapter | PocketBase does not expose SQLite FTS5 through its API. Bleve keeps the "no extra service" promise. The search code sits behind an interface so you can swap the backend. |
| ADR-6 | **Authentication = PocketBase's built-in `users` auth collection** — **decided**. PocketBase stores the credentials and issues the tokens, and also handles password, OTP email codes, MFA, OAuth2, verification and password-reset emails (via its own SMTP settings). PocketBase stays private: clients call `/api/v1/auth/*` on docwell-server, which forwards to PocketBase. The server checks bearer tokens through a small hook route (`pb_hooks/docwell.pb.js`, cached 30 s) and adds Docwell's rules: signup policy and domain allow-list, `status = disabled` blocks sign-in (PocketBase `authRule`), and the first account becomes the instance admin (`is_admin`). **Authorization** (workspace, space and page permissions) stays in docwell-server. | Less security-critical code to write and maintain, and auth features (MFA, OTP, OAuth2) come out of the box. Trade-offs: tokens are PocketBase JWTs, so sign-out is client-side (to revoke every session, rotate the user's `tokenKey`), and swapping PocketBase for Postgres later would need a token migration plan. |
| ADR-7 | **Frontend monorepo with shared packages** (npm workspaces): `@docwell/editor`, `@docwell/ui`, `@docwell/api-client` (generated from OpenAPI), `@docwell/i18n` | Web app, admin panel, desktop app and mobile WebView all reuse the same editor and UI kit. |
| ADR-8 | **API contract = OpenAPI 3.1 written first** → Go server stubs (`oapi-codegen`) + TS client (`openapi-typescript`) + Dart client (`openapi-generator`) | Keeps four clients in sync. |
| ADR-9 | **Background jobs = in-process worker pool** with a PocketBase `jobs` collection as a durable queue (no Redis) | Fits a single-node deployment. For multi-node later, add NATS or Redis behind an interface. |
| ADR-10 | **License = AGPL-3.0** for the whole repository (services, apps and packages) — **decided** | Same license as Docmost and AppFlowy. Anyone who runs a modified Docwell as a hosted service must publish their changes. |
| ADR-11 | **Desktop = Wails v3** — **decided** | v3 adds multi-window support, a system tray, a better bindings generator and a cleaner app/service API than v2. Pin an exact v3 version and upgrade on purpose. |
### 2.3 Scaling note (PocketBase = SQLite)
SQLite in WAL mode can handle a few thousand active users on a single node, and that covers the self-host market. The limits to know about: one writer at a time, and a single node, because the collab relay keeps doc rooms in memory. Mitigations: batch Yjs update writes (debounce 1–2 s per doc), store large blobs as files, keep the `Store` interface DB-agnostic, and plan a "Postgres store" plus a "Redis/NATS pub-sub for collab rooms" for horizontal scale in v2+.
## 3. Repository layout (monorepo)
Scaffolded in Phase 0. Folders marked *(planned)* do not exist yet.
```
Docwell/
├── api/openapi.yaml # API contract (source of truth for all clients)
├── Database/ # docwell-db: official PocketBase + pb_migrations/ + pb_hooks/
├── Server/ # docwell-server (Go module docwell/server)
│ ├── cmd/docwell-server/
│ ├── internal/
│ │ ├── httpapi/ # router (net/http ServeMux), CORS, logging, handlers
│ │ ├── config/
│ │ ├── store/pocketbase # superuser REST client
│ │ ├── admin/ # embeds the admin SPA build (dist/)
│ │ └── auth, acl, collab, ycrdt, search, jobs, importer, exporter, mail (planned)
│ └── admin/ # admin panel: Vue 3 + Vite + Tailwind (@docwell/admin)
├── Web-App/ # docwell-web (Go module docwell/web)
│ ├── cmd/docwell-web/
│ ├── internal/spa/ # embeds the web app build, /config.json, optional proxy
│ └── frontend/ # end-user app: Vue 3 + Vite + Tailwind (@docwell/web-app)
├── Desktop-App/ # Wails v3 (Go module docwell/desktop)
│ └── frontend/ # thin host that mounts @docwell/web-app with a desktop platform
├── Phone-App/ # Flutter (android + ios)
├── Packages/
│ ├── editor/ # @docwell/editor – Tiptap schema + Vue component
│ ├── ui/ # @docwell/ui – Tailwind theme tokens + components
│ ├── api-client/ # @docwell/api-client – TS client, types generated from api/
│ └── editor-bridge/, i18n/ (planned)
├── Docker/ # docker-compose: db + server + web as separate services
├── Docker-AIO/ # single all-in-one image (PocketBase + server + web)
├── Design/ # design assets
├── docs/
├── go.work # Go workspace: Server, Web-App, Desktop-App
└── package.json # npm workspaces
```
## 4. Tech stack details
| Layer | Choice |
|---|---|
| Go | Go 1.26, stdlib `net/http` router (method + wildcard patterns), `nhooyr.io/websocket` (now `coder/websocket`), `slog`, `koanf` config, `oapi-codegen`, `wazero`, `bleve/v2`, `go-oidc`, `pquerna/otp`, `testify` + `testcontainers-go` (spins up PocketBase) |
| PocketBase | Official binary pinned to a version, used standalone, with JS migrations. The server talks to it through a thin typed REST client and authenticates with a superuser token |
| Vue (web, admin, desktop) | Vue 3.5 + `<script setup>` TS, Vite, Pinia, Vue Router, VueUse, TanStack Query (vue), Tailwind CSS 4, Reka UI (headless), `vue-i18n`, Lucide icons |
| Editor | Tiptap + extensions: StarterKit, Collaboration, CollaborationCaret, Table, TaskList, Mention, Placeholder, CodeBlockLowlight, Image, Mathematics (KaTeX), plus custom: Callout, Embed, Mermaid, Drawio, Excalidraw, Toggle, PageLink, Attachment |
| Desktop | Wails v3 (Go backend + embedded webview; Go services bound to the frontend through generated TS bindings). Uses the `apps/web` UI with a desktop adapter: native menus, tray, deep links `docwell://`, OS keychain token storage, auto-update, multi-server accounts. v2: local SQLite cache + offline Yjs |
| Mobile | Flutter 3.x, Riverpod, go_router, dio + generated Dart client, `flutter_secure_storage`, `flutter_inappwebview` editor host, push via FCM/APNs (server sends through ntfy/Gotify or direct FCM) |
| CI/CD | GitHub Actions: lint/test per package, build multi-arch Docker images (GHCR), Wails builds (win/mac/linux), Flutter builds (apk/ipa), release-please, Renovate |
| Quality | golangci-lint, ESLint + Prettier, Vitest, Playwright E2E, `flutter test`, k6 load test on the collab relay |
## 5. Data model (PocketBase collections)
| Collection | Key fields |
|---|---|
| `workspaces` | name, slug, logo(file), settings(json: allowed_domains, default_role, auth_providers) |
| `users` (PocketBase **auth** collection) | built-in: email, password, tokenKey, verified, name, avatar; Docwell fields: status (active/invited/disabled), is_admin, locale, theme, last_seen |
| `workspace_members` | workspace, user, role (owner/admin/member/guest) |
| `groups`, `group_members` | workspace, name / group, user |
| `spaces` | workspace, name, slug, icon, description, visibility (open/private), default_permission |
| `space_members` | space, principal_type (user/group), principal_id, role (admin/editor/commenter/viewer) |
| `pages` | workspace, space, parent (self-ref), position (fractional index string), title, icon, cover(file), creator, last_editor, is_template, archived_at, deleted_at, content_json (latest JSON snapshot), content_text (plain text), word_count |
| `page_permissions` | page, principal_type, principal_id, role, inherit(bool) |
| `page_ydoc` | page, state (file/bytes: compacted Yjs state), state_vector, updated_at |
| `page_yupdates` | page, update (bytes), client_id, created — compacted and pruned periodically |
| `page_versions` | page, snapshot (Yjs state), content_json, author(s), created, label |
| `comments` | page, thread_root, parent, author, body_json, anchor (Yjs relative position), resolved_at, reactions(json) |
| `attachments` | workspace, page, file, mime, size, uploader |
| `favorites`, `page_views` | user, page / user, page, viewed_at |
| `share_links` | page, token, include_children, expires_at, password_hash, allow_search_index |
| `notifications` | user, type, payload(json), read_at |
| `page_watchers` | page, user |
| `api_tokens` | user, name, token_hash, scopes, last_used, expires_at |
| `webhooks`, `webhook_deliveries` | workspace, url, secret, events[] / status, response |
| `audit_log` | workspace, actor, action, target, ip, ua, meta(json) |
| `jobs` | type, payload, status, attempts, run_at, error |
| v2: `databases`, `db_properties`, `db_rows`, `db_views` | (rows are pages; property values stored as json per row) |
## 6. Collaboration flow
1. The client opens `wss://server/collab?page=<id>` with its session token. The server checks ACLs: viewers get read-only, commenters can only touch comment marks.
2. The server loads the room (in-memory), runs the Yjs sync step 1/2 using `page_ydoc.state` + pending `page_yupdates`, and starts relaying updates and awareness to peers.
3. Incoming updates are appended to an in-memory buffer and flushed to `page_yupdates` every ~1 s (or 50 updates).
4. A compaction job (wazero/yrs) runs on idle (30 s with no edits) or on room close. It merges updates into `page_ydoc.state`, derives `content_json` + `content_text`, updates the search index and backlinks, and creates a `page_versions` entry on a time/size heuristic (e.g. every 10 min of activity, or when the last editor leaves).
5. Comments anchor to Yjs relative positions, so they survive concurrent edits.
## 7. Delivery roadmap
Time estimates assume ~2 full-time developers. Scale them for your team.
### Phase 0 — Foundations (2–3 weeks)
- Monorepo, CI, lint/test scaffolding, license, CONTRIBUTING, Code of Conduct.
- `api/openapi.yaml` v0 (auth, workspaces, spaces, pages), with codegen wired up for Go, TS and Dart.
- docwell-db Docker image + first migrations. Typed Go PocketBase client + `Store` interface.
- **Spikes (go/no-go):** (1) yrs.wasm under wazero: merge updates, extract JSON, benchmark. (2) Tiptap editor in a Flutter WebView with a JS bridge on iOS + Android. (3) Wails v3 app embedding `apps/web`, with tray, deep link and auto-update checked on Windows, macOS and Linux.
- docker-compose that brings up all three services.
### Phase 1 — MVP wiki (8–10 weeks) → release `0.1`
- **Server:** auth (email+password, magic link, invites, domain allow-list), workspaces, members, groups, spaces + space permissions, page tree CRUD + move/reorder, trash, favorites, recents, attachments (local/S3 via PocketBase), Markdown/HTML import + export, Bleve search, SMTP mail, public share links.
- **Collab:** WebSocket relay, persistence, compaction, presence/cursors, page history list + restore.
- **Web app:** login/onboarding, sidebar tree (drag-and-drop), editor with the MVP block set, slash menu, bubble menu, mentions, inline comments (basic), search + Ctrl+K palette, share dialog, trash, settings, dark mode, i18n (EN + PL), responsive layout.
- **Admin panel:** dashboard (users, pages, storage), user management (invite, disable, role, reset), workspace settings (branding, signup rules, auth), SMTP + storage config, PocketBase backup trigger/download, job queue viewer, system health/version.
- **Deploy:** multi-arch images, `docker compose up` quick start, docs site.
### Phase 2 — v1.0 "team ready" (8–10 weeks)
- Page-level permissions, guests, groups in sharing dialog.
- Comment threads, resolve, reactions. Notifications (in-app + email digest). Page watching.
- Version diff view, templates, archive, backlinks, TOC, toggles, math, Mermaid, Draw.io, Excalidraw, embeds, link cards, block links.
- OAuth (Google, GitHub, Microsoft), generic OIDC, TOTP MFA, audit log, API tokens + public REST API, webhooks.
- Notion zip import, DOCX import, PDF export, full space export.
- **Desktop app (Wails) 1.0:** multi-server login, native menus, deep links, keychain, auto-update; Windows/macOS/Linux installers.
- **Mobile app (Flutter) 1.0:** login, workspace/space/page browsing, search, read + edit (WebView editor), comments, notifications (push), share sheet ("save to Docwell"), offline read cache.
### Phase 3 — v2 "Notion-class" (12+ weeks, iterative)
- Databases: inline + full-page, table/board/calendar views, core property types, filters/sorts/grouping, rows as pages.
- AI: provider-agnostic (OpenAI-compatible API, Anthropic, Ollama). Writing assistant in editor. Workspace Q&A with RAG (embeddings stored in SQLite via `sqlite-vec` or in the search backend) and citations. MCP server endpoint for agents.
- Offline-first desktop (local SQLite + y-indexeddb sync queue), then mobile.
- Publish as a public site with a custom domain. SAML, LDAP, SCIM. Confluence import. Slack/GitHub integrations. Plugin API (editor extensions + server webhooks).
- Scale-out option: Postgres `Store` and NATS for collab room fan-out.
## 8. Admin panel scope (docwell-server `/admin`)
| Area | Functions |
|---|---|
| Overview | Active users, pages, storage used, collab rooms online, job queue depth, version + update check |
| Users | List/search, invite, change role, disable, force logout, reset MFA, impersonate (audited) |
| Workspaces | Create/edit, branding (logo, colors, name), default language |
| Authentication | Enable/disable email login, magic link, OAuth providers, OIDC config, domain allow-list, session lifetime, MFA enforcement |
| Storage | Local vs S3 (passes through to PocketBase settings), quotas, orphaned file cleanup |
| Email | SMTP config + test send, templates |
| Search | Reindex, backend selection (Bleve/Meilisearch) |
| Security | Audit log viewer/export, API tokens overview, webhooks |
| Maintenance | Backups (PocketBase snapshot create/download/restore), jobs viewer/retry, logs tail, feature flags |
| AI (v2) | Provider keys, models, usage limits |
## 9. Testing strategy
- **Go:** unit tests per package. Integration tests run against a real PocketBase container (testcontainers). Collab convergence tests drive N simulated Yjs clients doing random edits through the relay and assert identical final state. Fuzz-test the protocol parser.
- **Frontend:** Vitest for stores/composables/editor extensions. Playwright E2E for core journeys (signup → create space → co-edit in two browsers → comment → share link).
- **Mobile:** widget tests and integration tests against the docker-compose stack.
- **Load:** k6 with 500 concurrent editors across 50 rooms. Target p95 update fan-out under 100 ms on a 2 vCPU node.
- **Security:** authz matrix tests (every endpoint × every role), gosec, dependency scanning, CSP + sanitization of pasted HTML.
## 10. Risks and mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| yrs.wasm under wazero is slow or has gaps | Compaction/search extraction blocked | Phase 0 spike. Fallbacks: cgo + yffi, or optional Node sidecar for compaction only |
| WebView editor feels non-native on mobile | Poor mobile UX | Native toolbar above the keyboard in Flutter, tuned scrolling/keyboard insets, prefetch the editor bundle. Native read-only renderer for fast viewing |
| SQLite write contention | Lag at higher scale | Batched writes, WAL, files outside the DB, `Store` interface ready for Postgres |
| PocketBase is pre-1.0 with breaking changes | Upgrade pain | Pin the version, keep usage to the documented REST API + migrations, wrap it in our client, run an upgrade test in CI |
| Wails v3 APIs still changing between releases | Desktop app breaks on upgrade | Pin the exact version, keep Wails-specific code in a thin adapter layer in `apps/desktop`, and run desktop builds in CI on every upgrade |
| Scope creep toward "full Notion" | Never ships | Strict MVP/v1/v2 gates from FEATURES.md. Databases only after v1.0 |
| Four clients drifting apart | Bugs, duplicated work | OpenAPI-first codegen, shared editor package, shared i18n catalog |
## 11. Immediate next steps
1. ~~Confirm the license and the Wails version~~ — decided: AGPL-3.0 for everything, Wails v3. Add the official AGPL-3.0 `LICENSE` text and SPDX headers (`AGPL-3.0-only` or `-or-later`) during scaffolding.
2. Scaffold the monorepo (Phase 0 layout above) and docker-compose with the three services.
3. Run the three Phase 0 spikes and record the results as ADRs in `docs/adr/`.
4. Write `api/openapi.yaml` v0 and the first PocketBase migrations.