How bwtidy is built¶
This page maps the code for someone who changes it. You can start with the container and follow a browser request through the frontend and the HTTP API to the backend. The later sections trace a write to the vault and show where state lives. The last part explains where to put new code and tests.
The rules bwtidy follows and their reasons are in spec.md. How one
function works is in its module's docstring.
backend/tests/repo/test_architecture_doc.py checks that every backend
module and every frontend directory is named here and that every path named
exists.
What bwtidy talks to¶
bwtidy talks to three things outside its container. Your browser loads the web page and calls the HTTP API. An MCP client such as an AI agent calls the MCP server with its token. Both reach bwtidy over HTTP.
The vault server is the third. Only the Bitwarden CLI (bw) that each
worker runs opens a connection to it.
The container¶
bwtidy is one container with two kinds of process. Both are entry points of
the Python package bwtidy. How bwtidy fits together
draws them for two accounts.
The gateway (gateway/, entry point bwtidy-gateway) runs as root and is the
only listener. It serves the web page and proxies the API and MCP requests to
the workers (The gateway says how).
A worker (main.py, entry point bwtidy) serves one account for one
session. It runs as the account's own uid on a unix socket in the account's
socket directory. It starts its own bw serve as a child on a second socket
and holds the unlocked vault in RAM. It exits when the session ends.
The gateway listens on port 8000 in the container. A worker answers on
app.sock in its account's socket directory under /data/accounts/.run/ and
its bw serve on bw.sock beside it
(spec.md, Socket directories).
compose.yaml runs the image of the Dockerfile target app as the
container bwtidy. BWTIDY_IMAGE and BWTIDY_VERSION name the image in the
.env made from example.env. The published image is
docker.io/tnek213/bwtidy, which the GitHub Actions workflow "Image" builds
and pushes for every release. compose.build.yaml
builds it from the checkout as bwtidy:local instead, and Run
bwtidy says how to run it.
The container has a read-only root file system with a tmpfs /tmp. It has
the capabilities the gateway needs to start workers as other uids and a health
check on /api/health. Its port 8000 is published on the host's 127.0.0.1
(8765 by default). It mounts the volume bwtidy-accounts at /data/accounts
and the backups at /backups. The backups are the volume bwtidy-backups or
the host directory that BWTIDY_BACKUPS names, with
BWTIDY_BACKUPS_ROOT=/backups. It mounts the volume bwtidy-stats at
/stats too, with BWTIDY_STATS_DB=/stats/stats.db. A stop gets 150
seconds. STOP_TIMEOUT in gateway/workers.py plus the gateway's request
drain must stay below that.
Without the worker settings main.py runs as a single-user backend on a
TCP port. The integration tests use this mode.
The app stage holds the backend's source with its installed dependencies but
no tests. It also holds the built frontend and bw with
docker/unref-share-timers.js, which makes a bw command exit as soon as it
has answered. docs/restore.md sits at /app/docs/restore.md because every
backup holds it as its RESTORE.md. The docs site sits at /app/site. The
venv's bwtidy command is linked into /usr/local/bin for bwtidy stats,
so the image's own python3 stays first on PATH.
That bw is the open source build of the Bitwarden CLI. The
bitwarden-cli-source stage builds it from the commit of Bitwarden's source
that docker/bitwarden-cli/source.json pins. The bitwarden-cli stage puts
that build in place of the npm package's own and installs the packages it
brings along from docker/bitwarden-cli/package-lock.json.
The docs stage builds that site with scripts/docs-site build from
zensical.toml and docs/ as well as overrides/main.html, which shows the
beta disclaimer as a banner on every page. It uses the Zensical of the
backend's dependency group docs, which stays out of the app's venv. The
workflow .github/workflows/docs.yml builds the same site and publishes it on
GitHub Pages. The user docs follow Diátaxis (https://diataxis.fr) with one
folder per kind of page under docs/. AGENTS.md (Writing docs) holds the
rules for writing them.
The dev stage is the app container of the dev stack (compose.dev.yaml). It
runs the tests from a mount of backend/ and mounts the worktree's docs/ at
/app/docs read-only. Its docs site is the one its image was built with, so
scripts/docs-site serve previews a change of the docs.
The frontend¶
The frontend under frontend/src uses React, MUI and AG Grid with MUI X's
date picker for date fields. main.tsx mounts App.tsx. That is the gate
and the page switch. As the gate it shows the account form, the vault login
or the unlock until the app opens. Then it shows the app bar and one page.
React Query holds the server's data. A grid edit posts an operation to
POST /api/queue for the worker to write in its next automatic commit. The
commit tracker holds the state of those edits in a React context. The page
refetches its data once the commit settles.
These directories hold the pages and the app bar. Each is independent of the others:
about/the About page with the version and the license as well as the credits and the third-party packages.appbar/the app bar. It holds the page links and Commit now as well as the MCP switch and the color mode. Log out and the more menu sit there too.backups/the alert about backups to re-encrypt after a new master password.changelog/the Change log page with its filters and restore as well as delete backup and the diff report.grid/the Vault grid page with its cells, toolbar and dialogs. Each dialog is one file ingrid/dialogs/.queue/the Queue page.session/the account form and the vault login as well as the unlock and the heartbeat.settings/the Settings page with the display settings and the default generator as well as deleting the data.statistics/the Statistics page.templates/the Types page with the templates and the datatypes.
Four directories hold what the pages share. Layers and their rules explains what each may import.
api/the backend's resources, one file each with its fetchers and React Query keys and JSON types. It also holdsapiFetchinapi/api.tsand the operation builders inapi/operations.ts. The rules of a page live in the page.shared/the helpers and small components that belong to no page:- the coordinates (a mirror of
items/coordinates.py) - the account's lifecycle (reopening, switching and the other tabs) and the lock
- how a cell value shows
- the queue's failure text
- the generator's limits and checks
- the item types and template coordinates that the grid and the Types page share
- the date and time format and the date field
- the form dialog and the generator form
- the password managers' opt-out
- the coordinates (a mirror of
commit/the commit tracker, which isAutoCommitProviderwith its context and the unread marks.theme/the color mode and the layout (Normal or Compact) as well asProse, the paragraph with balanced lines.
The API between them¶
The frontend reaches the backend only through HTTP. The browser sends every
call to the gateway. The gateway answers both forms of the health route
(/api/health and /api/health/) and /gateway/account itself. It routes
the remaining /api requests to a worker using the bwtidy_account cookie.
It strips that routing cookie before forwarding the request. An unlock
or the start of a vault login can start the worker.
Routing cookie and proxy describes the
gateway's responses. It can refuse a worker start with 422 for an account
error or 429 for a limit. It answers 503 if the worker fails to start and
502 if the worker fails to answer.
The frontend defines its request and response types by hand. The gateway
turns off FastAPI's Swagger UI and ReDoc pages. Its /openapi.json
describes the gateway's own routes. The table pairs frontend
fetchers with the corresponding route modules. The last column links to the
routes of each group. The tool note is a vault item where bwtidy stores
settings that travel with the vault.
| Frontend | Backend | What the group does | Routes in the spec |
|---|---|---|---|
api/account.ts |
gateway/app.py |
the account the browser opens, before any worker runs | Routes of the gateway itself |
api/version.ts |
gateway/app.py |
the version, from the gateway's /api/health |
Routes of the gateway itself |
api/session.ts |
api/session.py, api/bwlogin.py, api/mcp.py |
the unlock, the heartbeat and log out, the vault login from the web UI and the MCP switch and token | Session and access, The server, the switch and the token |
api/grid.ts |
api/grid.py |
the vault as a grid and the one route that answers a secret | Grid, Secret values |
api/queue.ts |
api/queue.py |
the queue with the UI edits and the decisions | The queue, UI edits and the auto-commit |
api/changeLog.ts |
api/operations.py, api/backups.py |
the change log and the restore plans, and listing, downloading and deleting backups | The Change log page, Restoring a change log row |
api/templates.ts |
api/templates.py |
the templates section and the matches, and the tool note's rename back and keep name | Routes and applyTemplate, The note section |
api/datatypes.ts |
api/datatypes.py |
the datatypes section and the live pattern checks | Datatypes, The routes |
api/generator.ts |
api/generator.py |
the generator settings and an example value | The generator section |
api/statistics.ts |
api/statistics.py |
the numbers of the Statistics page | Statistics |
api/settings.ts |
api/settings.py |
the display settings | Settings |
api/deleteData.ts |
api/account.py |
deleting the account's data, or the whole account | Deleting data |
Two modules of the frontend's api/ call no route of their own.
api/api.ts holds the shared request helpers. api/operations.ts builds
the operations that api/queue.ts posts.
A few fetchers sit outside api/. grid/toFill.ts calls api/grid.py for
the list of secret fields still to fill in.
grid/normalize.ts calls the same module for
near-duplicates. grid/formats.ts calls
api/datatypes.py to check a value against a saved datatype.
commit/autoCommit.ts calls api/queue.py for the auto-commit status and
settings and to commit now (Auto-commit).
shared/account.ts logs out through api/session.py and clears the routing
cookie through gateway/app.py. POST /api/operations in
api/operations.py is for scripts and test setup (Writes).
The browser API uses these conventions:
- The shared helpers ask for JSON with
Accept: application/jsonand setContent-Type: application/jsonwhen sending a body.apiFetchreturns nothing for 204.apiFetchWithHeadersalso returns the response headers for the change log. Backup downloads use a link and return a file. - API errors usually answer with a JSON string field named
detail. Conflicts can addconflictsormergeConflicts. A partial write failure fromapi/errors.pyincludesappliedandfailedalong withpending,backupandconflicts. The shared helpers throwApiErrorwith the status and any parsed JSON body. When there is a text detail they include it too. api/errors.pymaps a locked vault to 401 and a conflict to 409. It maps a refused operation to 422 and backup and write errors to 500. ABwErrorgives 502.validation.pyrejects an invalid request body with 422. Itsdetailis a list of issues withtype,locandmsgfields and omits the submitted values.- An unlock sets the
bwtidy_sessioncookie. Routes that require an unlocked vault takeSessionfromapi/deps.py. The dependency gives 401 without a valid session cookie. The gateway gives 401 "No account" when the routing cookie is missing or unknown. It also gives that answer when no worker is running for a request other than an unlock or the start of a vault login. - The request helpers notify
onLockedlisteners for any 401. The app uses this to return the browser to the appropriate account or login screen. - Polls that pass the background option carry
X-Bwtidy-Background: 1. The session dependency skips its activity update for those requests. The data deletion and CLI logout routes give 403 withoutX-Bwtidy-Request: 1. A page on another site would need a preflight to send that header.
An MCP client reaches the same listener at /mcp or a path below it. The
gateway finds the account by the bearer token and forwards the request to
its running worker. The worker's mcp/ checks the token again
(spec.md, MCP). The MCP tools page
lists the tools.
The backend¶
The backend is the Python package bwtidy under backend/src/bwtidy. The
gateway and the worker share it, and each takes only what its process needs.
The gateway¶
The gateway serves the built frontend at / and the docs site at /docs/.
It keeps the browser's routing cookie. It answers /api/health itself and
proxies the rest of /api/* to the worker of that cookie's account. It
proxies /mcp to the worker of the bearer token's account. A vault login for
a new account makes the gateway create the account's directory. When the
browser unlocks or starts a vault login, the gateway starts the account's
worker. Before a worker runs it answers from the account directory whether
the account exists and whether it is pending and has its CLI logged in.
With BWTIDY_STATS=1 the gateway also records the usage stats of the requests
it proxies in a file of its own. The code for that is in stats/
(spec.md, Usage stats). create_gateway_app takes
extra routers and an on_worker_exit hook as well. The routers come before
the docs site and the static files. So an outside package such as the demo
can wrap the gateway without bwtidy knowing about it
(spec.md, Extra routes and the exit hook).
The gateway imports only from the worker's Foundation tier. That includes
modules such as config.py and login_state.py as well as parts of stats/.
The gateway contract excludes db.py and stats/report.py. The latter
reports the worker's stats and brings the MCP SDK along. What the gateway, the
worker and the frontend all read lives in protocol.py. That covers the
cookie names and the headers as well as the file names of the account
directory and the backup file name.
The worker¶
The worker's seven tiers group code by responsibility. Imports can go
within a tier or down to a lower tier. The picture shows
them with main.py on top and the gateway beside the Foundation.

The tiers group the fifteen rungs of the contract "Layers of the worker" in
backend/pyproject.toml. That contract orders every package strictly, so a
module can import down the stack. Modules within one package can also
import each other. The entries sharing a rung are independent of one another.
The table shows how each tier maps to the contract:
| Rung | Modules | Tier |
|---|---|---|
| 1 | main.py |
Entry |
| 2 | api/ |
Doors |
| 3 | mcp/ |
Doors |
| 4 | queue/ |
Write flow |
| 5 | writes/ |
Write flow |
| 6 | worker.py |
Session |
| 7 | session.py |
Session |
| 8 | backups/ |
Vault model |
| 9 | vault/ |
Vault model |
| 10 | operations.py |
Vault model |
| 11 | sections/ |
Vault model |
| 12 | items/ |
Vault model |
| 13 | bw/ |
Bitwarden CLI |
| 14 | config.py, login_state.py, stats/ |
Foundation |
| 15 | the eight basics | Foundation |
At the top main.py is the composition root. Its create_app builds every
object and passes the hooks at construction.
The doors come next. api/ is the browser's door with one route module per
resource. mcp/ is the agent's door with read tools that hold no secrets and
propose tools that feed the queue.
The write flow is the queue and the one write path. queue/ is the review
queue, where every edit becomes an entry that is checked on arrival and
approved into the write path. writes/ is the one write path. It holds the
check of a batch and the batch driver as well as the writes by kind of
operation.
The session tier holds the session in session.py and the worker's life
around it in worker.py.
The vault model is the state and the vocabulary. backups/ makes a backup,
keeps them and reads one back. vault/ keeps the account's state in RAM. That
is the vault and the chain of bwtidy's own writes as well as the tool note's
id, the formats of the values and the hidden values. operations.py is one
flat module with the operation models and what each touches. sections/
holds the tool note's sections and the scoring of an item against the
templates and datatypes. items/ holds pure functions and models on item
dicts.
Below them bw/ talks to the Bitwarden CLI. It covers HTTP to bw serve as
well as bw's processes and its JSON.
At the bottom lies the Foundation. Its lower rung holds the basics. They are
eight flat modules that import nothing of bwtidy and nothing of each other
(Backend packages names them). Above them config.py
and login_state.py as well as stats/ form a rung of their own. They are
basics too but read other basics, as config.py reads the version and
login_state.py the names of protocol.py. stats/ holds the usage stats
and reads those names too.
A lower rung calls up only through a hook. main.create_app passes each hook
when it builds the object, which makes it the one place where the flow of a
session is visible. The hooks are these:
SessionHooks(session.py) has four.on_unlockedstarts the background backup, records the login state and clears the pending marker.before_endcommits the pending UI edits.on_endedstops the background backup and drops the decrypted one.after_endmakes the worker exit.VaultCachecallson_loadto keep the tool note's id, prune the to-fill list and refresh the formats.ReviewQueuecallson_ui_entryfor the auto-commit's clock andon_writtenfor the to-fill list.BwServeProcesscallson_restartto unlock the new bw serve.BackupKeeperasksqueue_in_usewhether a backup is in use. The queue answers withbackup_in_use(queue/wipe.py) on the database, so the keeper is built before the write path and the queue. The queue in turn gets the keeper as a peer of the write path for the account data deletion.
Backend packages¶
Under backend/src/bwtidy each module gets one line, in the order of the
rungs. A package's __init__.py names its theme and takes one of three
forms:
- It re-exports exactly what modules outside the package import from it.
They import from the package (
from bwtidy.writes import WritePath) and never from a module of it. This holds forbw/andvault/and forbackups/,writes/andmcp/. - It re-exports nothing and the package's modules are imported by name
(
from bwtidy.queue.review import ReviewQueue). This holds foritems/andqueue/and forapi/andgateway/. sections/lies in between. Its__init__.pydefinesSection,SECTIONSandSectionChangeand re-exports what reads and writes the notes JSON as a whole. Its section modules are imported by name.
No module imports a name that starts with an underscore from another module.
backend/tests/repo/test_package_surfaces.py checks all of this.
The basic modules, with the two above the others first:
config.pythe worker's settings from the environment (Settings), with the session timeouts (Policy) and the backup retention (Retention).login_state.pythe filebw-login-statethat tells the gateway whether the CLI is logged in.logs.pythe log format, with a time on every line and other libraries from WARNING up.timing.pythe step durations of a slow operation, for one INFO line.version.pysemver, the version as semver.org spells it. It uses the stdlib only so thatscripts/devlib/versions.pycan load it by path.validation.pythe answer to a refused request body (never the body), and the one text of a validation error.passphrase.pyage passphrase encryption with the master password and the password hash, the only caller of scrypt.mcp_token.pythe MCP token's record and its checks, which the gateway and the worker share.protocol.pythe strings the gateway, the worker and the frontend agree on.db.pyDatabase, the SQLite file at its one schema. It holds the change log and the queue as well as the settings and the backup fingerprints.
The usage stats in stats/, beside config.py and kept only with
BWTIDY_STATS=1:
stats/db.pythe gateway's stats file withMIGRATIONSas well as the writes and the retention.stats/labels.pythe plain names for worker routes in the demo tables.stats/parse.pywhat the gateway reads of a request and checks against the worker's names. That is the route templates and the JSON-RPC methods and tool names as well as the outcomes and the error report.stats/recorder.pyRecorder, which holds what was seen in RAM and writes it in batches off the request path. It also takes the capacity samples.stats/report.pythe worker's side with its names at/stats/namesand the error header of its 500.stats/summary.pysummary(the one dict that a page orbwtidy statsshows) and the top errors.
Talking to bw in bw/:
bw/client.pyBwClient, the async client of bw serve's API.bw/serve.pyBwServeProcessstarts bw serve and restarts it when it exits.bw/process.pyrun_cli(the one way to run a bw CLI command) andstop_bw.bw/login.pyBwLogin, the CLI login in a pseudo-terminal for the web UI and the CLI's logout.bw/revision.pysame_revision, the one comparison of two revisionDates.bw/cli_state.pycli_archived_trash_ids, the one read of bw's CLI state file: the ids of the archived items in the trash, which bw lists only with premium.
The vocabulary in items/:
items/coordinates.pywhere a value lives in an item (its grid column), andis_secret.items/normalize.pyrenaming fields and merging columns and items, with the near-duplicate hints.items/patterns.pythe datatype pattern engine, bounded for untrusted patterns.items/ssh_keys.pyan SSH key's public key and fingerprint from its private key.
The tool note's sections in sections/:
sections/__init__.pySECTIONS(each section's rules by name) andSectionChange.sections/notes.pythe notes JSON andSectionRules, what every section module builds on.sections/templates.pythe templates section with its model, its parser and its changes.sections/datatypes.pythe datatypes section and the check that no datatype a template uses is deleted.sections/generator.pythe generator section and the query of bw's generator for a set of options.sections/to_fill.pythe toFill section as the note stores it, and its changes.sections/note.pythe note section, the name the tool note is expected to have.sections/matching.pythe scoring and matching of an item against the templates and datatypes.
The operations:
operations.pythe operation models and what each touches.
The account's state in RAM in vault/:
vault/cache.pyVaultCache, the vault in RAM.vault/own_writes.pyOwnWrites, the chain of bwtidy's own writes this session.vault/tool_note.pyfinds and creates the tool note, keeps its id (ToolNoteId) and its backup password fields.vault/hidden.pyHiddenValues, the age identity that encrypts queued secret values.vault/formats.pythe cached note's templates and datatypes andFormats, how the cached values match them.vault/statistics.pythe counters of how hard the pattern checks work, kept byFormats.
Backups in backups/:
backups/files.pythe backup files with their listing and names, the retention rule and the fingerprint.backups/crypto.pythe age encryption of a backup file and the re-encryption after a new master password.backups/collect.pycreate_backup, which checks the exports and listings through bw and puts them into one zip with its RESTORE.md.backups/reader.pyBackupReader, a decrypted backup in RAM.backups/keeper.pyBackupKeeperwith the backup of a write, the background backup and the retention.
The session:
session.pySessionManagerwith the unlock and the session token as well as the timeouts and the end.worker.pyWorkerLifetimewith the exit after the session and the pending marker.
The write path in writes/:
writes/path.pyWritePath.apply(the batch driver) andWriteContext, what the modules of the kinds call on it. That covers the vault in RAM and bw serve as well as the backups and the shared steps of a write. It also holdsAPPLYwith the function of each kind of operation typed to its class.writes/check.pyvalidate, the check of a batch before anything is written.writes/rules.pythe secret rules every write checks.writes/planners.pywhat an operation makes of an item, without writing.writes/saves.pya section save with its check and the notes as its write leaves them.writes/restore_plan.pywhat a restoreItems does per item of a change log row.writes/items.pythe writes of one item or a few. They change a leaf or the URIs and set the collections. They move, rename and merge items and handle the trash.writes/create.pycreateItem and the conversions that create a new item and trash the old one.writes/folders.pythe folder of a move or a new item, and the folder kinds.writes/attachments.pyrenameAttachment, an upload and a delete that leave one copy.writes/note.py_write_note, the one write of the tool note's notes.writes/restore.pyrestoreItems, step by step as the plan says.
The review queue in queue/:
queue/review.pyReviewQueue, the facade the doors andmain.pycall.queue/state.pyQueueState(what the modules share) and an entry's stored form.queue/intake.pywhat comes in, with the checks on arrival and the stores.queue/commit.pyapproveandretry, which send a batch through the write path and apply or blame each entry.queue/entries.pythe rows with the one status write, the listing and the decisions without a write.queue/agent.pywhat the agent reads of its own entries.queue/sections.pya section as the saves under way leave it.queue/wipe.pythe account data deletion and the backups the queue still needs.queue/view.pyan entry's summary and its masked diff.queue/autocommit.pyAutoCommit, the commit of the UI's entries on time or count.queue/to_fill.pyToFill, the list of secret fields still to fill in.
The agent's door in mcp/:
mcp/server.pyBwtidyMcp, which gates every tool. Itscreate_mcp_serverregistersTOOLSand hands each tool its interface, which isAgentVaultfor the read and propose tools andSessionActionsfor the session tools.mcp/vault.pyAgentVault, the vault as the agent sees it. It says what each tool may read and puts its proposals into the queue.mcp/texts.pywhat the agent reads, which is the instructions and each tool's description.mcp/read_tools.pythe read tools.mcp/propose_tools.pythe propose tools, one operation each.mcp/session_tools.pythe two tools that end the session after the answer andSessionActions(all they may do).mcp/auth.pyMcpToken(the worker's token file) andRequireMcpTokenin front of/mcp.
The browser's door in api/:
api/app_state.pyAppState, the parts that every route reaches throughapp_state(request). Among them are the settings and the database with the vault in RAM. The session and the write path are there too along with the keeper and the queue.api/deps.pywhat the route modules share, such as the session dependency and the request header check. It also gives the session's state as the login routes answer it and the tool note.api/errors.pythe HTTP answer of each domain error.api/sections.pywhat the section routes share, which is the queued changes and the current view.api/session.pyunlock, heartbeat and log out.api/bwlogin.pythe Bitwarden CLI login from the web UI.api/grid.pythe vault as a grid, and the one route that answers a secret.api/queue.pythe queue with the UI edits, the decisions and the auto-commit.api/operations.pyPOST /api/operationsstraight to the write path for scripts and test setup. It also answers the change log and restore plans, each from the parts thatAppStateholds.api/backups.pylisting and taking backups as well as downloading and deleting them.api/templates.pythe templates section and the matches, and the tool note's rename back and keep name straight to the write path.api/datatypes.pythe datatypes section and the live pattern checks.api/generator.pythe generator settings and an example value.api/statistics.pythe numbers of the Statistics page.api/mcp.pythe MCP switch and the MCP token.api/settings.pythe display settings.api/account.pydeleting the account's data, or the whole account.
The composition root:
main.pycreate_appand thebwtidyentry point with its commandbwtidy stats.
The gateway in gateway/:
gateway/app.pythe gateway's routes, the account state machine and the static files.gateway/proxy.pythe proxy to the workers, with the routing by cookie and token and the headers that pass.gateway/settings.pythe gateway's settings from the environment.gateway/accounts.pyaccount keys, directories and uids.gateway/backups.pyBackupsRoot, each account's directory under the backups root.gateway/workers.pystart, watch and stop one worker per account.gateway/stats.pyStatsMiddlewarearound the proxy, which notes each request that reaches a worker for the recorder and learns the workers' names.
Across the parts¶
These sections follow what crosses the frontend, the API and the backend. They show one write from the cell to the vault, where state lives and who writes each kind of data. The last one lists where the secret rules are enforced.
How a write flows¶
A grid edit travels from the cell to a reload in the browser. The picture shows a successful batch of cell edits. The text below follows the batch and explains how failures settle.

AG Grid runs with readOnlyEdit, so an edit in a cell becomes an operation
(grid/useCellEvents.ts with the builders of api/operations.ts).
grid/writer.ts posts it to POST /api/queue (api/queue.ts). The route
(api/queue.py) parses the operations and hands them to ReviewQueue.
On arrival queue/intake.py checks every operation of the batch with
validate (writes/check.py) on the vault in RAM before it stores any. A
refusal answers 409 or 422 and stores nothing. Otherwise the hidden identity
(vault/hidden.py) encrypts each secret value and the batch is stored as
pending entries in one transaction (db.py). The grid shows the queued values
as an overlay (grid/queued.ts).
The auto-commit (queue/autocommit.py) approves every pending UI entry once
the oldest is old enough or enough are pending. It runs one commit at a time.
Then approve (queue/commit.py) marks the entries approved with the diff they
show (queue/view.py). It decrypts their hidden values into RAM and hands the
operations to the write path as one batch.
Under its lock the write path (writes/path.py) syncs bw serve and loads the
vault (vault/cache.py) before it runs validate again. Then it takes a
backup from backups/keeper.py. That is the newest backup when it holds the
vault as it is or else a new one (backups/collect.py). Delete and the
retention keep it until the batch ends. One more sync and load follow, and the
check runs again when the vault changed.
The write path then applies one operation at a time using its handler in
writes/ and the steps in WriteContext. For a cell edit it GETs the item
and checks it against the chain of own writes (vault/own_writes.py) and
what the grid showed. It checks the secret rules (writes/rules.py) and
changes only the touched leaves before it PUTs the whole item. Each write
gets a change log row (db.py). A successful write marks its queue entry
applied at once (queue/commit.py).
At the end of the batch writes/path.py reloads the vault and starts a
background backup after the operation loop, even when a write failed.
Then queue/commit.py settles the batch. A conflict or an invalid operation
that the check found fails the entries it blames. The queue tries the rest
again. A write that fails midway fails its entry and puts the later ones
back to pending. The queue counts the settled commit.
In the browser commit/AutoCommitProvider.tsx polls the auto-commit's status
(GET /api/queue/auto-commit). Once the commit count has changed and no
commit runs, it refetches the grid and the other pages' data and reports the
failed entries.
The other ways in:
- A tool note section save covers the templates and the datatypes as well as
the generator and the to-fill list. It is a UI entry of single changes
(
api/sections.pyandqueue/intake.py) whose commit the route starts at once. Its write applies the changes to the note as it is then (writes/saves.pyandwrites/note.py), so two saves never undo each other. Every read of a section under way folds the pending saves over the cached note (queue/sections.py). - An MCP proposal comes from a propose tool (
mcp/propose_tools.py). The tool builds the operation and its summary and queues it throughAgentVaultwith the source mcp. The check on arrival refuses any secret value. The auto-commit never takes it, so the user approves it on the Queue page through the same approve. - The tool note's rename back and keep name (
POST /api/tool-note/rename-backandPOST /api/tool-note/keep-nameinapi/templates.py) call the write path directly without the queue. POST /api/operations(api/operations.py) calls the write path directly without the queue, for scripts and test setup.
Where state lives¶
- Worker RAM goes with the session. It holds the master password with its
hash and the session key (
session.py) as well as the vault and the chain of own writes (vault/). It also holds the hidden identity and the last decrypted backup. When each UI entry was queued is kept there too along with the format results and the pattern counters. - Gateway RAM holds the routing cookie's account and the running workers. A restart forgets both, and the browser logs in again.
- The usage stats exist only with
BWTIDY_STATS=1. The gateway keeps them instats.db(stats/db.py), which lies next to the accounts directory unlessBWTIDY_STATS_DBnames another place. The file survives restarts and updates through its migrations. - SQLite in
app/bwtidy.sqlite(db.py) survives a restart and a deploy. At a worker's start the queue fails what a killed commit left approved and deletes the hidden values of failed entries (queue/entries.py). Pending UI entries are due at the next unlock. - The tool note travels with the vault. Its notes JSON holds the sections
templatesanddatatypesas well asgeneratorandtoFill(one module each insections/). Its hidden fields hold the backups' passwords. - The account directory
/data/accounts/HOST/EMAIL/(spec.md, Account directory) is made at the account's first vault login. It holdsapp/with the SQLite file andmcp-token.sha256as well asbw-login-stateand the delete marker. Next to it lie the CLI statebw/as well ashome/andworker.log. The sockets lie in the account's socket directory under/data/accounts/.run/, which the gateway empties at its start. - The backups
*.zip.agelive under the backups root in/backups/HOST/EMAIL/withcompose.yaml. Otherwise they live inapp/backups/of the account directory, or whereBWTIDY_BACKUPS_DIRpoints. -
The browser holds state of four kinds:
- React Query holds the server's data and two entries of the page's own.
These are the account (
api/account.ts) and the note above the unlock form (shared/session.ts). - The context of
commit/autoCommit.tsholds the settling entries and the failures as well as the conflict marks. - localStorage holds per account the form's last server and email
(
session/account.ts), the account in use (api/account.ts) and the last log out (shared/account.ts). It also holds the queue entries seen (commit/unread.ts) and the failed entries reported (commit/autoCommit.ts). Per browser it holds the layout (theme/layout.tsx). - The cookies are
bwtidy_consentand the color mode (theme/colorMode.tsx) as well asbwtidy_accountof the gateway andbwtidy_sessionof the worker. The tabs of a profile share them, so a tab reloads when another changes the account or logs out.GatewaySettingsreadsBWTIDY_COOKIE_NOTICEand the account API exposes it to the frontend. The browser's account resolution waits for consent before it writes to localStorage or opens an account. See Browser consent.
Drafts and typed secrets stay in their component.
- React Query holds the server's data and two entries of the page's own.
These are the account (
Who writes each kind of data¶
Each kind of data has one writer. Where another module writes it too, the table says why.
| Data | Writer | Module | Exception, and why |
|---|---|---|---|
| Vault items | WritePath.apply under its lock, each kind through its function in APPLY |
writes/path.py, writes/items.py, writes/create.py, writes/attachments.py, writes/restore.py |
ensure_tool_note (vault/tool_note.py) creates the tool note at the unlock. No session exists yet then and the write path needs the session's backup |
| Folders | the folder writes under the same lock | writes/folders.py |
None |
| The tool note's notes JSON | _write_note, for a section save and for the entries of a converted item |
writes/note.py |
new_tool_note (vault/tool_note.py) gives a new note its first notes at the unlock |
| The tool note's fields, the backup passwords | set_backup_passwords from the unlock in session.py and new_tool_note for a new note |
vault/tool_note.py |
The whole kind is outside the write path. It runs at the unlock before the backups are re-encrypted to a new master password |
| SQLite schema | create_schema, for a new file only |
db.py |
None. Nothing changes the tables of an existing file |
SQLite change_log |
Database.record, from WritePath.apply only |
writes/path.py |
wipe_account_data (queue/wipe.py) clears it for the account data deletion |
SQLite queue |
The intake stores the rows with enqueue and store_refused_secret or with store_ui in one transaction. decide writes every status, and decide_all writes those of a batch in one transaction. dismiss and forget_failed_values delete failed rows and their hidden values |
queue/intake.py, queue/entries.py |
retry (queue/commit.py) puts failed rows back to pending with their operations refreshed in one transaction (reset_queue_entries). wipe_account_data deletes every row except the pending MCP proposals kept on Write first |
tool_note_id in SQLite settings |
ToolNoteId |
vault/tool_note.py |
None |
auto_commit_after_seconds, auto_commit_max_entries in SQLite settings |
AutoCommit.configure |
queue/autocommit.py |
None |
hidden_identity in SQLite settings |
HiddenValues |
vault/hidden.py |
None |
mcp_token_last_used in SQLite settings |
McpToken, deleted with the token |
mcp/auth.py |
None |
date_format, hide_tool_note, rare_fields_max in SQLite settings |
set_display |
api/settings.py |
None |
SQLite backup_fingerprints |
create_backup, one row per backup |
backups/collect.py |
BackupKeeper (backups/keeper.py) forgets a row with its backup and wipe_account_data clears the table |
Backups *.zip.age |
write_encrypted, from create_backup and reencrypt_all |
backups/crypto.py |
BackupKeeper deletes them for the retention (prune in backups/files.py), for Delete and for the account data deletion (wipe_account_data in queue/wipe.py) |
mcp-token.sha256 |
McpToken.create and remove |
mcp/auth.py |
None |
bw-login-state |
LoginStateFile.record, through BwLogin.note |
login_state.py, bw/login.py |
None |
The delete marker app/delete-requested |
write_delete_marker, for Delete my account |
api/account.py |
At a worker's start drop_stale_delete_marker deletes one that an earlier worker left. The gateway acts on it when the worker exits (Gateway.delete_on_request) |
The pending marker .pending |
Accounts.create |
gateway/accounts.py |
WorkerLifetime.unlocked (worker.py) deletes it after the first unlock, which only the worker sees |
| The account directories | Accounts.create (under a temporary name that it renames into place last) as well as Accounts.delete and sweep_pending |
gateway/accounts.py |
None |
| An account's directory under the backups root | BackupsRoot.make and remove |
gateway/backups.py |
None |
stats.db, the usage stats |
Recorder.write in batches from what StatsMiddleware notes and from the samples of Recorder.capacity, both through stats/db.py |
stats/recorder.py, gateway/stats.py |
open_stats (stats/db.py) runs the migrations at the gateway's start and roll_up runs the retention |
worker.log |
Accounts.create makes it and open_log opens it for the worker without following a link or blocking |
gateway/accounts.py, gateway/workers.py |
None |
The CLI state bw/ of an account |
bw itself, run by BwLogin and BwServeProcess as well as run_cli |
bw/ |
None |
| The vault in RAM | VaultCache.load |
vault/cache.py |
replace_item puts a tool note just written in at once (from WritePath and set_backup_passwords), so a save reads as saved before the next load |
| The chain of own writes | OwnWrites, recorded by the write path's PUTs |
vault/own_writes.py |
None |
Where the secret rules are enforced¶
The rules are in spec.md (Secret values). These places keep them:
items/coordinates.pyis_secretdecides what is secret, and every check below asks it.api/grid.pymasks secret cells. Itssecretroute is the only one that answers a secret.mcp/vault.pygives the agent column names and projections without secret values. It never hands over an item of the cache and leaves the tool note out.mcp/server.pyanswers only while a session is unlocked and MCP is on, and it reports an error by its type only.queue/intake.pyrefuses an agent's secret and stores a silent refusal without its value. It encrypts every queued secret throughvault/hidden.py.queue/agent.pyreports a failure to the agent as one fixed word.queue/view.pymasks secrets in every diff.writes/rules.pykeeps a secret out of plain columns. It checks invalidatein batch order and on a new item, and at write time on the item each write GETs.writes/path.pypasses on only the text ofBwErrorandValueError.db.pykeeps kinds, ids and coordinates in the change log but never values or error messages.stats/parse.pykeeps of a request only the names that the worker gives (stats/report.py). It never keeps a path or an id and never an argument or a message.validation.pynever quotes a refused value in a validation error in either app.logs.pykeeps other libraries at WARNING.bw/login.pymasks the password and the session key in the CLI's output.backups/collect.pypassesBW_SESSIONin the environment, and no export touches the disk in plain.- Tests compare a secret with the value they expect and assert only the bool
(
secret_isintests/e2e/support/api.py).
Working on the code¶
These sections are for changing the code. They hold the layers with their rules and where a new thing goes. Then come how the architecture itself changes and where each kind of test lives.
Layers and their rules¶
Linters in scripts/ci hold the layers, so a change that breaks one fails
before it lands. A change that breaks a rule moves the import to the layer it
belongs in. When the rule itself is what changes, the config file and this
section change in the same commit.
The backend's rules are the contracts of [tool.importlinter] in
backend/pyproject.toml. import-linter checks them
(uv run --locked lint-imports in backend/). A contract holds for indirect
imports too, so a chain through other modules breaks it just like a direct
import. The contracts are these:
- "Layers of the worker" orders the fifteen rungs of
The worker from
main.pydown to the basics. The modules of a package may import each other but the flat modules that share a rung never do. - "The gateway takes only basics from the worker" lets
gateway/import no rung but the Foundation (stats/among it). Of those it never importsdb.pyorstats/report.py. - "Route modules are independent" means that no route module of
api/imports another. Ofapi/they import onlyapi/deps.pyandapi/app_state.pyas well asapi/errors.pyandapi/sections.py. - "bw knows no vocabulary" means that
bw/imports nothing ofitems/,sections/orvault/. - "The vocabulary knows no state and no bw" covers
operations.pywithsections/anditems/. They import nothing ofbw/and nothing of the state invault/,writes/andqueue/.
The frontend's rules live in three config files under frontend/:
frontend/.dependency-cruiser.cjs(npm run lint:deps) says what imports what undersrc/.api/imports only itself andshared/importsapi/.commit/importsapi/andshared/whiletheme/is a leaf. A page directory (appbar/among them) imports those four and itself but never another page. OnlyApp.tsxandmain.tsximport a page's*Page.tsx. No cycle is allowed, and a type-only import counts.frontend/knip.json(npm run lint:exports) allows no file, export or type that nothing uses. The test files are entries besidesmain.tsx.frontend/.oxlintrc.json(npm run lint) runs oxlint with the import rules andconsistent-type-imports. The import rules forbid a cycle, a self import and a duplicate import.
The rules hold for the production code. A test may import what it tests from
anywhere. So may test-utils.tsx and test-setup.ts as well as a page's
test support such as grid/testSupport.tsx. No production file imports any of
them.
Where a new thing goes¶
-
An operation kind has its model in
operations.py. It joins the unionOperationthere and gets a branch intouchedand initem_ids. Its check goes in_check_opofwrites/check.py. The function that applies it lives in thewrites/module of its kind with its entry inAPPLYofwrites/path.py. When it computes an item it also gets a planner inwrites/planners.py. Itsdiffandsummarizego inqueue/view.pyand it needs an entry inMINIMAL_OPERATIONSoftests/support/queue_helpers.py.In the frontend it gets a builder in
api/operations.tsand a label inshared/operationLabels.ts. If the agent may ask for it, it also gets a propose tool inmcp/propose_tools.pywith its description inmcp/texts.pyand its line inTOOLSofmcp/server.py. Every chain ends withassert_never, so a forgotten branch fails the type check. A forgotten entry inAPPLYfailstests/unit/writes/test_path.py. - A tool note section is one module insections/that fills in aSectionRules. Its name goes intoSectionandSECTIONSand its change models intoSectionChange(all insections/__init__.py). It needs a route module inapi/that saves throughqueue_changesand reads the section as the saves under way leave it (both inapi/sections.py). It also needs its page or tab. - A route goes in theapi/module of its resource or in a new module whose routermain.create_appincludes. It takesSessionfromapi/deps.pyand reaches the parts throughapp_state(request). It raises domain errors, whichapi/errors.pyanswers. What two route modules need goes intoapi/deps.py. - A name that the gateway and the worker (or the frontend) both read goes intoprotocol.py. A cookie, a header and a file of the account directory are such names. - A page is a directory underfrontend/srcwith its components and its rules. The fetchers it needs go in theapi/module of their resource. It also gets a value ofPageinappbar/AppBar.tsxand a line in the page switch ofApp.tsx. A rule that two pages need goes intoshared/. - A dialog is a file in the directory of its page. A dialog of the grid is a file ingrid/dialogs/named for the dialog, with a case in theGridDialogorNormalizeDialogswitch ofgrid/dialogs/index.tsx. - A setting of the deployment is an environment variable read inconfig.pyorgateway/settings.pyand named inexample.env. Where a setting of the user lives depends on what it belongs to. One that travels with the vault lives in the tool note as a section (like the generator's). One that belongs to the account on this machine lives in the SQLite settings table (like the auto-commit numbers and the date format). One that belongs to the browser lives in a cookie or localStorage (like the color mode). - A test goes where Tests says. A helper that two test files share goes into a support module and never into a test.
Changing the architecture¶
The layers, the packages and the contracts that hold them are the maintainers' choice. They are never the side effect of a change. A change fits into them, so a new module goes where Where a new thing goes says and a new import follows the layers.
When a change does not fit, it waits for the maintainers to change the architecture. That change updates this document and the contract in one commit with the reason beside the rule. It lands before the change that needs it or together with it.
A contract is never loosened to let a change pass. That means no new ignore or
exception in a contract and no modules merged to break a cycle. It also means
no import moved into a function or under TYPE_CHECKING to hide it.
A review judges the code against this document, and code that breaks it is a defect. Another way to organize the code is a proposal for the maintainers rather than a defect. Nothing moves until they take it.
These are the contracts and what runs each:
- The
[tool.importlinter]contracts inbackend/pyproject.toml, run byuv run --locked lint-imports. frontend/.dependency-cruiser.cjs, run bynpm run lint:deps.frontend/knip.json, run bynpm run lint:exports.backend/tests/repo/test_package_surfaces.py, one rule for the__init__of every package.backend/tests/repo/test_architecture_doc.py, which checks that this document names every module and directory and that its paths exist.
Tests¶
- Unit tests (
scripts/ci) live inbackend/tests/unitand cover logic and routes. They mirror the packages and are named after the module, liketests/unit/writes/test_path.pyforwrites/path.py. They usetests/support/fake_bw.pyin place of bw serve and build the app from oneAppEnv(tests/support/app_env.py). - Frontend tests (
scripts/ci) are vitest's*.test.tsxnext to the code. The grid's builder and renderer are ingrid/testSupport.tsx. - Script tests (
scripts/ci) live inbackend/tests/scriptsand cover what the files inscripts/do. They load a script by name throughload_script(tests/scripts/conftest.py). - Repo tests (
scripts/ci) live inbackend/tests/repoand check the facts that span files. They check this document (tests/repo/test_architecture_doc.py) and the two versions (tests/repo/test_versions.py) as well as the third-party list (tests/repo/test_third_party.py) and the test tree (tests/repo/test_test_tree.py). The test tree check holds four rules:- No test imports a test or a conftest.
- Every test file is in
unitorscriptsorrepoorintegrationore2e. - Every unit test file is named after a module.
- Every folder of
unitis a package.
- Support lives in
backend/tests/supportand holds what several test files share, imported astests.support.NAME. That is the fake bw and the sample vault as well as the test environments and the docs shots. - The integration tests share the package
backend/tests/integration/supportinstead. It holds the bw CLI and the dev credentials (tests/integration/support/cli.py) and the in-process app with the items made elsewhere (tests/integration/support/app.py). It also holds theVaultand the comparisons (tests/integration/support/vault.py) and the restore round trip (tests/integration/support/restorer.py). Only the fixtures are intests/integration/conftest.py. - Integration tests (
scripts/integration) live inbackend/tests/integration. They run the single-user backend against Vaultwarden and real bw for what depends on bw's real answers. That means the backups and the writes as well as the login. - End-to-end tests (
scripts/e2e) live inbackend/tests/e2eand drive the UI with Playwright through the gateway.tests/e2e/conftest.pyholds the fixtures and the packagebackend/tests/e2e/supportholds the helpers, one module per theme. - Docs screenshots (
scripts/docs-shots) come frombackend/tests/e2e/docs, e2e tests that write the images ofdocs/images.
scripts/ci also checks the generated files (scripts/third-party and
scripts/mcp-reference) and the docs. dev/testing.md says how to run and
write each kind of test. The dev stack is in dev/dev-vault.md and the
commands for one file are in AGENTS.md.