Viewing Mode

Architecture

The stack

Rails 8.1 or newer, and the pieces Rails ships: Propshaft for assets, import maps for JavaScript (with tailwindcss-rails for CSS), Hotwire (Turbo and Stimulus) for interaction, the built-in authentication generator’s shape for sessions, and Solid Queue, Solid Cache, and Solid Cable on SQLite. Every fork starts on that stack, and every page here assumes it: there is no Devise, no JavaScript bundler, no React, no Sprockets, and no Redis-backed queue, and a fork that adds one of them is off the path every other page here describes. The ModelRails/StackFloor cop (lib/rubocop) fails a Gemfile line that brings in one of those, or pins rails below 8.1, on commit.

Rails comes from a pinned commit

The template runs on Rails main (8.2.0.alpha) for two features that have not shipped in a release yet: HTML templates compiled through Herb, and alternative text on Action Text attachments, which turns on Lexxy’s ALT button. The Gemfile pins rails with ref: to one full commit, never a branch, so every checkout and every fork resolves exactly the code that was tested.

Images saved before Lexxy 1.0. Lexxy 0.9 wrote each uploaded image’s file name into its alternative text, so on Rails main those images open the ALT dialog pre-filled with something like IMG_2034.JPG, which reads as a description someone wrote. A deployment that saved images under Lexxy 0.9 runs this once:

DRY_RUN=1 bin/rails action_text:clear_filename_alts   # counts the rich texts it would change
bin/rails action_text:clear_filename_alts

On a deployment, through Kamal:

bin/kamal app exec "bin/rails action_text:clear_filename_alts" --env DRY_RUN:1
bin/kamal app exec "bin/rails action_text:clear_filename_alts"

It removes alt only where it equals that same attachment’s file name, leaves every other attribute and the surrounding text alone, and writes the body without touching the owning record or its timestamps. A second run finds nothing. Afterwards those images open the dialog empty and render like new uploads: an image nobody has described gets alt="", so screen readers skip it and read the caption, which names the file once.

