# Architecture

## Layers

DDD + clean architecture. Dependencies point inward. The domain knows nothing about
HTTP, SQL, git, or Topcoat.

```
web / ssh  (interface)   →  application (use cases)  →  domain (entities, ports)
                                    ↑
                         infrastructure (sqlite, git binary, argon2)
                         implements the ports the domain/application declare
```

| Layer | Holds | Must not import |
|---|---|---|
| `domain` | entities, value objects, typed IDs, repository traits, `DomainError` | anything infrastructural |
| `application` | use cases, ports (`GitStorage`, `GitProtocolServer`, `PasswordHasher`), `AppConfig` | concrete adapters |
| `infrastructure` | SQLite repos, `git` subprocess wrappers, Argon2, sessions, web handlers | — |

**Every operation takes an `Actor`.** Authorization is checked in the use case, before
any side effect. Not in the handler, not in the adapter. The previous attempt got this
right and it paid off — `serve_push` could enforce `Role::Owner` in one place
regardless of transport.

### Access

**`application/access.rs` is the one place that decides who may do what.** It holds
`is_org_owner`, `is_org_member`, `instance_owner` and the four resolvers every
repository use case starts with — `visible_repo` (the one visibility rule: public, or a
member of the owning org), `readable_repo` (that plus the ownership flag),
`writable_repo` and `changeable_repo` (owner-only, `NotFound` for what the actor cannot
see and `Forbidden` for what they can). A use case asks this module; it does not read a
`Role` or compare a `UserId` itself, and it does not repeat the visibility body — the
three copies that existed on 2026-09-10 were folded back into `visible_repo`.

**Two kinds of caller, two predicates, both named.** Everything above answers a question
about an `Actor` — a person with a session. The other caller is a *machine*: a control
plane holding `STEID_OPERATOR_TOKEN`, with no session and no user to be. That one is
authenticated by `web::operator::operator_authorized`, a constant-time bearer-token
comparison living in the web layer because a transport credential is a transport
concern, and it grants exactly the operator routes — never a repository, never a user's
data. A page never decides either question inline: it asks `context::owned_repo`,
`context::owned_profile` or `context::instance_owner`.

The same module holds **`Stores`**, the bundle of the three ports a repository is
reached through — organisations, memberships, repositories. Fifty-six use cases needed
exactly those three together, so they travel as one borrowed value rather than three
parameters. Ports only some use cases need (issues, labels, pulls, users, git) stay
separate arguments; a bundle that grows to hold everything is a service locator.

That is not tidiness. Milestone 7's graded permissions — a collaborator who may comment
but not merge — are a change to these predicates and, where a permission has to be
named, to their signatures. Roughly twenty lines there instead of thirty use cases,
*provided* no use case decided authorization inline in the meantime.

## Conventions

These come from two prior attempts. They earned their place.

### Typed IDs — never raw strings for entity references

```rust
// CORRECT — the compiler catches a swapped argument
fn get_member(&self, org_id: &OrgId, user_id: &UserId) -> ...

// WRONG — silently compiles, fails at runtime
fn get_member(&self, org_id: &str, user_id: &str) -> ...
```

`UserId`, `OrgId`, `MembershipId`, `RepoId`, `InviteCodeId`, `SshKeyId`.

### `new()` validates, `from_trusted()` doesn't

`new()` is for user input and returns `Result`. `from_trusted()` is for rows loaded
out of the database, which were validated on the way in. Infrastructure repos should
always use `from_trusted()` — re-validating DB rows means a validation-rule change
turns old rows unreadable.

### `from_str` returns `Result`, never `Option`

A silently-defaulted enum parse is a bug that surfaces days later as wrong
permissions. Applies to `Role`, `Visibility`, `ImportState`, `IssueState`.

### Every repository port gets two implementations

An in-memory one and a SQLite one. The in-memory one is what makes use cases testable
without a database — attempt #2 reached 60 tests this way and they ran fast enough to
stay in the loop.

### Ports live where they're consumed

Repository traits in `domain/repository/`. Service ports the application needs
(`GitStorage`, `GitProtocolServer`, `PasswordHasher`) in `application/port.rs`. Use
cases take `&impl Port`, not a boxed trait object.

Git is deliberately several narrow ports rather than one service, and how the binary is
actually invoked lives in one place — `git_command`, `count_spawn` and `run_git` in
`infrastructure/git/mod.rs`, which the per-port adapter files beneath it all call.
[0006](decisions/0006-git-binary-behind-narrow-ports.md). One file per port:
`git/{storage,protocol,archive,import,merge}.rs`, and the read port's two
implementations sit together in `infrastructure/git_query/`.

