Docs menu

Docs Under the hood1.10.1

Architecture

OpenTodo is a local-first application with a thin sync server. Every device holds a full copy of the user's data in IndexedDB and edits it offline; the server keeps an append-only operation log, resolves it to current values, and offers the same data to other devices, scripts and integrations.

On this page
┌──────────────────────── browser / PWA ─────────────────────────┐
│  React views  ◄── useLiveQuery ──  IndexedDB (Dexie)           │
│       │                               ▲        │               │
│   mutate()  ──► applyOps (LWW) ───────┘        └► outbox       │
│                                                       │        │
│  sync engine: push outbox / pull since cursor ◄───────┘        │
└──────────────────────────────┬─────────────────────────────────┘
                               │  POST /api/v1/sync  (JSON, same origin)
                               │  GET  /api/v1/sync/events  (SSE wake-ups, cursor only)
┌──────────────────────────────▼─────────────────────────────────┐
│  Go server (single static binary)                              │
│                                                                │
│  httpapi ── REST, auth, CalDAV (/dav), MCP (/mcp), SSE         │
│     │                                                          │
│  sync: Apply / ApplyStrict ── op log + scope_fields (SQLite)   │
│     │  after commit: observer, sinks, notifier                 │
│     ├─► webhook queue + worker      ├─► notify (in-app)        │
│     └─► Notifier (wake devices)                                │
│                                                                │
│  background: push scheduler · email poller · backup scheduler  │
│              trash retention · audit pruning · webhook worker  │
│                                                                │
│  embedded web app (internal/web/dist)        /data (SQLite)    │
└────────────────────────────────────────────────────────────────┘

Data flow#

Every write is an op#

All task, project, label, section, view, reminder, comment and project-preference data changes as field-level operations ({entity, entityId, field, value, ts, device}), never as direct row writes. internal/sync validates each op against Schema (internal/sync/ops.go), resolves its sharing scope (user:<id> for personal data, project:<id> for a shared project and everything in it), checks the author's role, stores it in ops / op_scopes and updates the winner per field in scope_fields by last-writer-wins (ts, then device). Replaying the same ops in any order gives the same state. The protocol is in sync.md.

The writers are:

Writer Path Device id
Web app on each device POST /api/v1/sync → sync.Apply (refused ops reported per op, never block the outbox) the device's id
REST API, CLI handler turns body fields into ops → sync.ApplyStrict (all or nothing) server:<boot id> (server in ops from older releases)
CalDAV clients /dav/ PUT, PROPPATCH, MKCALENDAR, DELETE → one op per changed property caldav:<app password id>
Email to task IMAP poller → ApplyStrict, ids derived from account and Message-ID server:<boot id>
Issue import poller → ApplyStrict per page, ids derived from connection and issue issues:<connection id>
Automation rules observer queues events after commit; worker and minute scheduler → ApplyStrict per task, op ids derived from rule, run key and field rule:<rule id>
Import background job, batches of 1,000 ops import
Server itself reminder delivery (delivered_at), unassigning people who leave a project or whose account is deleted, recurring completion via REST server:<boot id>

Every server-side writer takes its timestamps from one strictly increasing clock (sync.Service.ServerTS), and the boot id is chosen when the process starts, so two server writes never tie under last-writer-wins.

Membership, accounts, tokens, settings, webhooks, audit events and backup runs are not ops: they are server-side account data in ordinary tables, changed only through authenticated REST routes.

Request flow for a REST write#

POST /api/v1/tasks → auth middleware resolves the user (session cookie with origin check, or bearer token with its scope) → body fields become ops with ts = Service.ServerTS(), device = "server:<boot id>" → sync.ApplyStrict resolves each op's scope and checks the caller's role → after commit the observer queues webhook deliveries for genuine changes (for every member who can see the scope) and notification sinks record assignments and mentions → sync.NotifyApplied wakes the open event streams of everyone who can see the change → the entity is re-read from scope_fields → JSON response. Devices receive the ops on their next sync, which the wake-up triggers at once.

Reads#

REST collections, the export, MCP tools (the shared agent tool registry in internal/agenttools, whose write tools plan changes and apply them with ApplyStrict as device agent:<token-id>) and resources, CalDAV reports and webhook payloads all read materialised entities through sync.List / sync.Get (and helpers such as TaskComments, Memberships), restricted to the scopes the caller can see. History and activity are derived on request from the op log (ActivityOps, activity.Derive); there is no separate activity table on the server.