With load_defaults 8.2, HTML templates compile through Herb, which parses the HTML around the ERB. A template with broken structure, such as an unclosed tag or ERB output where an attribute name belongs, fails when it compiles, naming the file and line, instead of rendering malformed markup. bin/rails herb:check compiles every HTML template on the view paths without rendering anything. It reports one file today, a partial inside the biscuit-rails gem that the app overrides and never renders (#1341). spec/code_smells/templates_compile_through_herb_spec.rb runs the same check on every pull request, over the Lookbook previews, the Turbo Stream templates and the static pages in public/ as well, with that partial as its one reviewed exception, which the spec drops once the gem’s copy compiles. Other formats, such as text mailers and Turbo Stream templates, still compile through Erubi.

One test gem needs accommodating on Rails main: rspec-rails is pinned to a commit of its own main branch, where its Rails-main fixes are merged but not yet released (#1338). Bullet needed a load shim until 8.3.0 learned Active Record 8.2 (#1337); it now loads like any other gem, and spec/config/bullet_spec.rb proves it still catches an N+1.

Dependabot does not bump git-pinned gems: its bundler block ignores exactly the gems Gemfile.lock takes from git, and a template invariant keeps the two lists equal in both directions. The pin moves by hand:

  • When. On every Rails security release, and otherwise at most once a month.
  • How. Take the commit from gh api repos/rails/rails/commits/main --jq .sha, put it in the ref:, run bundle update rails, then the full suite, bin/rails herb:check, bin/bundler-audit, and both the production image and devcontainer builds. A security advisory written as “fixed in 8.2.0” may flag 8.2.0.alpha even on a commit that has the fix; record that in the audit’s ignore file with the commit that carries the fix, and remove the entry at the next move.
  • The way back. When 8.2.0 ships, gem "rails", "~> 8.2.0" replaces the git line. The security-floor invariant and the StackFloor cop already accept that requirement, and the Dependabot invariant fails until the Rails gems leave the ignore list.

Data Model Hierarchy

User
  └── Workspace (personal, auto-created on sign-up under the default preset)
  └── Workspace (organizational, created manually)
        ├── Membership (user + Role with permissions JSON)
        ├── Invitation (polymorphic — workspace or project or client)
        └── Project (collaboration space)
              ├── ProjectMembership (user + enum role: creator/editor/viewer)
              ├── ClientAccess (external client ↔ project; NOT a Membership)
              └── Resource (polymorphic registry)
                    └── Document (Action Text rich content)

Key Concepts

Workspace — organizational boundary. Billing, roles, member management. Under the default preset (Solo-default) every user gets a personal workspace on sign-up; the other presets put new users in one shared workspace or in none.

Project — collaboration boundary. Lightweight, purpose-driven. Who works together on what. Created only through Workspace#create_project (atomic with the creator’s project membership). Lifecycle asymmetry is deliberate: an archived workspace still accepts new projects — archive means “no new people, existing work continues” — while a suspended (locked) workspace refuses them; suspension raises a disclosing SuspendedError to members where Workspace#admit raises the non-disclosing NotAdmittableError to outsiders.

Resource — content within a project. Polymorphic registry pattern: Resource holds title, status, position; type-specific content lives in the resourceable (e.g., Document). Resources with shared_with_client: true and status: published are visible in the client area.

Role — workspace-level roles with permissions JSON. Four system defaults: Owner, Admin, Member, Viewer. Forkers add custom roles via seeds.

ProjectMembership — project-level roles as a simple enum (creator/editor/viewer). Upgrade path to Role model documented.

ClientAccess — external client’s scoped access to a single project. A client is a regular User; this row is the external relationship — deliberately NOT a Membership, so clients never enter workspace Pundit policies or member-seat counting. Discardable (soft-deletable). Only createable when project.clientside_enabled? is true. See app/models/client_access.rb.

ProjectTools::Registry + ProjectTools::Tool — code-defined catalogue of per-project tools (navigable sections of a project). Defined in app/lib/project_tools/. Each Tool is an immutable value object (Data.define) with a key, a route helper, and default-enabled/implemented flags. The per-project enabled set is stored as a JSON array in projects.enabled_tools; Project#tools returns the intersection of the registry’s implemented tools and the project’s enabled set.

Authorization

Pundit policies check permissions at two levels:

  • Workspace level: ApplicationPolicy#can?("permission_name") reads from role.permissions JSON
  • Project level: ProjectPolicy and ResourcePolicy check project_membership.creator? / .editor? / .viewer?

Authorization is opt-in per action (there is no global verify_authorized), but it’s enforced at CI: spec/code_smells/mutating_actions_are_authorized_spec.rb walks every mutating (POST/PATCH/PUT/DELETE) route and fails the suite if the action neither calls authorize nor is on a reviewed allow-list. The allow-list holds only actions that are public auth-entry flows or act solely on the current user’s own resources. So a new mutating controller that forgets authorize on a tenant resource fails a test rather than shipping a silent IDOR — add the authorize call, or add the action to the allow-list with a one-line rationale if it’s genuinely public/self-scoped. Pairs with the tenant-load guard (no_unscoped_tenant_loads_spec): that one stops loading the wrong record, this one stops the missing check.

The signed-in user is Current.user everywhere in app code (Current.user! where nil is a bug). current_user is defined exactly once, on ApplicationController, as the bridge Pundit’s pundit_user and the mounted engines call; a second definition on any controller or helper is a shim, and the ModelRails/NoCurrentUserShim cop (lib/rubocop) fails it on commit.

Granting roles is gated separately by ApplicationPolicy#may_grant?(role): an actor can grant a role only if they already hold every permission it confers (a superset check, not a rank). This blocks privilege escalation — e.g. an Admin promoting anyone to Owner — and MembershipPolicy#update?/#reactivate? additionally refuse to manage a membership whose role the actor couldn’t grant. Workspace#admit (invitation-accept / open-link self-join) deliberately does not re-check this: the role is authorized when the invitation or link is created (authorize_role_grant!), not when redeemed. If you add a new membership-grant entry point, gate the role where it is minted, not where it is consumed — and declare its actor stance (granted_by: or self_join:), which spec/code_smells/membership_creation_declares_actor_stance_spec.rb enforces; see Notifications § The actor rule.

The Clientside:: controller namespace is a distinct, authenticated access axis that never sets Current.workspace and is never covered by workspace Pundit policies. Project resolution in that namespace is gated on a kept ClientAccess record — slug knowledge alone grants nothing. See the Security page for the full threat model.

Concurrency: SQLite’s Single Writer as a Race-Safety Net

The template runs on single-host SQLite in WAL mode. WAL admits many concurrent readers but still exactly one writer at a time — every write transaction is serialized by a database-level writer lock. Two consequences shape how multi-row invariants are enforced:

  • Lock-then-guard is atomic. Rails’s SQLite adapter opens write transactions with BEGIN IMMEDIATE, taking the writer lock before the first read. So a transaction { lock!; guard; mutate } block is genuine check-then-act: no other write can land between the check and the change. (One adapter quirk: lock! raises on records with unsaved changes, so these guarded mutators require clean records.)
  • Row-level lock! is not a cross-connection lock. SQLite locks are per-connection, so workspace.lock! in a pre-flight validation is silently a no-op against a racing connection. Pre-flight checks therefore exist for their user-facing error message, not for safety. The safety comes from re-checking the invariant after the write, inside the same transaction: by that point the database’s writer lock has already serialized the transaction against any racer, so a COUNT/EXISTS there reflects committed state — including a racer that slipped in first. If the invariant is broken, the check raises and the whole transaction rolls back.

This is also the shape of the creation verb on an aggregate root — Workspace#create_project, Workspace.create_owned: a verb on the tenant root wrapping lock! + lifecycle guard + every row of the assembly (record plus its membership) in one transaction, returning the possibly-invalid record for form re-render, with deliberately no bang twin until a non-form caller exists. Any create that needs a second row to be usable takes this shape; two sequential writes reproduce the orphaned-record class #660/#676 closed. A follow-up that enqueues (an invitation’s mail) sits outside the verb’s transaction; Workspace.create_for_owner_email composes create_owned with Invitation.bulk_invite! in that order for exactly this reason.

Four kinds of sites lean on this property:

  • Capacity checks — both tenant limits take the same shape. Membership’s and Project’s pre-flight validators produce the friendly error; an after_create invariant check inside the create transaction is what stops two simultaneous inserts from going over capacity. The two comparisons differ on purpose: Workspace#at_capacity? / #at_project_capacity? are >= (full once kept rows have reached max_members / max_projects, evaluated before the insert), while Membership#enforce_capacity_invariant and Project#enforce_project_capacity_invariant are a strict > because by the time they run the new row is already in the count — a >= there would roll back a legitimate at-the-limit insert. Do not route either net through at_capacity? / at_project_capacity?. A caller that wraps the insert in its own transaction must give the save a savepoint and use the bang form (Workspace#create_project): a non-bang save joins the outer transaction instead of opening a rollback boundary, and ActiveRecord::Validations#save rescues the RecordInvalid the net raises — the over-capacity row would then commit with the outer transaction.
  • Last-owner / owner-floor checks — deactivating, demoting, or transferring away a workspace’s owner re-counts remaining kept owners after the mutation and rolls back if none remain. Ownership transfer additionally uses an atomic conditional UPDATE (demote only if still owner; zero affected rows → abort before promoting the target), so a racing transfer can never leave a workspace with two owners.
  • Last-operator check — Operatorship#revoke_by_operator! counts kept operatorships under the writer lock (lock! is the block’s first statement, so it materializes BEGIN IMMEDIATE) before discarding one; a count of two or more followed by a single discard cannot reach zero, so it needs no after-write re-count. The Postgres caveat below applies in full — there is no parent row to lock.
  • Sweep jobs — ExpiredSessionsSweepJob, WebauthnChallengesSweepJob, NotificationCleanupJob, and ActivityLogRetentionSweepJob all delete_all in batches of ~100. A large one-shot delete would hold the single writer lock for seconds and block interactive writes (sign-ins, incoming notifications); per-batch transactions release the lock between rounds, capping any single stall. The swept tables have no destroy callbacks or dependent: cascades, so delete_all is behavior-identical to destroy_all and instantiates nothing.

Two smaller habits follow from the same lock. Inside a guarded mutator (Workspace#archive!, #unarchive!, #discard!, Suspendable#suspend!, #unsuspend!) an early exit is next, not return: next leaves the transaction do block with nothing to commit, whereas the meaning of return inside a transaction block has changed across Rails versions (it now commits; it used to roll back), so the guarded shape never relies on it. And a validation that needs the network — the Have I Been Pwned range check behind User#precheck_password_pwned! — runs before save, outside BEGIN IMMEDIATE, and memoizes its answer for the validation to consume; a slow external call inside the write transaction would hold the database-wide writer lock for its whole duration and turn one vendor’s latency into an app-wide write outage (#674). Controllers that accept a password call the precheck between assign_attributes and save; an unprechecked save still checks live, bounded by the initializer timeouts.

A lifecycle cascade stays inside its parent’s transaction. Workspace#discard! discards the workspace’s kept projects in the same transaction, so the workspace and its projects are discarded together or not at all. On SQLite that one write transaction is also what keeps a concurrent create_project from slipping a project in mid-cascade, because lock! is a no-op there: Arel’s SQLite visitor emits no lock clause. The price is the writer lock held for one UPDATE per project, bounded by max_projects (default 3). A fork that raises max_projects past about 100 should move the cascade into a job that carries the actor. A discarded? guard on create_project was considered and declined: #688 pins that the model deliberately does not guard it (#1040).

A fork moving to Postgres must revisit all of this. The assumptions invert: SELECT … FOR UPDATE (lock!) becomes a real cross-connection lock — so the pre-flight lock-then-check patterns become what prevents the race — while the after-write re-checks lose their guarantee, because under READ COMMITTED concurrent transactions don’t see each other’s uncommitted rows and two racers can both pass an in-transaction COUNT. Carry each invariant with an explicit mechanism instead: row locks on the parent workspace, database constraints, or advisory locks. The batched sweeps remain harmless on Postgres, just no longer necessary for writer-lock latency.

Activity Tracking

The Trackable concern auto-creates ActivityLog records via after_commit callbacks. Models opt in with include Trackable. Sensitive attributes (tokens, passwords) are stripped from metadata. Credential models do not include it — their events reach ActivityLog through the security-tier writer instead, on the stricter guarantee described below.

The trail has two write guarantees, and the difference is deliberate. Workspace-domain rows (everything written through Trackable) are best-effort: they rescue and log rather than failing the business operation they describe, so that tier is an operational/product feature, not compliance-grade evidence. Account-security rows — the actions named in ActivityLog::SECURITY_ACTIONS — are strict: the audit row commits in the same transaction as the credential mutation it records, with no rescue, so a failed audit write fails the credential write. That is an evidence-over-availability trade, made on the reasoning that for a credential change an unrecorded mutation is worse than a refused one. See Notifications § Security event audit coverage for the per-event table and what corroborates each row. Rows are read-only once persisted (#604), relation-level writes are fenced by spec/code_smells/activity_log_immutability_spec.rb, and every security-tier write is funnelled through ActivityLog.record_security_event! — fenced by spec/code_smells/security_events_route_through_writer_spec.rb. actor: and visibility: are parameters on that writer, defaulting to the self-event shape (the subject is the actor, personal visibility); a writer whose actor is someone else, like Operatorship.grant!/#revoke!, overrides both. The actor-name snapshot is written by the same callback for both tiers, and it reads the actor’s encrypted first and last name, so a strict-tier write now depends on decrypting them; a user whose own name will not decrypt is already broken, but the dependency is new (#1253).

The tier is the contract, not the call site, and there is no third. Some best-effort writers live outside Trackable because their events never reach its callbacks: Membership::Ownership#record_ownership_demotion (a callback-skipping conditional update_all), ApplicationController#log_blocked_role_grant (a refusal, so there is no record to track), Authenticatable#detect_and_record_new_device (a sign-in, corroborated by the Session row), and Invitation#record_suppressed_delivery (fired from mailer callbacks, where the concern’s hooks must not run). The strict writers are User#audit_password_digest_change, WebauthnCredential#audit_added and the removal audit inside WebauthnCredential#discard!, and Operatorship.grant!/#revoke!. A new writer picks one of the two guarantees. Tier and retention are independent axes: the new-device row is best-effort yet an ActivityLog::SECURITY_ACTIONS member, so it keeps the security retention floor.

An audit row outlives the people in it. actor_id deliberately carries no foreign key: a user who has ever acted must still be deletable, and both obvious cleanups are wrong — dependent: :destroy deletes history to delete a person, and dependent: :nullify rewrites immutable rows to hide who acted (the immutability guard fences that spelling by name). Instead the row snapshots the actor’s name into the encrypted actor_name column at write time, so the historical fact stops depending on the user row surviving — and stops following a later rename, which is what an audit table wants. trackable_id is polymorphic and has never had a foreign key; both columns now fail the same way rather than in opposite directions (#1122). Rows written before that column existed fall back to the association while it resolves and read as a former member once it does not — never as System, which would credit a person’s action to a job. Those rows do still follow a rename, since they resolve live; that asymmetry is the price of not backfilling, and it ages out with them. There is no backfill on purpose: an UPDATE across the table to add a field is exactly the rewrite the immutability guarantee exists to prevent.

user.destroy works for a user who created nothing. The audit trail was one of six columns pointing at users with no cleanup path, and the only one where both standard cleanups were wrong; the other five now have a posture (#1248): a user’s pending challenge rows go with them, and the creator of a project, resource or join link is refused with an error naming what they still own, because those columns are non-null and the choice between reassigning, nullifying with a fallback, and a name snapshot belongs to the fork that adds account deletion. spec/code_smells/users_foreign_keys_have_a_cleanup_posture_spec.rb derives every foreign key into users from the schema and fails on any without a posture. The design also rests on one unstated database fact: users.id is AUTOINCREMENT, so ids are never reused. Under plain rowid SQLite hands the next insert max(rowid)+1, and deleting the highest-id user would silently re-attribute their audit rows to the next person who signs up.

The workspace-domain trail dies with its workspace. Workspace has_many :activity_logs, dependent: :delete_all (#921): without a dependent: the foreign key refused the DELETE, so the only workspaces that could be hard-destroyed were ones nobody had ever done anything in, and “Delete permanently” is a user-facing action. It is :delete_all rather than :destroy for a reason that is not performance: ActivityLog#readonly? is persisted?, so instance-level destroy raises ReadOnlyRecord by design, and relation-level deletion is the only door — the same one the retention sweep uses, registered as a reviewed bypass in the immutability spec rather than disabled inline. This cannot reach the security retention floor: every SECURITY_ACTIONS row is written by record_security_event! with workspace_id: nil, so none is in the association’s scope (pinned in workspace_spec). The strict-tier sibling on User, audit_password_digest_change, stays an after_update inside the credential write, while its notifier stays after_update_commit: enqueuing into Solid Queue’s separate SQLite file while holding the primary write lock is a cross-database lock-ordering hazard against queue workers.

Actors are parameters. A model reads Current in one place: Trackable, where a callback cannot take an argument and a nil actor is a true answer (a job or the console has no user). Every domain verb takes its actor explicitly — Workspace#admit(user, role:, granted_by:), Membership#deactivate!(removed_by:) — and a record’s tenant is its own association, never Current.workspace, because the request’s workspace and the record’s can differ. The one best-effort writer outside the concern, Membership::Ownership#record_ownership_demotion, attributes the demotion to the owner stepping down (the membership’s own user), which is exact from every caller and needs no ambient read (#1008). The ModelRails/NoAmbientCurrentInModels cop (lib/rubocop) fails any other Current read under app/models on commit; Trackable, Tenanted’s opt-in scope, and Current itself are its only exclusions. The rule and its reasoning: playbook standards/backend/models.md §What a model may read.

Retention is bounded at 12 months by ActivityLogRetentionSweepJob (#438). Bounded retention is the honest guarantee: keeping a best-effort trail forever would make the system’s behavior contradict its own contract — exactly what a fork owner would misread as compliance evidence. An unbounded high-write table on single-host SQLite is also a backup/VACUUM problem discovered at the worst possible time. The sweep is the one documented door through the immutability guarantee — it is registered, with its reason, in the immutability spec’s allowed_bypasses. A regulated fork that needs longer retention changes one line (RETENTION_WINDOW). Account-security rows are exempt from that window and swept on their own floor, ActivityLogRetentionSweepJob::SECURITY_RETENTION_FLOOR (365 days) — the exemption keys off action membership in ActivityLog::SECURITY_ACTIONS, never off visibility. The two values are numerically the same today, so the split is a decoupling rather than an extension: it only makes a difference once a fork shortens RETENTION_WINDOW. A fork promoting the workspace-domain tier to compliance-grade would move those writes inside the business transaction the way the security tier already is.

Owner Lookup

Workspace#owner returns a single owning user and deliberately uses detect over memberships (not joins + find_by) so it works from preloaded associations without a per-row query in list views.

Workspace#owners returns all users currently holding a kept owner-role membership — used by the capacity-approaching sweep to alert every owner, and by any ownership-management UI that needs the full roster. It always issues a fresh query, even when memberships is preloaded: its callers are notifier recipient resolution paths that run right after mutations changing the owner roster, so a cached array can’t be trusted.

Render paths that only need a last-owner existence check (the Leave button — MembershipPolicy#destroy?) use Membership.other_kept_owners(...).exists? instead: one indexed EXISTS, fired only for owner rows, rather than materializing the roster per render.

Real-Time

Turbo Stream broadcasts via broadcast_refresh_to (Turbo 8 morph-based refresh). Workspace stream for membership/invitation/settings. Project stream for resource changes.

Markdowndocs Gem Integration

The markdowndocs gem renders this site’s /docs content. Two host-side adaptations layer on top of the gem’s defaults so it fits this app’s design system and CSP:

View overrides (app/views/markdowndocs/docs/) — six ERB files (show, index, _card, _breadcrumb, _navigation, _mode_switcher) that mirror the gem’s templates but route every color through this app’s semantic tokens (bg-surface-raised, text-text-heading, text-accent, etc.) instead of the gem’s hardcoded Tailwind palette pairs. The token system flips coherently with class="dark" on <html>. Rails view resolution prefers app/views/ over engine view paths, so these overrides take precedence at render time.

Mobile sidebar Stimulus controller (app/javascript/controllers/docs_sidebar_controller.js) — replaces the gem’s inline onclick handler for the mobile hamburger toggle. The host’s CSP locks script-src to :self with nonces and disallows unsafe-inline, so the host override of show.html.erb wires the toggle via Stimulus actions instead.

Both layers can be removed if the gem itself starts shipping token-friendly templates and CSP-clean Stimulus interactivity. Until then, see troubleshooting.md if a class fails to compile or a controller fails to register.