### Every form carries a CSRF token, and every POST handler checks it

`csrf_field()` in the form, `csrf_verified(cx, &submitted.csrf_token).await?` as the
first line of the handler — before the ownership guard and before the use case. The
token is `HMAC-SHA-256(per-boot secret, session token hash)`, so nothing is stored.
[0008](decisions/0008-csrf-double-submit-bound-to-the-session.md).

A `#[route]` handler returns a response rather than a view and so cannot reach the 403
page the root layout renders; it uses `csrf_verified_response` instead, in the `if let
Some(response) = …` shape `throttled` established.

A route that genuinely cannot carry a token goes in `csrf::EXEMPT` **with the reason**.
`web/csrf_scan.rs` reads this directory's source and fails the build for any POST route
that does neither — which is the only thing making a hand-written check in thirty-one
handlers safe.

## DB-plus-filesystem writes

Creating a repo writes to two places that can't share a transaction: the
`repositories` row and the bare repo on disk. Neither prior attempt fully solved this.

Attempt #1 used a **compensating transaction** — create on disk first, and if the DB
insert fails, delete the directory:

```rust
let repo = self.repository.create(&id).await?;
if let Err(e) = self.repo_record_repo.create(&record).await {
    let _ = self.repository.delete(&id).await;  // compensate
    return Err(e.into());
}
```

That leaks an orphaned directory if the process dies between the two calls, and a
directory without a row is worse than invisible — it silently blocks re-creating a
repository by that name.

**The durable fix is written.** `application/reconcile.rs` is the boot sweep: it lists
the directories on disk, subtracts the rows, and quarantines the remainder under
`orphaned/` rather than deleting it, so the name is freed and the objects are still
there. It runs beside the interrupted-import and reflog sweeps, and for the same
reason — nothing has been spawned yet, so a directory with no row is genuinely finished
rather than half-written by a task still running. It covers all three ways to get one:
a create that died before the insert, a rename that died after the directory moved, and
an import whose repository was deleted mid-clone.

The compensating transaction stays as the fast path. The sweep is what makes it safe to
rely on, and it is a sweep rather than pending rows because a pending row still needs
somebody to come along and resolve it.

## Data access

Topcoat's grain is async components that query the database directly and check
permissions inline. State comes from `app_context::<T>(cx)`, and the framework's own
guidance is to "prefer composable `cx: &Cx` functions over middleware/extractors for
auth and request-scoped data."

That reads as a view layer reaching for the data layer, which the rules above forbid.
It was a genuinely hard question while SSH was the git transport, because an SSH
channel handler has no `Cx` — so authorization expressed in a component was invisible
to `serve_push`, and the two had to share something.

[Decision 0001](decisions/0001-git-over-http-not-ssh.md) removed that transport. Every
caller now has a `Cx`, so nothing *forces* a transport-neutral use case layer. The
position is therefore a choice, taken deliberately:

**Writes and authorization go through use cases. Reads may go direct.**

- Any mutation, and any decision about what an actor is allowed to do, lives in an
  application use case that takes an `Actor` and the ports it needs. One place, one
  answer, reachable from a page, an `/api` route, or a future SSH adapter alike.
- Straightforward reads for display may query through the pool in a component.

**This is what actually happened.** The 2026-09-06 organisation review found **all 34
POST handlers going through a use case that takes an `Actor`** — not one writes through
a repository port directly — and `infrastructure/web/` importing `domain::repository`
nowhere. The rule held across four waves of parallel agents, which is the evidence it
is a workable line rather than an aspiration.

One thing the original position expected did *not* happen: `#[memoize]` was named as
what would make per-component fetching pay, and **nothing in the tree uses it**. Reads
are cheap enough, or already hoisted into a use case that returns a whole view struct,
that no page has needed to deduplicate a query. Treat it as available, not as load-
bearing; the earlier text credited it with earning its keep, and it had not been asked
to.

The tell for when a read has outgrown that: if it starts deciding whether the viewer is
allowed to see something, it isn't a read any more — move it.

Revisit if `/api` and the pages start duplicating query logic. That's the signal the
line is in the wrong place.

## Migrations