Live updates#

GET /api/v1/sync/events is a server-sent event stream per device (httpapi/events.go). It carries only the latest op cursor, never data; the client reacts by running the ordinary sync exchange. sync.Notifier is the in-memory per-user fan-out (at most 10 streams per account; httpapi/events.go also caps streams per client address and per server). See sync.md.

Background work#

Every tenant describes its background work once, as a list of jobs (tenant.Jobs, package jobs): when each job is next due (Next) and what to run (Run). The same list runs in both modes:

  • Self-hosted: tenant.StartJobs runs the list with jobs.Runner, only in the process that holds the jobs lock (cmd/opentodo, rolling updates). The runner sleeps until the earliest due time, asks a job again at least every 30 s, and never runs one job twice at once. Jobs run independently, so a long backup does not hold up a delivery.
  • Host: the host's shared scheduler writes the same due times into its index and calls the same Run (see host).

Services report new work through the tenant's jobs.Signal:

  • Wake-ups:
    • a queued webhook delivery or channel message, or a webhook or channel turned on again, wakes the webhooks job;
    • a queued rule event wakes the rules job;
    • a saved backup schedule wakes the backup job.
  • Committed batches: every committed batch asks every job again after one second (a new reminder, a moved task with a calendar event).
  • Other processes: a once-a-second PRAGMA data_version probe notices writes made by another process on the same data directory.

A job that is still due after it ran waits its retry pause (30 s, 1 s for deliveries, 1 h for housekeeping). Stopping waits for the runs in progress, so their outcome is recorded before the database closes.

