Architecture¶
How relaybay is built. Behaviour is specified in SPEC.md; upcoming work is in the roadmap and the design documents; single decisions are ADRs (HTMX + SSE, desktop shell).
Goal and boundaries¶
relaybay gives a person who runs many Claude Code sessions across many repositories one live view of the work: projects → tasks → stages → reports, and which session is doing what right now.
- relaybay listens: sessions call its MCP tools and Claude Code's hooks post events to it. Its only outbound calls are the update check of the latest GitHub release (the server's and the desktop program's, both opt-out) and, when the user clicks Update in the program, the download of that release's installer (SPEC §13).
- It contains no LLM client, no Agent SDK and handles no credentials. Agents are always the ordinary
claudeCLI or desktop app under the user's own login, and relaybay starts none: a card is worked by a desktop session bound to it. Runs inside the program (0.9 to 0.11) were removed in 0.12 (design 0025). - Single user, local machine. No accounts, no cloud hosting, no issue-tracker sync.
Processes¶
Claude Code sessions (CLI, desktop app) Browser (desktop / phone)
│ MCP, Streamable HTTP │ hooks │ HTML (htmx) ▲ SSE /events
│ │ command hook ─► POST │ POST forms │
▼ ▼ ▼ │
┌───────────────────────── relaybay process (uvicorn) ─────────────────┴────┐
│ SecurityMiddleware: Host allow-list, Origin, token / cookie, CSRF, headers │
│ /mcp mcp_server ─┐ │
│ /hooks web/hooks ─┼─► Service ──► SQLite (WAL) │
│ / web/routes ─┘ │ state change + event row, one transaction │
│ ▼ │
│ EventBus (asyncio, in-process) ──► SSE fan-out │
└────────────────────────────────────────────────────────────────────────────┘
▲
│ reads/writes only ~/.claude/settings.json, on an explicit command
relaybay setup (CLI process, or the Integrations page in the server)
- One process, one writer. MCP, hooks and the board live in one uvicorn process. Every write goes
through
Service, which updates state tables and appends aneventrow in the sameBEGIN IMMEDIATEtransaction and publishes the event on the in-process bus after commit. While a server runs no other process writes the database, so there is no cross-process notification and SQLite locking stays trivial. Outside a running server two commands open it:relaybay import --applymigrates and writes it through the service, and a new version's first start (server or import) copies it intobackups/first (backup.py, SQLite's backup API). - Short-lived helper processes never touch the database:
relaybay tokenandrelaybay setup --checktalk to the server over HTTP; the command hook is a standard-library forwarder started by Claude Code for each hook event:relaybay-hookfrom the installed program,python -I -m relaybay.hook_clientfrom a source or Python install. - Events are the sync protocol.
event.idis monotonic and is the SSE id; a reconnecting browser sendsLast-Event-IDand gets the newer rows replayed. State tables are the source for reads; the log is for the feed, catch-up (events_since) and audit ("event-sourcing lite", no projections to rebuild).
Modules (src/relaybay/)¶
| Module | Responsibility |
|---|---|
__main__.py, cli.py |
relaybay [serve], token, setup, doctor, demo, import, export, desktop, hook; standard-library argparse |
config.py |
Settings: defaults → config.toml → RELAYBAY_* → flags; data dir via platformdirs |
app.py |
FastAPI app: lifespan (service start, MCP session manager), routers, static files, middleware; OpenAPI and docs UI disabled |
security.py |
Token file, cookie and CSRF values (HMAC of the token), token_id, SecurityMiddleware (pure ASGI, so streams pass through) |
service.py |
Use cases (create_task, set_stage, add_report, record_hook, …): validation, rules checks, transaction, event append, publish |
events.py |
EventBus: one bounded asyncio.Queue (256) per subscriber, optional project filter; a full queue drops the subscriber, which then resyncs |
db/ |
connection.py (aiosqlite, WAL, foreign_keys, busy timeout, numbered migrations by user_version), repo.py (SQL), migrations/*.sql |
domain/ |
Models, stages, report parsing, task field list, rules (validate, merge, hash, check), sessions, hooks parsing, environments (access fields, secret checks, levels, proposals), the PreToolUse guard (identifier matching, mutating heuristics, decisions), the card's state line and its Open (card.py), digests (digest.py: gathered data to sections to budgeted text, no I/O), questions to the owner (questions.py: the rules of asking, the answer's text), approvals (approvals.py: what a tool call does as an action and its target, which approval covers it, the decision's text), quoting of external text kept from intake (intake.py), errors |
mcp_server/ |
server.py: MCPServer with the instructions, tools and resources, mounted at exactly /mcp; format.py: markdown output |
web/ |
routes.py (pages with the sidebar, Inbox, Sessions, Activity with the live journal, project Settings, fragments, forms, comments, /events, Integrations), sse.py, hooks.py (POST /hooks/claude-code and the wake-up long poll …/wait), api.py (GET /api/notifications for the tray), markdown.py, templates, vendored static assets |
machine_setup.py |
relaybay setup: detect, plan, marked JSON merge with backup, plan hash, remove, check (server and Claude Code file checks, shared with doctor) |
doctor.py |
relaybay doctor: read-only diagnosis built from the setup checks plus versions, data folder, token and rules hash |
demo.py |
relaybay demo: seeds the demo workspace through the service layer |
markdown_import.py, markdown_export.py, domain/markdown_layout.py |
relaybay import and export: the markdown layout, a plan with a hash on a copy of the database, writes through the service, the export manifest |
hook_client.py |
The command hook: stdin → POST → stdout (a 200 JSON answer only), always exit 0; the guard and tool calls one 0.3 s try (5 s for a call that may need an approval), state-bearing events a retry and the spool (hook-spool.jsonl in the config folder, sent first by a later run); with --wait the wake-up hook (long poll, exit 2 with the comment on stderr) |
logs.py |
uvicorn log config that redacts the /login query string |
policy/ |
Policy as data: layers (preset, legacy config.toml keys, policy.json, project, environment) merged into an effective policy with the source of each value; schema.json, presets/*.json |
install.py |
How this copy was installed (install_kind()), its executable and whether its location is stable; used by upgrade hints, the updater, doctor and the hook command |
updates.py |
The update check of the latest GitHub release and the installer download, checked against SHA256SUMS.txt |
backup.py |
last_version and the backup of the database and settings files before a new version migrates, with rotation (backup_keep) |
gitinfo.py |
Reads of git for the approval check: which branch a folder has checked out, under a time limit; never a write |
desktop/ |
The desktop program: GUI loop and window (pywebview), tray (pystray), embedded server thread, desktop.toml settings and Settings window, start at login, single instance, window state, tray notifications |
Data model¶
project id, slug UNIQUE, name, repo_path, description, task_seq, created_at, updated_at,
archived_at, pulse, pulse_at, pulse_by
-- repo_path: always the path of the first project_repo (kept for older readers)
project_repo id, project_id, name (UNIQUE per project), path (as written),
kind (app|web|api|lib|other, optional), position, created_at, updated_at
task_repo id, task_id, project_repo_id, added_by, how (auto|agent|owner), added_at, branch,
worktree
-- UNIQUE (task_id, project_repo_id)
task_pr id, task_id, project_repo_id (optional, SET NULL), url (http/https), number,
title, added_by, added_at -- UNIQUE (task_id, url)
task_block id, task_id (CASCADE), blocker_id (CASCADE, a task of any project), created_by,
created_at -- UNIQUE (task_id, blocker_id); blocks while the blocker is in
plan|dev|review|test, read from its stage
task_doc_section id, task_id (CASCADE), document_id (CASCADE), anchor (as linked), created_by,
created_at -- UNIQUE (task_id, document_id, anchor); task_doc_link
project_area id, project_id, name, color (a palette key), position, created_at
-- UNIQUE (project_id, lower(name)); at most 24 per project (the service)
task id, project_id, key UNIQUE, title, stage CHECK(plan|dev|review|test|live|done), stage_note,
waiting_on, next_step, branch, doc_path, description, progress, session_id,
priority, version, tracker_ref, tracker_name, tracker_url, tracker_logged,
deploy_notes, deploy_done, cancelled, cancelled_at,
next_step_at, stage_changed_at, created_at, updated_at, closed_at, size (S|M|L),
plan_status (draft|accepted), plan_accepted_at, plan_accepted_by,
archived_at, archived_by, unarchived_at (the hand archive of a done task),
rank -- the owner's order within the stage column, lower first; INDEX (project_id, stage, rank)
area_id -- project_area, ON DELETE SET NULL
report id, task_id, session_id, author, state, size, summary, body_md, created_at
report_check id, report_id, line, location (the `where` of `verified: <where>`), claim
-- INDEX (report_id, line); parsed when the report is written
report_item id, report_id (CASCADE), task_id (CASCADE), kind (finding|question), n, title
(a question's text), body, location, item_kind, area, question_default,
backlog_id (SET NULL), dismissed_at, dismissed_by, dismiss_reason, created_at
-- UNIQUE (report_id, kind, n); open while neither backlog_id nor dismissed_at
time_mark id, at (UTC), kind (start|pause|switch), task_id (SET NULL), task_key, project_id
(SET NULL), label, actor, session_id (SET NULL), created_at, updated_at
-- CHECK a pause names no card, start|switch exactly one of task_key and label;
INDEX (at, id), (task_id); the day time log, spans derived (domain/timelog.py)
tracker_worklog id, task_id (SET NULL), task_key, project_id (SET NULL), day (local), minutes
(-1440..1440, not 0), ref, reason, actor, session_id (SET NULL), created_at
-- append-only; INDEX (task_id, day)
decision id, task_id, project_id, text, decided_by, created_at, scope (project|task),
source_kind (report|event|comment|message), source_ref, source_text, valid_from,
valid_to, recorded_at, superseded_at, superseded_by (decision.id), area (a name)
document id, project_id, slug (UNIQUE per project), title, kind, version, created_at,
updated_at, source_url (set: lives in a repository)
document_version id, document_id, version (UNIQUE per document), body, author, reason,
base_version, section, created_at
memory id, scope (global|role|project), project_id, role, kind
(user|feedback|project|reference), title, body, tags, source_kind, source_ref,
source_text, links, review_at, valid_from, valid_to, recorded_at, updated_at,
superseded_at, superseded_by (memory.id), last_read_at, read_count, version, author
memory_block id, scope (global|project), project_id, label, description, body, char_limit,
owner_only, version, updated_by, updated_at, created_at
-- UNIQUE (COALESCE(project_id, 0), label)
search_index FTS5 (kind, ref, project_id, title, body, stems), created at start when SQLite has
FTS5; rebuilt from the tables when its row count is off
session id, external_id UNIQUE (local_<uuid>), name (unique among rows without external_id),
project_id, cwd, kind, desktop_link, status (working|idle|waiting|ended), activity,
cc_session_id UNIQUE, cc_exact, activity_at, unlinked_reason,
no_live_at, no_live_by, last_seen_at, created_at
app_setting key PK, value, updated_at, updated_by
-- the tables of runs, schedules, usage, budgets, the brake, session messages
-- and intake of 0.4 to 0.11 were kept unread from 0.12 and dropped by
-- migrations 0058 and 0059
question id, task_id, run_id (unread since 0.12), session_id (who asked), asked_by, kind (question|look), text,
options (JSON), default_answer, blocking (0|1), look_url, look_account,
default_after, asked_at, status (open|answered|defaulted|withdrawn), answer,
answered_by (owner|default), answered_at, defaulted_at, withdrawn_at, withdrawn_by,
turn_id (unread since 0.12), comment_id (the owner comment carrying
it), told_at, delivered_at
-- a look question blocks and has its URL; a blocking one has no default_after
approval id, task_id, run_id (unread since 0.12), session_id (who asked), requested_by, requested_via
(agent|guard|denial), action (commit|push|merge|deploy|sql),
mode (plain|force|delete), repository, branch, pr,
environment_id, environment, summary, rollback, requested_at,
status (open|approved|refused|used|expired), decision, decided_by, decided_at,
decision_text, valid_until, used_at, used_by (the call: tool and masked input), used_session,
expired_at, expired_reason,
turn_id (unread since 0.12), comment_id (the owner comment carrying
it), told_at, delivered_at
reserved_at, reserved_for (the call's tool_use_id), reserved_call,
reserved_session_id, released_count
-- one approval allows one call: reserved by the guard's check, in one tx; used at
-- that call's PostToolUse
comment id, task_id, author_kind (owner|agent|external), author, session_id, body_md, in_reply_to,
created_at, delivered_at, delivered_to_session_id, read_at, step_id, attachment_id
review_step id, task_id, position (UNIQUE per task), title, details_md,
status (open|accepted|rejected), decided_at, decided_by, created_by, created_at,
updated_at
attachment id, task_id, step_id, kind (image), stored_name UNIQUE, original_name, mime, size,
sha256, caption_md, created_by, created_at
annotated_name, annotated_size, annotated_sha256, annotated_sent_sha256
-- the files: <data dir>/attachments/<project>/<task key>/<stored_name>, and
-- the latest flattened PNG beside it
annotation id, attachment_id, kind (rect|arrow|freehand|pin), colour, stroke_width,
geometry (JSON, fractions of the image size), pin_number (UNIQUE per attachment,
never reused), body_md, created_by, created_at, updated_at, deleted_at (soft delete)
annotation_reply id, annotation_id, author_kind (owner|agent), author, session_id, body_md,
created_at
plan_step id, task_id, position (UNIQUE per task), title, details_md,
status (pending|in_progress|done|blocked), done_at, link, outcome, conformance,
created_by, created_at, updated_at
plan_revision id, task_id, revision (UNIQUE per task), body (JSON: status and steps), author,
reason, created_at
session_todo session_id, cc_session_id, item_id, subject, status (pending|in_progress|completed),
active_form, position, updated_at -- PK (session_id, item_id)
task_session id, task_id, session_id, bound_at, unbound_at, bound_by -- one open row per task
session_alias name PK, session_id, created_at
tracker_entry id, task_id, tracker_name, tracker_ref, tracker_url, logged_at, unlogged_at, created_at
project_rules project_id PK, body (JSON), updated_at
environment id, project_id, name (UNIQUE per project), kind (local|test|live), base_url,
sign_in_allowed (CHECK: 0 on live), login_state_path, notes,
level (none|read|ask|full, NULL = the policy's level), overrides (JSON),
position, created_at, updated_at, updated_by
environment_access id, environment_id, kind (ssh|kubectl|db|gitops|logs|monitoring|other),
fields (JSON, references only; {"value", "test": true} for a test secret),
created_at, updated_at, updated_by
environment_proposal id, project_id, change (JSON), reason, proposed_by, session_id,
status (pending|accepted|rejected), created_at, decided_at, decided_by
policy_layer id, project_id, environment_id (NULL = the project layer), body (JSON),
updated_at, updated_by -- UNIQUE (project_id, COALESCE(environment_id, 0))
policy_proposal id, scope (global|<project>|<project>/<environment>), project_id, patch
(JSON), reason, proposed_by, session_id, status, created_at, decided_at, decided_by
rule_set id, scope (display name), project_id (NULL = global), current_version, config_hash
-- UNIQUE scope, UNIQUE COALESCE(project_id, 0)
rule_version id, rule_set_id, number, body (JSON), rendered, author, session_id, reason, diff,
notice_open, created_at -- UNIQUE (rule_set_id, number)
rule_proposal id, scope, project_id, patch (JSON), reason, proposed_by, session_id, status
(open|accepted|rejected), version, created_at, decided_at, decided_by
rule_seen session_id, project_id (0 = global), version -- PRIMARY KEY (session_id, project_id)
saved_filter id, project_id, name, stage, area, waiting_on, session, q, created_at
-- UNIQUE (project_id, name)
event id AUTOINCREMENT, ts, kind, project_id, task_id, session_id, actor, payload (JSON)
import_item kind (document|task|task_note|decision|note|backlog), item, source_path, target_id,
content_hash, target_hash, imported_at
backlog_item id, project_id, title, body_md, area, origin (session|review|intake|owner),
origin_task_id, origin_session_id, intake_message_id (a number, its table is gone), status
(new|later|planned|done|declined), decline_reason, link, priority, assignee,
task_id, decided_at, decided_by, created_at, created_by, kind
(bug|idea|question|debt), location, origin_text, triage_note, duplicate_of,
found_on
reader_cursor reader, level (portfolio|project|task), ref_id (0 = portfolio), last_event_id,
read_at -- PRIMARY KEY (reader, level, ref_id)
task.versiongrows on every write;expected_versionturns a write into a compare-and-set.- Event payloads carry the changed fields (
{"from": "dev", "to": "test"}), enough to render a feed line and to decide which fragment to refetch. - The archive by age is computed from
closed_at(or a laterunarchived_at) anddone_window_days; only the hand markarchived_atis stored. Events are kept forever; SSE replays at most the last 5000. - Migrations: SPEC §11.
Live updates and front-end¶
Server-rendered Jinja2 + htmx, no build step and no Node toolchain (ADR-0001).
GET /events(optionally?project=<slug>) streamsid,event, small JSONdata; every page uses the unfiltered stream so the sidebar's Inbox count stays live; heartbeat every 15 s;retry: 3000. The stream subscribes to the bus before reading the backlog, so nothing committed in between is lost; duplicates are skipped by id.- The page never receives HTML over SSE:
app.jsmaps an event to the fragment it affects (column, card, dialog view, comment thread, Inbox badge and list, sessions list) and asks htmx to refetch it, so replay is idempotent; the Activity page asks for the rows newer than its newest one. nav.js(loaded before the body, not deferred) applies the remembered collapsed sidebar before the first paint and runs the phone drawer.visibilitychangeandonlineforce a reconnect (phones killEventSourcein the background);resyncreloads the page.- The phone layout switches columns with radio buttons and CSS, without JavaScript.
board.jsorders the cards: native pointer events (no library) drag a card, the card's menu does the same from the keyboard; it moves the card in the page at once, posts the move, puts the card back on a refusal, and holdsapp.js's live refetches while a drag or a save is under way.
MCP transport¶
- Streamable HTTP at
http://127.0.0.1:8765/mcpinside the main process, built with the official Python SDKmcp2.x (MCPServer,streamable_http_app). Its routes are added to the app at exactly/mcp(a mount would redirect/mcpto/mcp/); the SDK's session manager runs in the app lifespan. - The SDK's
TransportSecuritySettingsget the same Host and Origin allow-lists as the middleware. - Many sessions (CLI and the desktop app's local sessions) connect to the one server; writes reach
the board at once through the bus. Registration is
claude mcp add --transport http --scope user relaybay …(connect guide). - Rejected: one stdio server per session, which would mean many writer processes and no live board.
Hooks transport¶
- Default: a
commandhook per event that runs<python> -I -m relaybay.hook_client --url …/hooks/claude-code --token-file …with the interpreter that runs relaybay (isolated mode, nothing onPATHneeded). It reads the token file itself, so no token or environment variable is in the settings file, and it is silent when relaybay is down. From a frozen build the command is the bundledrelaybay-hook(the same module, frozen alone) by its full path. - Optional
httphooks (relaybay setup --mode http): Claude Code posts directly withAuthorization: Bearer ${RELAYBAY_TOKEN}andallowedEnvVars. POST /hooks/claude-codereads at most 256 KB, keeps only session id, event,cwd, source, tool name and notification message, and answers immediately;SessionStartreturnsadditionalContextwith the hook session id so the agent can link itself exactly. Prompt and tool events answer with the owner comments for an exactly linked session (additionalContext),Stopwith adecision: "block"while they are unacknowledged;PreToolUsealso runs the guard (permissionDecisiondeny/askor a warning, and alive.actionevent for live) and never answersallow; the Stop counter and the wake-up waiters live in the service's memory (lost on restart, which only means one more reminder).SessionStartalso adds the task context or a short project digest. The answer shares the hook client's 0.3 s timeout, so the digests read bounded lists through the read connection and write only when a reader's cursor really moves; a failure there is logged and leaves the old answer.- Opt-in wake-up hook: an
asyncRewakecommand hook atStoplong-pollsPOST /hooks/claude-code/wait(polling the database once a second, up to 25 minutes, one waiter per session) and exits 2 with the comment on stderr.
Security layers¶
Host allow-list → Origin check → token (/mcp, /hooks, /api) or cookie (board) → CSRF for
cookie writes → security headers (CSP default-src 'self') → untrusted-content rendering. Details,
threat model and non-goals: SPEC §9.
Packaging and cross-platform¶
pyproject.toml(hatchling), console scriptsrelaybayandrelaybay-hook(the hook forwarder), the GUI scriptrelaybay-desktop, andpython -m relaybay. Runtime dependencies:aiosqlite,fastapi,jinja2,jsonschema,markdown-it-py,mcp>=2,<3,platformdirs,python-multipart,regex,snowballstemmer,uvicorn. The optional extradesktop(pywebview,pystray,pillow) is forrelaybay desktop. Development:httpx,pytest,pytest-asyncio,ruff; the docs site: the optionaldocsgroup (mkdocs-material).- All file I/O is explicit UTF-8;
pathlibeverywhere; Windows, macOS and Linux run in CI with Python 3.12 and 3.13. - No OS service: the user starts
relaybay serve, runs the Docker image, or starts the desktop program. Wheel and sdist,uv tool install/uvx/pipx, the Docker image and the tag-driven release workflow follow the packaging design. install.pytells how this copy was installed (install_kind(): the desktop program per OS, Docker, a uv tool, pipx, uvx, a checkout, pip). Upgrade hints, the updater,doctorand the hook command depend on it.
Desktop program¶
relaybay.desktop (design 0016,
ADR-0002) runs the same create_app(settings) in a server thread
(EmbeddedServer) inside a process whose main thread belongs to the GUI loop (pywebview); a pystray
icon carries the menu. desktop.toml in the per-user config folder holds the data folder, the
server mode (embedded, or external: the program and the CLI talk to a remote server with a saved
token) and start at login; config.load_settings reads it, so the CLI and the program find the same
data. The frozen builds (PyInstaller onedir, packaging/) carry three executables:
relaybay, relaybay-desktop and relaybay-hook (the hook forwarder alone, standard library
only). From a frozen build, relaybay setup writes hooks that start that relaybay-hook by its full
path; the program checks them read-only at each start and offers Settings → Reconnect Claude Code,
which runs the same plan and write as relaybay setup.
Repository layout¶
README.md CONTRIBUTING.md AGENTS.md CHANGELOG.md LICENSE mkdocs.yml Dockerfile
CODE_OF_CONDUCT.md SECURITY.md GOVERNANCE.md
pyproject.toml uv.lock .github/workflows/{ci.yml, desktop.yml, docs.yml, release.yml}
.github/ISSUE_TEMPLATE/
scripts/ gen_reference.py (docs/reference/*.md) check_dist.py changelog_notes.py
hook_timing.py record_gif.md
src/relaybay/ cli.py config.py app.py security.py service.py events.py machine_setup.py
doctor.py demo.py markdown_import.py markdown_export.py hook_client.py logs.py
install.py updates.py backup.py gitinfo.py
db/ desktop/ domain/ mcp_server/ policy/ web/
packaging/ relaybay.spec launchers/ icons/ windows/ macos/ linux/
examples/ compose.yaml (Docker server for the desktop client)
tests/ one module per area (service, mcp, board, sse, hooks, setup, rules, …), fixtures/,
e2e/ (scenarios against a real server with a fake `claude`)
docs/ index.md SPEC.md ROADMAP.md architecture.md mcp-tools.md connect-claude-code.md
design/ adr/ reference/ getting-started/ how-to/ llms.txt