**A shipped migration is immutable, comments included.** `sqlx::migrate!` checksums the
whole file and refuses to boot when an applied one has changed; a comment edit in a
shipped file stops every existing instance. A digest test pins every released set
since 0.5.0, which between them hold every migration that has ever shipped
([releases.md](releases.md#where-each-releases-set-actually-lives)).

**Every migration must be one the *previous release's* binary can run against.** The
binary carries its schema (`sqlx::migrate!` runs on boot, see `infrastructure/
database.rs`), so a migration lands the instant a new build starts — while the old
build may still be serving from the same file.

Two situations make that not hypothetical:

- **A fleet upgrade runs unattended.** [Control-plane decision 0002](../../steid-control-plane/decisions/0002-machine-per-tenant.md)
  makes a fleet upgrade N `deploy.sh` runs against N machines nobody is watching. A
  migration the running build cannot tolerate takes a customer's instance down between
  the migration and the restart, with no one at the keyboard.
- **Zero-downtime deploys, when they are built.** The plan in `current.md` runs the old
  and new processes side by side over one SQLite file while Caddy is repointed. The new
  one migrates on boot; the old one keeps serving. A dropped column breaks it mid-swap.

So: **expand, deploy, contract.**

| Phase | What it may do | When |
|---|---|---|
| **Expand** | `create table`; `create index`; `alter table … add column` **nullable, or with a `default`**; backfill with `update` | any release |
| **Deploy** | ship the binary that writes the new shape and stops writing the old | the same release, or a later one |
| **Contract** | drop the column, drop the table, rename, tighten to `not null` | **a release later**, once no deployed binary reads the old shape |

Forbidden in the same release as the code that needs it, and the lexical guard in
`database_compat_tests.rs` fails the build for each:

- `drop column` — the old binary's `select *` still names it.
- `drop table` — likewise, and a `select` against a missing table is an error, not a
  null.
- `rename` (table or column) — a drop and an add at once, so it is both failures.
- `alter table … add column … not null` **without a `default`** — SQLite refuses it
  outright on a non-empty table, and even where it succeeds the old binary's inserts
  omit the column.

Contracting is not forbidden, only deferred: it is a migration in the *next* release,
written when that release is cut. `plans/releases.md` records which migrations each
release shipped, so "what the previous release's binary reads" is a fact rather than a
guess — check it before writing a contracting migration.

The rule is enforced two ways, and only one of them is a real test:

- **The lexical guard** reads `migrations/` at test time and rejects the four
  statements above. It covers every migration automatically, including one added after
  this was written. It is a grep, so it is fooled by a rebuild-the-table-and-swap done
  in `create`/`insert`/`drop` steps — which is exactly why the rule is written down
  here as well.
- **The replay test** applies the previous release's migration set to a fresh database
  and runs the *current* binary's reads against it. That is the honest half: proving
  the *old* binary reads the *new* schema would need the old binary linked in, and it
  is not. It still earns its place — `steid backup` opens the pool without migrating
  (see `database::open`), so a new binary genuinely does read an old schema — but the
  forward direction the rule is about is covered by the guard and by review, not by a
  test.

**A binary started against a newer database must boot**, because that is what a rollback
is: a newer release migrated the file, failed, and the previous binary was put back.
An old process that is *already running* keeps serving under the rule above; one
*started* against the newer file meets sqlx's migrator first. Expand-only makes it
*able* to read the newer schema, but sqlx's default `ignore_missing: false` stops it
from trying: an applied migration it does not know is `VersionMissing`, the binary
exits, and systemd restarts it for ever. So `migrate()` calls
`set_ignore_missing(true)`. Only the unknown versions are excused — every migration the
binary carries is still checked against its stored checksum, so an edited shipped
migration is still `VersionMismatch`.

- **Since 0.8.1.** The fix only helps a rollback *to* a version that carries it. 0.8.0 →
  0.7.0 can never roll back; the first rollback that can work is onto 0.8.1 or later
  ([launch 1.2](../../plans/launch.md#phase-1-before-anything-else)).
- **Tested in process, not against a real binary.**
  `a_database_one_migration_ahead_still_boots` starts *this* binary's migrator against
  a database one migration ahead, after checking that sqlx's default refuses that same
  database, and then reads the table the newer migration widened.
  `an_edited_migration_is_still_refused` checks the strictness that is kept. Booting
  the real previous release's binary against the current schema needs a Linux binary,
  so it belongs with the contract tests (launch 5.6), not in `cargo test`.

## Safety

Safe Rust only. No `unsafe`.

## Test files

A module's tests live in `mod tests` at the bottom of the file until the file passes
about 1,500 lines; past that they move to a sibling `<module>_tests.rs` declared as

```rust
#[cfg(test)]
#[path = "repo_tests.rs"]
mod tests;
```

`#[path]` changes only where the file is read from, not the module tree: the block is
still `module::tests`, `use super::*` still means the module under test, and no
private item needs widening — which is why it beats a `tests/` directory (that turns
`repo.rs` into `repo/mod.rs`) for this. The sibling sorts beside its module. Six files
follow it as of 2026-09-08; `web/pulls.rs` and `repository/in_memory.rs` are over the
threshold and do not yet.