The jobs:

  • Reminders (unless OPENTODO_PUSH=off): due at the earliest firing time.
    • A single query over scope_fields (reminders are always personal) selects reminders whose fire_at has passed, not deleted, not delivered or dismissed for the current firing, whose task is open.
    • Each is encrypted and posted to every subscription of the owner (404/410 removes the subscription), then delivered_at is written through sync.Apply as device server.
    • Delivery state lives in the op log, so a restart neither loses nor repeats a push (a crash between send and write can repeat one).
  • Webhooks: sends queued webhook deliveries and notification channel messages (channels never on a demo instance) when they are due; retries follow webhook.Backoff.
  • Calendars: subscription fetches and calendar sync cycles, at their next due time, while their owner switches are on.
  • Issues: issue connection polls, at their next poll time, while the owner switch is on.
  • Digest: weekly digest emails at each user's chosen hour, while outgoing email is configured.
  • Rules: queued rule events at once, time triggers at the minute.
  • Backup: scheduled backups; a missed run executes once at startup.
  • Housekeeping:
    • Retention deadlines. Each runs when the oldest item passes its retention: Trash retention (OPENTODO_TRASH_RETENTION_DAYS), the audit log (the owner's retention), expired sign-ups, the 30-day delivery logs and read notifications after 90 days.
    • Upkeep. Hourly, and only after something changed: PRAGMA optimize, the delivery logs' size limits, the rule run log, and secrets of deleted connections.
  • Compaction: a day after its last complete pass (an hour after start-up for the first), and only after something changed: deletes superseded note versions received more than 30 days ago (sync.CompactNotes), returns freed pages with incremental vacuum and converts an older database once at a quiet moment; a pass larger than its 20-second budget continues a minute later. See sync.md.
  • Checkpoint: about a second after a change, copies the write-ahead log back into the database (store.CheckpointWAL, PRAGMA wal_checkpoint(PASSIVE)) from the reader pool, beside the writer, so no commit pays for it; a checkpoint a reader kept from finishing runs again a second later. When the log file is over 64 MB it is also truncated (TRUNCATE, which waits for readers and holds writes meanwhile). The writer's own automatic checkpoint is only a backstop at 10,000 pages (about 40 MB) for a process that runs no jobs. A host keeps no due time for it after a tenant closes: closing the database checkpoints what is left.
  • Email (only when OPENTODO_EMAIL_* is set): polls the IMAP mailbox every OPENTODO_EMAIL_POLL_SECONDS.
  • Demo (demo instances only): expired sandboxes every 5 minutes, the reset at 03:00 UTC.

Server packages (cmd/opentodo, internal/)#

Package Responsibility
config OPENTODO_* environment variables with defaults and validation; nothing is mandatory
codesize Test only: go test ./... fails when a function under internal/ is longer than 150 lines or a file longer than 1,100 lines; exceptions need a reason, and the list can only shrink
writepaths Test only: go test ./... fails when code outside sync uses Apply instead of ApplyStrict, or SQL writes the synced tables (ops, op_scopes, scope_fields, purges, project_scopes), at a place not allow-listed with its reason
store Opens SQLite (pure-Go modernc.org/sqlite, WAL, synchronous=NORMAL): one writer connection whose write transactions begin IMMEDIATE and whose automatic checkpoint is only a backstop (wal_autocheckpoint 10,000 pages; the checkpoint job copies the log back, CheckpointWAL), and a pool of query-only reader connections (OpenReader) for pure reads such as sync List, Get and Pull; applies embedded migrations (migrations/NNNN_*.sql) by PRAGMA user_version; runs PRAGMA optimize at open (and the housekeeping job hourly after changes); Lock holds <data>/opentodo.lock for the process lifetime. Its sub-package storetest gives tests a copy of one migrated template database instead of migrating a new one
stt Speech to text: the owner's OpenAI-compatible transcription service (OPENTODO_STT_* overrides, key in <data>/secrets/stt.json), requests through outbound, audio and text in memory only. See speech-to-text.md
daypart A task's part of the day (OpenSpec day-parts): reads Morning, Afternoon or Evening from day_part and the evening flag, and the pairing every server writer uses (REST, CalDAV, the agent tools, the CLI and the vault), like web/src/lib/dayParts.ts. See day-parts.md
frames Calendar frames (OpenSpec calendar-frames): the occurrences of a user's recurring background windows for a date range, weekday lists and HH:MM wall times, kept identical to web/src/lib/frames.ts by shared vectors; used by the frames REST routes and the list_frames agent tool
freetime Free time (OpenSpec assistant-time-blocks): the stretches of each day within the working day that no calendar event, frame, slot or timed task takes, as the calendar draws them, kept identical to web/src/lib/freeTime.ts by shared vectors; used by the find_free_time agent tool (the device has its twin) and the assistant's free time block
closedlist Today's closed list (OpenSpec today-closed-list): fills the slots of the Today limit first come, first served (focus, taken slots, Earlier, creation order) with the available rule passed in, like web/src/lib/closedList.ts (shared vectors); used by today_summary and ot today
urgency The urgency score (OpenSpec urgency-sort): one derived number per open task from its due day, deadline, priority, the tasks it blocks, its age, a running timer and the blocked, deferred and Someday terms, kept identical to web/src/lib/urgency.ts by shared vectors; used by list_tasks with sort: urgency and ot list --sort urgency
textutil Small string helpers shared by server packages: Truncate cuts a string to a byte limit on a character boundary, for names and messages stored under a length limit
tenant Builds one server around one data directory: the database and its lock, the services, the notifier, the HTTP handler and the background jobs. A self-hosted server opens exactly one tenant. Its sub-package services is the composition root: Build constructs, seeds and wires every service into a Set, which httpapi.New receives; registering routes builds nothing
jobs The one model of background work (change one-job-model): Job{Name, Next, Run} says when a job is next due and what to run; tenant.Jobs builds a tenant's list once, and both a self-hosted server (Runner) and a host's scheduler run it. Services report new work through a Signal; Upkeep is maintenance due only after a change; Runner sleeps until the earliest due time, wakes on a signal, waits a retry pause when work is still due after a run, and never runs a job twice at once
ratelimit Rate limits and AI agent limits that survive a restart (change persistent-limits): a Store over the tenant's database loads the windows still open, hashes every key with a per-database salt, and writes the windows its Parts changed through the tenant's limits job and on close; checks stay in memory. Times is the sliding-window part the relay and outgoing email use; httpapi's limiters and agenttools.Limiter are parts of their own
host Optional multi-tenant host, built only with OPENTODO_HOST_URL: a registry of tenants beside their data directories, host-name routing, lazy open and idle close, one scheduler for every tenant's background work, per-tenant limits and the operator interface a control plane drives
settings Owner-level key/value settings (settings table, JSON values), the owner on/off switches (Switch: cached, with a default and an optional environment override) and 0600 secret files under <data>/secrets/
sync Op schema and validation, Apply (idempotent, LWW, per-op authorisation and refusal reasons) and ApplyStrict (REST), Pull (cursor, member backfill), materialised reads, sharing scopes (scope.go) and membership (members.go), trash, history and purge, the post-commit observer and sinks, Notifier (per-user live wake-ups)
auth Users and roles, argon2id passwords, sessions, API tokens and their scopes, CalDAV app passwords, invitations, password resets, user administration, TOTP and recovery codes, step-up, passkeys storage, provider identities (subject-first matching, verified-email linking, provisioning, the SSO-only rule)
webauthn Passkey verification: clientDataJSON, authenticator data, COSE keys (ES256, Ed25519, RS256), signature checks; uses fxamacker/cbor for CBOR (the other third-party Go modules are SQLite and golang.org/x/crypto for argon2). testauth is a synthetic authenticator for tests
mcpoauth The OAuth 2.1 authorization server in front of the MCP endpoint (OpenSpec mcp-oauth): registered clients, the table of known AI connector platforms and their redirect addresses (Gemini, ChatGPT, Claude; mcp-oauth-connector-redirects), single-use authorization codes, grants with a refresh token that rotates on every use and revokes the grant when an old one comes back (Google's connector keeps one token, as its guide requires; mcp-oauth-refresh-rotation), and the PKCE check, over SQLite. Storage and cryptography only: no HTTP and no policy, since httpapi/mcp_oauth.go owns the endpoints and mints the access token through auth, so an OAuth access token is an ordinary API token
oidc Single sign-on with one OpenID Connect provider, standard library only: discovery, PKCE, code exchange, JWKS cache, identity-token verification, the signed flow-state cookie, owner configuration and OPENTODO_OIDC_* overrides. oidctest is an in-process provider for tests. See self-hosting/sso.md
audit The closed catalogue of security events with typed constructors and an allow-list for details, recording (in the same transaction as credential changes), queries, NDJSON export and retention pruning
outbound The policy for every request to an address a user or the owner typed: http(s) only, no private network targets unless the owner allows them, the connection pinned to the address that was checked. Used by webhooks (and through their client by push and the assistant), by calendar subscriptions and by issue connections
demo The public demo instance (OPENTODO_DEMO=true): a hidden owner, a private short-lived sandbox per visitor seeded through the op log, the nightly reset; the HTTP side and its deny list are in httpapi/demo.go
httpapi Router (stdlib net/http with method patterns), middleware (auth, origin check, security headers, rate limits, logging), JSON error envelope, handlers for every /api/v1 route, the CalDAV app passwords and switch (caldav.go), the MCP transport (mcp.go) and the event stream. Its sub-package httpx holds what route packages share with it (the route policy and Router, the JSON envelope and body helpers, the caller of a request); route packages register through that Router and never build a mux: speech (speech to text), maproutes (the map proxy) and davroutes (the CalDAV endpoint /dav/)
web Embeds the Vite build (internal/web/dist) and serves it with SPA fallback and cache headers
notify Post-commit events for people: the Sink interface the sync service calls after a batch commits, and the in-app sink that stores notifications for assignments and mentions
channels A person's delivery channels (ntfy, Pushover, Gotify, a signed webhook): a notify sink and a consumer of the reminder scheduler that queue one message per channel and firing, one worker through outbound with the webhooks' retries, secrets in <data>/secrets/notification-channels.json. See notification-channels.md
activity Pure derivation of attributed activity events from ops (fold by actor and entity within 5 s, classify by touched fields, page newest first); mirrored by web/src/lib/activity.ts and pinned by a shared fixture
webhook Maps observed changes to events, durable queue in SQLite, one worker with retries, HMAC signing, SSRF-safe HTTP client. See webhooks.md
deliveryq The machinery of the two durable outbound queues, webhook deliveries and notification channel messages: the parallel pass over due rows (Fanout, Drain), pruning the log, and the next-due times of the webhooks job. Each queue keeps its payloads, its send and the recording of an attempt (the retry schedule is webhook.Backoff)
compaction The notes compaction job (change notes-compaction): schedules sync.CompactNotes, reclaims freed pages with incremental vacuum, converts an older database to incremental mode once (quiet moment, free disk check), and keeps the report (settings key compaction.last) that GET /api/v1/settings/storage and the Database storage card show
poll The pass shared by the subscription pollers (calendar feeds, issue connections): Each handles the items due now with bounded concurrency; when a pass runs is the jobs' business
push Web push for reminders with the standard library: VAPID key pair in <data>/push_vapid.pem, ES256 JWTs, RFC 8291 aes128gcm, per-device subscriptions and the scheduler. See reminders.md
recurrence Parser and next-occurrence calculator for recurrence rules; mirrored by web/src/lib/recurrence.ts against shared vectors. Compatible is the form every writer stores, the one 1.0 reads when it means the same thing; recurrence10 is the frozen 1.0.0 grammar that the writers' tests check against (test-only). See recurrence.md
quickadd Go port of the quick-add parser (web/src/lib/nlp): dates and times, #project @label p1 +30m, recurrence and reminder phrases in nine languages, kept identical by shared vectors; used by the CLI and the importer
zoned Resolves time-zone-fixed due values to instants (gaps and overlaps included); mirrored by web/src/lib/dates.ts against shared vectors
defaultreminder The default reminder rule: the reminder a person's write adds when a task gets a due date, its once-per-task id and the switch between a date only and a time; mirrored by web/src/lib/defaultReminder.ts against shared vectors and used by the REST task routes (?default_reminder=true) and the agent write tools
flow Project and section flows (Parallel, Sequential, Area) and the one "available task" rule: blocked, waiting in sequence, Someday and deferred; mirrored by web/src/lib/flow.ts against shared vectors and used by the agent tools, the MCP resources, the digest and the CLI
sector Time sectors: validity of a task's week, month or quarter, the viewer's current periods, relative names, carry-over and the planning list's groups; mirrored by web/src/lib/sectors.ts against shared vectors and used by sync, REST, CalDAV, the vault, the agent tools and the CLI
kept Kept subtasks: open under a live completed ancestor, left out of lists, counts and reminders; mirrored by web/src/lib/subtasks.ts against shared vectors and used by the agent tools, the digest, the push scheduler and the CLI
inbox Inbox membership: open, without a project and not scheduled (no do-on date, start date, Someday or time sector), with no placed parent; mirrored by web/src/lib/inbox.ts against shared vectors and used by the agent tools, the MCP views and the CLI
habits Habit numbers (OpenSpec habits-assistant): scheduled dates, day states, kept, strength, streaks, at risk and back on track over a habit's lineage and records, the answers of list_habits, get_habit and the habits route, and the log planner of log_habit; mirrored by web/src/lib/habits.ts against shared vectors
notelinks Note links (note-links D1, D5): the internal link grammar of a note's Markdown ([title](?note=<id>), ?task=, ?project=, outside code spans and fences); mirrored by web/src/lib/noteLinkGrammar.ts against shared vectors and used by MCP get_note/get_task (links, linked_from, plaintext accounts only), ot notes links and the perf fixture. The backlink index lives on the device (web/src/lib/noteLinks.ts)
notesearch Note search (notes-overview D4): normalisation (NFKD, marks removed, lower case), Markdown stripping, phrases, matching, ranking (title matches first) and highlighted snippets; mirrored by web/src/lib/noteSearch.ts against shared vectors and used by the note agent tools and ot notes search
reuse Reusable lists (reusable-lists D2, D4): title normalization, the item an add matches and the duplicates a device collapses; mirrored by web/src/lib/reusable.ts against shared vectors and used by POST /api/v1/tasks with reuse and the create_tasks agent tool
filter Go port of the filter query parser, used to validate saved views; evaluation stays on the client. See filters.md
origin A task's origin (where it came from): the one validation of the task.origin value (the sync schema's check, the CLI, the agent tools, the importers, email to task) and the table that recognises GitHub, GitLab, Jira and Linear issue links, kept identical to web/src/lib/taskOrigin.ts by shared vectors. Never requests a URL. See capture.md
timetrack Tracked time (OpenSpec time-tracking): the one-running-entry rule every device and the time entry routes apply, an entry's minutes and the day it belongs to, typed durations (45m, 1h30) and the time entries CSV, kept identical to web/src/lib/time.ts by shared fixtures. See time-tracking.md
importer Reads the own export, CSV and other apps' JSON exports into rows, plans projects, labels, parents and duplicates, and writes ops in background jobs with undo. sanitize is a command that turns a real export into a test fixture; it is never linked into the server. See import.md
blobs Attachment bytes as immutable files under <data>/attachments/, written once through a temporary file with the size and SHA-256 checked, streamed and never read whole. See attachments.md
calfeed Calendar feeds: other people's calendars read into read-only events (fetched through outbound), and the user's tasks written as an iCalendar feed. See calendar-feeds.md
ruleval Automation rule values (trigger, condition, actions) with their checks and the condition matcher; a leaf package sync uses for the rule entity's kinds, pinned to the web matcher by web/src/lib/rules/match.vectors.json. See automations.md
rules Automation rules engine: the planner (shared fixture with the web planner), the post-commit observer, the durable queue, the worker with limits and loop depth, the minute scheduler for time triggers and the run log; the owner switch with OPENTODO_AUTOMATIONS. See automations.md
davpush Push to calendar apps: the WebDAV-Push subscriptions of CalDAV clients (a side table, never an op) and the job that pushes a subscribed calendar's change, encrypted and signed by push, at most once per subscription every 30 seconds, behind the owner switch caldav.push. See caldav.md
calsync Calendar sync: a user's own CalDAV, Google or Microsoft (Outlook, Microsoft 365) calendar receives their dated tasks as events and sends changes back. Connections, secrets in <data>/secrets/calendar-sync.json, a WebDAV client on outbound (discovery, sync-collection, conditional writes), a Microsoft Graph client (delta cursors, an extended property on OpenTodo's events, conditional writes) behind the same transport interface, Google and Microsoft OAuth with PKCE, and the cycle on the jobs leader that pulls before it pushes and writes ops with device calsync:<id>; shown calendars are stored as managed calfeed subscriptions. calsynctest is an in-process CalDAV server and graphtest an in-process Microsoft sign-in and Graph for tests. See calendar-sync.md
syncscope The part of an account a calendar sync connection or a CalDAV app password covers: all, only or except chosen workspaces, projects and Inboxes. Stored in a side table of the connection or the app password, never an op; CalDAV hides calendars outside it and calendar sync reads its tasks through the same view. See calendar-sync.md and caldav.md
issues Issue import: per-user GitHub and GitLab connections, tokens in <data>/secrets/issues.json, two REST clients on outbound without redirects, the mapping of issues to task ops (deterministic ids, a field changes only when the issue changed it) and the poller on the jobs leader. Never writes to the provider. See issue-import.md
backup Snapshots (VACUUM INTO), tar/gzip archives, OTBK1 encryption, local / S3 (SigV4) / WebDAV destinations, scheduler, retention, Restore. See backups.md
caldav Protocol pieces of the CalDAV endpoint: iCalendar tokenizer and serialiser for VTODO, the VTODO ↔ task mapping (unmapped lines kept in ical_extra), WebDAV XML parsing and multistatus rendering; HTTP handling lives in httpapi. capture is a command that turns a client's request log into sanitised fixtures for the verification runs, never linked into the server. See caldav.md and caldav-verification.md
mcp Model Context Protocol server: a JSON-RPC 2.0 subset that serves the tools of agenttools (read tools always; write tools behind the owner's switch, the user's switch and an agent token) and read-only opentodo:// resources, plus the owner switches. See mcp.md
relay Device relay for encrypted accounts (mcp-device-relay): opted-in devices bound to their session, an in-memory hub that sends each MCP call's decrypt and encrypt requests, sealed per stream (ECDH P-256, HKDF, AES-GCM), to one of the account's online devices and waits for the answer within the relay limits. Never stores, caches or logs a relayed value
agenttools The one registry of tools an AI agent can call (definitions, argument validation, planning into change sets, untrusted-text marking, write limits, the write permission gate, agent.write audit), shared by MCP and the in-app assistant; writes only through ApplyStrict. Also the per-user "Allow AI assistants to make changes" switch
assistant The in-app assistant: the owner's configuration and provider keys, per-user consent and token usage, the model providers (Anthropic through the official Go SDK, one standard-library Chat Completions adapter for OpenAI, Gemini and compatible endpoints) and the agent loop that runs read tools and plans write tools without applying them; the browser applies the confirmed part. See assistant.md
email Email to task: minimal IMAP client (TLS or STARTTLS), MIME parsing to title and description, sub-address routing, per-account inboxes, limits and the poller. See email.md
location A task's location and a saved location's coordinates: the one validation every write path uses (sync, REST, the importers). See locations-and-places.md
maps The map proxy: the owner's switch with OPENTODO_MAPS* overrides, the provider's style rewritten so every URL points back to the server, tiles, fonts and sprites cached under <data>/cache/maps (LRU, capped, never backed up), and Photon search. No viewer data reaches the provider. See self-hosting/maps.md
mail Optional outgoing email: the owner's SMTP configuration with OPENTODO_SMTP_* overrides, a standard-library SMTP transport with an explicit TLS policy, plain-text templates in ten languages, sending limits and audit events; every message goes through Service.Send. smtptest is an in-process SMTP server for tests
digest The opt-in weekly email digest: per-user settings, the scheduler on the jobs leader, and the content built from the user's materialised rows with the same definitions as the Statistics screen
e2ee Server side of end-to-end encryption: stores the wrapped key record with optimistic versioning, recognises ciphertext so server-side features degrade explicitly, purges superseded content ops. The server runs no content cryptography; its sub-package crypt is the same format for the ot client only (ot encryption, ot mcp --decrypt), on the standard library, pinned by the shared vectors and never linked into the server. See e2ee.md
websign The signed web app's file list (OpenSpec signed-web-app): reads app-manifest.json (an envelope around the exact bytes of a manifest naming every file of the web app with its SHA-256), verifies its ECDSA P-256 signatures, computes key fingerprints, orders versions and checks a build's files; the official keys and the report-only switch are in release-keys.json. The server links it for its startup line; its sub-package sign (key generation, signing) is linked only by cmd/websign (keygen, sign, verify), never by the server. See Signed app code
ids UUID v4, name-based ids (SHA-256, version 8 UUIDs, for recurring occurrences and tasks created from email) and random secrets
templatelib The template library on the server: library.json, the same compiled file as web/src/generated/templates.json (both written by make templates), read for a routine's Create a project from a template step, with the library's offsets resolved from a start day (routines-engine)
imgfit Scales the images the server stores, on the standard library alone: the centre square of a sign-in provider's picture to 256 px, the owner's logo to every icon size and a padded maskable icon (oidc-profile-pictures, instance-branding)
themes The theme document format (OpenSpec themes): Validate checks a document against format 1 (seeds, the token list, colours as #rrggbb or in-gamut oklch(), shape, type, 16 KB) with the same refusal codes as web/src/lib/theme/format.ts, both pinned by the shared examples in testdata/; Migrate brings an older format to the current one. No derivation and no renderer: the server never draws a theme. See themes.md
iconset The icon catalogue's names, categories and keywords, generated from web/src/ui/icons/catalogue.json and checked against it by a test; Valid checks an icon name in REST and MCP writes, Search orders matches as the app's icon picker does
cli The ot command-line client (cmd/ot): profiles, REST calls, table and --json output. See cli.md
perfseed The 10,000-task account of the performance budgets, for cmd/perfseed only (a test keeps it out of the server): built from a fixed seed through the op log (device perfseed), an encrypted variant, a summary of counts and ids; its tests are the server's count checks at that size. See performance.md
perf The server half of the nightly time benchmark (built only with the perf tag): the server binary on copies of the fixture, every server budget of scripts/perf/budgets.json five times, memory from /proc
vault The Markdown vault behind ot vault, for the client only (a test keeps it out of the server): the Obsidian Tasks line grammar, the document parser and printer, the state file, the three-way merge per field and the sync loop over POST /api/v1/sync as device vault:<id>. See vault.md

Tables#

Area Tables
Op log and current values ops (append-only, user_id = author, seq autoincrement), op_scopes (the sharing scope of each op), scope_fields (winner per field within a scope), purges (markers for permanently deleted entities)
Sharing project_scopes, project_members (effective roles, outside the op log; via names the groups a role comes from), project_grants (direct and group grants; project_members is recomputed from them), member_backfills (history replay per member device)
Workspaces workspaces (one default per account), workspace_members, groups, group_members, workspace_invites (hashed link secrets)
Accounts and credentials users, user_status, sessions, session_auth, session_oidc, api_tokens, api_token_scopes, api_token_agent, user_agent_access, app_passwords, passkeys, identities, mfa_totp, mfa_recovery_codes, trusted_devices, invitations, password_resets
Features notifications, push_subscriptions, notification_channels, notification_deliveries, webhooks, webhook_deliveries, import_jobs, import_items, caldav_resources, email_inboxes, email_receipts, encryption_keys
Operations settings (owner key/value settings, also the log generation), audit_events, backup_runs

Files in the data directory: opentodo.db (plus WAL files), opentodo.lock, push_vapid.pem, secrets/ (backup and single sign-on secrets, 0600, never archived) and backups/ (default local backup folder).

Client (web/)#

Module Responsibility
lib/db.ts Dexie database: projects, tasks, labels, views, reminders, sections, comments, prefs (synced project_prefs), outbox, meta (device settings), plus caches (memberships, notifications) and the local activity log
lib/types.ts Entity types; each extends its op fields from generated/opSchema.ts, which internal/sync generates from Schema with the row defaults and content fields
lib/hlc.ts Hybrid logical clock and the shared wins() rule
lib/ops.ts applyOps (per-field LWW into IndexedDB, merge-and-republish of note documents), mutate (local apply + outbox + notify), entity helpers and defaults
lib/sync.ts Background push/pull loop, triggers, live-update channel (EventSource with backoff), status store (useSyncStatus)
lib/api.ts Fetch wrappers and ApiError
lib/e2ee.ts, lib/crypto.ts, lib/e2eeSync.ts End-to-end encryption: key record handling, AES-256-GCM field encryption, encrypt at upload and decrypt before apply
lib/nlp/ Natural-language quick add (tokenizer, dates, attributes, languages)
lib/filter/, lib/filters.ts Filter query parser and evaluator, duration predicates
lib/recurrence.ts, lib/recurring.ts Recurrence grammar and the completion, skip and detach flows
lib/dates.ts Floating and zoned due values
lib/ordering.ts, lib/dnd.ts Fractional positions and pointer drag and drop (no library)
lib/reminders.ts, lib/reminderTime.ts, lib/reminderWatcher.ts, lib/push.ts Reminder writes and time arithmetic, the in-app watcher, the device's push subscription
lib/comments.ts, lib/activity.ts, lib/feed.ts, lib/markdown.ts Comments and mentions; the shared activity rule, local recording and merging of older server pages; the cross-project feed and unread counts; the in-house Markdown subset (rendered by app/Markdown.tsx as React elements, so raw HTML never reaches the DOM)
lib/docfields.ts, lib/richtext.ts, lib/richtextEditor.ts, app/NotesEditor.tsx Rich-text notes (sync.md): the document field list and lazy loader; the Yjs document code (envelope, merge, growth check, Markdown projection); the ProseMirror schema and binding; the editor component. The last three are lazy chunks
lib/share.ts Parsing of share-target and bookmarklet payloads
public/push-sw.js Imported by the service worker: push, notificationclick (snooze and dismiss written as ops into the outbox), notificationclose
sw.ts, lib/appInstall.ts, lib/appCode.ts, lib/appTrust.ts, lib/pagePolicy.ts The service worker: it installs and serves the app from the signed file list app-manifest.json (written by scripts/app-manifest.mjs), checking each update's signature, version and file hashes (report-only for now, Signed app code); the trust record; the page policy it writes
app/ Router, auth screens, shell, views (lists, board, calendar, filters, dashboards, feed, trash), detail panel, settings panels, Vim layer (app/vim/, lazy)

The UI never talks to the server for task data. Views subscribe to IndexedDB with useLiveQuery; local edits and remote ops surface through the same path. Screens in web/src/app never open IndexedDB themselves: they read through web/src/lib (localData.ts and liveTasks.ts, enforced by ESLint), where widely read tables (tasks, projects, labels, memberships, views, preferences, field definitions) each have one shared live snapshot instead of every component scanning the table on every change, and where one visibility rule decides which projects a screen sees (live ones, archived included; browsing lists narrow them with visibleProjects; only the Trash, history and statistics read deleted ones). Shared UI in web/src/ui, overlays included, never imports a screen. Account-level screens (users, audit log, backups, webhooks, tokens) call the REST API directly and need a connection.

Build and packaging#

web/ builds into internal/web/dist, which go:embed compiles into the binary (internal/web/dist/.gitkeep keeps the embed compiling on a fresh clone). The Dockerfile runs both builds on the build platform, cross-compiles a static binary (CGO_ENABLED=0, -trimpath -s -w) and copies it into gcr.io/distroless/static-debian12:nonroot. CI publishes linux/amd64 and linux/arm64 images to GHCR and attaches the server and ot binaries, the browser extension zip, the agent skill and the site bundle (opentodo-site-bundle-<version>.tar.gz: the docs website, screenshots, colour tokens, icons, the brand mark, changelog and a feature manifest, which the website repository builds from) to releases; every CI run on main and in the merge queue that changes the docs uploads the same bundle as an artefact. The server binary is about 41 MB for linux/amd64, as released (about 5 MB of it is the official Anthropic SDK for the in-app assistant, about 1.6 MB the five interface language catalogs). Nothing in the server may use text/template, html/template or reflect.Value.MethodByName: any of them stops the linker from pruning unused methods and adds about 13 MB.

Specs#

Behaviour is specified in openspec/specs/<capability>/spec.md (live) and proposed in openspec/changes/; shipped changes are archived under openspec/changes/archive/. See CONTRIBUTING.md.

Edit this page on GitHub