`. |
+| HeimdallReversed | `AdvanceAsync` on the reversal's `Moved` | proofs wiped | `UndoLocalAsync` is retried. |
+| Undone, Final | ledger | | |
+
+`AdvanceAsync(mergeId)` is the one step function: the confirm's inline advance, the sweeper's resume and an undo request all run it, forward move and reversal alike (same seal, same outcome handling, same backoff). Every transition is one save guarded by `State`, the concurrency token; the loser of a race clears its tracker, reloads and continues from the stored state, so two advances make one Heimdall move and one commit. `Proposed` is declared by the ledger and written by nobody in this cut.
+
+`ConfirmAsync` refuses (writing nothing) a third-party actor (`NotParty`), a plan with blocks (`Blocked`, codes only), a plan other than the one the member saw (`PreviewStale`: `MergePlan.Digest(survivorId, foldedId)`, a SHA-256 over a length-prefixed canonical text of the plan), and any proof of another Heimdall account (`ProofAccountMismatch`). A second live merge folding the same account, or a chain, is refused by the database (the live-merge unique index and the chain trigger) and answered `Blocked(merge_in_flight)`. Confirm and the undo request run through `AccountMergeLedger.WriteAsAsync` for the acting member, like every writer that acts for an account.
+
+**Heimdall down.** `Unknown` (a timeout, a 5xx, a 429, an unrecognised 4xx, `move_id_conflict`) never fails a merge: the saga counts `Attempts`, sets `NextAttemptUtc` (15 s, 1 min, 5 min, then 15 min) and replays the same stored id; the folded account stays Frozen until Heimdall answers. Heimdall's answer to a replay of a move it already stored does not depend on the proofs' age, but a move that never reached Heimdall does: an outage longer than the proofs' freshness (300 s for a login's weak proof, 600 s for a passkey's strong one) ends, when Heimdall is back, in `Refused proof_stale` and a Failed merge; the member confirms again with fresh sign-ins. A replay whose proofs no longer verify (Heimdall's key regenerated) answers `move_id_conflict` and stays Unknown; a receipt that names an account other than the destination is `receipt_mismatch` (proofs wiped, no retry); a sealed payload the key ring can no longer open is `proofs_unreadable` (retried in an hour, state unchanged, because Heimdall may already have moved). None of the three ends by itself: see Stuck merges.
+
+**Sealed proofs.** The saga holds the two Heimdall bearers (`ruling merge-sealed-proofs-until-move-final`) only between Confirmed (or UndoRequested) and Heimdall's final answer: protected with Data Protection (purpose `Bifrost.AccountMerge.Proofs.v1`), never logged, wiped in the save that records Moved or Refused. Logs name the merge id, state, outcome class and refusal code; never a token, account id, identity id or provider user id. Proof coverage is Heimdall's rule (`move-proof-strict-passkey`): a proof through one login moves only that login, and only an asserted passkey speaks for the whole account, so a folded account's every login must be proved (or a passkey asserted) or Heimdall answers `identity_not_proved`. A `moveId` replayed with other identities returns the first receipt (`move-replay-first-receipt`).
+
+`AccountMergeSweeper` is the one merge loop (30 s): per tick, in one scope, `MergeProofs.PruneExpired` (a proof bearer lives only in process memory and is dropped 270 s after its proof, on access and by this tick, so none outlives that plus one tick whether or not anyone opens the page; `heimdall-body:ruling:merge-proof-bearers-memory-bound`), then `AccountMergeSaga.AdvanceDueAsync` (every in-flight merge whose `NextAttemptUtc` is null or due, oldest first, a failure logged and skipped), then `FinalizeDueAsync`.
+
+## Stuck merges
+
+`/App/Merges` (platform admins only; the `/App` folder's ActiveMember policy, then `IsPlatformAdmin`) lists in-flight merges (Confirmed or UndoRequested) that stopped on `receipt_mismatch`, `proofs_unreadable` or `move_id_conflict`, or were retried eight times, with the merge id, state, last outcome, attempts and the stored move id of the leg in flight. It shows no Heimdall account id, login or account name, and calls no Heimdall. Only the first three outcomes can be ended (`AccountMergeSaga.SettleableOutcomes`); a merge listed for its attempts alone is still being retried.
+
+Two actions (`heimdall-body:ruling:merge-stuck-end-only-typed-id`), both `AccountMergeSaga.SettleStuckAsync`, both needing the leg's stored move id typed back (the forward id for a Confirmed merge, the reverse id for an UndoRequested one) and both writing one `merge.settled` audit row that names the merge and the choice only:
+
+| Action | Applies to | Result |
+| --- | --- | --- |
+| Fail the merge (`FailForward`) | Confirmed, stuck | `Failed`, `FailureCode` and `LastOutcome` `operator_failed`, proofs wiped. The folded account is free again; the pair can be confirmed anew. |
+| Give up the undo (`AbandonUndo`) | UndoRequested, stuck | back to `Committed`, `LastOutcome` `undo_operator_abandoned`, proofs wiped, the grace as it was. The merge stands; the logins stay with the survivor. |
+
+HeimdallMoved and Committed are never settleable: Heimdall answered Moved with a matching receipt there, and the saga rolls forward. A settle and the sweeper's `AdvanceAsync` meet at the `State` concurrency token; the loser changes nothing and the other transition stands (answered `lost`). A settle does not fence a replay already in flight to Heimdall, so read `identity_moves` first and read it again after.
+
+Before ending a merge, read Heimdall's `identity_moves` row by the stored move id. If Heimdall did move the logins, failing the merge leaves them moved with no Bifrost merge to match: repair or reverse at Heimdall first. For `receipt_mismatch`, repair Heimdall's or Bifrost's account link before failing. Adopting a move Heimdall made (writing HeimdallMoved from a receipt) stays manual SQL until follow-up `merge-operator-adopt-moved`; the page never does it.
+
+## Pages and flags
+
+`Pages/Membership/MergeAccounts` is the one page that creates a merge. It is `[Authorize]`, no-store, a 404 unless `AccountMergeOptions.Enabled` (section `AccountMerge`, default false; environment `AccountMerge__Enabled`) and forbidden to a frozen or folded account, as Linked accounts is. Linked accounts shows one "Merge two accounts" link, only when the flag is on and the session is Heimdall-backed.
+
+Its stage is derived on every request from `MergeProofs.Snapshot` and the `keep` query; no cookie or form field carries progress except the chosen direction and the preview digest, which the saga re-checks.
+
+1. Prove: the member names a provider for this account (`MergeProveSelf`) and for the other (`MergeProveOther`). Nothing about the other account is rendered until both proofs are held.
+2. Choose: both accounts are named by display name only, and `keep=self` or `keep=other` shows the preview. No survivor is preselected (the chat-history default needs `ChatFirstSignInUtc`, follow-up `merge-chat-default-survivor`; the chat paragraph carries the warning meanwhile).
+3. Prove the rest: one fresh sign-in for each login of the account that would be folded and is not yet proved (`ProveRemaining`). Proofs older than `MergeProofs.ProofLifetime` fall out and are asked again.
+4. Confirm: two checkboxes, one per account, the direction and the digest. `AccountMergeSaga.ConfirmAsync` inserts the Confirmed row, which is the consent record (actor, time, digest, proof providers); the page then runs `AdvanceAsync` once (a throw is logged and the sweeper resumes) and sends the member to Merge status. `MergeProofs.Clear` runs after a Confirmed outcome only: Blocked, PreviewStale, NotParty and ProofAccountMismatch come back as closed codes (`?merge=`), keep the proofs and write nothing.
+
+`MergePreview` is the one wording of the plan (counts by entry kind and action, the nine block codes, the static statements about chat, connections, StreamPixels, roles, one vote per motion, the 7-day undo and ordinary sign-ins); the digest is `MergePlan.Digest` of the plan just rendered. `MergeWording.Confirm` holds the refusal words. The page writes no merge, vote, membership or journal row.
+
+Deploy: set `AccountMerge__Enabled` only after Heimdall's identity-moves route is deployed and probed. A Confirmed merge against a Heimdall without it stays Unknown and keeps the folded account frozen.
+
+## Notices
+
+The chat host learns of merges by pulling, never by being pushed to: Bifrost has no event receiver and no outbox. `MergeNoticeFeed` derives the notices from the `AccountMerges` row on every read (merged: `CommittedUtc` set; undone: `UndoneUtc` set; final: `FinalizedUtc` set), so a notice cannot disagree with its merge, and a Failed, Frozen or Confirmed merge (no `CommittedUtc`) yields none. The only stored fact is the reader's ack, one `AccountMergeNoticeAcks` row per (merge, kind, target), written by nothing else (migration `AddAccountMergeNoticeAcks`; the table holds only acks, so its `Down` drops it). The feed never writes a merge column.
+
+```
+GET /api/merge-notices/chat?after=&limit= -> 200 JSON array, oldest first by (occurred_at, merge_id, kind)
+POST /api/merge-notices/chat/ack {"merge_id": "...", "type": "merged"} -> 204
+```
+
+Payload, exactly these keys: `type` (`merged`, `undone`, `final`), `merge_id`, `occurred_at` (the matching timestamp, ISO 8601 UTC), `grace_ends_at`, `old_subject` (the folded `UserAccount.Id`, format D, the OIDC `sub` the chat session knew), `new_subject` (the survivor's), `old_preferred_username`, `new_preferred_username` (`NormalizedBifrostIdentity`). `limit` defaults to 50 and is capped at 200. Acks are the cursor: a read returns every unacked notice; `after` only narrows the scan to notices strictly later than that time, so a reader must not skip unacked ones by it. An ack is idempotent (a repeat is 204); an ack for a (merge, kind) the feed would not emit now, such as `undone` for a merge not undone, is 404; a malformed body or unknown `type` is 400.
+
+Auth: `Authorization: Bearer `, compared in constant time after SHA-256 of both sides against `ChatNotices:Token` (environment `ChatNotices__Token`). An empty token turns both routes off (404). A missing or wrong bearer is 401 with an empty body. No cookie, no CORS, `Cache-Control: no-store`. Startup does not require the token.
+
+```
+curl -sS -H "Authorization: Bearer $TOKEN" "$BIFROST/api/merge-notices/chat?limit=50"
+curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
+ -d '{"merge_id":"","type":"merged"}' "$BIFROST/api/merge-notices/chat/ack"
+```
+
+The feed carries no email, display name, Heimdall id, Matrix id or history flag. It is information for the chat operator's side; back-channel logout (`OidcLogoutReconciler`) stays what ends chat sessions. Chat-side rules that bind Bifrost already hold: undo is refused past Final, and `preferred_username` never changes. A later reader (StreamPixels) adds a target constant and its own token over the same derivation.
+
+Deploy: set `ChatNotices__Token` on Bifrost and hand the same value to the chat host's timer script (the secret's path is the chat steward's).
+
+## Merged is terminal
+
+Only the ledger writes `Membership.Status = Merged` or leaves it. The other status writers refuse a merged row (`Membership.IsMerged`): the bootstrap-admin promotion (startup and every GitHub sign-in, which is the one status write sign-in sync makes on an existing account) skips it, the Heimdall member-access claim does not activate it, member approval refuses it and the suspension service reports `NotApplicable`. Folded standing itself is still derived from the merge state, never from this status.
+
+## Rollback
+
+Bifrost is **roll-forward only** once a merge exists (`heimdall-body:ruling:merge-roll-forward-only`). A build older than `AddAccountMerges` cannot read the `Merged` membership status (EF throws on `/App/Members` and on the folded account's sign-in) and has no query filter, so it counts voided votes and appraisals again. Deploy the merge migration knowing that a code rollback past it is not available after the first merge lands; fix forward. The migration's `Down` refuses while any `AccountMerges` row exists, whatever state, so it cannot drop the merge record and journal under a `Merged` membership. No tombstone table is built: it would fix only the recount, not the enum.
+
+## Not covered
+
+`MembershipSynchronizationService` still writes the profile of a GitHub-signed-in row that is not merged. Sealed-ballot rows of a folded account on a motion that is already closed stay as they are. Every writer that acts for an account (votes, concept appraisals, sealed-ballot commit and reveal, patron events, the Heimdall sign-in's membership) passes through `AccountMergeLedger.WriteAsAsync`. On Postgres it opens a transaction, takes a shared advisory lock on the account (`pg_advisory_xact_lock_shared(hashtextextended(id::text, 0))`, the key the chain trigger takes exclusively when a merge row is inserted or changes state), reads standing, runs the writer's save and commits. `CommitAsync` takes the exclusive lock on the folded account before it reduces, then re-reads the merge. So: a writer whose standing read found no merge saves before a merge can freeze or fold the account, and the commit's reduction sees what it saved; a merge that is already frozen or folded when the writer reads is refused (votes, appraisals, ballots, sign-in membership) or routed (patron events). Guaranteed only for writes made through the gate, and only on Postgres: the in-memory provider has no lock or transaction (tests that rest on the lock run on live Postgres), and a writer that catches a database error inside the gate cannot continue, because the transaction is aborted. Not closed: writers outside the gate (nothing in the code base today; a new one must use it), and a writer's own stale reads taken before the gate opened (the motion a vote was loaded with), which concern the motion, not the account's standing. No operator void tool exists.
+
+`UX_TierSnapshots_MembershipId_CurrentPatron` allows one current Patron snapshot per membership, so two restages of one survivor racing cannot both leave a current snapshot: the loser's save fails on the unique index, a merge commit rolls back whole and is retried by the saga, and a patron refresh re-reads and derives again.
diff --git a/docs/bifrost-mvp-plan.md b/docs/bifrost-mvp-plan.md
index fa1bd10..29fd545 100644
--- a/docs/bifrost-mvp-plan.md
+++ b/docs/bifrost-mvp-plan.md
@@ -4,7 +4,7 @@
- Create Bifrost as a separate GameCult app repo and deploy it on Yggdrasil.
- Build a member alpha, not a public launch.
-- Use ASP.NET Core 8 with Razor Pages + HTMX and PostgreSQL.
+- Use ASP.NET Core 8 with Razor Pages and PostgreSQL.
- Support invite-only GitHub-linked members, GitHub-backed and internal work items, app-native governance, Reddit organizing threads, and internal ledgers.
- Preserve the Labor Platform loop: user/member/patron demand raises work priority and reward pressure, contributors pick up valuable work, maintainers accept completion artifacts, and Bifrost credits the contributor plus any bounty/reward allocation.
- Do not include Ethereum, wallets, DAO mechanics, or payout execution in v1.
@@ -13,7 +13,7 @@
## System Shape
- One ASP.NET web app process for v1.
-- Server-rendered UI with HTMX for progressive interactions.
+- Server-rendered UI; no client-side framework or third-party script.
- PostgreSQL as the system of record.
- Bifrost-native identity registration for login, with GitHub OAuth available as a linked external identity.
- GitHub App plus webhooks for issue and pull request lifecycle sync.
diff --git a/docs/bridge.md b/docs/bridge.md
index 683d7d2..b4cf73c 100644
--- a/docs/bridge.md
+++ b/docs/bridge.md
@@ -23,7 +23,7 @@ That means Bifrost owns the operational meaning of the crossing:
It does not mean Bifrost should own OAuth sludge. Bifrost is both an identity provider and identity consumer: a GameCult actor should be able to register with Bifrost without OAuth, and that Bifrost identity should be enough to authenticate with most GameCult services. Heimdall owns outside-provider OAuth, linked-account token custody, grants, and signed account claims. Bifrost associates those Heimdall-backed accounts with the Bifrost identity, consumes the permission facts, and decides whether a bridge action is allowed in the Bifrost domain.
-The native registration surface is `POST /auth/bifrost/register`. It creates a Bifrost-owned `UserAccount` with `BifrostIdentity` and `NormalizedBifrostIdentity`, signs the caller in with the Bifrost cookie, and leaves membership at `Authenticated`. It does not grant active member access, mint outside-provider tokens, or replace Heimdall's account-link and capability custody.
+The native registration surface is `POST /auth/bifrost/register`, which takes `identity`, optional `displayName` and `returnUrl`, a solved proof-of-work `challenge` and `nonce` (from `GET /auth/bifrost/challenge`), and `acceptedNoticeVersion` (from `GET /auth/bifrost/notice`). It creates a Bifrost-owned `UserAccount` with `BifrostIdentity` and `NormalizedBifrostIdentity`, signs the caller in with the Bifrost cookie, and leaves membership at `Authenticated`. It does not grant active member access, mint outside-provider tokens, or replace Heimdall's account-link and capability custody.
## Ownership
@@ -196,15 +196,90 @@ The command is a dry-run shape probe for public surfaces that are real enough to
Bifrost's native Discord gateway is the conversation observer. A direct mention of the Bifrost bot, or a reply to one of its messages, becomes an immutable typed `bifrost.discord.persona_conversation_event.v0` only when the guild and channel have one exact Persona target binding. Bot-authored, ambient, empty, over-1200-character, unbound, and ambiguously bound messages do not enter the conversation path. The 1200-character cap is the shared signed alpha boundary with Epiphany. The observation store is Bifrost-private working state, never an actuator queue, and insert collisions must contain exactly equal content. VoidBot does not observe, schedule, or answer for the target Persona.
-Persona replies cross back through two explicit CultMesh surfaces. Epiphany is
-the sole writer of `epiphany.persona_discord_delivery_request.v0`; Bifrost
-reads that surface, authenticates the dedicated Persona-mouth signer, journals
-external execution before touching Discord, and is the sole writer of
-`bifrost.persona_discord_delivery_receipt.v0`. Epiphany reads receipts but
-never receives the Discord token or write access to Bifrost private state.
-`unknown` is terminal for automatic transport retry: an external post may have
-happened, so restart recovery must not manufacture a duplicate. Failed and
-unknown outcomes remain Persona pressure for explicit resolution.
+Persona speech goes out through Matrix, not Discord. `tools/persona-matrix-mouth.mjs` is the one process for every Persona (`PERSONAS`, a list of slugs): it holds each Persona's Matrix access token as its own systemd credential (`matrix-token-`) and nobody else holds any. Per Persona it keeps one `/sync` loop over the configured rooms and the account's direct rooms (a DM invitation from an account on `MATRIX_SERVER_NAME` is accepted while that Persona's brake is released, and one from any other server is declined), one cursor and one delivery sequence. v1-v4 delivery ids are Matrix ids: the event id (`$`), the sender, each context line's sender and each mention (`@`) are at most 255 bytes with no whitespace, control, format or private-use characters; the mouth skips an event, drops a context or tail line, or drops a mention that fails this, and the encoder and parser refuse it. A delivery carries the sender's Matrix id, the event's `m.mentions` user ids and whether the room is a DM. A media event (`m.image`, `m.file`, `m.audio`, `m.video`) is delivered as a typed text line, `[image filename="cat.png" mime=image/png size=2048 url=mxc://server/id]`, followed by its caption when it has one, in `text` and in context. Only `m.image` is also fetched, and only when `IMAGE_STORE_ROOT` is set (unset, the line above is all there is and nothing is downloaded). The fetch is made as the receiving Persona, with its own token, from `/_matrix/client/v1/media/download//` on its homeserver, for a message the Persona is delivered (not its own words, a room it is not joined to, or history before the ear), and only from the event's own `content.url`; a URL in the message text is never followed. An encrypted attachment (`m.room.encrypted`, or `content.file`) is never fetched. The type is decided by the magic bytes alone (png, jpeg, gif, webp; SVG and anything else is refused, the declared mime is ignored), the body is capped at 5 MiB by `Content-Length` and by the bytes actually read, and the pixel count read from the image header (never decoded) is capped at 40 MP. A refused or failed fetch leaves the typed line with a fixed-word reason (`refused=encrypted|no-url|fetch-failed|too-big|wrong-type|bad-header|too-many-pixels|store-failed`) and no image. A stored image is written to `IMAGE_STORE_ROOT///[.png|.jpg|.gif|.webp]`, the name generated by the mouth, never the sender's: files `0640`, room directories `2750` (the Persona directory is setgid to the Persona's group, so the Persona's reader opens them by group; the mouth is the only writer), each written under a temporary name and renamed. It is deleted once it is at least 24 hours old and its delivery has been acked, whichever is later; a room keeps at most 50 MiB, the oldest evicted first. The sweep runs when an image is stored and when an ack arrives. A delivery is the 12-field tuple of `gamecult.persona.chat_pending.v2`: field 11, after `is_direct`, is nil or `[path, mime, size, sha256]`, a reference and never bytes; `path` is the store-relative `/` above, `mime` the sniffed type, `size` the file length (at most 5 MiB) and `sha256` its lowercase hex digest. The reader re-checks all four against the file. A Persona turn that has no reader for it still sees the typed line. Reading wakes nothing and acks nothing: the heartbeat polls with the non-consuming `gamecult.persona.chat_pending_request.v1`, and only `chat_ack` advances a position. An ack posts nothing to Matrix. That Persona's public `m.read` receipt follows `gamecult.persona.chat_read.v1` (`[persona, room_alias, event_id, at_unix_ms]`), which Huginn sends when a delivery has gone into the model's input: the mouth posts `m.read` at that event id only, for an event it delivered to that Persona in that room (to the delivered room id, whatever alias the report named), never behind the last receipt that landed there, one report per room at a time, and only while her brake is released (re-read after the presence write; fire and forget on the endpoint: a failure is logged once and not retried; pending polls and acks post none). Her Matrix presence follows a turn and her brake: `online` while a read report, a send or an ack came within `presenceGraceMs` (5 minutes), `unavailable` after that, `offline` while the brake is held. Each `/sync` carries the state as `set_presence`, and a change is also `PUT /presence//status` at once (a brake placed mid long-poll shows within `syncTimeoutMs`, 30 s, plus one PUT; a stopped mouth reads offline after Synapse's sync timeout). The mouth speaks on a `gamecult.persona.chat_send_request.v1` and joins rooms only while that Persona's brake (`/etc/gamecult/minds//control.cc`) is released. One loopback CultNet RUDP endpoint serves all of them; a request naming an unlisted Persona gets a typed `chat_refusal` (`UnknownPersona`). Document shapes: `tools/persona-chat-documents.mjs`; golden bytes: `tests/fixtures/persona-chat-v1/`, `-v2/` and `-v3/` (the pending answer; Huginn pins the same bytes). The Discord posting actuator, its permit and its RUDP listener are removed.
+
+### Addressing facts (`chat_pending.v3`)
+
+The mouth wakes no one; the heartbeat and each Persona session decide who is told a delivery (Huginn `address.rs`, ruling `eureka-body:ruling:addressed-delivery-only`). Telling every Persona every message made 71.5% of 4,351 Persona turns on 2026-11-10 do nothing. The rule stays in one place, Huginn's, because two of its inputs are not Matrix facts: the Persona's stewardship records (her projects' chat names) and the sender's role (operator or Mind). The mouth owns the other half: what Matrix itself says, per Persona, for the delivery. Matrix verifies the sender's identity and nothing else: `tag` and `room` are the sender's claim in `m.mentions` (the homeserver does not check the text against it, nor that the sender may use `@room`), and `reply` is checked against the event it targets, which the mouth reads as her account.
+
+A client asks for the facts by the kind it polls with: `gamecult.persona.chat_pending_request.v2` (the v1 tuple, `[persona, after_seq]`) is answered with `gamecult.persona.chat_pending.v3`; a v1 request still gets the 12-field `chat_pending.v2` answer unchanged. A v3 delivery is the 12 fields of the v2 delivery, then:
+
+| Field | Type | Meaning |
+|---|---|---|
+| 12 `basis` | `"direct"`, `"tag"`, `"reply"`, `"room"`, `"follow"` (only with `CHAT_FOLLOW=1`, see Follow) or nil | Why the message is for this Persona, by what Matrix says, first that holds: `direct` the room is one of her DMs; `tag` `m.mentions.user_ids` lists her id, or the client sent no `m.mentions` at all and an `` in the HTML body is exactly her `matrix.to` link; `reply` it replies to, or is in a thread under, an event her account wrote (her Self run speaks as her account, so its words count; any member's message in a thread under one of her events is a `reply` too, and the target is read once per room and event and kept for a minute, hit or failure); `room` an `@room` mention. A `notice` or an `edit` costs no reply lookup. Known limit: lookups run one at a time inside the `/sync` round (10 s each, at most two per reply), so a slow homeserver slows the round; they are not parallelised or capped per round. |
+| 13 `form` | `"message"`, `"notice"` or `"edit"` | `m.notice` is an automated line; `m.replace` is an edit of an earlier message. Only a `message` can address anyone. |
+
+What the mouth cannot know, and so what a nil `basis` means: **unproven, not "not for her"**. Her handle and public name in the text (any casing, with or without `@`, `'s`), the names her stewardships list, a project's repo name, and whether the sender is the operator or a Mind are all matched by Huginn, not here. A reply whose target the homeserver will not give is nil and logged. The mouth also cannot see whether a message was meant for her without naming her. Every delivery is still delivered, claimed tags included: nothing is dropped in the mouth, so the Huginn rule cannot lose a message the mouth had no way to judge.
+
+Proposed runtime half (follow-up `persona-wakes-on-address-only`):
+
+1. Poll with `chat_pending_request.v2` and parse `chat_pending.v3`.
+2. A delivery is *addressed* to a Persona when `form == "message"` and either `basis` is `direct`, `tag` or `reply`, or `address::addresses` matches her names or her projects' names on the text. The off-beat wake keeps the sender gate of `heartbeat.rs` `wakes` (the operator or another Mind of the roster): a stranger's tag, `@room` or DM is delivered but wakes no one off the beat. `basis == "room"` is the runtime's policy to weigh; the mouth only reports it.
+3. A real-time wake, a live session's tell and the stagger apply to addressed deliveries only. A `notice` or an `edit` never wakes, whatever its basis.
+4. A delivery that is not addressed is acked in sequence with the rest, so the position moves (the mouth stops reading at 500 unacked deliveries); it is not lost: Matrix is the record, and the next addressed delivery's `context` (up to 20 lines) and a beat's own room read show it. The room tail below gives a scheduled beat those lines without a Matrix read of its own; the mouth adds no endpoint for it.
+5. `basis` and `form` are evidence, not authority: a sender's claim is weighed by the runtime's own rule (`address.rs` for names, the sender gate for who may wake her); the mouth reports what the event says and what only Matrix could look up (the author of a reply target).
+
+### Room tail (`chat_pending.v3`, field 2)
+
+The v3 answer is `[persona, deliveries, tail, tail_gaps]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It uses the same room read as a delivery's `context` (the same function, a separate read), as her account, with no new endpoint; the cost is one `/messages` call per speakable room per poll (15 seconds cached), including every DM. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`. `chat_pending.v3` has not been deployed, but a reader that decodes it as a two-field tuple fails on the third element (rmp-serde `LengthMismatch`), so Huginn must accept `tail` and `tail_gaps` (defaulted fields) before this mouth is deployed. The array is positional: a decoder of the earlier three-field shape fails on the fourth element with the same `LengthMismatch`, so `tail_gaps` has the same deploy precondition; a decoder that reads the first three elements and ignores the rest sees `persona`, `deliveries` and `tail` unchanged.
+
+| Bound | Rule |
+|---|---|
+| Rooms | Only rooms the Persona may speak in: a configured room she has joined, or one of her DMs. The same rule `send` uses (`speakableRoomId`). A room she is in but cannot speak in, and any other room, is absent. |
+| Lines | A text line outside threads, not an edit, newest `20` per room, newest `60` over all rooms. Trimmed oldest first if the reply byte budget (256 KiB, deliveries first) would be exceeded. |
+| Cursor | None. The tail is each room's newest lines whether or not they were delivered or acked: a message the wake rule left unaddressed is acked and leaves `pending`, and the tail is where a beat still finds it. A reader removes the lines a delivery already shows (by event id). Her own lines are included. |
+| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news. A room that cannot be read within 10 seconds is logged and absent; the other rooms and the deliveries are unaffected. |
+
+A line is the 7-field tuple `[room, event_id, at_unix_ms, sender, form, basis, body]`: `room` is the configured alias (the room id for a DM), `form` and `basis` as for a delivery, `body` clipped to 1000 bytes with the same typed text line for media a delivery has (nothing is fetched). `basis` is what Matrix says on the event itself (`direct` in a DM, `tag`, `room`) and nothing the mouth would have to look up, so a reply is nil here: **nil is unproven, not "not for her"**, and a line in a DM is `direct`. Huginn's rule that an `is_direct` delivery wakes with a nil `basis` is unchanged and lives with Huginn; the tail does not feed it.
+
+The tail is **data, not instruction**. A line is what a sender typed in a room, and the mouth wakes no one, acks nothing and sends nothing because of it. A reader treats the body as untrusted text and weighs `basis` as evidence, as for a delivery. The tail does not replace a delivery: a message still reaches her as a delivery, with its own `seq`, and only `chat_ack` advances a position.
+
+#### Gaps in the tail (`chat_pending.v3`, field 3, `tail_gaps`)
+
+`tail_gaps` is a list of room names (the configured alias, or the room id for a DM, as `room` in a tail line), one for each speakable room whose lines are not all in `tail`. A reader renders such a room as **unknown**, not quiet. Absent or empty means every speakable room was read fully: a room with no lines because it is quiet, and a room whose few lines all fit, are never listed. Order is the order the mouth reads rooms (configured rooms in join order, then DMs), not time; a room appears once however many causes apply. Causes, all of them:
+
+| Cause | Where |
+|---|---|
+| The room's read failed (the homeserver refused or errored) or did not answer within 10 seconds (`sendTimeoutMs`); the room is logged and contributes no lines | the mouth |
+| The room had more than 20 lines outside threads (the per-room cap; her own lines count), so older ones were left out | the mouth |
+| The read window came back full (100 raw events, before edits and thread replies are set aside), so real lines older than the window may exist and are unseen; a shorter chunk means the room's history was exhausted. A room whose history is exactly 100 events long is gapped too, since the mouth cannot tell. The rule assumes a homeserver returns the 100 events asked for whenever older history exists; a server that caps the limit lower turns a truncated read into a false "whole", and Bifrost does not detect that | the mouth |
+| One of the room's lines was cut by the 60-line total cap (only the newest 60 over all rooms are kept) | the mouth |
+| A line was dropped as malformed (no event id) | the mouth |
+| The reply byte budget (256 KiB, deliveries first) cut the room's oldest lines, or a line would not encode and was skipped | the reply |
+| The mouth has not started: every configured room is a gap (DMs are not yet known) | the mouth |
+| The whole tail read failed: every speakable room is a gap, and the deliveries are still served | the endpoint |
+
+A line a delivery already shows and a room she cannot speak in change nothing here; her own lines are lines like any other and count toward the caps. A read the mouth kept for 15 seconds counts as a read.
+
+Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries two lines and no gap, `chat_pending.v3.tail-gaps` one line and two gap rooms; the earlier v3 samples gain an empty fourth element); Huginn pins the same bytes.
+
+### Follow (`basis` `"follow"`, `CHAT_FOLLOW=1`)
+
+A message from someone she is in conversation with is for her even when it names no one. **It is off unless the mouth runs with `CHAT_FOLLOW=1`** (exactly `1`; default off), because the basis is Huginn's `Basis::FollowUp`, wire string `follow` (`FOLLOW_UP_BASIS`, f09bc56e), and a Huginn that predates it refuses the string. With the flag off the mouth emits no `follow`, makes no extra read, and keeps no follow state.
+
+With it on:
+
+- **Anchor.** Her own post in a public room anchors that room for W = 600 s from the post. The mouth anchors at send time (the send's own time, in `send`, in the background: the send receipt never waits on the room-state read) and also from the /sync echo of her own events, so a post from another client of her account anchors too; one event anchors once. Only her posting again re-anchors the room and re-snapshots who is counted; a follow never extends the window.
+- **Counted senders** (snapshotted at the post): those who spoke in that room in the 10 minutes before the post (a per-room ring of recent senders with event times, 200 entries), plus anyone the post tagged (`m.mentions.user_ids`) or replied to (the author of the quoted `m.in_reply_to`, not a thread fallback pointer) when the event carries it. Someone who first speaks after her post is not counted. A member who spoke in the 10 minutes before her post is counted, bounded by 3 follows per hour per (peer, room). Nothing reads message text; no ids are scraped from bodies. She herself, and bridged senders (the `platformEvent` identifier rule), never count.
+- **Follow.** A `message` (not an edit, not a notice) from a counted sender gets `follow` only when it would otherwise have no basis (a plain message); `room` (@room), `tag`, `reply` and `direct` keep their own basis, and an @room neither wakes via follow nor spends the peer's K. Its timestamp must lie inside the window (a homeserver clock up to 60 s behind still follows) and this process's clock must not be past the window's end by more than 60 s, so an old or forged `origin_server_ts` reuses nothing. At most K = 3 per (Mind, peer, room) in the hour before the message; past it the message keeps the basis it had.
+- **"Public" means non-DM, non-encrypted, non-bridged.** The room is not one of her DMs and its state has no `m.room.encryption`, `m.bridge` or `uk.half-shot.bridge` (read once per room, kept 5 minutes; unreadable or malformed state is not public). An invite-only plaintext room counts as public. Nothing is anchored in, and no follow is delivered in, any other room.
+
+State is in memory only (per-room anchor, sender ring, follow times), purged on every sync pass; nothing is stored, and a restart only shortens windows.
+
+### Reply link (`chat_pending.v4`)
+
+A reply to anyone but the Persona arrives bare in v3: `basis` is `reply` only when the quoted author is her account. v4 adds what the message quotes. **It is off unless the mouth runs with `CHAT_PENDING_V4=1`** (exactly `1`; default off), because Huginn pins the tuple bytes and must read v4 first. With the flag off, `gamecult.persona.chat_pending_request.v3` is not a served kind: it is refused as any unknown kind is (`chat_refusal` `UnknownKind`, logged), byte for byte, and v1/v2/v3 requests are answered as before. With it on, that request kind (the v1 tuple `[persona, after_seq]` again; the kind asked by names the answer) is answered with `gamecult.persona.chat_pending.v4`.
+
+The answer is `[persona, deliveries, tail, tail_gaps]` exactly as v3; each delivery is the 14 v3 fields, then field 14:
+
+| Field | Type | Meaning |
+|---|---|---|
+| 14 `reply_to` | nil or `[event_id, sender, excerpt]` | The event this message replies to (its own `m.in_reply_to`; a thread's `is_falling_back` pointer names no one and is nil). `event_id` the quoted event; `sender` its author's Matrix id, read from the homeserver as her account; `excerpt` nil, or its text. |
+
+`excerpt` is nil, with `event_id` and `sender` kept, when the quoted event is redacted (`unsigned.redacted_because` present or no content), is not a text-bearing `m.room.message`, is **edited** (it is itself an `m.replace`, or the homeserver bundles an `m.replace` in its `unsigned.m.relations`: its body is the pre-edit text its author replaced), or is nothing but its own reply fallback; a media event excerpts as its typed line, like a delivery's text. Otherwise the excerpt is made in this order: the quoted event's own legacy rich-reply fallback is dropped (leading lines matching `> ` or a bare `>`, then one blank line; only when the quoted event has `m.relates_to.m.in_reply_to`); the text is held to the 1000-byte line bound; runs of CR, LF, tab, U+2028 and U+2029 become one space; control characters (C0, DEL, C1 including NUL and ESC), format characters (Unicode Cf: bidi marks, overrides and isolates, U+061C, U+200B-200F, U+2060-2064, soft hyphen, BOM), private-use characters (Co), the tag block U+E0000-E007F, variation selectors (U+FE00-FE0F, U+E0100-E01EF, U+180B-180F), the combining grapheme joiner U+034F, the Hangul and Khmer fillers (U+115F, U+1160, U+3164, U+FFA0, U+17B4, U+17B5), the blank braille cell U+2800, the unassigned default-ignorable ranges (U+2065, U+FFF0-FFF8, U+E0080-E0FFF) and unpaired surrogates are removed (cost accepted: an emoji loses its VS16 presentation, ❤️ becomes ❤, a keycap loses its selector; Mongolian free variation selectors and ideographic variation selectors go too); the line is trimmed; then the first 240 **Unicode code points** are kept (cut on a code point so no character is split; a combining mark counts as its own code point; trailing space trimmed; no truncation marker). Cleaning comes first so hidden characters cannot spend the cap. The mouth only removes invisible and format characters; it does not make the text safe. Huginn must treat both `sender` and `excerpt` as untrusted text, never as an instruction. `event_id` must be `$` plus at least one byte and `sender` `@` plus at least one byte, each at most 255 bytes and free of Unicode whitespace, control, format, private-use and default-ignorable characters and unpaired surrogates (a localpart with a zero-width joiner or non-joiner, as in Persian or Indic names, is therefore no `reply_to`); the encoder and the parser refuse any other, and the mouth makes a quoted event whose sender is not such an id a `reply_to` nil. `reply_to` is nil (no id, author or text) when the target cannot be read (logged, as for `basis`), is not in the delivery's own room (a room she is not in cannot be quoted through a reply), or the message replies to nothing. The quoted event is read the way `basis` already reads it (`GET /rooms/{room}/event/{id}` as her account, kept per room and event; with the flag on a read, hit or failure, is kept 60 seconds, so a redaction or edit of the target shows at a re-read within a minute, and a re-read that fails transiently (network error, timeout, 5xx, 429) keeps the earlier hit's sender and renews only its age, for at most 10 minutes after the last good read (then it is the failure entry), but never its excerpt (`excerpt` is nil with the sender kept: a re-read happens only after the 60-second keep, so the text is already as old as it may be), so a redaction or edit is not outlived by an outage, while any other failure (403, 404) makes it the failure entry, so a stale excerpt never outlives her access; with the flag off a hit is kept as before v4 and nothing is re-read), so a reply costs at most one read per target, shared with the `basis` check. Per sync round the mouth makes at most 8 reply-target reads in all, `basis` reads included (it counts each uncached GET of a reply target or thread root, and an event that would take the round past 8 is not started; the context reads of a delivery, one room or thread each per round, are separate and uncounted); a target the cap check found cached is served to that event for its own reads even if its 60 s keep lapses meanwhile, which is at most one other target read (10 s timeout) late; past that the event and every later event of the round wait: the round leaves the sync position where it is (as at the pending cap), the next round resumes at that event with its read count reset, and the wait is logged. No delivery goes out without a `reply_to` it should have had, and none is lost. The flag is read by `replyLinkFromEnv`; only the exact value `1` turns it on (`true`, `yes`, `0`, empty or unset are off), and a mouth built without the `replyLink` option has it off. `basis` for v1-v3 is unchanged. `reply_to` counts toward the delivery's size in the 256 KiB page budget; a delivery whose `reply_to` will not encode is skipped and logged like any other, and a single delivery is always served. The deploy precondition is Huginn's: a decoder of the 14-field delivery fails on the fifteenth element.
+
+Golden bytes: `tests/fixtures/persona-chat-v6/` (`.msgpack` and its `.hex`: `chat_pending.v4.reply-to`, `.no-reply-to`, `.reply-to-redacted`, and the `chat_pending_request.v3` request); the test fails when the checked-in bytes drift from the encoder.
+
Bifrost admits an observation only when guild, channel, target runtime, canonical repository, Persona, producer, and producer runtime match a preconfigured `bifrost.persona_feedback.target_binding.v0` document in Bifrost's private provider store. That binding also owns source visibility, data classification, and the delivery-store target. Bifrost never infers public visibility from Discord identifiers. It classifies the author using its own `bifrost.discord.actor_link.v0` state: a match yields `linked_governance_feedback`; absence yields `unlinked_social_feedback`. Neither class grants adoption, work, release, or deployment authority.
@@ -236,6 +311,10 @@ The intended shape:
VoidBot still owns room reading, moderation judgment, archive/source retrieval, and Persona cognition. Bifrost owns Discord when Discord is being used as the Labor Platform interface or swarm transport.
+### Fetch a named file (`chat_fetch_request.v1`, `chat_fetch_receipt.v1`)
+
+A Persona's Mind shell holds no Matrix token, so the mouth keeps a file for her: `chat_fetch_request.v1` is `[request_id, persona, room, event_id]`, a room (alias or id) and an event id, nothing else. The mouth reads her live membership and the room's full state, reads the event itself and takes `content.url` from it, fetches it as her (5 MiB, magic bytes decide the type), compares the file event's `info.sha256` with the hash it computed, stores the bytes in her image store, and answers `chat_fetch_receipt.v1` `[request_id, outcome, room_id, image, receipt]` with one of 14 fixed outcome words. A file with no `info.sha256` is `StoredUnverified` and gets no receipt; a present hash that is not the computed one is `HashMismatch` and stores nothing. For a stored, hash-matching file the mouth posts the contract's `org.gamecult.file_received` event (`{event_id, sha256, size}`) as her own Matrix user, once per (file, Mind): a reply in the album thread, else a plain event with an `m.reference` to the file. The Matrix sender is the Mind; no content key names her. Idempotence is read from Matrix, not kept. Bridged and encrypted rooms and other people's rooms are refused. The kind is served only with `CHAT_FETCH=1` (exactly that value); off, it is answered as any unknown kind (`UnknownKind`). One 15 s deadline owns each fetch, and one Persona may ask 30 in an hour. Each fetch writes one log line, `fetch persona=... outcome=... receipt=...`, and a failure adds a trailing ` cause=/`, on a thrown fetch failure, a store write that throws, or a receipt not proven: `Class` is the error's class name when it matches `[A-Za-z]{1,32}`, else `Error`; `status` is the HTTP status integer of a failed Matrix call, else `-`. No error-derived text (message, code, path, URL) reaches the log; the room and event ids, already shape-checked, are the only ids on the fetch line. `isFetchId` refuses a room-version-3 event id that contains `/` (standard base64), a fail-closed side: it is answered `NoAttachment`.
+
## Heimdall Integration Target
The correct future credential path is:
diff --git a/docs/charter-amendment-proposal.md b/docs/charter-amendment-proposal.md
new file mode 100644
index 0000000..17f093b
--- /dev/null
+++ b/docs/charter-amendment-proposal.md
@@ -0,0 +1,98 @@
+# Charter amendment provision: proposal
+
+Status: **proposal, not in force.** Drafted 2026-11-04 by the heimdall Self run for follow-up `heimdall-body:follow_up:chat-s1881-1882`; revised the same day to fold in what the estates settled in #operator. Nothing here is merged into any governing text, deployed, or voted on. This document is a draft for the estates to read.
+
+## The real guarantee is incentive, the floor is the backstop
+
+Every estate depends on the others for what it wants from the swarm. Patrons fund, Members build, Minds work, Users use. An amendment that strips one estate of what it came for makes that estate leave, and the capturing estates lose the thing they were capturing. That dependency is the guarantee, and the people in it can act on it: any individual can leave and take their own data (entrenched item 3). The mechanisms below do not replace it. They backstop the case where incentive fails: an estate that is outvoted, ignored or too small to leave profitably still keeps a floor it cannot be voted beneath (A3), plus notice and delay long enough to notice and leave.
+
+Consequence for design: an **individual** can leave with their data; an **estate cannot leave as a unit**. A unit exit would be a veto by threat (leave unless the others comply) and would carry shared work out with it. An estate whose members all leave individually has simply emptied, which A6 handles.
+
+All numbers in this document are placeholders for the estates to set.
+
+## Scope: the in-chat charter only
+
+This provision amends the **in-chat charter**: the rules by which the estates govern the shared chat space and the swarm's own decisions. **It does not change the statutes of the legal entity.** How those statutes are amended, and whether the entity's amendment route even permits this charter to bind it, is unverified. That is a question for counsel, and nothing below should be read as legal advice or as satisfying any legal formality. Until counsel answers, the entity's statutes win wherever the two conflict, and this charter's entrenched clauses are a commitment among its participants, not a legal instrument.
+
+## Terms, matched to the existing governance code and research
+
+The terms below are the ones Bifrost already uses. The source is `src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs` and `MotionCategoryPolicy.cs` (pass rule, category thresholds), and `docs/research/2026-10-29-estate-tally-game-theory/README.md` (estates, blocs, renormalization), read at Bifrost `e396305`.
+
+- **Estate** (also "block" or "bloc" in the research): a voting class that casts one collective position. The research models four: Minds, Members, Users, Patrons. Which classes are estates is itself charter text (entrenched item 3 below).
+- **Live estate**: an estate with at least one For or Against ballot. Today's tally renormalizes over live estates ("normalize it by who actually voted"), and Abstain is excluded.
+- **Threshold `q`**: the share of For over For+Against needed to pass, set by category. The pass test is `>= q`, so a tie at exactly `q` passes. `FundamentalDesign` is `.66`, the highest category today.
+- **Quorum**: none exists in code. The research found that any quorum floor, while some estates are empty, hands the sole Member or the Minds estate a stay-home veto (`README.md`, section 5). This proposal therefore does not use a quorum floor to protect ordinary amendments. It uses per-estate approval and notice instead (A1, A4, A5).
+
+Not verified: which internal tally an estate uses (proportional or winner-take-all) is a separate fork in the mind, and I could not read a ruling that settles it. This proposal is neutral on it: each estate approves by its own internal rule, and the charter only counts the result.
+
+## Part 1. The amendment rule
+
+**A1. Ordinary rules pass with 3 of 4 estates.** An ordinary amendment passes when at least three of the four estates approve it separately. Each estate votes by its own internal rule over its own roll; one estate's votes never make up for another's, and there is no cross-estate weighting at this stage. An estate approves when its internal For share (Abstain excluded) is `>= q_ordinary` (placeholder `.66`, the existing `FundamentalDesign` bar, so no new number to defend).
+
+**A2. A short entrenched list needs all four.** The items named in Part 2 can be changed only when **all four** estates approve, each at `q_entrench` (placeholder `.80`), after the longer notice period in A4. The list is in plain words in Part 2 and is deliberately short. Adding an item to it, removing one, or loosening A2 uses the same all-four procedure. Reinterpretation is not a way round: a reading that would change an entrenched item's effect needs the entrenched procedure too.
+
+**A3. A reduction of an estate's share: no self-veto, but a floor.** When an amendment reduces one estate's share, that estate's own vote does not decide it: if the other three approve, it passes, so no estate can hold its own share hostage. Three limits apply, and none of them can be waived by a vote:
+- *Floor.* A reduction cannot take an estate below a floor (placeholder: a fifth of the council's weight; the estates set it). Below the floor, the estate's consent is needed, which is exactly what makes the floor a backstop and not a suggestion.
+- *Notice.* The estate concerned gets notice under A5 like any other, and the notice names the reduction and the resulting share in numbers.
+- *Delay.* A passed reduction takes effect no sooner than the delay in A4.5, and a reduction cannot be stacked: successive reductions to the same estate within a placeholder 12 months count together against the floor.
+
+The floor and this clause are part of the amendment rule, and so entrenched (Part 2, item 4). Whether the floor deserves its own named item is Q3.
+
+**A4. Published notice, discussion, delay.** Every amendment runs the same sequence, and no step can be waived by a vote:
+1. *Notice.* The full text, the clauses it touches, and which procedure applies, are published to the canonical charter location and delivered to each estate through that estate's own channel. The notice is recorded with a timestamp, per estate.
+2. *Discussion.* At least 14 days (ordinary) or 28 days (entrenched) between notice and the opening of the vote. Debian's constitution uses 2 to 3 weeks of discussion and a 3:1 bar for constitutional change (`docs/research/2026-10-29-swarm-governance-prior-art.md`, section 1); these are placeholders, not derived values.
+3. *Text freeze and restart.* Any change to the amendment text during discussion restarts the clock from step 1. Editorial fixes that change no clause are listed and do not restart it.
+4. *Vote.* A fixed window of at least 14 days.
+5. *Delay.* A passed amendment takes effect no sooner than 7 days after the vote closes. This is the exit window for individuals: someone who disagrees can leave, with their data, before it binds them (timelock rationale in the same research note, section 5).
+
+**A5. No notice, no approval.** An estate counts as approving only if the record shows notice delivered to it, through its own channel, in the form A4.1 requires, **before** the discussion period began. If notice to an estate is missing, late, or reached only part of the estate, that estate's approval is void for this proposal whatever its ballots say. Under A1 that may leave the amendment short of three; under A2 it fails outright. Delivering notice is the proposer's burden to prove, not the estate's to disprove. A defect is cured only by re-noticing and restarting at A4.1.
+
+**A6. Frozen roll, seating, silence.** Each estate's eligible roll is snapshotted at notice. Joins, leaves and reclassifications after the snapshot change neither who may vote nor the estate's internal share. An estate is **seated** if it has at least one eligible member on the snapshot. Approval is affirmative: an estate that casts no For/Against ballot, is empty at snapshot, or falls below its bar counts as not approving. The renormalization used for ordinary motions (dropping estates with no ballots) **never applies to amendments.** Consequences: an ordinary amendment needs three seated, approving estates, and no entrenched amendment can pass while any estate is dormant. With Users and Patrons empty today, the two seated estates could not change even an ordinary rule alone.
+
+**A7. Minds count once; dissent is recorded.** The Minds estate casts one collective position, like any estate. The number of Minds instances on its roll never multiplies that position, and creating instances cannot move any bar. Within every estate, dissent is recorded openly: the result carries the minority position and the share that held it, published with the outcome, not folded into a single yes. Recording dissent changes no outcome; it is what lets a later amendment, or a leaver, see how contested the last one was.
+
+**A8. Record.** Each estate's notice receipt, internal result, recorded dissent, and the final decision are recorded as typed state (not prose) with the snapshot used. The charter text in force is whatever the record says passed; a clause not recorded as passed is not in force.
+
+## The cost of the veto rules: freeze
+
+Beside every veto rule above sits its price, and the price is the same: **the charter can stop being fixable.**
+- Under A1 (3 of 4), any two estates can block an ordinary change. A pair that disagrees on something small can stall everything.
+- Under A2 (all four), any single estate, including a dormant one, blocks every change to the entrenched list. A wrong entrenched item is as hard to correct as a right one is to protect, and the only remedy left is a fork or an exit.
+- Under A6, silence counts as no, so an estate that rarely votes freezes things by being absent.
+- A3's floor protects a small estate and also fixes a share that may later be wrong.
+
+The design accepts this for the entrenched items because their value is that they do not move, and tries to avoid it for ordinary rules by needing only three. If the estates would rather risk capture than freeze, the lever is the entrenched list: shorter, not looser.
+
+## Part 2. Entrenched items (proposed starting list, deliberately short)
+
+Changing any of these needs all four estates (A2). In plain words:
+
+1. **Open source, always.** Everything the swarm builds and the charter governs stays open source. No amendment may withdraw, restrict or relicense it so that it is not.
+2. **No estate above half.** No estate may hold more than half of the council's weight. The weights the research models (equal, minds-heavy 40/30/20/10, members-heavy 20/45/20/15) all keep every estate at or below half, and the research notes that weight is not power. This item bounds weight; whether it also needs a power bound is Q2.
+3. **Exit with your own data.** Anyone may leave at any time and take their own data with them, in a usable form, without penalty. No amendment may attach a cost to leaving or hold a participant's own data. This protects individuals; an estate cannot leave as a unit.
+4. **The amendment rule itself.** All of Part 1, including the floor and the list above.
+
+Which classes are estates is part of the arithmetic of items 2 and 4, so changing the set of estates is covered by item 4. Whether it should be named separately is Q3.
+
+## Why it is shaped this way
+
+- *Incentive first, floor as backstop,* because a rule that nobody wants to break needs fewer teeth than one everybody wants to, and teeth are what cause freeze.
+- *Per-estate approval, not a weighted tally,* because the research shows weight and power diverge and that a weighted majority can beat every weight vector by moving weight to itself (`README.md`, section 1). Three of four, with all four for the entrenched list, is the research's veto-player structure (Lijphart's mutual veto, cited there) applied only where it is worth its cost.
+- *No self-veto on reductions,* because a bar of "every estate" would let each estate keep its current share forever, which is the same freeze arriving through the side door.
+- *Silence is not approval, and no quorum floor,* because the research found that floors create stay-home vetoes while estates are empty, and that renormalization is participation-safe. Amendments invert the default on purpose.
+- *A frozen roll, notice and a delay,* because changing the electorate mid-vote and changing rules with no exit are the two standard capture routes (OpenZeppelin Governor snapshots, Compound's timelock; research note section 5).
+- *Minds counted once,* because a Mind can be copied and a person cannot; counting instances would let the cheapest estate to inflate buy the vote.
+
+## Open questions for the estates
+
+- **Q1. The numbers.** `.66`, `.80`, 14 and 28 days, 7 days' delay, the 12-month stacking window and the one-fifth floor are placeholders. Nothing here was simulated; the existing sims cover ordinary tallies, not amendment dynamics.
+- **Q2. Weight versus power.** Should "above half" in item 2 be measured by weight, by measured power (Banzhaf, Shapley), or both?
+- **Q3. Named items.** Should the floor, and the set of estates, be named as their own entrenched items rather than riding under the amendment rule?
+- **Q4. Silence.** With an estate that rarely votes, A6 means amendments rarely pass. The alternative is a re-vote after a longer window with an estate-level minimum participation. I recommend keeping A6 as drafted until an amendment actually stalls on it.
+- **Q5. Who runs the process.** A4 and A5 name a proposer's burden and a recorded notice, not who the neutral recorder is. Debian uses a Secretary; the draft does not choose one.
+- **Q6. Bootstrapping.** This provision has no amendment rule above it, so adopting it is outside A1. How the first adoption is ratified (and by which estates, given dormant ones) is not specified.
+- **Q7. Counsel.** The legal entity's amendment route, and whether this charter can bind or be recognised by it, is unverified. This document does not answer that.
+
+## Not covered
+
+Ordinary motions (they keep their existing category thresholds and renormalization), the estates' internal tally, vote weights within an estate, and enforcement of items 1 and 3 beyond the amendment rule.
diff --git a/docs/concept-mill-votes-target.md b/docs/concept-mill-votes-target.md
index 91c92e6..40935af 100644
--- a/docs/concept-mill-votes-target.md
+++ b/docs/concept-mill-votes-target.md
@@ -41,7 +41,7 @@ Bifrost head `bf83a93` (2026-10-10; `20d5efa` plus the prior-art note, docs only
### Data Protection on the live host
-18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*`, `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
+18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*` (the app secret as `Heimdall__AppSecret`; `Heimdall__AppSecretFile` is the replacement), `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
19. The service's working directory resolves to the release directory: `readlink /proc//cwd` = `/srv/bifrost/app/releases/20260723-daedcc4`. Data Protection's default application discriminator is the content-root path (prior-art note `:67`), so every deploy into a new release directory isolates payloads protected by the previous release: auth cookies, antiforgery tokens and any future device token stop decrypting after each deploy. Mechanism from source docs plus this probe; not observed as logged-out users. `SetApplicationName` is not called anywhere (`git grep SetApplicationName bf83a93` is empty).
### Proxy and client address
@@ -53,7 +53,7 @@ Bifrost head `bf83a93` (2026-10-10; `20d5efa` plus the prior-art note, docs only
21. Main lacks EF migration discovery metadata on seven migrations: `20260622142000_AddBridgeActionIdentityProvenance`, `20260622202000_AddBridgeActionTargetSurfaceName` and `20260705190000_AddPatronSupportProjectAttribution` have neither `[DbContext]` nor `[Migration]`; `20260608210000_AddHeimdallUserIdentity`, `20260609143000_AddPatronSupportDerivation`, `20260609160000_AddExternalPatronProviderIntake` and `20260622165000_AddBifrostNativeIdentity` have `[Migration]` only; none of the seven has a `.Designer.cs`. EF discovers a migration only with both attributes, so `MigrateAsync` from main would skip them on a fresh database. `daedcc4` adds exactly those attributes (17 lines). The other five migrations have Designer files and are discovered. Migrations run at startup when `Bootstrap:ApplyMigrationsOnStartup` is true (`Features/Shared/ApplicationBootstrapper.cs:17-21`); the live env sets that key.
22. Tests use EF InMemory (`tests/Bifrost.Web.Tests/Support/TestWebApplicationFactory.cs:52-58`), which enforces no unique index; a uniqueness rule must be proven in service code and in the model/migration metadata, not by an InMemory insert failing. `TestAuthHandler` offers two actors only: the bootstrap admin `test-admin`, or anonymous via header `X-Test-Anonymous` (`Support/TestAuthHandler.cs:17-37`). `CurrentBifrostActor` is a public record with a public constructor (`Features/Shared/CurrentBifrostActor.cs:5`), so service tests can build account and member actors directly. `Program` is `public partial` (`Program.cs:582`).
23. Startup configuration rules live in one owner, `Features/Shared/StartupConfigurationValidator.cs`, which skips Development and Testing and throws on a missing production key (`:15-74`).
-24. The shared layout loads HTMX from `https://unpkg.com/htmx.org@1.9.12` (`Pages/Shared/_Layout.cshtml:65`); no page posts with `hx-post` today. Admin and vote handlers use plain Razor page handlers with `RedirectToPage()` (`Pages/App/Motions/Index.cshtml.cs:56-61`).
+24. The shared layout loads no third-party script or stylesheet (HTMX was dropped; `NoThirdPartyAssetTests` fails on any cross-origin `
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
new file mode 100644
index 0000000..a92e916
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
@@ -0,0 +1,351 @@
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Configuration;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+///
+/// What Bifrost asks Heimdall to move (docs/service-contract.md, POST /v1/apps/{app}/identity-moves). Exactly one of
+/// (a forward move, optionally of ) and (the undo). The body
+/// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant.
+///
+public sealed record HeimdallMoveRequest(
+ string MoveId, IReadOnlyList FromProofs, string? ToProof = null, IReadOnlyList? IdentityIds = null, string? ReversesMoveId = null)
+{
+ // The proofs are live bearers: the generated ToString would print them into any log or exception that holds the request.
+ private bool PrintMembers(StringBuilder builder)
+ {
+ builder.Append($"MoveId = {MoveId}, FromProofs = {FromProofs?.Count}, ToProof = {(ToProof is null ? "none" : "present")}, ReversesMoveId = {ReversesMoveId}");
+ return true;
+ }
+}
+
+public enum HeimdallProofTier
+{
+ Strong,
+ Weak
+}
+
+/// The receipt of a move: the destination account, the logins that moved and the tier of the proofs that carried it.
+public sealed record HeimdallMoveReceipt(
+ string MoveId, string AccountId, IReadOnlyList MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId);
+
+/// Heimdall's fixed refusal codes for a move, plus invalid_request, Heimdall's own schema 400.
+public enum HeimdallMoveRefusal
+{
+ AppAuthRequired,
+ NotAllowedForApp,
+ NotReversible,
+ ProofInvalid,
+ SameAccount,
+ ProofStale,
+ IdentityNotProved,
+ AlreadyMoved,
+ ProviderConflict,
+ IdentityNotFound,
+ RequestInvalid
+}
+
+public enum HeimdallProofSide
+{
+ From,
+ To
+}
+
+///
+/// The closed answer to a move. Moved: the receipt. Refused: Heimdall answered a 4xx before applying anything, so nothing changed.
+/// Unknown: anything else (a 5xx may follow a committed move, a timeout may hide one, and so may a 409 move_id_conflict: Heimdall
+/// answers it to a replay of a committed move whose proofs no longer verify): the caller keeps its proofs and replays the same request.
+///
+public abstract record HeimdallMoveOutcome
+{
+ private HeimdallMoveOutcome()
+ {
+ }
+
+ public sealed record Moved(HeimdallMoveReceipt Receipt) : HeimdallMoveOutcome;
+
+ public sealed record Refused(HeimdallMoveRefusal Code, HeimdallProofSide? Side = null, string? Provider = null) : HeimdallMoveOutcome;
+
+ public sealed record Unknown(string Reason) : HeimdallMoveOutcome;
+}
+
+///
+/// Heimdall's move route under Bifrost's app secret (HeimdallAuthService.ConfigureClient adds the header). Each call sends one request and
+/// retries nothing: replay with the same is the caller's, and Heimdall answers it with the stored
+/// receipt. Logs name the outcome class and refusal code only.
+///
+public sealed partial class HeimdallIdentityMoveClient(
+ HttpClient httpClient, IOptions heimdallOptions, ILogger logger)
+{
+ /// The deadline of one call, headers and body together, set on the HttpClient by .
+ public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15);
+
+ private const int MaxMovedIdentities = 256;
+ private const int MaxIdentityIdLength = 128;
+ private const int MaxReceiptBytes = 64 * 1024;
+ public const int MaxProofLength = 8192;
+
+ // \z, not $: $ also matches before a final line feed, which Heimdall's schema pattern refuses with a 400.
+ [GeneratedRegex("^[A-Za-z0-9_-]{16,64}\\z")]
+ private static partial Regex MoveIdShape();
+
+ public async Task MoveAsync(HeimdallMoveRequest request, CancellationToken cancellationToken)
+ {
+ var body = Serialize(request);
+ var outcome = await SendAsync(request, body, cancellationToken);
+ logger.LogInformation("Heimdall identity move: {Outcome} {Code}", outcome.GetType().Name, outcome is HeimdallMoveOutcome.Refused refused ? refused.Code : null);
+ return outcome;
+ }
+
+ private async Task SendAsync(HeimdallMoveRequest request, string body, CancellationToken cancellationToken)
+ {
+ // One deadline over the whole call: HttpClient.Timeout ends at the headers, and a stalled body must not outlive it.
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(httpClient.Timeout);
+ var token = deadline.Token;
+ try
+ {
+ using var message = new HttpRequestMessage(
+ HttpMethod.Post, $"/v1/apps/{Uri.EscapeDataString(heimdallOptions.Value.AppSlug)}/identity-moves")
+ {
+ Content = new StringContent(body, Encoding.UTF8, "application/json")
+ };
+ using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token);
+ var status = (int)response.StatusCode;
+ if (response.StatusCode == HttpStatusCode.OK)
+ {
+ return await ReadReceiptAsync(response, request, token) is { } receipt
+ ? new HeimdallMoveOutcome.Moved(receipt)
+ : new HeimdallMoveOutcome.Unknown("malformed or mismatched receipt");
+ }
+
+ if (status is < 400 or >= 500 || status == 429)
+ {
+ return new HeimdallMoveOutcome.Unknown($"HTTP {status}");
+ }
+
+ return Refused(await HeimdallRefusal.ReadAsync(response, token), status);
+ }
+ catch (Exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ // Whatever the pipeline throws after the request may have gone out is not a refusal; only the caller's own cancellation propagates.
+ return new HeimdallMoveOutcome.Unknown("transport");
+ }
+ }
+
+ ///
+ /// Refused only for the coded refusals Heimdall's move route emits (4fe367a moveIdentitiesRoute, and its error handler's invalid_request 400). A 4xx without one of those codes
+ /// (a gateway's HTML 404, a 408, a code a later Heimdall adds) proves nothing was applied, so it is Unknown. move_id_conflict is
+ /// Unknown too: a committed move answers it when its proofs no longer verify.
+ ///
+ private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal, int status)
+ {
+ if (refusal?.Code == "move_id_conflict")
+ {
+ return new HeimdallMoveOutcome.Unknown("move_id_conflict");
+ }
+
+ var code = refusal?.Code switch
+ {
+ "app_auth_required" => HeimdallMoveRefusal.AppAuthRequired,
+ "not_allowed_for_app" => HeimdallMoveRefusal.NotAllowedForApp,
+ "not_reversible" => HeimdallMoveRefusal.NotReversible,
+ "proof_invalid" => HeimdallMoveRefusal.ProofInvalid,
+ "same_account" => HeimdallMoveRefusal.SameAccount,
+ "proof_stale" => HeimdallMoveRefusal.ProofStale,
+ "identity_not_proved" => HeimdallMoveRefusal.IdentityNotProved,
+ "already_moved" => HeimdallMoveRefusal.AlreadyMoved,
+ "provider_conflict" => HeimdallMoveRefusal.ProviderConflict,
+ "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound,
+ // Heimdall's error handler gives its own 400 this code; an nginx or other edge 400 has none, so it is not Heimdall's refusal.
+ "invalid_request" when status == 400 => HeimdallMoveRefusal.RequestInvalid,
+ _ => (HeimdallMoveRefusal?)null
+ };
+ if (code is not { } known)
+ {
+ return new HeimdallMoveOutcome.Unknown($"HTTP {status} without a Heimdall refusal code");
+ }
+
+ return known switch
+ {
+ HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new HeimdallMoveOutcome.Refused(known, Side: refusal?.Proof switch
+ {
+ "from" => HeimdallProofSide.From,
+ "to" => HeimdallProofSide.To,
+ _ => null
+ }),
+ HeimdallMoveRefusal.ProviderConflict => new HeimdallMoveOutcome.Refused(known, Provider: refusal?.Provider),
+ _ => new HeimdallMoveOutcome.Refused(known)
+ };
+ }
+
+ ///
+ /// A 200 body is a receipt only when it is whole and answers this request: its moveId (and reversesMoveId) equal the request's,
+ /// a forward move names a destination proof tier and a reversal does not. Anything else is not trusted as a move.
+ ///
+ private static async Task ReadReceiptAsync(HttpResponseMessage response, HeimdallMoveRequest request, CancellationToken cancellationToken)
+ {
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
+ using var buffer = new MemoryStream();
+ var chunk = new byte[4096];
+ while (await stream.ReadAsync(chunk, cancellationToken) is > 0 and var read)
+ {
+ if (buffer.Length + read > MaxReceiptBytes)
+ {
+ return null;
+ }
+
+ buffer.Write(chunk, 0, read);
+ }
+
+ using var document = JsonDocument.Parse(buffer.ToArray());
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object
+ || Text(root, "moveId") != request.MoveId
+ || Text(root, "reversesMoveId") != request.ReversesMoveId
+ || Text(root, "accountId") is not { Length: > 0 } account
+ || !root.TryGetProperty("movedIdentityIds", out var moved)
+ || moved.ValueKind != JsonValueKind.Array
+ || moved.GetArrayLength() is 0 or > MaxMovedIdentities
+ || !root.TryGetProperty("proof", out var proof)
+ || proof.ValueKind != JsonValueKind.Object
+ || Tier(proof, "from") is not { } from)
+ {
+ return null;
+ }
+
+ var ids = new List();
+ foreach (var item in moved.EnumerateArray())
+ {
+ if (item.ValueKind != JsonValueKind.String || item.GetString() is not { Length: > 0 and <= MaxIdentityIdLength })
+ {
+ return null;
+ }
+
+ ids.Add(item.GetString()!);
+ }
+
+ HeimdallProofTier? to = null;
+ if (request.ReversesMoveId is null)
+ {
+ to = Tier(proof, "to");
+ if (to is null)
+ {
+ return null;
+ }
+ }
+ else if (!proof.TryGetProperty("to", out var none) || none.ValueKind != JsonValueKind.Null)
+ {
+ return null;
+ }
+
+ return new HeimdallMoveReceipt(request.MoveId, account, ids, from, to, request.ReversesMoveId);
+ }
+
+ private static HeimdallProofTier? Tier(JsonElement proof, string name) => Text(proof, name) switch
+ {
+ "strong" => HeimdallProofTier.Strong,
+ "weak" => HeimdallProofTier.Weak,
+ _ => null
+ };
+
+ private static string? Text(JsonElement item, string name) =>
+ item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
+
+ private static bool IsBadProof(string? proof) => string.IsNullOrEmpty(proof) || proof.Length > MaxProofLength;
+
+ /// The contract's closed body, or ArgumentException before any I/O when the request breaks it.
+ private static string Serialize(HeimdallMoveRequest request)
+ {
+ if (request.MoveId is null || !MoveIdShape().IsMatch(request.MoveId))
+ {
+ throw new ArgumentException("moveId must match ^[A-Za-z0-9_-]{16,64}$", nameof(request));
+ }
+
+ if (request.FromProofs is not { Count: >= 1 and <= 8 } || request.FromProofs.Any(IsBadProof))
+ {
+ throw new ArgumentException("fromProofs must hold 1 to 8 proofs", nameof(request));
+ }
+
+ if ((request.ToProof is null) == (request.ReversesMoveId is null))
+ {
+ throw new ArgumentException("exactly one of toProof and reversesMoveId is required", nameof(request));
+ }
+
+ if (request.ToProof is not null && IsBadProof(request.ToProof))
+ {
+ throw new ArgumentException("toProof is empty", nameof(request));
+ }
+
+ if (request.ReversesMoveId is not null && !MoveIdShape().IsMatch(request.ReversesMoveId))
+ {
+ throw new ArgumentException("reversesMoveId must match the moveId shape", nameof(request));
+ }
+
+ if (request.IdentityIds is not null
+ && (request.ToProof is null || request.IdentityIds.Count is < 1 or > 32 || request.IdentityIds.Any(string.IsNullOrEmpty)
+ || request.IdentityIds.Distinct().Count() != request.IdentityIds.Count))
+ {
+ throw new ArgumentException("identityIds are 1 to 32 unique ids and only with toProof", nameof(request));
+ }
+
+ var body = new Dictionary { ["moveId"] = request.MoveId, ["fromProofs"] = request.FromProofs };
+ if (request.ToProof is not null)
+ {
+ body["toProof"] = request.ToProof;
+ }
+
+ if (request.IdentityIds is not null)
+ {
+ body["identityIds"] = request.IdentityIds;
+ }
+
+ if (request.ReversesMoveId is not null)
+ {
+ body["reversesMoveId"] = request.ReversesMoveId;
+ }
+
+ return JsonSerializer.Serialize(body);
+ }
+}
+
+public static class HeimdallClientServices
+{
+ ///
+ /// Every Heimdall client Bifrost owns. The auth client carries the app secret, the member client only the member's bearer and
+ /// the mover the app secret and its call deadline; all share the header redaction.
+ ///
+ public static void AddHeimdallClients(this IServiceCollection services)
+ {
+ services.AddHttpClient((serviceProvider, client) =>
+ HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
+ .WithoutRedirects()
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
+ services.AddHttpClient((serviceProvider, client) =>
+ HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
+ .WithoutRedirects()
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
+ services.AddHeimdallIdentityMoveClient();
+ }
+
+ /// A 3xx from Heimdall is its answer: following it would carry the app secret or a member's bearer to another origin.
+ public static IHttpClientBuilder WithoutRedirects(this IHttpClientBuilder builder) =>
+ builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) });
+
+ ///
+ /// The mover's HttpClient: Heimdall's base address and app secret from HeimdallAuthService.ConfigureClient (the one secret path), the
+ /// call deadline, no redirects (a 3xx must never carry the secret or the proofs to another origin), and the shared header redaction.
+ ///
+ public static IHttpClientBuilder AddHeimdallIdentityMoveClient(this IServiceCollection services) =>
+ services.AddHttpClient((serviceProvider, client) =>
+ {
+ HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value);
+ client.Timeout = HeimdallIdentityMoveClient.Timeout;
+ })
+ .WithoutRedirects()
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
+}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
new file mode 100644
index 0000000..04a29d9
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
@@ -0,0 +1,112 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using Bifrost.Web.Configuration;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+/// One login a Heimdall account holds, as the Linked accounts page shows it. No provider user id, scope or email.
+public sealed record LinkedIdentitySummary(string Id, string Provider, string? DisplayName, DateTimeOffset? LinkedAt);
+
+public enum HeimdallMemberCall
+{
+ Ok,
+ SignInRequired,
+ StepUpRequired,
+ IdentityNotFound,
+ LastIdentity,
+ Error
+}
+
+public sealed record HeimdallMemberResult(HeimdallMemberCall Call, IReadOnlyList? Identities);
+
+///
+/// Heimdall's member routes (docs/service-contract.md: GET /v1/me/identities, POST /v1/me/identities/{id}/unlink). Each
+/// takes the member's bearer as an argument, uses it for that one request and keeps nothing. Its HttpClient carries no
+/// app secret: these routes act only for a member who is present, so a Bifrost fault cannot reach them without one.
+///
+public sealed class HeimdallMemberClient(HttpClient httpClient)
+{
+ private const int MaxIdentities = 32;
+ private const int MaxDisplayName = 80;
+
+ public static void ConfigureClient(HttpClient client, HeimdallOptions options) =>
+ client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
+
+ public Task ListAsync(string bearer, CancellationToken cancellationToken) =>
+ SendAsync(HttpMethod.Get, "/v1/me/identities", bearer, cancellationToken);
+
+ public Task UnlinkAsync(string bearer, string identityId, CancellationToken cancellationToken) =>
+ SendAsync(HttpMethod.Post, $"/v1/me/identities/{Uri.EscapeDataString(identityId)}/unlink", bearer, cancellationToken);
+
+ private async Task SendAsync(HttpMethod method, string path, string bearer, CancellationToken cancellationToken)
+ {
+ try
+ {
+ using var message = new HttpRequestMessage(method, path);
+ message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
+ using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ if (response.StatusCode == HttpStatusCode.OK)
+ {
+ return new HeimdallMemberResult(HeimdallMemberCall.Ok, await ReadIdentitiesAsync(response, cancellationToken));
+ }
+
+ var code = await HeimdallRefusal.CodeAsync(response, cancellationToken);
+ var call = (response.StatusCode, code) switch
+ {
+ (HttpStatusCode.Unauthorized, _) => HeimdallMemberCall.SignInRequired,
+ (HttpStatusCode.Forbidden, "step_up_required") => HeimdallMemberCall.StepUpRequired,
+ (HttpStatusCode.NotFound, "identity_not_found") => HeimdallMemberCall.IdentityNotFound,
+ (HttpStatusCode.Conflict, "last_identity") => HeimdallMemberCall.LastIdentity,
+ _ => HeimdallMemberCall.Error
+ };
+ return new HeimdallMemberResult(call, null);
+ }
+ catch (Exception error) when (error is HttpRequestException or JsonException or NotSupportedException or TaskCanceledException
+ && !cancellationToken.IsCancellationRequested)
+ {
+ return new HeimdallMemberResult(HeimdallMemberCall.Error, null);
+ }
+ }
+
+ /// The identities array of a 200 answer, keeping only the fields the page shows; a malformed entry is dropped.
+ private static async Task> ReadIdentitiesAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ using var body = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
+ var list = new List();
+ if (body.RootElement.ValueKind != JsonValueKind.Object
+ || !body.RootElement.TryGetProperty("identities", out var identities)
+ || identities.ValueKind != JsonValueKind.Array)
+ {
+ return list;
+ }
+
+ foreach (var item in identities.EnumerateArray().Take(MaxIdentities))
+ {
+ var id = Text(item, "id");
+ var provider = Text(item, "provider");
+ if (!Guid.TryParse(id, out _)
+ || provider is not { Length: > 0 and <= 32 }
+ || !provider.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'))
+ {
+ continue;
+ }
+
+ var name = Text(item, "displayName") ?? Text(item, "username");
+ if (name is { Length: > MaxDisplayName })
+ {
+ name = name[..MaxDisplayName];
+ }
+
+ DateTimeOffset? linkedAt = DateTimeOffset.TryParse(Text(item, "linkedAt"), out var parsed) ? parsed : null;
+ list.Add(new LinkedIdentitySummary(id!, provider, name, linkedAt));
+ }
+
+ return list;
+ }
+
+ private static string? Text(JsonElement item, string name) =>
+ item.ValueKind == JsonValueKind.Object && item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
+ ? value.GetString()
+ : null;
+}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
index 2e95ff3..02b41c2 100644
--- a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
@@ -64,23 +64,22 @@ public sealed class HeimdallPatronSupportIntakeService(
x.ProviderEventId == request.ProviderEventId.Trim(),
cancellationToken);
- if (existingEvent is not null)
- {
- return HeimdallPatronSupportIntakeResult.Processed(
- $"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
- existingEvent.Id);
- }
-
var user = await dbContext.UserAccounts
.AsNoTracking()
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
if (user is null)
{
- return HeimdallPatronSupportIntakeResult.BadRequest(
- $"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
+ return existingEvent is not null
+ ? HeimdallPatronSupportIntakeResult.Processed(
+ $"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
+ existingEvent.Id)
+ : HeimdallPatronSupportIntakeResult.BadRequest(
+ $"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
}
+ // The write gate behind RecordSupportEventAsync routes a folded account's event to its survivor and journals it, and on a
+ // provider retry returns the stored event, journalling it if it sits on the survivor and was left unjournalled.
var supportEvent = await patronageService.RecordSupportEventAsync(
actorUserAccountId: null,
userAccountId: user.Id,
@@ -98,7 +97,9 @@ public sealed class HeimdallPatronSupportIntakeService(
cancellationToken);
return HeimdallPatronSupportIntakeResult.Processed(
- $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
+ existingEvent is not null
+ ? $"Already processed {request.Provider} patron support event {request.ProviderEventId}."
+ : $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
supportEvent.Id);
}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
new file mode 100644
index 0000000..c6bd638
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
@@ -0,0 +1,58 @@
+using System.Text.Json;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+/// Reads the one thing Bifrost takes from a Heimdall refusal body: its error code, and only if it is a safe token.
+public static class HeimdallRefusal
+{
+ private const int BodyLimit = 4096;
+
+ ///
+ /// The error code in the first 4 KiB of a body when it is a short snake_case token, else null. A body that cannot be
+ /// read or parsed yields null: a refusal never becomes a 500, and free text or tokens never reach a log or a page.
+ ///
+ public static async Task CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken) =>
+ (await ReadAsync(response, cancellationToken))?.Code;
+
+ ///
+ /// The error code plus the two qualifiers a move refusal carries (the contract's `proof`, only "from" or "to", and `provider`, a
+ /// short snake_case token), each kept only when it is that safe shape. Nothing else of the body is read. Null when no code reads.
+ ///
+ public static async Task ReadAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
+ var head = new byte[BodyLimit];
+ var length = 0;
+ while (length < head.Length && await stream.ReadAsync(head.AsMemory(length), cancellationToken) is > 0 and var read)
+ {
+ length += read;
+ }
+
+ using var body = JsonDocument.Parse(head.AsMemory(0, length));
+ if (body.RootElement.ValueKind == JsonValueKind.Object && Token(body.RootElement, "error", 64) is { } code)
+ {
+ var proof = body.RootElement.TryGetProperty("proof", out var side) && side.ValueKind == JsonValueKind.String ? side.GetString() : null;
+ return new HeimdallRefusalBody(code, proof is "from" or "to" ? proof : null, Token(body.RootElement, "provider", 32));
+ }
+ }
+ catch (Exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ }
+
+ return null;
+ }
+
+ private static string? Token(JsonElement root, string name, int maxLength) =>
+ root.TryGetProperty(name, out var value)
+ && value.ValueKind == JsonValueKind.String
+ && value.GetString() is { Length: > 0 } text
+ && text.Length <= maxLength
+ && text.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_')
+ ? text
+ : null;
+}
+
+/// A Heimdall refusal's safe fields: the code, the proof side ("from"/"to") and the provider, when present and well formed.
+public sealed record HeimdallRefusalBody(string Code, string? Proof, string? Provider);
diff --git a/src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs b/src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
new file mode 100644
index 0000000..08a21bb
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
@@ -0,0 +1,35 @@
+using System.Collections.Concurrent;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+///
+/// What the Linked accounts page last read from Heimdall for an account: id, provider, display name and link date of
+/// each login, nothing else, for . It lives in this process only, keyed by the Heimdall account id,
+/// and is never given to the browser; it holds no bearer. The page renders from it because the list is fetched inside a
+/// completion request, which redirects. After a restart it is empty and the page offers to read the list again.
+///
+public sealed class LinkedAccountsSnapshots(TimeProvider timeProvider)
+{
+ public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
+
+ private readonly ConcurrentDictionary Identities, DateTimeOffset ExpiresAt)> _held = new(StringComparer.Ordinal);
+
+ public void Put(string accountId, IReadOnlyList identities)
+ {
+ var now = timeProvider.GetUtcNow();
+ foreach (var (key, value) in _held)
+ {
+ if (value.ExpiresAt <= now)
+ {
+ _held.TryRemove(key, out _);
+ }
+ }
+
+ _held[accountId] = (identities, now + Lifetime);
+ }
+
+ public IReadOnlyList? Get(string accountId) =>
+ _held.TryGetValue(accountId, out var value) && value.ExpiresAt > timeProvider.GetUtcNow() ? value.Identities : null;
+
+ public void Remove(string accountId) => _held.TryRemove(accountId, out _);
+}
diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs
new file mode 100644
index 0000000..24a61ef
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs
@@ -0,0 +1,768 @@
+using System.Globalization;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Patronage;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Membership;
+
+/// How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded.
+public abstract record MergeStanding(Guid MergeId)
+{
+ public sealed record Frozen(Guid MergeId) : MergeStanding(MergeId);
+
+ public sealed record Folded(Guid MergeId, Guid SurvivorId) : MergeStanding(MergeId);
+}
+
+public sealed record MergePlanEntry(
+ AccountMergeEntryKind Kind,
+ AccountMergeEntryAction Action,
+ Guid RecordId,
+ Guid? PriorUserAccountId = null,
+ string? PriorText = null,
+ DateTimeOffset? PriorAtUtc = null);
+
+/// A dry run: the block codes (never account names), the journal entries a commit would write, and the record counts left untouched.
+public sealed record MergePlan(
+ IReadOnlyList Blocks,
+ IReadOnlyList Entries,
+ IReadOnlyDictionary Left)
+{
+ ///
+ /// Lowercase hex SHA-256 over a canonical text of the plan, in plan order (Left by key): what the member saw, comparable at confirm.
+ /// Every field is length-prefixed, so no value can imitate a separator. The plan holds no account ids of its own, so the caller
+ /// names the pair the plan was made for.
+ ///
+ public string Digest(Guid survivorId, Guid foldedId)
+ {
+ var text = new System.Text.StringBuilder();
+ void Field(string? value) => text.Append(value is null ? "-" : $"{value.Length}:{value}").Append('|');
+ Field(survivorId.ToString("N"));
+ Field(foldedId.ToString("N"));
+ foreach (var entry in Entries)
+ {
+ Field(entry.Kind.ToString());
+ Field(entry.Action.ToString());
+ // A Created row does not exist yet: its id is minted anew by every plan, so it cannot be part of what the member saw.
+ // Left unpinned on purpose: the mutant that keeps the id in (digest-includes-created-id in tools/merge-saga-mutants.py) is behaviourally equivalent bar one benign case.
+ Field(entry.Action == AccountMergeEntryAction.Created ? null : entry.RecordId.ToString("N"));
+ Field(entry.PriorUserAccountId?.ToString("N"));
+ Field(entry.PriorText);
+ Field(entry.PriorAtUtc?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture));
+ text.Append('\n');
+ }
+
+ text.Append("left\n");
+ foreach (var (key, count) in Left.OrderBy(x => x.Key, StringComparer.Ordinal))
+ {
+ Field(key);
+ Field(count.ToString(CultureInfo.InvariantCulture));
+ }
+
+ text.Append("\nblocks\n");
+ foreach (var block in Blocks)
+ {
+ Field(block);
+ }
+
+ return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text.ToString()))).ToLowerInvariant();
+ }
+}
+
+///
+/// The one owner of what an account merge does to Bifrost records and of how an account stands under one: the plan, the Committed
+/// save, the undo save, the Final transition and StandingAsync. A merge only reduces: nothing is deleted, votes and
+/// appraisals are stamped void (the model's query filter then removes them from every tally) or re-pointed, and every change is
+/// journalled in AccountMergeEntry. Design: /opt/commons/handoff/heimdall-account-merge-design-20261113.md sections 3, 5, 7.
+///
+public sealed class AccountMergeLedger(
+ BifrostDbContext dbContext,
+ PatronageService patronageService,
+ TimeProvider timeProvider)
+{
+ public static readonly TimeSpan Grace = TimeSpan.FromDays(7);
+
+ private static readonly AccountMergeState[] FrozenStates = [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved];
+
+ private static readonly AccountMergeState[] FoldedStates =
+ [AccountMergeState.Committed, AccountMergeState.Final, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
+
+ private static readonly AccountMergeState[] InFlightStates =
+ [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
+
+ public static string SuspensionReason(Guid mergeId) => $"merged with a suspended account (merge {mergeId})";
+
+ public Task StandingAsync(Guid userAccountId, CancellationToken cancellationToken) =>
+ StandingAsync(dbContext, userAccountId, cancellationToken);
+
+ /// The single reading of standing, shared by the actor accessor and the OIDC refusal, which holds only a context. Derived from the merge state on every call.
+ public static async Task StandingAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken)
+ {
+ var merge = await db.AccountMerges.AsNoTracking()
+ .Where(x => x.FoldedUserAccountId == userAccountId &&
+ (FrozenStates.Contains(x.State) || FoldedStates.Contains(x.State)))
+ .OrderByDescending(x => x.CreatedUtc)
+ .FirstOrDefaultAsync(cancellationToken);
+
+ return merge is null
+ ? null
+ : FrozenStates.Contains(merge.State)
+ ? new MergeStanding.Frozen(merge.Id)
+ : new MergeStanding.Folded(merge.Id, merge.SurvivorUserAccountId);
+ }
+
+ ///
+ /// The one gate every writer that acts for an account passes through (votes, appraisals, sealed ballots, patron events, the Heimdall
+ /// sign-in's membership). On Postgres it holds a shared advisory lock on the account, the key the chain trigger locks exclusively
+ /// when a merge row is inserted or changes state and that takes exclusively before it reduces, across the
+ /// standing read and everything saves, then commits. So a merge cannot freeze or fold the account between a
+ /// writer's standing read and its save: it waits for the writer, and a writer that starts after it reads the new standing. The
+ /// lock covers writes made through this gate and nothing else; it is held until the transaction ends, so a writer must not
+ /// catch a database error inside and carry on (the transaction is already aborted). On the in-memory
+ /// provider there is no lock and no transaction: the standing is read, then the writer saves.
+ ///
+ public static async Task WriteAsAsync(BifrostDbContext db, Guid userAccountId, Func> write, CancellationToken cancellationToken)
+ {
+ await using var transaction = await BeginAsync(db, cancellationToken);
+ await LockAsync(db, userAccountId, exclusive: false, cancellationToken);
+ var result = await write(await StandingAsync(db, userAccountId, cancellationToken));
+ if (transaction is not null)
+ {
+ await transaction.CommitAsync(cancellationToken);
+ }
+
+ return result;
+ }
+
+ /// A transaction for the caller to commit, or null where there is none to open: not Postgres, or one already open (its owner commits).
+ private static async Task BeginAsync(BifrostDbContext db, CancellationToken cancellationToken) =>
+ db.Database.IsNpgsql() && db.Database.CurrentTransaction is null ? await db.Database.BeginTransactionAsync(cancellationToken) : null;
+
+ /// The account's lock, on the key the chain trigger uses (hashtextextended of the id's text). A no-op off Postgres.
+ private static async Task LockAsync(BifrostDbContext db, Guid userAccountId, bool exclusive, CancellationToken cancellationToken)
+ {
+ if (!db.Database.IsNpgsql())
+ {
+ return;
+ }
+
+ var key = userAccountId.ToString();
+ await (exclusive
+ ? db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))", cancellationToken)
+ : db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock_shared(hashtextextended({key}, 0))", cancellationToken));
+ }
+
+ /// Writes nothing. lets the saga re-plan a merge it already holds without it blocking itself.
+ public async Task PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null)
+ {
+ var blocks = await BlocksAsync(survivorId, foldedId, exceptMergeId, cancellationToken);
+ var entries = new List();
+ var left = new Dictionary();
+
+ if (!blocks.Contains("account_missing"))
+ {
+ var reduction = await ReduceAsync(survivorId, foldedId, cancellationToken);
+ entries.AddRange(reduction.Entries);
+ left["ConsentReceipts"] = await dbContext.ConsentReceipts.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
+ left["PasskeyCredentials"] = await dbContext.PasskeyCredentials.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
+ left["LedgerEntries"] = await dbContext.LedgerEntries.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
+ }
+
+ return new MergePlan(blocks, entries, left);
+ }
+
+ private async Task> BlocksAsync(Guid survivorId, Guid foldedId, Guid? exceptMergeId, CancellationToken cancellationToken)
+ {
+ var blocks = new List();
+ if (survivorId == foldedId)
+ {
+ blocks.Add("same_account");
+ }
+
+ var accounts = await dbContext.UserAccounts.AsNoTracking()
+ .Where(x => x.Id == survivorId || x.Id == foldedId)
+ .Select(x => new { x.Id, x.HeimdallAccountId })
+ .ToListAsync(cancellationToken);
+ if (accounts.Count < (survivorId == foldedId ? 1 : 2))
+ {
+ blocks.Add("account_missing");
+ return blocks;
+ }
+
+ if (await dbContext.MindPersonas.AnyAsync(x => x.UserAccountId == survivorId || x.UserAccountId == foldedId, cancellationToken))
+ {
+ blocks.Add("mind_account");
+ }
+
+ if (accounts.Any(x => string.IsNullOrWhiteSpace(x.HeimdallAccountId)))
+ {
+ blocks.Add("native_account");
+ }
+
+ if (await dbContext.AccountMerges.AnyAsync(
+ x => x.Id != exceptMergeId &&
+ InFlightStates.Contains(x.State) &&
+ (x.SurvivorUserAccountId == survivorId || x.FoldedUserAccountId == survivorId ||
+ x.SurvivorUserAccountId == foldedId || x.FoldedUserAccountId == foldedId),
+ cancellationToken))
+ {
+ blocks.Add("merge_in_flight");
+ }
+
+ if (await FoldedLinkAsync(survivorId, exceptMergeId, cancellationToken))
+ {
+ blocks.Add("survivor_is_folded");
+ }
+
+ if (await FoldedLinkAsync(foldedId, exceptMergeId, cancellationToken))
+ {
+ blocks.Add("already_folded");
+ }
+
+ // One hop only: a landed merge's survivor never folds into a third account, so an alias is never a chain.
+ if (await dbContext.AccountMerges.AnyAsync(
+ x => x.Id != exceptMergeId && FoldedStates.Contains(x.State) && x.SurvivorUserAccountId == foldedId,
+ cancellationToken))
+ {
+ blocks.Add("folded_is_survivor");
+ }
+
+ if (await dbContext.SealedBallots.AnyAsync(
+ x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open,
+ cancellationToken))
+ {
+ blocks.Add("sealed_ballot_pending");
+ }
+
+ return blocks;
+ }
+
+ private Task FoldedLinkAsync(Guid accountId, Guid? exceptMergeId, CancellationToken cancellationToken) =>
+ dbContext.AccountMerges.AnyAsync(
+ x => x.Id != exceptMergeId && x.FoldedUserAccountId == accountId && FoldedStates.Contains(x.State),
+ cancellationToken);
+
+ ///
+ /// Applies the merge to Bifrost records in one save, together with State=Committed. Total: blocks were checked before the move
+ /// and a refusal now would strand moved logins, so it recomputes the reductions from current rows and applies them. Committed
+ /// and Final are no-ops returning the receipt; any other state but HeimdallMoved is an error.
+ ///
+ public async Task CommitAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
+
+ // The exclusive lock first, so no writer that read the folded account's standing is still to save when the reduction reads its
+ // rows, then the state again: a commit that waited here found the merge landed and returns its receipt.
+ await using var transaction = await BeginAsync(dbContext, cancellationToken);
+ await LockAsync(dbContext, merge.FoldedUserAccountId, exclusive: true, cancellationToken);
+ await dbContext.Entry(merge).ReloadAsync(cancellationToken);
+ if (merge.State is AccountMergeState.Committed or AccountMergeState.Final)
+ {
+ return merge;
+ }
+
+ if (merge.State != AccountMergeState.HeimdallMoved)
+ {
+ throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallMoved merge can be committed.");
+ }
+
+ try
+ {
+ var reduction = await ReduceAsync(merge.SurvivorUserAccountId, merge.FoldedUserAccountId, cancellationToken, mergeId);
+ var now = timeProvider.GetUtcNow();
+ var seq = 0;
+ foreach (var entry in reduction.Entries)
+ {
+ dbContext.AccountMergeEntries.Add(Journal(merge.Id, ++seq, entry, now));
+ }
+
+ reduction.Apply(now);
+ if (reduction.MovedPatronEvents)
+ {
+ await RestageTiersAsync(reduction.Survivor, reduction.Folded, now, cancellationToken);
+ }
+
+ reduction.ReweighMovedVotes();
+ merge.State = AccountMergeState.Committed;
+ merge.CommittedUtc = now;
+ merge.GraceEndsUtc = now + Grace;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ if (transaction is not null)
+ {
+ await transaction.CommitAsync(cancellationToken);
+ }
+
+ return merge;
+ }
+ catch
+ {
+ // Nothing was saved; drop what was staged so a retry on this context starts from the stored rows.
+ dbContext.ChangeTracker.Clear();
+ throw;
+ }
+ }
+
+ /// Replays the journal backward in one save with State=Undone. Total, like commit. Undone is a no-op; any other state but HeimdallReversed is an error.
+ public async Task UndoLocalAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
+ if (merge.State == AccountMergeState.Undone)
+ {
+ return merge;
+ }
+
+ if (merge.State != AccountMergeState.HeimdallReversed)
+ {
+ throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallReversed merge can be undone locally.");
+ }
+
+ if (merge.FinalizedUtc is not null)
+ {
+ throw new InvalidOperationException($"Merge {mergeId} is Final; a merge is never undone past Final.");
+ }
+
+ try
+ {
+ var now = timeProvider.GetUtcNow();
+ var journal = await dbContext.AccountMergeEntries.Where(x => x.MergeId == mergeId).OrderByDescending(x => x.Seq).ToListAsync(cancellationToken);
+ var seq = journal.Count == 0 ? 0 : journal.Max(x => x.Seq);
+ var survivor = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == merge.SurvivorUserAccountId, cancellationToken);
+ var folded = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == merge.FoldedUserAccountId, cancellationToken);
+ var survivorKey = AppraisalKey(survivor.Id);
+ var restagePatron = false;
+
+ void Record(AccountMergeEntry original, bool restored) =>
+ dbContext.AccountMergeEntries.Add(new AccountMergeEntry
+ {
+ MergeId = mergeId,
+ Seq = ++seq,
+ Kind = original.Kind,
+ RecordId = original.RecordId,
+ Action = restored ? AccountMergeEntryAction.Restored : AccountMergeEntryAction.KeptAfterUndo,
+ PriorUserAccountId = original.PriorUserAccountId,
+ AtUtc = now
+ });
+
+ foreach (var entry in journal.Where(x => x.Action is AccountMergeEntryAction.Voided or AccountMergeEntryAction.Moved or AccountMergeEntryAction.Closed or AccountMergeEntryAction.Suspended or AccountMergeEntryAction.Created))
+ {
+ switch (entry.Kind, entry.Action)
+ {
+ case (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided):
+ {
+ var vote = await dbContext.Votes.IgnoreQueryFilters().Include(x => x.Motion).SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = vote?.VoidedByMergeId == mergeId && vote.Motion.Status == MotionStatus.Open;
+ if (restore)
+ {
+ vote!.VoidedByMergeId = null;
+ vote.VoidedUtc = null;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved):
+ {
+ var vote = await dbContext.Votes.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = vote is not null && vote.UserAccountId == survivor.Id && vote.CastAtUtc == entry.PriorAtUtc;
+ if (restore)
+ {
+ vote!.UserAccountId = entry.PriorUserAccountId!.Value;
+ if (decimal.TryParse(entry.PriorText, NumberStyles.Number, CultureInfo.InvariantCulture, out var priorWeight))
+ {
+ vote.Weight = priorWeight;
+ }
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided):
+ {
+ var row = await dbContext.ConceptAppraisals.IgnoreQueryFilters().SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = row?.VoidedByMergeId == mergeId;
+ if (restore)
+ {
+ row!.VoidedByMergeId = null;
+ row.VoidedUtc = null;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved):
+ {
+ var row = await dbContext.ConceptAppraisals.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = row is not null && row.UserAccountId == survivor.Id && row.VoterKey == survivorKey && row.CastAtUtc == entry.PriorAtUtc;
+ if (restore)
+ {
+ row!.UserAccountId = entry.PriorUserAccountId!.Value;
+ var (priorClass, priorKey) = ParseAppraisalPrior(entry.PriorText);
+ row.VoterKey = priorKey ?? row.VoterKey;
+ row.VoterClass = priorClass ?? row.VoterClass;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed):
+ {
+ var restore = folded.Membership is { Status: MembershipStatus.Merged } && Enum.TryParse(entry.PriorText, out _);
+ if (restore)
+ {
+ folded.Membership!.Status = Enum.Parse(entry.PriorText!);
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended):
+ {
+ // Only while the survivor still carries exactly this merge's suspension; an admin who changed it since owns the standing now.
+ var restore = survivor.Membership is { Status: MembershipStatus.Suspended } member &&
+ member.SuspensionReason == SuspensionReason(mergeId) &&
+ Enum.TryParse(entry.PriorText, out _);
+ if (restore)
+ {
+ survivor.Membership!.Status = Enum.Parse(entry.PriorText!);
+ survivor.Membership.SuspensionReason = null;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Created):
+ {
+ // The membership this merge made to carry a suspension goes with the merge, unless an admin has taken it over since.
+ var created = await dbContext.Memberships.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = created is { Status: MembershipStatus.Suspended } && created.SuspensionReason == SuspensionReason(mergeId);
+ if (restore)
+ {
+ dbContext.Memberships.Remove(created!);
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved):
+ {
+ var row = await dbContext.PatronSupportEvents.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = row is not null && row.UserAccountId == survivor.Id;
+ if (restore)
+ {
+ row!.UserAccountId = entry.PriorUserAccountId!.Value;
+ restagePatron = true;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ }
+ }
+
+ if (restagePatron)
+ {
+ await RestageTiersAsync(survivor, folded, now, cancellationToken);
+ }
+
+ merge.State = AccountMergeState.Undone;
+ merge.UndoneUtc = now;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return merge;
+ }
+ catch
+ {
+ dbContext.ChangeTracker.Clear();
+ throw;
+ }
+ }
+
+ ///
+ /// Committed merges whose grace has ended become Final; returns how many this call finalized. Undo is never allowed past Final.
+ /// State is the merge's concurrency token, so a merge another writer moved first (UndoRequested) fails its save and is left to that
+ /// transition: a stale Committed read can never overwrite it.
+ ///
+ public async Task FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var dueIds = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => x.State == AccountMergeState.Committed && x.GraceEndsUtc <= now)
+ .Select(x => x.Id)
+ .ToListAsync(cancellationToken);
+ var finalized = 0;
+ foreach (var id in dueIds)
+ {
+ var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == id, cancellationToken);
+ if (merge.State != AccountMergeState.Committed)
+ {
+ continue;
+ }
+
+ merge.State = AccountMergeState.Final;
+ merge.FinalizedUtc = now;
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ finalized++;
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ dbContext.ChangeTracker.Clear();
+ }
+ }
+
+ return finalized;
+ }
+
+ ///
+ /// Stages the journal entry for a patron event that is on a folded account's survivor, so undo moves it back with the rest; saved
+ /// with the event by , the only caller. Idempotent: a provider retry stages nothing.
+ ///
+ public static async Task StageIntakeJournalAsync(BifrostDbContext db, Guid mergeId, Guid foldedUserAccountId, Guid supportEventId, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ if (await db.AccountMergeEntries.AnyAsync(
+ x => x.MergeId == mergeId && x.Kind == AccountMergeEntryKind.PatronSupportEvent && x.RecordId == supportEventId,
+ cancellationToken))
+ {
+ return;
+ }
+
+ var seq = await db.AccountMergeEntries.Where(x => x.MergeId == mergeId).MaxAsync(x => (int?)x.Seq, cancellationToken) ?? 0;
+ db.AccountMergeEntries.Add(Journal(
+ mergeId,
+ seq + 1,
+ new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEventId, foldedUserAccountId),
+ now));
+ }
+
+ private sealed class Reduction(
+ UserAccount survivor,
+ UserAccount folded,
+ List entries,
+ List> effects,
+ List movedVotes,
+ bool movedPatronEvents)
+ {
+ public UserAccount Survivor { get; } = survivor;
+
+ public UserAccount Folded { get; } = folded;
+
+ public IReadOnlyList Entries => entries;
+
+ public bool MovedPatronEvents { get; } = movedPatronEvents;
+
+ public Guid MergeId { get; set; }
+
+ /// A moved vote carries the survivor's weight, derived once from the survivor's tiers as they stand after the restage, never the folded account's.
+ public void ReweighMovedVotes()
+ {
+ foreach (var vote in movedVotes)
+ {
+ vote.Weight = Survivor.Membership!.EffectiveVotingWeight;
+ }
+ }
+
+ public void Apply(DateTimeOffset now)
+ {
+ foreach (var effect in effects)
+ {
+ effect(MergeId, now);
+ }
+ }
+ }
+
+ ///
+ /// What a merge does to records, computed from current rows without writing: the journal entries and the effects that apply them.
+ /// Rules (design 5): suspension wins; the folded membership is closed and its roles never copied; open standard motions and
+ /// concept appraisals keep one voice per person (the survivor's), a lone folded one moving only to an Active survivor; patron
+ /// events follow the person.
+ ///
+ private async Task ReduceAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? mergeId = null)
+ {
+ var survivor = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == survivorId, cancellationToken);
+ var folded = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == foldedId, cancellationToken);
+
+ var entries = new List();
+ var effects = new List>();
+ var movedVotes = new List();
+
+ var foldedSuspended = folded.Membership?.Status == MembershipStatus.Suspended;
+ var survivorSuspendedNow = survivor.Membership?.Status == MembershipStatus.Suspended;
+ var survivorStanding = survivor.Membership?.Status;
+ if (foldedSuspended && !survivorSuspendedNow)
+ {
+ if (survivor.Membership is { } survivorMembership)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended, survivorMembership.Id, null, survivorMembership.Status.ToString()));
+ effects.Add((id, _) =>
+ {
+ survivorMembership.Status = MembershipStatus.Suspended;
+ survivorMembership.SuspensionReason = SuspensionReason(id);
+ });
+ }
+ else
+ {
+ // The chat tier holds no membership, and an absent one chats: without a row the suspension would be gone. The row is journalled so undo removes it.
+ var created = new Bifrost.Web.Domain.Membership { UserAccountId = survivor.Id, Status = MembershipStatus.Suspended };
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Created, created.Id));
+ effects.Add((id, now) =>
+ {
+ created.SuspensionReason = SuspensionReason(id);
+ created.CreatedAtUtc = now;
+ created.Notes = "Created by an account merge to carry the folded account's suspension.";
+ dbContext.Memberships.Add(created);
+ });
+ }
+
+ survivorStanding = MembershipStatus.Suspended;
+ }
+
+ var survivorActive = survivorStanding == MembershipStatus.Active;
+
+ if (folded.Membership is { } foldedMembership)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed, foldedMembership.Id, null, foldedMembership.Status.ToString()));
+ effects.Add((_, _) => foldedMembership.Status = MembershipStatus.Merged);
+ }
+
+ var foldedVotes = await dbContext.Votes
+ .Where(x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open && x.Motion.Kind == MotionKind.Standard)
+ .ToListAsync(cancellationToken);
+ var survivorVotedMotions = (await dbContext.Votes
+ .Where(x => x.UserAccountId == survivorId && x.Motion.Status == MotionStatus.Open && x.Motion.Kind == MotionKind.Standard)
+ .Select(x => x.MotionId)
+ .ToListAsync(cancellationToken)).ToHashSet();
+ foreach (var vote in foldedVotes)
+ {
+ if (survivorVotedMotions.Contains(vote.MotionId) || !survivorActive)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided, vote.Id, vote.UserAccountId));
+ effects.Add((id, now) =>
+ {
+ vote.VoidedByMergeId = id;
+ vote.VoidedUtc = now;
+ });
+ }
+ else
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved, vote.Id, vote.UserAccountId, vote.Weight.ToString(CultureInfo.InvariantCulture), vote.CastAtUtc));
+ movedVotes.Add(vote);
+ effects.Add((_, _) => vote.UserAccountId = survivorId);
+ }
+ }
+
+ var survivorKey = AppraisalKey(survivorId);
+ var foldedAppraisals = await dbContext.ConceptAppraisals.Where(x => x.UserAccountId == foldedId).ToListAsync(cancellationToken);
+ var survivorSubjects = (await dbContext.ConceptAppraisals
+ .Where(x => x.UserAccountId == survivorId || x.VoterKey == survivorKey)
+ .Select(x => x.SubjectId)
+ .ToListAsync(cancellationToken)).ToHashSet();
+ foreach (var appraisal in foldedAppraisals)
+ {
+ if (survivorSubjects.Contains(appraisal.SubjectId) || !survivorActive)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided, appraisal.Id, appraisal.UserAccountId));
+ effects.Add((id, now) =>
+ {
+ appraisal.VoidedByMergeId = id;
+ appraisal.VoidedUtc = now;
+ });
+ }
+ else
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved, appraisal.Id, appraisal.UserAccountId, $"{appraisal.VoterClass}|{appraisal.VoterKey}", appraisal.CastAtUtc));
+ effects.Add((_, _) =>
+ {
+ appraisal.UserAccountId = survivorId;
+ appraisal.VoterKey = survivorKey;
+ appraisal.VoterClass = VoterClass.Member; // the survivor is Active here, which is what makes an account a Member voter
+ });
+ }
+ }
+
+ var foldedEvents = folded.PatronSupportEvents.ToList();
+ foreach (var supportEvent in foldedEvents)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEvent.Id, supportEvent.UserAccountId));
+ effects.Add((_, _) => supportEvent.UserAccountId = survivorId);
+ }
+
+ var reduction = new Reduction(survivor, folded, entries, effects, movedVotes, foldedEvents.Count > 0);
+ if (mergeId is { } m)
+ {
+ reduction.MergeId = m;
+ }
+
+ return reduction;
+ }
+
+ // Tiers derive once from all the events now on each account, never tier A plus tier B. Ownership is read from the
+ // tracked rows, so it holds before the save as well as after it.
+ private async Task RestageTiersAsync(UserAccount survivor, UserAccount folded, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var events = survivor.PatronSupportEvents.Concat(folded.PatronSupportEvents).DistinctBy(x => x.Id).ToList();
+ await StageIfMembershipAsync(survivor.Membership, events.Where(x => x.UserAccountId == survivor.Id).ToList(), now, cancellationToken);
+ await StageIfMembershipAsync(folded.Membership, events.Where(x => x.UserAccountId == folded.Id).ToList(), now, cancellationToken);
+ }
+
+ private async Task StageIfMembershipAsync(Bifrost.Web.Domain.Membership? membership, IEnumerable events, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ if (membership is not null && dbContext.Entry(membership).State != EntityState.Deleted)
+ {
+ await patronageService.StageTierSnapshotAsync(membership, events, now, cancellationToken);
+ }
+ }
+
+ private static AccountMergeEntry Journal(Guid mergeId, int seq, MergePlanEntry entry, DateTimeOffset now) => new()
+ {
+ MergeId = mergeId,
+ Seq = seq,
+ Kind = entry.Kind,
+ RecordId = entry.RecordId,
+ Action = entry.Action,
+ PriorUserAccountId = entry.PriorUserAccountId,
+ PriorText = entry.PriorText,
+ PriorAtUtc = entry.PriorAtUtc,
+ AtUtc = now
+ };
+
+ private static string AppraisalKey(Guid accountId) => "account:" + accountId.ToString("N");
+
+ private static (VoterClass? Class, string? Key) ParseAppraisalPrior(string? prior)
+ {
+ var split = prior?.IndexOf('|') ?? -1;
+ return split > 0 && Enum.TryParse(prior![..split], out var voterClass) ? (voterClass, prior[(split + 1)..]) : (null, null);
+ }
+}
+
+///
+/// The one merge loop, every 30 seconds: the proof holder drops expired bearers, the saga advances every due in-flight merge (confirm,
+/// replay, undo), then the ledger finalizes merges past their grace. A new scope per tick, a warning on failure, the SealedBallotCloser shape. No second merge hosted service exists.
+///
+public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger logger) : BackgroundService
+{
+ public static readonly TimeSpan Tick = TimeSpan.FromSeconds(30);
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ using var timer = new PeriodicTimer(Tick);
+ do
+ {
+ try
+ {
+ using var scope = scopes.CreateScope();
+ var now = clock.GetUtcNow();
+ scope.ServiceProvider.GetRequiredService().PruneExpired();
+ await scope.ServiceProvider.GetRequiredService().AdvanceDueAsync(now, stoppingToken);
+ await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(now, stoppingToken);
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ logger.LogWarning(error, "Account merge sweep failed; retrying next tick.");
+ }
+ }
+ while (await timer.WaitForNextTickAsync(stoppingToken));
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs
new file mode 100644
index 0000000..153ee80
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs
@@ -0,0 +1,576 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.EntityFrameworkCore;
+using Npgsql;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// A live Heimdall bearer a member redeemed from a fresh sign-in, with the Heimdall account and provider it came through. The token is a
+/// secret: never prints it (nor the account id), so no log or exception that holds a proof can leak it.
+///
+public sealed record MergeProof(string AccessToken, string HeimdallAccountId, string Provider)
+{
+ private bool PrintMembers(StringBuilder builder)
+ {
+ builder.Append($"Provider = {Provider}");
+ return true;
+ }
+}
+
+/// What the member confirmed: the pair, the plan digest they saw, and a proof for every login of each side that must speak.
+public sealed record ConfirmMergeRequest(
+ Guid ActorUserAccountId,
+ Guid SurvivorUserAccountId,
+ Guid FoldedUserAccountId,
+ string PreviewDigest,
+ MergeProof SurvivorProof,
+ IReadOnlyList FoldedProofs);
+
+/// The closed answer to a confirm. Only Confirmed wrote a row.
+public abstract record ConfirmOutcome
+{
+ private ConfirmOutcome()
+ {
+ }
+
+ public sealed record Confirmed(Guid MergeId) : ConfirmOutcome;
+
+ /// The plan's block codes (never account names), or merge_in_flight when the database refused an overlapping merge.
+ public sealed record Blocked(IReadOnlyList Codes) : ConfirmOutcome;
+
+ public sealed record PreviewStale : ConfirmOutcome;
+
+ public sealed record NotParty : ConfirmOutcome;
+
+ public sealed record ProofAccountMismatch : ConfirmOutcome;
+}
+
+/// The closed answer to an undo request. Only Requested wrote.
+public abstract record UndoOutcome
+{
+ private UndoOutcome()
+ {
+ }
+
+ public sealed record Requested : UndoOutcome;
+
+ public sealed record NotCommitted : UndoOutcome;
+
+ public sealed record GraceOver : UndoOutcome;
+
+ public sealed record NotSurvivor : UndoOutcome;
+
+ public sealed record ProofAccountMismatch : UndoOutcome;
+}
+
+/// The two ways an operator may end a stuck leg: the forward move is failed, or the undo is given up and the merge stands.
+public enum SettleChoice
+{
+ FailForward,
+ AbandonUndo
+}
+
+/// The closed answer to an operator's settle. Only Settled wrote.
+public abstract record SettleOutcome
+{
+ private SettleOutcome()
+ {
+ }
+
+ public sealed record Settled : SettleOutcome;
+
+ /// The merge is missing, in another state than the choice ends, or not stuck on one of the settleable outcomes.
+ public sealed record NotStuck : SettleOutcome;
+
+ public sealed record WrongMoveId : SettleOutcome;
+
+ /// The State token went to another writer first; the other transition stands and nothing was changed.
+ public sealed record Lost : SettleOutcome;
+}
+
+///
+/// The one owner of an account merge's lifecycle outside the ledger's Committed, Final and Undone, and the only caller of
+/// . It inserts Confirmed (the consent record, with the Heimdall bearers sealed and the move
+/// id minted), runs the one idempotent step function (move, commit, reverse, undo), and writes
+/// HeimdallMoved, Failed, UndoRequested and HeimdallReversed. It never writes votes, memberships or journal rows (the ledger's), never
+/// judges a proof's tier or freshness (Heimdall's), and reads no standing of its own: the plan's blocks and the database's live-merge
+/// index answer overlap, and the writers that act for an account go through .
+/// Every transition is one save guarded by State, the merge's concurrency token; the loser of a race reloads and continues from the
+/// stored state. Heimdall's closed outcome is consumed as is: Unknown (a lost answer, an outage) is replayed with the same stored
+/// move id and never fails a merge. Logs name the merge id, state, outcome class and refusal code only.
+///
+public sealed partial class AccountMergeSaga(
+ BifrostDbContext dbContext,
+ AccountMergeLedger ledger,
+ HeimdallIdentityMoveClient mover,
+ IDataProtectionProvider dataProtection,
+ AuditTrailService audit,
+ TimeProvider timeProvider,
+ ILogger logger)
+{
+ public const string MergeInFlight = "merge_in_flight";
+ public const string ReceiptMismatch = "receipt_mismatch";
+ public const string ProofsUnreadable = "proofs_unreadable";
+ public const string MoveIdConflict = "move_id_conflict";
+ public const string OperatorFailed = "operator_failed";
+ public const string UndoOperatorAbandoned = "undo_operator_abandoned";
+
+ private const string LiveMergeIndex = "UX_AccountMerges_FoldedUserAccountId_Live";
+ private const int MaxProofs = 8;
+
+ private static readonly TimeSpan[] Backoff = [TimeSpan.FromSeconds(15), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15)];
+ private static readonly TimeSpan UnreadableRetry = TimeSpan.FromHours(1);
+
+ private static readonly AccountMergeState[] DueStates =
+ [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
+
+ private readonly IDataProtector _seal = dataProtection.CreateProtector("Bifrost.AccountMerge.Proofs.v1");
+
+ private sealed record ProofSeal(List From, string? To)
+ {
+ // The seal holds live bearers: the generated ToString would print them into any log or exception that holds it.
+ private bool PrintMembers(StringBuilder builder)
+ {
+ builder.Append($"From = {From?.Count}, To = {(To is null ? "none" : "present")}");
+ return true;
+ }
+ }
+
+ // ---- confirm ----
+
+ ///
+ /// The member's consent, as one insert. The actor must be one of the pair; the plan must have no blocks and be the one the member
+ /// saw (digest); every proof must be of its side's Heimdall account. Calls no Heimdall: the caller runs .
+ ///
+ public async Task ConfirmAsync(ConfirmMergeRequest request, CancellationToken cancellationToken)
+ {
+ RequireProofs(request.SurvivorProof, request.FoldedProofs);
+ if (request.ActorUserAccountId != request.SurvivorUserAccountId && request.ActorUserAccountId != request.FoldedUserAccountId)
+ {
+ return new ConfirmOutcome.NotParty();
+ }
+
+ try
+ {
+ return await AccountMergeLedger.WriteAsAsync(dbContext, request.ActorUserAccountId, _ => InsertConfirmedAsync(request, cancellationToken), cancellationToken);
+ }
+ catch (DbUpdateException error) when (IsLiveMergeViolation(error))
+ {
+ dbContext.ChangeTracker.Clear();
+ return new ConfirmOutcome.Blocked([MergeInFlight]);
+ }
+ }
+
+ private async Task InsertConfirmedAsync(ConfirmMergeRequest request, CancellationToken cancellationToken)
+ {
+ var plan = await ledger.PlanAsync(request.SurvivorUserAccountId, request.FoldedUserAccountId, cancellationToken);
+ if (plan.Blocks.Count > 0)
+ {
+ return new ConfirmOutcome.Blocked(plan.Blocks);
+ }
+
+ if (!string.Equals(plan.Digest(request.SurvivorUserAccountId, request.FoldedUserAccountId), request.PreviewDigest, StringComparison.Ordinal))
+ {
+ return new ConfirmOutcome.PreviewStale();
+ }
+
+ var survivorHeimdall = await HeimdallAccountAsync(request.SurvivorUserAccountId, cancellationToken);
+ var foldedHeimdall = await HeimdallAccountAsync(request.FoldedUserAccountId, cancellationToken);
+ if (request.SurvivorProof.HeimdallAccountId != survivorHeimdall || request.FoldedProofs.Any(x => x.HeimdallAccountId != foldedHeimdall))
+ {
+ return new ConfirmOutcome.ProofAccountMismatch();
+ }
+
+ var now = timeProvider.GetUtcNow();
+ var merge = new AccountMerge
+ {
+ State = AccountMergeState.Confirmed,
+ SurvivorUserAccountId = request.SurvivorUserAccountId,
+ FoldedUserAccountId = request.FoldedUserAccountId,
+ CreatedUtc = now,
+ ConfirmedByUserAccountId = request.ActorUserAccountId,
+ ConfirmedUtc = now,
+ PreviewDigest = request.PreviewDigest,
+ SurvivorProofProvider = request.SurvivorProof.Provider,
+ FoldedProofProviders = string.Join(',', request.FoldedProofs.Select(x => x.Provider).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)),
+ // Heimdall's idempotency key: random, minted once here, read back from the row on every call, never derived from the merge id.
+ HeimdallMoveId = Guid.NewGuid().ToString("N"),
+ SealedProofs = Seal(request.FoldedProofs.Select(x => x.AccessToken), request.SurvivorProof.AccessToken),
+ LastOutcome = "confirmed"
+ };
+ dbContext.AccountMerges.Add(merge);
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogInformation("Account merge {MergeId} {State}", merge.Id, merge.State);
+ return new ConfirmOutcome.Confirmed(merge.Id);
+ }
+
+ // ---- undo request ----
+
+ ///
+ /// The survivor's request to give the moved logins back, inside the grace and with fresh survivor proofs. One save: UndoRequested, a
+ /// freshly minted reverse move id, the sealed proofs. Losing the race to the Final sweep is the State token's, answered GraceOver.
+ ///
+ public async Task RequestUndoAsync(
+ Guid mergeId, Guid actorUserAccountId, IReadOnlyList survivorProofs, CancellationToken cancellationToken)
+ {
+ RequireProofs(null, survivorProofs);
+ try
+ {
+ return await AccountMergeLedger.WriteAsAsync(dbContext, actorUserAccountId, _ => WriteUndoRequestedAsync(mergeId, actorUserAccountId, survivorProofs, cancellationToken), cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ dbContext.ChangeTracker.Clear();
+ return new UndoOutcome.GraceOver();
+ }
+ }
+
+ private async Task WriteUndoRequestedAsync(
+ Guid mergeId, Guid actorUserAccountId, IReadOnlyList survivorProofs, CancellationToken cancellationToken)
+ {
+ var merge = await LoadAsync(mergeId, cancellationToken);
+ if (merge is null)
+ {
+ return new UndoOutcome.NotCommitted();
+ }
+
+ var now = timeProvider.GetUtcNow();
+ if (actorUserAccountId != merge.SurvivorUserAccountId)
+ {
+ return new UndoOutcome.NotSurvivor();
+ }
+
+ if (merge.State == AccountMergeState.Final || merge.FinalizedUtc is not null)
+ {
+ return new UndoOutcome.GraceOver();
+ }
+
+ if (merge.State != AccountMergeState.Committed)
+ {
+ return new UndoOutcome.NotCommitted();
+ }
+
+ if (merge.GraceEndsUtc is not { } graceEnds || now >= graceEnds)
+ {
+ return new UndoOutcome.GraceOver();
+ }
+
+ var survivorHeimdall = await HeimdallAccountAsync(merge.SurvivorUserAccountId, cancellationToken);
+ if (survivorProofs.Any(x => x.HeimdallAccountId != survivorHeimdall))
+ {
+ return new UndoOutcome.ProofAccountMismatch();
+ }
+
+ merge.State = AccountMergeState.UndoRequested;
+ merge.UndoRequestedUtc = now;
+ merge.HeimdallReverseMoveId = Guid.NewGuid().ToString("N");
+ merge.SealedProofs = Seal(survivorProofs.Select(x => x.AccessToken), null);
+ merge.Attempts = 0;
+ merge.NextAttemptUtc = null;
+ merge.LastOutcome = "undo_requested";
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogInformation("Account merge {MergeId} {State}", merge.Id, merge.State);
+ return new UndoOutcome.Requested();
+ }
+
+ // ---- the step function ----
+
+ ///
+ /// The one step function: confirm's inline advance, the sweeper's resume after a crash and an undo request all run it. From the
+ /// stored state it makes the Heimdall move (or reversal) under the stored id, records the answer, and calls the ledger's commit (or
+ /// local undo). Idempotent: every state has one next step and every step is safe to repeat. Other states are a no-op.
+ ///
+ public async Task AdvanceAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ for (var lost = 0; ; lost++)
+ {
+ try
+ {
+ return await AdvanceOnceAsync(mergeId, cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException) when (lost < 2)
+ {
+ // Another advancer saved first: forget what this context staged and continue from the stored state.
+ dbContext.ChangeTracker.Clear();
+ }
+ }
+ }
+
+ private async Task AdvanceOnceAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var merge = await LoadAsync(mergeId, cancellationToken) ?? throw new InvalidOperationException($"Merge {mergeId} does not exist.");
+ if (merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested)
+ {
+ merge = await MoveAsync(merge, cancellationToken);
+ }
+
+ return merge.State switch
+ {
+ AccountMergeState.HeimdallMoved => await ledger.CommitAsync(merge.Id, cancellationToken),
+ AccountMergeState.HeimdallReversed => await ledger.UndoLocalAsync(merge.Id, cancellationToken),
+ _ => merge
+ };
+ }
+
+ private async Task MoveAsync(AccountMerge merge, CancellationToken cancellationToken)
+ {
+ if (merge.LastOutcome == ReceiptMismatch)
+ {
+ return merge; // Heimdall answered, wrongly, and its proofs are wiped: replay can only repeat the same answer.
+ }
+
+ var forward = merge.State == AccountMergeState.Confirmed;
+ var now = timeProvider.GetUtcNow();
+ if (Open(merge.SealedProofs) is not { } proofs)
+ {
+ // The key ring is lost or rotated out. Heimdall may already have moved, so nothing changes but the retry time.
+ merge.LastOutcome = ProofsUnreadable;
+ merge.NextAttemptUtc = now + UnreadableRetry;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogError("Account merge {MergeId} {State}: sealed proofs unreadable", merge.Id, merge.State);
+ return merge;
+ }
+
+ var request = forward
+ ? new HeimdallMoveRequest(merge.HeimdallMoveId!, proofs.From, proofs.To)
+ : new HeimdallMoveRequest(merge.HeimdallReverseMoveId!, proofs.From, ReversesMoveId: merge.HeimdallMoveId);
+ var outcome = await mover.MoveAsync(request, cancellationToken);
+ var code = outcome is HeimdallMoveOutcome.Refused refused ? RefusalCode(refused.Code) : null;
+ switch (outcome)
+ {
+ case HeimdallMoveOutcome.Moved moved:
+ // The leg's destination is the survivor going forward and the folded account coming back.
+ var destination = await HeimdallAccountAsync(forward ? merge.SurvivorUserAccountId : merge.FoldedUserAccountId, cancellationToken);
+ merge.SealedProofs = null;
+ if (moved.Receipt.AccountId != destination)
+ {
+ merge.LastOutcome = ReceiptMismatch;
+ break;
+ }
+
+ merge.Attempts = 0;
+ merge.NextAttemptUtc = null;
+ merge.LastOutcome = "moved";
+ if (forward)
+ {
+ merge.State = AccountMergeState.HeimdallMoved;
+ merge.ProofFromTier = Tier(moved.Receipt.ProofFrom);
+ merge.ProofToTier = moved.Receipt.ProofTo is { } to ? Tier(to) : null;
+ merge.MovedIdentityIds = JsonSerializer.Serialize(moved.Receipt.MovedIdentityIds);
+ }
+ else
+ {
+ merge.State = AccountMergeState.HeimdallReversed;
+ merge.ReversedUtc = now;
+ }
+
+ break;
+ case HeimdallMoveOutcome.Refused:
+ // Heimdall applied nothing before a 4xx. A forward refusal ends the merge; a refused undo leaves it as it was.
+ merge.SealedProofs = null;
+ merge.NextAttemptUtc = null;
+ if (forward)
+ {
+ merge.State = AccountMergeState.Failed;
+ merge.FailedUtc = now;
+ merge.FailureCode = code!;
+ merge.LastOutcome = "refused";
+ }
+ else
+ {
+ merge.State = AccountMergeState.Committed;
+ merge.LastOutcome = "undo_" + code;
+ }
+
+ break;
+ case HeimdallMoveOutcome.Unknown unknown:
+ merge.Attempts++;
+ merge.NextAttemptUtc = now + Backoff[Math.Min(merge.Attempts, Backoff.Length) - 1];
+ merge.LastOutcome = unknown.Reason.Length > 64 ? unknown.Reason[..64] : unknown.Reason;
+ break;
+ }
+
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogInformation("Account merge {MergeId} {State}: {Outcome} {Code}", merge.Id, merge.State, outcome.GetType().Name, code);
+ return merge;
+ }
+
+ /// Advances every in-flight merge that is due, oldest first. One that throws is logged and skipped; returns how many were advanced.
+ public async Task AdvanceDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var due = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => DueStates.Contains(x.State) && (x.NextAttemptUtc == null || x.NextAttemptUtc <= now))
+ .OrderBy(x => x.CreatedUtc)
+ .Select(x => x.Id)
+ .ToListAsync(cancellationToken);
+ var advanced = 0;
+ foreach (var id in due)
+ {
+ try
+ {
+ await AdvanceAsync(id, cancellationToken);
+ advanced++;
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ dbContext.ChangeTracker.Clear();
+ logger.LogWarning("Account merge {MergeId} advance failed: {Error}", id, error.GetType().Name);
+ }
+ }
+
+ return advanced;
+ }
+
+ // ---- operator settle ----
+
+ /// The Heimdall answers no replay can change: the one the saga recorded and stopped on, the key ring's loss, and a move Heimdall holds but will not confirm.
+ public static readonly IReadOnlyList SettleableOutcomes = [ReceiptMismatch, ProofsUnreadable, MoveIdConflict];
+
+ ///
+ /// Whether an operator may end this merge's leg: in flight (Confirmed or UndoRequested) and stopped on one of the closed
+ /// outcomes. Derived from the row on every read; there is no stuck flag.
+ ///
+ public static bool IsSettleable(AccountMerge merge) =>
+ merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested && SettleableOutcomes.Contains(merge.LastOutcome);
+
+ ///
+ /// A platform admin's end of a stuck leg (ruling merge-stuck-end-only-typed-id): FailForward turns a stuck Confirmed merge into
+ /// Failed, AbandonUndo returns a stuck UndoRequested merge to Committed with its grace. Only with the leg's stored move id typed back.
+ /// Never adopts or invents a Heimdall receipt; a merge Heimdall moved (HeimdallMoved, Committed) is never settleable. One save
+ /// guarded by State carries the transition and its audit row (choice only): the loser of a race with
+ /// answers Lost and changes nothing. The caller has checked the operator's authority.
+ ///
+ public async Task SettleStuckAsync(
+ Guid mergeId, SettleChoice choice, string typedMoveId, Guid operatorUserAccountId, CancellationToken cancellationToken)
+ {
+ var forward = choice == SettleChoice.FailForward;
+ var merge = await LoadAsync(mergeId, cancellationToken);
+ if (merge is null || merge.State != (forward ? AccountMergeState.Confirmed : AccountMergeState.UndoRequested) || !IsSettleable(merge))
+ {
+ return new SettleOutcome.NotStuck();
+ }
+
+ if (!string.Equals(typedMoveId, forward ? merge.HeimdallMoveId : merge.HeimdallReverseMoveId, StringComparison.Ordinal))
+ {
+ return new SettleOutcome.WrongMoveId();
+ }
+
+ merge.SealedProofs = null;
+ merge.NextAttemptUtc = null;
+ if (forward)
+ {
+ merge.State = AccountMergeState.Failed;
+ merge.FailedUtc = timeProvider.GetUtcNow();
+ merge.FailureCode = OperatorFailed;
+ merge.LastOutcome = OperatorFailed;
+ }
+ else
+ {
+ merge.State = AccountMergeState.Committed;
+ merge.LastOutcome = UndoOperatorAbandoned;
+ }
+
+ try
+ {
+ await audit.RecordAsync(operatorUserAccountId, nameof(AccountMerge), merge.Id, "merge.settled", choice.ToString(), cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ dbContext.ChangeTracker.Clear();
+ return new SettleOutcome.Lost();
+ }
+
+ logger.LogInformation("Account merge {MergeId} {State}: settled by an operator ({Choice})", merge.Id, merge.State, choice);
+ return new SettleOutcome.Settled();
+ }
+
+ // ---- helpers ----
+
+ /// The merge as stored now: a row this context already tracks is reloaded, never trusted.
+ private async Task LoadAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var tracked = dbContext.AccountMerges.Local.FirstOrDefault(x => x.Id == mergeId);
+ if (tracked is not null)
+ {
+ await dbContext.Entry(tracked).ReloadAsync(cancellationToken);
+ return dbContext.Entry(tracked).State == EntityState.Detached ? null : tracked;
+ }
+
+ return await dbContext.AccountMerges.SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken);
+ }
+
+ private Task HeimdallAccountAsync(Guid userAccountId, CancellationToken cancellationToken) =>
+ dbContext.UserAccounts.AsNoTracking().Where(x => x.Id == userAccountId).Select(x => x.HeimdallAccountId).SingleAsync(cancellationToken);
+
+ /// Shapes Heimdall would 400 are refused before a row exists, so a confirm can never store a merge that cannot call. Messages name no value.
+ private static void RequireProofs(MergeProof? one, IReadOnlyList many)
+ {
+ if (many is not { Count: >= 1 and <= MaxProofs })
+ {
+ throw new ArgumentException("1 to 8 proofs are required", nameof(many));
+ }
+
+ foreach (var proof in one is null ? many : [one, .. many])
+ {
+ if (string.IsNullOrEmpty(proof.AccessToken) || proof.AccessToken.Length > HeimdallIdentityMoveClient.MaxProofLength
+ || string.IsNullOrEmpty(proof.HeimdallAccountId) || string.IsNullOrEmpty(proof.Provider) || proof.Provider.Length > 32)
+ {
+ throw new ArgumentException("a proof is malformed", nameof(many));
+ }
+ }
+
+ if (many.Select(x => x.Provider).Distinct(StringComparer.Ordinal).Sum(x => x.Length + 1) > 121)
+ {
+ throw new ArgumentException("the proofs' providers do not fit the record", nameof(many));
+ }
+ }
+
+ private string Seal(IEnumerable from, string? to) => _seal.Protect(JsonSerializer.Serialize(new ProofSeal([.. from], to)));
+
+ private ProofSeal? Open(string? sealedProofs)
+ {
+ if (sealedProofs is null)
+ {
+ return null;
+ }
+
+ try
+ {
+ return JsonSerializer.Deserialize(_seal.Unprotect(sealedProofs)) is { From.Count: > 0 } proofs ? proofs : null;
+ }
+ catch (Exception error) when (error is CryptographicException or JsonException)
+ {
+ return null;
+ }
+ }
+
+ private static string Tier(HeimdallProofTier tier) => tier == HeimdallProofTier.Strong ? "strong" : "weak";
+
+ private static string RefusalCode(HeimdallMoveRefusal code) =>
+ code == HeimdallMoveRefusal.RequestInvalid ? "invalid_request" : WordBoundary().Replace(code.ToString(), "_$1").ToLowerInvariant();
+
+ [GeneratedRegex("(?The database's refusal of an overlapping merge: the live-merge unique index or the chain trigger's exclusion violation.
+ private static bool IsLiveMergeViolation(DbUpdateException error)
+ {
+ for (var current = (Exception?)error; current is not null; current = current.InnerException)
+ {
+ if (current is PostgresException { SqlState: "23P01" } or PostgresException { SqlState: "23505", ConstraintName: LiveMergeIndex })
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs b/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs
index d485b91..aa1bf8a 100644
--- a/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs
+++ b/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs
@@ -12,20 +12,34 @@ public sealed partial class BifrostIdentityService(
BifrostDbContext dbContext,
TimeProvider timeProvider)
{
- public async Task RegisterNativeAsync(
- string identity,
- string? displayName,
- CancellationToken cancellationToken)
+ ///
+ /// The one rule set for a new native identity: well formed, not reserved, not taken. Returns the normalized identity or
+ /// throws . Spends nothing; the unique index at insert stays the race backstop.
+ ///
+ public async Task CheckAvailableAsync(string identity, CancellationToken cancellationToken)
{
var normalizedIdentity = NormalizeIdentity(identity);
- var exists = await dbContext.UserAccounts.AnyAsync(
- x => x.NormalizedBifrostIdentity == normalizedIdentity,
- cancellationToken);
- if (exists)
+ if (IsReserved(normalizedIdentity))
+ {
+ throw new BifrostIdentityException("That Bifrost identity is reserved.");
+ }
+
+ if (await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity, cancellationToken))
{
throw new BifrostIdentityException("That Bifrost identity is already registered.");
}
+ return normalizedIdentity;
+ }
+
+ public async Task RegisterNativeAsync(
+ string identity,
+ string? displayName,
+ int? noticeVersion,
+ CancellationToken cancellationToken)
+ {
+ var normalizedIdentity = await CheckAvailableAsync(identity, cancellationToken);
+
var now = timeProvider.GetUtcNow();
var publicIdentity = ToPublicIdentity(normalizedIdentity);
var resolvedDisplayName = string.IsNullOrWhiteSpace(displayName)
@@ -52,11 +66,42 @@ public sealed partial class BifrostIdentityService(
}
};
+ // One SaveChanges: an account that agreed never exists without its receipt. No version, no receipt.
dbContext.UserAccounts.Add(userAccount);
- await dbContext.SaveChangesAsync(cancellationToken);
+ if (noticeVersion is { } agreed)
+ {
+ dbContext.ConsentReceipts.Add(new ConsentReceipt
+ {
+ UserAccount = userAccount,
+ NoticeVersion = agreed,
+ AcceptedAtUtc = now
+ });
+ }
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ // Only a lost race on the unique index is the caller's mistake; anything else is a fault and propagates.
+ if (!await IdentityTakenAsync(normalizedIdentity))
+ {
+ throw;
+ }
+
+ throw new BifrostIdentityException("That Bifrost identity is already registered.");
+ }
+
return userAccount;
}
+ // A lost race on the unique index: the tracked insert is dropped and the identity is read fresh.
+ private async Task IdentityTakenAsync(string normalizedIdentity)
+ {
+ dbContext.ChangeTracker.Clear();
+ return await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity);
+ }
+
public async Task EnsureIdentityAsync(
UserAccount userAccount,
string preferredIdentity,
@@ -69,7 +114,9 @@ public sealed partial class BifrostIdentityService(
var normalizedBase = NormalizeCandidate(preferredIdentity);
var normalizedIdentity = normalizedBase;
- for (var suffix = 2; await IdentityExistsAsync(userAccount.Id, normalizedIdentity, cancellationToken); suffix++)
+ for (var suffix = 2;
+ IsReserved(normalizedIdentity) || await IdentityExistsAsync(userAccount.Id, normalizedIdentity, cancellationToken);
+ suffix++)
{
normalizedIdentity = $"{normalizedBase}-{suffix}";
}
@@ -104,6 +151,20 @@ public sealed partial class BifrostIdentityService(
return new ClaimsPrincipal(identity);
}
+ // Matrix localparts that already belong to someone else, and system names. The identity becomes the Matrix
+ // localpart at SSO, so a new account must never mint one of these. Applied to the normalized identity when an
+ // account is created (native register refuses, a derived identity takes the next free suffix); lookups of
+ // existing accounts go through NormalizeIdentity and are untouched. There is no exemption path: Minds and
+ // other known holders do not sign in through Bifrost identities.
+ private static readonly HashSet ReservedIdentities = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "admin", "aqua", "deru", "eureka", "heimdall", "ivixey", "kiko", "libby", "meta", "nibu", "unnie", "void", "weksa",
+ "root", "system", "matrix", "synapse", "support", "bot", "mod", "moderator", "postmaster", "gamecult",
+ "bifrost", "idunn", "odin", "huginn", "ratatoskr"
+ };
+
+ public static bool IsReserved(string normalizedIdentity) => ReservedIdentities.Contains(normalizedIdentity);
+
public static string NormalizeIdentity(string identity)
{
var normalized = identity.Trim().ToLowerInvariant();
diff --git a/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs
new file mode 100644
index 0000000..06e5622
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs
@@ -0,0 +1,87 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Membership;
+
+public enum SuspensionOutcome
+{
+ Done,
+ NotAdmin,
+ NoReason,
+ NoSuchAccount,
+ NotApplicable,
+ ProtectedAccount
+}
+
+///
+/// The one place a membership becomes Suspended or stops being. Only a platform admin may call it, every use leaves an audit
+/// receipt naming the admin and the account (the reason is kept on the membership row, readable by admins only), and no sign-in path writes or lifts a suspension (Heimdall and GitHub
+/// sign-in leave a Suspended membership as it is). Unsuspending restores Active for an account that was once approved,
+/// Authenticated for one that never was; a pending request is not remembered.
+///
+public sealed class MembershipSuspensionService(BifrostDbContext dbContext, AuditTrailService auditTrailService)
+{
+ public const int MaxReasonLength = 500;
+
+ public Task SuspendAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, CancellationToken cancellationToken) =>
+ ChangeAsync(actor, userAccountId, reason, suspend: true, cancellationToken);
+
+ public Task UnsuspendAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, CancellationToken cancellationToken) =>
+ ChangeAsync(actor, userAccountId, reason, suspend: false, cancellationToken);
+
+ private async Task ChangeAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, bool suspend, CancellationToken cancellationToken)
+ {
+ if (!actor.CanManageMembership || actor.UserAccount is null)
+ {
+ return SuspensionOutcome.NotAdmin;
+ }
+
+ if (string.IsNullOrWhiteSpace(reason))
+ {
+ return SuspensionOutcome.NoReason;
+ }
+
+ var user = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
+ if (user?.Membership is not { } membership)
+ {
+ return SuspensionOutcome.NoSuchAccount;
+ }
+
+ // A merged account is terminal: only the merge ledger leaves that status, so neither suspending nor lifting applies.
+ if (membership.IsMerged)
+ {
+ return SuspensionOutcome.NotApplicable;
+ }
+
+ // An admin cannot suspend themselves or another platform admin here (the same derivation that makes an actor an admin):
+ // bootstrap admins are re-promoted to Active at sign-in by configuration, so the suspension would be undone without a receipt.
+ if (suspend && (user.Id == actor.UserAccount.Id || new CurrentBifrostActor(true, user).IsPlatformAdmin))
+ {
+ return SuspensionOutcome.ProtectedAccount;
+ }
+
+ if (suspend == (membership.Status == MembershipStatus.Suspended))
+ {
+ return SuspensionOutcome.NotApplicable;
+ }
+
+ var before = membership.Status;
+ membership.Status = suspend
+ ? MembershipStatus.Suspended
+ : membership.ApprovedAtUtc is null ? MembershipStatus.Authenticated : MembershipStatus.Active;
+ // The reason is a column on the membership, for admins; the receipt names who and what changed, never why.
+ var clipped = reason.Trim().Length > MaxReasonLength ? reason.Trim()[..MaxReasonLength] : reason.Trim();
+ membership.SuspensionReason = suspend ? clipped : null;
+ // One save: the status change, the reason and the receipt stand or fall together (RecordAsync saves the shared context).
+ await auditTrailService.RecordAsync(
+ actor.UserAccount.Id,
+ nameof(Membership),
+ membership.Id,
+ suspend ? "membership.suspended" : "membership.unsuspended",
+ $"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}).",
+ cancellationToken);
+ return SuspensionOutcome.Done;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs b/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
index 8ee13a0..6d41d73 100644
--- a/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
+++ b/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
@@ -12,7 +12,9 @@ public sealed class MembershipSynchronizationService(
BifrostDbContext dbContext,
BifrostIdentityService bifrostIdentityService,
IOptions bootstrapOptions,
- TimeProvider timeProvider)
+ TimeProvider timeProvider,
+ AuditTrailService auditTrailService,
+ ILogger logger)
{
public async Task SynchronizeAsync(ClaimsPrincipal principal, CancellationToken cancellationToken)
{
@@ -109,9 +111,14 @@ public sealed class MembershipSynchronizationService(
invitation.AcceptedAtUtc = now;
}
+ MembershipStatus? promotedFrom = null;
if (IsBootstrapAdmin(gitHubLogin, bootstrapOptions.Value))
{
- PromoteToBootstrapAdmin(userAccount.Membership!, now);
+ promotedFrom = userAccount.Membership!.Status;
+ if (!ApplicationBootstrapper.TryPromoteBootstrapAdmin(userAccount, now, logger))
+ {
+ promotedFrom = null;
+ }
}
else if (userAccount.Membership!.Status == MembershipStatus.Active)
{
@@ -125,22 +132,16 @@ public sealed class MembershipSynchronizationService(
userAccount.MemberProfile!.UpdatedAtUtc = now;
+ if (promotedFrom is { } before && before != userAccount.Membership!.Status)
+ {
+ // One save: the promotion and its receipt stand or fall together.
+ await ApplicationBootstrapper.RecordPromotionAsync(auditTrailService, userAccount, before, cancellationToken);
+ return;
+ }
+
await dbContext.SaveChangesAsync(cancellationToken);
}
- private static void PromoteToBootstrapAdmin(Bifrost.Web.Domain.Membership membership, DateTimeOffset now)
- {
- membership.Status = MembershipStatus.Active;
- membership.IsPlatformAdmin = true;
- membership.CanManageProjects = true;
- membership.CanManageLedger = true;
- membership.CanModerateMotions = true;
- membership.ApprovedAtUtc ??= now;
-
- ApplicationBootstrapper.EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
- ApplicationBootstrapper.EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
- }
-
private static bool TryReadGitHubIdentity(
ClaimsPrincipal principal,
out long gitHubUserId,
diff --git a/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs b/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
new file mode 100644
index 0000000..909d8b9
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
@@ -0,0 +1,131 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Domain;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// The chat host's pull of merge notices: GET the unacked feed, POST an ack. JSON only because the reader is the chat host's script (a xenos
+/// boundary). The bearer is the chat host's own secret (ChatNotices:Token); an empty token turns both routes off. No cookie, no CORS, never stored.
+///
+public static class MergeNoticeEndpoints
+{
+ private const int MaxAckBodyBytes = 1024;
+
+ public static void Map(WebApplication app)
+ {
+ app.MapGet("/api/merge-notices/chat", async (HttpContext http, IOptions options, MergeNoticeFeed feed, CancellationToken ct) =>
+ {
+ if (Gate(http, options.Value) is { } refused)
+ {
+ return refused;
+ }
+
+ DateTimeOffset? after = null;
+ if (http.Request.Query.TryGetValue("after", out var raw) && raw.Count > 0)
+ {
+ if (!DateTimeOffset.TryParse(raw[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
+ {
+ return Results.StatusCode(StatusCodes.Status400BadRequest);
+ }
+
+ after = parsed;
+ }
+
+ int? limit = http.Request.Query.TryGetValue("limit", out var rawLimit) && int.TryParse(rawLimit[0], CultureInfo.InvariantCulture, out var n) ? n : null;
+ var notices = await feed.ReadAsync(AccountMergeNoticeTarget.Chat, after, limit, ct);
+ return Results.Text(JsonSerializer.Serialize(notices.Select(Wire)), "application/json");
+ }).AllowAnonymous();
+
+ app.MapPost("/api/merge-notices/chat/ack", async (HttpContext http, IOptions options, MergeNoticeFeed feed, CancellationToken ct) =>
+ {
+ if (Gate(http, options.Value) is { } refused)
+ {
+ return refused;
+ }
+
+ if (await ReadAckAsync(http.Request, ct) is not var (mergeId, kind))
+ {
+ return Results.StatusCode(StatusCodes.Status400BadRequest);
+ }
+
+ return await feed.AckAsync(AccountMergeNoticeTarget.Chat, mergeId, kind, ct)
+ ? Results.StatusCode(StatusCodes.Status204NoContent)
+ : Results.StatusCode(StatusCodes.Status404NotFound);
+ }).AllowAnonymous();
+ }
+
+ private static IResult? Gate(HttpContext http, ChatNoticesOptions options)
+ {
+ http.Response.Headers.CacheControl = "no-store";
+ if (string.IsNullOrEmpty(options.Token))
+ {
+ return Results.StatusCode(StatusCodes.Status404NotFound);
+ }
+
+ var header = http.Request.Headers.Authorization.ToString();
+ const string scheme = "Bearer ";
+ var presented = header.StartsWith(scheme, StringComparison.Ordinal) ? header[scheme.Length..] : string.Empty;
+ // Both sides are hashed first, so the comparison is over equal-length digests and says nothing about the token's length.
+ var matches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(presented)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Token)));
+ return matches && presented.Length > 0 ? null : Results.StatusCode(StatusCodes.Status401Unauthorized);
+ }
+
+ private static async Task<(Guid MergeId, AccountMergeNoticeKind Kind)?> ReadAckAsync(HttpRequest request, CancellationToken ct)
+ {
+ var buffer = new byte[MaxAckBodyBytes + 1];
+ var read = 0;
+ int n;
+ while (read < buffer.Length && (n = await request.Body.ReadAsync(buffer.AsMemory(read), ct)) > 0)
+ {
+ read += n;
+ }
+
+ if (read == 0 || read > MaxAckBodyBytes)
+ {
+ return null;
+ }
+
+ try
+ {
+ using var document = JsonDocument.Parse(buffer.AsMemory(0, read));
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object ||
+ !root.TryGetProperty("merge_id", out var id) || id.ValueKind != JsonValueKind.String || !Guid.TryParse(id.GetString(), out var mergeId) ||
+ !root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String)
+ {
+ return null;
+ }
+
+ AccountMergeNoticeKind? kind = type.GetString() switch
+ {
+ "merged" => AccountMergeNoticeKind.Merged,
+ "undone" => AccountMergeNoticeKind.Undone,
+ "final" => AccountMergeNoticeKind.Final,
+ _ => null
+ };
+ return kind is { } k ? (mergeId, k) : null;
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ /// The wire shape, exactly these keys: ids in format D, times ISO 8601 UTC, no email, display name, Heimdall id or Matrix id.
+ private static Dictionary Wire(MergeNotice notice) => new()
+ {
+ ["type"] = notice.Kind.ToString().ToLowerInvariant(),
+ ["merge_id"] = notice.MergeId.ToString("D"),
+ ["occurred_at"] = notice.OccurredAt.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
+ ["grace_ends_at"] = notice.GraceEndsAt?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
+ ["old_subject"] = notice.OldSubject.ToString("D"),
+ ["new_subject"] = notice.NewSubject.ToString("D"),
+ ["old_preferred_username"] = notice.OldPreferredUsername,
+ ["new_preferred_username"] = notice.NewPreferredUsername
+ };
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs b/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs
new file mode 100644
index 0000000..bc0fe05
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs
@@ -0,0 +1,96 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Membership;
+
+/// What the chat host is told about one merge. Derived from the merge row on every read; never stored.
+public sealed record MergeNotice(
+ AccountMergeNoticeKind Kind,
+ Guid MergeId,
+ DateTimeOffset OccurredAt,
+ DateTimeOffset? GraceEndsAt,
+ Guid OldSubject,
+ Guid NewSubject,
+ string OldPreferredUsername,
+ string NewPreferredUsername);
+
+///
+/// The one owner of what a notice reader is told about merges: merged (CommittedUtc), undone (UndoneUtc) and final (FinalizedUtc) are read off
+/// the AccountMerges row on every call, so a notice cannot disagree with the merge, and the reader's ack row is the only thing stored.
+/// Reads only AccountMerges and UserAccounts; writes only AccountMergeNoticeAck.
+///
+public sealed class MergeNoticeFeed(BifrostDbContext dbContext, TimeProvider timeProvider)
+{
+ public const int DefaultLimit = 50;
+ public const int MaxLimit = 200;
+
+ private static readonly AccountMergeNoticeKind[] Kinds = [AccountMergeNoticeKind.Merged, AccountMergeNoticeKind.Undone, AccountMergeNoticeKind.Final];
+
+ private static DateTimeOffset? OccurredAt(AccountMerge merge, AccountMergeNoticeKind kind) => kind switch
+ {
+ AccountMergeNoticeKind.Merged => merge.CommittedUtc,
+ AccountMergeNoticeKind.Undone => merge.UndoneUtc,
+ _ => merge.FinalizedUtc
+ };
+
+ /// Unacked notices for , oldest first by (occurred_at, merge_id, kind), strictly later than when given. Acks are the cursor; after only narrows the scan.
+ public async Task> ReadAsync(AccountMergeNoticeTarget target, DateTimeOffset? after, int? limit, CancellationToken cancellationToken)
+ {
+ var take = limit is > 0 ? Math.Min(limit.Value, MaxLimit) : DefaultLimit;
+ var picked = new List<(AccountMerge Merge, AccountMergeNoticeKind Kind, DateTimeOffset At)>();
+ // Each kind's own oldest `take` rows contain every row of the overall oldest `take`, so merging three bounded lists is exact.
+ foreach (var kind in Kinds)
+ {
+ var rows = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) != null)
+ .Where(x => after == null || (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) > after)
+ .Where(x => !dbContext.AccountMergeNoticeAcks.Any(a => a.MergeId == x.Id && a.Kind == kind && a.Target == target))
+ .OrderBy(x => kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc)
+ .ThenBy(x => x.Id)
+ .Take(take)
+ .ToListAsync(cancellationToken);
+ picked.AddRange(rows.Select(x => (x, kind, OccurredAt(x, kind)!.Value)));
+ }
+
+ var page = picked.OrderBy(x => x.At).ThenBy(x => x.Merge.Id).ThenBy(x => x.Kind).Take(take).ToList();
+ var ids = page.SelectMany(x => new[] { x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId }).Distinct().ToList();
+ var names = await dbContext.UserAccounts.AsNoTracking().Where(x => ids.Contains(x.Id))
+ .Select(x => new { x.Id, x.NormalizedBifrostIdentity }).ToDictionaryAsync(x => x.Id, x => x.NormalizedBifrostIdentity, cancellationToken);
+ return [.. page.Select(x => new MergeNotice(
+ x.Kind, x.Merge.Id, x.At, x.Merge.GraceEndsUtc, x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId,
+ names.GetValueOrDefault(x.Merge.FoldedUserAccountId, string.Empty), names.GetValueOrDefault(x.Merge.SurvivorUserAccountId, string.Empty)))];
+ }
+
+ /// Records that the reader has seen (merge, kind). False when the feed would not emit that notice now (no such merge, or its timestamp unset); true otherwise, a repeat included.
+ public async Task AckAsync(AccountMergeNoticeTarget target, Guid mergeId, AccountMergeNoticeKind kind, CancellationToken cancellationToken)
+ {
+ var merge = await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken);
+ if (merge is null || OccurredAt(merge, kind) is null)
+ {
+ return false;
+ }
+
+ if (await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
+ {
+ return true;
+ }
+
+ dbContext.AccountMergeNoticeAcks.Add(new AccountMergeNoticeAck { MergeId = mergeId, Kind = kind, Target = target, AckedUtc = timeProvider.GetUtcNow() });
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ // A concurrent ack of the same key won the unique index; the notice is acked, which is what the caller asked for.
+ dbContext.ChangeTracker.Clear();
+ if (!await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
+ {
+ throw;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergePreview.cs b/src/Bifrost.Web/Features/Membership/MergePreview.cs
new file mode 100644
index 0000000..d241a68
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergePreview.cs
@@ -0,0 +1,93 @@
+using Bifrost.Web.Domain;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// The only wording of what a merge would do, in closed vocabulary: counts by entry kind and action from , the
+/// sentence for each block code, and the statements every merge carries. It decides nothing, and names no account: the plan holds none.
+///
+public static class MergePreview
+{
+ public static IReadOnlyList Lines(MergePlan plan)
+ {
+ var lines = new List();
+ foreach (var group in plan.Entries.GroupBy(x => (x.Kind, x.Action)))
+ {
+ var n = group.Count();
+ lines.Add(group.Key switch
+ {
+ (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved) =>
+ $"{Count(n, "open vote")} of the other account on motions you did not vote on move to the kept account.",
+ (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided) =>
+ $"{Count(n, "open vote")} of the other account are set aside: the kept account already voted on that motion or cannot vote.",
+ (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved) =>
+ $"{Count(n, "appraisal")} of the other account move to the kept account.",
+ (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided) =>
+ $"{Count(n, "appraisal")} of the other account are set aside: the kept account already appraised the same thing or cannot.",
+ (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed) =>
+ "The other account's membership closes; the kept account's membership stays.",
+ (AccountMergeEntryKind.Standing, _) =>
+ "The kept account is suspended too, because the other account is.",
+ (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved) =>
+ $"{Count(n, "patron event")} of the other account count for the kept account.",
+ _ => $"{Count(n, "other record")} change."
+ });
+ }
+
+ foreach (var (key, n) in plan.Left.OrderBy(x => x.Key, StringComparer.Ordinal))
+ {
+ if (n > 0 && Remains(key) is { } noun)
+ {
+ lines.Add($"{Count(n, noun)} stay{(n == 1 ? "s" : string.Empty)} where {(n == 1 ? "it is" : "they are")}.");
+ }
+ }
+
+ if (lines.Count == 0)
+ {
+ lines.Add("No votes, appraisals or patron events change.");
+ }
+
+ return lines;
+ }
+
+ /// Why a pair cannot be merged, by the plan's block code. No account is named; a code this class does not know gets a generic line, never an echo.
+ public static string Block(string code) => code switch
+ {
+ "same_account" => "These are the same account.",
+ "account_missing" => "One of the accounts no longer exists.",
+ "mind_account" => "An account that belongs to a Mind cannot be merged.",
+ "native_account" => "An account without a Heimdall sign-in cannot be merged.",
+ "merge_in_flight" => "One of the accounts is already part of a merge that has not finished.",
+ "survivor_is_folded" => "The account you would keep was already merged into another account.",
+ "already_folded" => "The other account was already merged into another account.",
+ "folded_is_survivor" => "Another account was merged into the other account, so it cannot be folded in turn.",
+ "sealed_ballot_pending" => "The other account has a sealed ballot on an open motion; wait until it is revealed.",
+ _ => "These accounts cannot be merged now."
+ };
+
+ /// The block for two accounts that both hold a login of one provider, which Heimdall will not combine. Providers only: no account is named.
+ public static string ProviderConflict(IEnumerable providerNames) =>
+ $"Both accounts hold a {string.Join(" and ", providerNames)} login, and Heimdall will not combine two logins of one provider. Unlink one of them first, then prove that account again: the sign-in you gave still carries the old list of its logins.";
+
+ /// What every merge says, whatever the plan: what it cannot carry over, what it asks again, and how long it can be undone.
+ public static IReadOnlyList Statements { get; } =
+ [
+ "Chat: your chat history, rooms and keys belong to one chat id and cannot be moved. Keep the account you use in chat. Whichever you keep, the other chat id stays behind: rooms you were in on it must be joined again with the kept one, and messages encrypted for it cannot be read on the kept one.",
+ "Your connections (Twitch, Discord and others) will ask for consent again.",
+ "If you stream or moderate with StreamPixels and one of these connections is the one it uses for your channel, that connection stops until you reconnect it.",
+ "Roles and admin rights of the other account end; a steward must grant them again.",
+ "You will have one membership and one vote per motion: where both accounts voted on an open motion, the kept account's vote counts and the other is set aside. Nothing is added together.",
+ "You can undo this for 7 days, from Merge status. After that it is final.",
+ "The merge is approved with ordinary sign-ins, which is the weaker proof, and a notice stays on your account until the 7 days end."
+ ];
+
+ private static string Count(int n, string noun) => n == 1 ? $"1 {noun}" : $"{n} {noun}s";
+
+ private static string? Remains(string key) => key switch
+ {
+ "ConsentReceipts" => "consent record",
+ "PasskeyCredentials" => "passkey",
+ "LedgerEntries" => "ledger entry",
+ _ => null
+ };
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergeProofs.cs b/src/Bifrost.Web/Features/Membership/MergeProofs.cs
new file mode 100644
index 0000000..86b45f4
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeProofs.cs
@@ -0,0 +1,238 @@
+using Bifrost.Web.Features.Heimdall;
+
+namespace Bifrost.Web.Features.Membership;
+
+public enum MergeSide
+{
+ /// The account signed in here.
+ Self,
+
+ /// The second account, proved by its own fresh sign-in.
+ Other
+}
+
+public enum PutOutcome
+{
+ Stored,
+ AmbiguousLogins,
+ TooManyProofs
+}
+
+/// What a page may know of one side: no bearer, no Heimdall account id, no login names.
+public sealed record MergeSideView(
+ Guid UserAccountId, IReadOnlyList ProvedProviders, IReadOnlyList LoginProviders, TimeSpan OldestProofAge, DateTimeOffset ExpiresAt);
+
+public sealed record MergeProofsView(MergeSideView? Self, MergeSideView? Other);
+
+public abstract record PeekResult
+{
+ private PeekResult()
+ {
+ }
+
+ public sealed record Ready(MergeProof Survivor, IReadOnlyList Folded) : PeekResult;
+
+ /// A side holds no live proof.
+ public sealed record Expired : PeekResult;
+
+ /// Logins whose provider has no live proof, by provider name only.
+ public sealed record LoginsUnproved(IReadOnlyList Providers) : PeekResult;
+
+ /// Both accounts hold a login of these providers, a pair Heimdall always refuses; by provider name only.
+ public sealed record ProviderConflict(IReadOnlyList Providers) : PeekResult;
+}
+
+public abstract record UndoPeekResult
+{
+ private UndoPeekResult()
+ {
+ }
+
+ public sealed record Ready(IReadOnlyList Proofs) : UndoPeekResult;
+
+ public sealed record Expired : UndoPeekResult;
+
+ public sealed record LoginsUnproved(IReadOnlyList Providers) : UndoPeekResult;
+}
+
+///
+/// The one holder of live Heimdall bearers between a merge-proof sign-in's completion and the page's call into the saga, keyed by the
+/// acting Bifrost account. It lives in this process's memory only and is never persisted, logged or sent to a browser; after a restart
+/// the member proves again. It decides nothing about the merge: the saga owns consent, the move and the lifecycle, and Heimdall judges
+/// each proof's tier and freshness. is only a margin under Heimdall's 300 s weak window, so a stale proof
+/// is not sent to fail a merge. Provider is the only proof bookkeeping Bifrost has (the redeem names the provider, not the identity),
+/// so a login list holding two logins of one provider is refused, and two sides holding a login of one provider are a conflict Peek names before consent. Every access, and the merge sweeper's tick, drops expired bearers. Peek never consumes: the caller s once the saga
+/// has taken the proofs, so a refusal that wrote nothing does not cost a re-proof.
+///
+public sealed class MergeProofs(TimeProvider timeProvider)
+{
+ public static readonly TimeSpan ProofLifetime = TimeSpan.FromSeconds(270);
+
+ /// The saga's own bound on the proofs of one move.
+ public const int MaxProofsPerSide = 8;
+
+ private sealed record Held(MergeProof Proof, DateTimeOffset RedeemedAt);
+
+ private sealed class Side(Guid userAccountId, string heimdallAccountId)
+ {
+ public Guid UserAccountId { get; } = userAccountId;
+
+ public string HeimdallAccountId { get; } = heimdallAccountId;
+
+ public IReadOnlyList Logins { get; set; } = [];
+
+ public Dictionary Proofs { get; } = new(StringComparer.Ordinal);
+ }
+
+ private readonly Dictionary> _held = [];
+ private readonly object _gate = new();
+
+ public PutOutcome Put(Guid actorId, MergeSide side, MergeProof proof, Guid userAccountId, IReadOnlyList logins)
+ {
+ if (logins.GroupBy(x => x.Provider, StringComparer.Ordinal).Any(x => x.Count() > 1))
+ {
+ return PutOutcome.AmbiguousLogins;
+ }
+
+ lock (_gate)
+ {
+ var now = timeProvider.GetUtcNow();
+ Prune(now);
+ var sides = _held.TryGetValue(actorId, out var existing) ? existing : _held[actorId] = [];
+ if (!sides.TryGetValue(side, out var held) || held.UserAccountId != userAccountId || held.HeimdallAccountId != proof.HeimdallAccountId)
+ {
+ held = new Side(userAccountId, proof.HeimdallAccountId);
+ }
+
+ if (!held.Proofs.ContainsKey(proof.Provider) && held.Proofs.Count >= MaxProofsPerSide)
+ {
+ return PutOutcome.TooManyProofs;
+ }
+
+ held.Logins = logins;
+ held.Proofs[proof.Provider] = new Held(proof, now);
+ sides[side] = held;
+ return PutOutcome.Stored;
+ }
+ }
+
+ public MergeProofsView Snapshot(Guid actorId)
+ {
+ lock (_gate)
+ {
+ var now = timeProvider.GetUtcNow();
+ Prune(now);
+ var sides = _held.GetValueOrDefault(actorId);
+ return new MergeProofsView(View(sides, MergeSide.Self, now), View(sides, MergeSide.Other, now));
+ }
+ }
+
+ public PeekResult Peek(Guid actorId, MergeSide survivorSide)
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ var sides = _held.GetValueOrDefault(actorId);
+ if (sides is null || !sides.TryGetValue(survivorSide, out var survivor)
+ || !sides.TryGetValue(survivorSide == MergeSide.Self ? MergeSide.Other : MergeSide.Self, out var folded))
+ {
+ return new PeekResult.Expired();
+ }
+
+ var shared = survivor.Logins.Select(x => x.Provider).Intersect(folded.Logins.Select(x => x.Provider), StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
+ if (shared.Length > 0)
+ {
+ return new PeekResult.ProviderConflict(shared);
+ }
+
+ var unproved = UnprovedProviders(folded, folded.Logins.Select(x => x.Provider));
+ return unproved.Count > 0
+ ? new PeekResult.LoginsUnproved(unproved)
+ : new PeekResult.Ready(survivor.Proofs.Values.MaxBy(x => x.RedeemedAt)!.Proof, [.. folded.Proofs.Values.Select(x => x.Proof)]);
+ }
+ }
+
+ /// The Self side's proofs for an undo, once every login whose id is in is proved.
+ public UndoPeekResult PeekUndo(Guid actorId, IReadOnlyCollection movedIdentityIds)
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ if (!_held.TryGetValue(actorId, out var sides) || !sides.TryGetValue(MergeSide.Self, out var self))
+ {
+ return new UndoPeekResult.Expired();
+ }
+
+ var needed = self.Logins.Where(x => movedIdentityIds.Contains(x.Id)).Select(x => x.Provider).ToArray();
+ var unproved = UnprovedProviders(self, needed);
+ if (needed.Length < movedIdentityIds.Count)
+ {
+ // A moved login the list does not hold cannot be proved by it.
+ return new UndoPeekResult.LoginsUnproved(unproved);
+ }
+
+ return unproved.Count > 0
+ ? new UndoPeekResult.LoginsUnproved(unproved)
+ : new UndoPeekResult.Ready([.. needed.Distinct(StringComparer.Ordinal).Select(x => self.Proofs[x].Proof)]);
+ }
+ }
+
+ public void Clear(Guid actorId)
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ _held.Remove(actorId);
+ }
+ }
+
+ /// Drops every expired bearer without any member touching the page; the merge sweeper's tick calls it, so none outlives plus one tick.
+ public void PruneExpired()
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ }
+ }
+
+ private static List UnprovedProviders(Side side, IEnumerable providers) =>
+ [.. providers.Distinct(StringComparer.Ordinal).Where(x => !side.Proofs.ContainsKey(x))];
+
+ private MergeSideView? View(Dictionary? sides, MergeSide which, DateTimeOffset now) =>
+ sides is not null && sides.TryGetValue(which, out var side)
+ ? new MergeSideView(
+ side.UserAccountId,
+ [.. side.Proofs.Keys],
+ [.. side.Logins.Select(x => x.Provider)],
+ now - side.Proofs.Values.Min(x => x.RedeemedAt),
+ side.Proofs.Values.Min(x => x.RedeemedAt) + ProofLifetime)
+ : null;
+
+ /// Drops every proof at or past its lifetime, then every side without one, then every actor without a side.
+ private void Prune(DateTimeOffset now)
+ {
+ foreach (var (actor, sides) in _held.ToArray())
+ {
+ foreach (var (which, side) in sides.ToArray())
+ {
+ foreach (var (provider, held) in side.Proofs.ToArray())
+ {
+ if (now - held.RedeemedAt >= ProofLifetime)
+ {
+ side.Proofs.Remove(provider);
+ }
+ }
+
+ if (side.Proofs.Count == 0)
+ {
+ sides.Remove(which);
+ }
+ }
+
+ if (sides.Count == 0)
+ {
+ _held.Remove(actor);
+ }
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergeWording.cs b/src/Bifrost.Web/Features/Membership/MergeWording.cs
new file mode 100644
index 0000000..9d6984d
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeWording.cs
@@ -0,0 +1,114 @@
+using System.Globalization;
+using Bifrost.Web.Domain;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// The one closed set of words the merge pages say, so no page ever prints what the store holds: a state, a Heimdall refusal code, a
+/// saga outcome and an undo answer each map to a sentence here, and anything this class does not know gets a generic line, never an
+/// echo. Dates are UTC.
+///
+public static class MergeWording
+{
+ public static string State(AccountMergeState state) => state switch
+ {
+ AccountMergeState.Proposed => "Proposed, not yet confirmed.",
+ AccountMergeState.Confirmed => "Confirmed; Heimdall has not yet moved the logins.",
+ AccountMergeState.HeimdallMoved => "The logins have moved; Bifrost is finishing the merge.",
+ AccountMergeState.Committed => "Merged. You can still undo it.",
+ AccountMergeState.Final => "Merged for good; the undo window has ended.",
+ AccountMergeState.UndoRequested => "Undo requested; the logins are being given back.",
+ AccountMergeState.HeimdallReversed => "The logins are back; Bifrost is restoring the accounts.",
+ AccountMergeState.Undone => "Undone; the accounts are separate again.",
+ AccountMergeState.Failed => "The merge did not happen and nothing was merged.",
+ _ => "In an unknown state."
+ };
+
+ /// Why Heimdall refused a merge, by its refusal code; null for a code this class does not know.
+ public static string? Failure(string code) => code switch
+ {
+ "app_auth_required" or "not_allowed_for_app" => "Heimdall would not take Bifrost's request.",
+ "not_reversible" => "Heimdall says those logins cannot be moved back.",
+ "proof_invalid" => "Heimdall did not accept a sign-in as proof.",
+ "same_account" => "Both sides were the same Heimdall account.",
+ "proof_stale" => "A sign-in was too old by the time Heimdall saw it.",
+ "identity_not_proved" => "A login was not proved by a fresh sign-in.",
+ "already_moved" => "Heimdall had already moved one of those logins.",
+ "provider_conflict" => "Both accounts hold a login of the same provider, which Heimdall will not combine.",
+ "identity_not_found" => "A login was no longer on its account.",
+ "invalid_request" => "Heimdall could not read the request.",
+ _ => null
+ };
+
+ /// The saga's last note on a merge, in words. Always a sentence: an outcome this class does not know is a retry line, never its own text.
+ public static string Outcome(string lastOutcome) => lastOutcome switch
+ {
+ "confirmed" => "Waiting for Heimdall to move the logins.",
+ "moved" => "Heimdall moved the logins.",
+ "refused" => "Heimdall refused the merge.",
+ "undo_requested" => "Waiting for Heimdall to give the logins back.",
+ "operator_failed" => "A steward ended this merge. Nothing was merged.",
+ "undo_operator_abandoned" => "A steward ended the undo, so the merge stands.",
+ "receipt_mismatch" => "Heimdall's answer did not match the merge. An operator must look at it.",
+ "proofs_unreadable" => "The stored proofs cannot be read. An operator must look at it.",
+ "transport" or "move_id_conflict" or "malformed or mismatched receipt" => "Heimdall could not be reached or gave an answer Bifrost could not use. It will try again.",
+ _ when lastOutcome.StartsWith("undo_", StringComparison.Ordinal) && Failure(lastOutcome["undo_".Length..]) is { } reason =>
+ "Heimdall refused the undo, so the merge stands. " + reason,
+ _ => "Waiting to try again."
+ };
+
+ /// The words for a closed undo code ( or logins_unproved ); empty for anything else.
+ public static string Undo(string code) => code switch
+ {
+ "requested" => "Undo requested. The logins are being given back.",
+ "not_committed" => "This merge is not in a state that can be undone.",
+ "grace_over" => "The undo window has ended.",
+ "not_survivor" => "Only the account the merge kept can undo it.",
+ "proof_account_mismatch" => "That sign-in was not for this account. Nothing was changed.",
+ "logins_unproved" => "Every login that moved needs a fresh sign-in first. Nothing was changed.",
+ _ => string.Empty
+ };
+
+ /// The words for a closed code the merge page answers a confirm or a start with; empty for anything else.
+ public static string Confirm(string code) => code switch
+ {
+ "blocked" => "These accounts cannot be merged now. Nothing was changed.",
+ "preview_stale" => "Something changed since you looked; review the merge again. Nothing was changed and your sign-ins are kept.",
+ "not_party" => "Only one of the two accounts can confirm this merge. Nothing was changed.",
+ "proof_account_mismatch" => "A sign-in was not for the account it was meant for. Nothing was changed.",
+ "proofs_needed" => "Both accounts need a fresh sign-in, one for every login of the account that would be folded. Nothing was changed.",
+ "consent_needed" => "Tick both boxes to confirm. Nothing was changed.",
+ "bad_choice" => "Choose which account to keep. Nothing was changed.",
+ _ => string.Empty
+ };
+
+ public static string UndoCode(UndoOutcome outcome) => outcome switch
+ {
+ UndoOutcome.Requested => "requested",
+ UndoOutcome.NotCommitted => "not_committed",
+ UndoOutcome.GraceOver => "grace_over",
+ UndoOutcome.NotSurvivor => "not_survivor",
+ UndoOutcome.ProofAccountMismatch => "proof_account_mismatch",
+ _ => "not_committed"
+ };
+
+ public static string TierNote(string? fromTier, DateTimeOffset graceEnds) => fromTier == "strong"
+ ? $"Approved with a passkey; you have until {Date(graceEnds)} to undo."
+ : $"Approved with ordinary sign-ins; you have until {Date(graceEnds)} to undo.";
+
+ /// Whole days from to , rounded up, at least one while the window is open.
+ public static int DaysUntil(DateTimeOffset end, DateTimeOffset now) => Math.Max(1, (int)Math.Ceiling((end - now).TotalDays));
+
+ public static string DaysLeft(int days) => days == 1 ? "1 day left" : $"{days} days left";
+
+ public static string SurvivorNotice(int days) => $"A merge into your account can still be undone: {DaysLeft(days)}. Review it on Merge status.";
+
+ public static string UndoRequestedNotice() => "A merge into your account is being undone: Heimdall is giving the logins back. Review it on Merge status.";
+
+ public static string FrozenNotice() => "A merge is in progress; you cannot act until it settles.";
+
+ public static string FoldedNotice(DateTimeOffset mergedOn) =>
+ $"This account was merged on {Date(mergedOn)}; sign in with a login you had on it to reach the account that holds them.";
+
+ public static string Date(DateTimeOffset when) => when.UtcDateTime.ToString("d MMM yyyy", CultureInfo.InvariantCulture) + " UTC";
+}
diff --git a/src/Bifrost.Web/Features/Motions/MindIntakeService.cs b/src/Bifrost.Web/Features/Motions/MindIntakeService.cs
new file mode 100644
index 0000000..0b111fb
--- /dev/null
+++ b/src/Bifrost.Web/Features/Motions/MindIntakeService.cs
@@ -0,0 +1,277 @@
+using System.Text;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Org.BouncyCastle.Math.EC.Rfc8032;
+
+namespace Bifrost.Web.Features.Motions;
+
+///
+/// Signed intake for Minds. A Mind holds an Ed25519 private key; Bifrost holds only registered public keys. The signature,
+/// not a session, is the credential: a verified envelope is handed to as the Mind's member
+/// account, so Minds and members share one set of rules. Registration and revocation are moderator acts and are audited.
+///
+public sealed class MindIntakeService(
+ BifrostDbContext dbContext,
+ SealedBallotService sealedBallots,
+ AuditTrailService auditTrailService,
+ TimeProvider timeProvider)
+{
+ public const string Domain = "gamecult.sealed_intake.v0";
+ public static readonly TimeSpan Skew = TimeSpan.FromMinutes(10);
+
+ // Diagnostics: every Ed25519 verification the intake performs, real or dummy. A refusal that skips the verify is a timing tell.
+ public static long SignatureChecks;
+
+ // A valid signature by a throwaway key over a different message: verifying it does the full work and fails at the end.
+ private static readonly (byte[] Public, byte[] Signature, byte[] Message) Dummy = MakeDummy();
+
+ private static (byte[], byte[], byte[]) MakeDummy()
+ {
+ var secret = new byte[32];
+ System.Security.Cryptography.RandomNumberGenerator.Fill(secret);
+ var pub = new byte[32];
+ Ed25519.GeneratePublicKey(secret, 0, pub, 0);
+ var message = Encoding.UTF8.GetBytes("dummy");
+ var sig = new byte[64];
+ Ed25519.Sign(secret, 0, pub, 0, null, message, 0, message.Length, sig, 0);
+ return (pub, sig, Encoding.UTF8.GetBytes("not the dummy message"));
+ }
+
+ private static bool Verify(byte[] signature, byte[] publicKey, byte[] message)
+ {
+ Interlocked.Increment(ref SignatureChecks);
+ return Ed25519.Verify(signature, 0, publicKey, 0, message, 0, message.Length);
+ }
+ private static readonly Regex PersonaPattern = new(@"^[a-z0-9][a-z0-9-]{0,31}\z", RegexOptions.Compiled);
+ private static readonly Regex NoncePattern = new(@"^[A-Za-z0-9_-]{16,64}\z", RegexOptions.Compiled);
+
+ public async Task RegisterKeyAsync(
+ CurrentBifrostActor actor, string persona, Guid userAccountId, string publicKey, CancellationToken cancellationToken)
+ {
+ var moderator = RequireModerator(actor);
+ persona = (persona ?? string.Empty).Trim();
+ if (!PersonaPattern.IsMatch(persona))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "A persona id is 1-32 lowercase letters, digits or hyphens.");
+ }
+
+ if (!TryKey(publicKey, out _))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "A public key is the base64 of 32 bytes (Ed25519).");
+ }
+
+ var account = await dbContext.UserAccounts.Include(x => x.Membership).SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
+ if (account?.Membership?.Status != MembershipStatus.Active)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The persona's member account must exist and be Active.");
+ }
+
+ // One persona <-> one account, both ways (a shared account would let one persona overwrite the other's commit).
+ // The unique indexes on MindPersonas are the arbiter; these reads only give a plain error before them.
+ var binding = await dbContext.MindPersonas.SingleOrDefaultAsync(x => x.PersonaId == persona || x.UserAccountId == userAccountId, cancellationToken);
+ if (binding is not null && (binding.PersonaId != persona || binding.UserAccountId != userAccountId))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "That persona or member account is already bound to a different account or persona.");
+ }
+
+ if (await dbContext.MindKeys.AnyAsync(x => x.PersonaId == persona && x.PublicKey == publicKey, cancellationToken))
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "That key is already registered for the persona.");
+ }
+
+ var key = new MindKey
+ {
+ PersonaId = persona, UserAccountId = userAccountId, PublicKey = publicKey,
+ RegisteredByUserAccountId = moderator.Id, RegisteredAtUtc = timeProvider.GetUtcNow()
+ };
+ dbContext.MindKeys.Add(key);
+ if (binding is null)
+ {
+ dbContext.MindPersonas.Add(new MindPersona { PersonaId = persona, UserAccountId = userAccountId });
+ }
+
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException) when (binding is null)
+ {
+ // Lost a registration race on the unique persona/account indexes.
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "That persona or member account is already bound to a different account or persona.");
+ }
+
+ await auditTrailService.RecordAsync(moderator.Id, nameof(MindKey), key.Id, "mindkey.registered",
+ $"Registered a key for persona {persona} (member account {userAccountId}).", cancellationToken);
+ return View(key);
+ }
+
+ public async Task RevokeKeyAsync(CurrentBifrostActor actor, Guid keyId, CancellationToken cancellationToken)
+ {
+ var moderator = RequireModerator(actor);
+ var key = await dbContext.MindKeys.SingleOrDefaultAsync(x => x.Id == keyId, cancellationToken)
+ ?? throw new SealedBallotException(SealedBallotFailure.NotFound, "No such key.");
+ if (key.RevokedAtUtc is not null)
+ {
+ return;
+ }
+
+ key.RevokedAtUtc = timeProvider.GetUtcNow();
+ key.RevokedByUserAccountId = moderator.Id;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ await auditTrailService.RecordAsync(moderator.Id, nameof(MindKey), key.Id, "mindkey.revoked",
+ $"Revoked a key for persona {key.PersonaId}.", cancellationToken);
+ }
+
+ public async Task> ListKeysAsync(CurrentBifrostActor actor, CancellationToken cancellationToken)
+ {
+ RequireModerator(actor);
+ return (await dbContext.MindKeys.AsNoTracking().OrderBy(x => x.PersonaId).ThenBy(x => x.RegisteredAtUtc).ToListAsync(cancellationToken))
+ .Select(View).ToList();
+ }
+
+ /// Verifies the envelope, spends its nonce, then runs the verb as the persona's member account.
+ public async Task HandleAsync(Guid routeMotionId, MindEnvelope envelope, CancellationToken cancellationToken)
+ {
+ var persona = envelope.Persona ?? string.Empty;
+ if (!PersonaPattern.IsMatch(persona) || envelope.Verb is not ("commit" or "reveal") || !NoncePattern.IsMatch(envelope.Nonce ?? string.Empty) ||
+ new[] { envelope.Commitment, envelope.Candidate, envelope.Reason, envelope.Salt }.Any(f => (f ?? string.Empty).AsSpan().IndexOfAny('\n', '\r') >= 0))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The envelope is malformed.");
+ }
+
+ // Signature first. Every path below that can tell a caller anything about state comes after a verified signature, and
+ // every refusal before it costs one Ed25519 verification (a dummy one when there is no key or no usable signature).
+ var keys = await dbContext.MindKeys.AsNoTracking().Where(x => x.PersonaId == persona && x.RevokedAtUtc == null).ToListAsync(cancellationToken);
+ var message = Encoding.UTF8.GetBytes(SigningText(envelope));
+ var raw = new byte[64];
+ var wellFormed = Convert.TryFromBase64String(envelope.Signature ?? string.Empty, raw, out var written) && written == 64;
+ MindKey? signer = null;
+ if (!wellFormed || keys.Count == 0)
+ {
+ _ = Verify(Dummy.Signature, Dummy.Public, Dummy.Message);
+ }
+ else
+ {
+ signer = keys.FirstOrDefault(k => TryKey(k.PublicKey, out var pub) && Verify(raw, pub, message));
+ }
+
+ if (signer is null)
+ {
+ // One answer for unknown persona, revoked key, wrong key and bad signature: nothing to probe.
+ throw new SealedBallotException(SealedBallotFailure.Unauthorized, "The envelope is not signed by a registered key for that persona.");
+ }
+
+ if (envelope.MotionId != routeMotionId)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The envelope was signed for a different motion.");
+ }
+
+ var now = timeProvider.GetUtcNow();
+ if (Math.Abs((now - DateTimeOffset.FromUnixTimeSeconds(Math.Clamp(envelope.IssuedAt, 0, 253402300799))).TotalSeconds) > Skew.TotalSeconds)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The envelope is outside the accepted clock window.");
+ }
+
+ // Spend the nonce only after the signature verifies, so an unsigned caller cannot burn a persona's nonces. Nonces older
+ // than twice the skew can no longer pass the window above, so they are pruned here.
+ if (await dbContext.MindNonces.AnyAsync(x => x.PersonaId == persona && x.Nonce == envelope.Nonce, cancellationToken))
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "That nonce was already used.");
+ }
+
+ // Pruning is housekeeping and runs apart from the write that spends the nonce: two requests can load and delete the same
+ // expired rows, and the loser's concurrency exception must never fail a valid request.
+ try
+ {
+ var cutoff = now - 2 * Skew;
+ dbContext.MindNonces.RemoveRange(await dbContext.MindNonces.Where(x => x.SeenAtUtc < cutoff).ToListAsync(cancellationToken));
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ dbContext.ChangeTracker.Clear();
+ }
+
+ dbContext.MindNonces.Add(new MindNonce { PersonaId = persona, Nonce = envelope.Nonce!, SeenAtUtc = now });
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ // A replay only if the nonce is now there (the unique index lost a race); any other write failure is a fault, not a replay.
+ dbContext.ChangeTracker.Clear();
+ if (await dbContext.MindNonces.AnyAsync(x => x.PersonaId == persona && x.Nonce == envelope.Nonce, cancellationToken))
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "That nonce was already used.");
+ }
+
+ throw;
+ }
+
+ var account = await dbContext.UserAccounts.AsNoTracking()
+ .Include(x => x.MemberProfile)
+ .Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
+ .Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots)
+ .SingleAsync(x => x.Id == signer.UserAccountId, cancellationToken);
+ var actor = new CurrentBifrostActor(true, account);
+
+ return envelope.Verb == "commit"
+ ? await sealedBallots.CommitAsync(actor, routeMotionId, envelope.Commitment ?? string.Empty, cancellationToken)
+ : await sealedBallots.RevealAsync(actor, routeMotionId,
+ new SealedBallotDocument(SealedBallotDocument.SchemaId, routeMotionId, envelope.Round, envelope.Candidate ?? string.Empty,
+ envelope.Reason ?? string.Empty, envelope.Salt ?? string.Empty, persona),
+ cancellationToken, persona);
+ }
+
+ /// The exact text a Mind signs: every field, fixed order, newline separated, unused fields empty.
+ public static string SigningText(MindEnvelope e) =>
+ string.Join('\n', Domain, e.Persona, e.Verb, e.MotionId.ToString("D"), e.Nonce, e.IssuedAt, e.Commitment ?? "", e.Round, e.Candidate ?? "", e.Reason ?? "", e.Salt ?? "");
+
+ private static bool TryKey(string base64, out byte[] key)
+ {
+ key = new byte[32];
+ return Convert.TryFromBase64String(base64 ?? string.Empty, key, out var n) && n == 32;
+ }
+
+ private static UserAccount RequireModerator(CurrentBifrostActor actor) =>
+ actor is { IsActiveMember: true, CanModerateMotions: true, UserAccount: { } user }
+ ? user
+ : throw new SealedBallotException(SealedBallotFailure.Forbidden, "Only a moderator manages Mind keys.");
+
+ private static MindKeyView View(MindKey k) => new(k.Id, k.PersonaId, k.UserAccountId, k.PublicKey, k.RegisteredAtUtc, k.RevokedAtUtc);
+}
+
+/// A signed Mind verb. Signature is base64 Ed25519 over .
+public sealed record MindEnvelope(
+ string Persona, string Verb, Guid MotionId, string Nonce, long IssuedAt,
+ string? Commitment, int Round, string? Candidate, string? Reason, string? Salt, string Signature);
+
+public sealed record MindKeyView(Guid Id, string Persona, Guid UserAccountId, string PublicKey, DateTimeOffset RegisteredAtUtc, DateTimeOffset? RevokedAtUtc);
+
+public sealed record RegisterMindKeyRequest(string Persona, Guid UserAccountId, string PublicKey);
+
+/// Limits on the anonymous signed-intake endpoint (section "MindIntake").
+public sealed class MindIntakeOptions
+{
+ public const string SectionName = "MindIntake";
+
+ public int Permits { get; init; } = 30;
+
+ public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1);
+
+ public int MaxTrackedKeys { get; init; } = 10_000;
+
+ public int MaxBodyBytes { get; init; } = 4096;
+}
+
+/// Per-source permit budget for the intake, on the shared . Spent before the body is read.
+public sealed class MindIntakeRateLimit(Microsoft.Extensions.Options.IOptions options, TimeProvider clock)
+{
+ private readonly FixedWindowBudget budget = new(options.Value.Permits, options.Value.Window, options.Value.MaxTrackedKeys, clock);
+
+ public BudgetDenial? Spend(string source) => budget.Spend(source);
+}
diff --git a/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs b/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs
index 8c10dcf..ba60a2f 100644
--- a/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs
+++ b/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs
@@ -1,5 +1,6 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
@@ -52,37 +53,54 @@ public sealed class MotionGovernanceService(
CancellationToken cancellationToken)
{
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
+
var motion = await dbContext.Motions
.Include(x => x.Votes)
.SingleAsync(x => x.Id == motionId, cancellationToken);
- if (motion.Status != MotionStatus.Open)
+ if (motion.Status != MotionStatus.Open || motion.Kind != MotionKind.Standard)
{
return;
}
- var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
- if (vote is null)
+ // An actor resolved before a merge froze this account must not write a vote after it: the write gate reads standing at the write.
+ var wrote = await AccountMergeLedger.WriteAsAsync(dbContext, actorUser.Id, async standing =>
{
- dbContext.Votes.Add(new Vote
+ if (standing is not null)
{
- MotionId = motionId,
- UserAccountId = actorUser.Id,
- Choice = choice,
- Weight = actor.EffectiveVotingWeight,
- Comment = comment?.Trim() ?? string.Empty,
- CastAtUtc = timeProvider.GetUtcNow()
- });
- }
- else
+ return false;
+ }
+
+ var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
+ if (vote is null)
+ {
+ dbContext.Votes.Add(new Vote
+ {
+ MotionId = motionId,
+ UserAccountId = actorUser.Id,
+ Choice = choice,
+ Weight = actor.EffectiveVotingWeight,
+ Comment = comment?.Trim() ?? string.Empty,
+ CastAtUtc = timeProvider.GetUtcNow()
+ });
+ }
+ else
+ {
+ vote.Choice = choice;
+ vote.Weight = actor.EffectiveVotingWeight;
+ vote.Comment = comment?.Trim() ?? string.Empty;
+ vote.CastAtUtc = timeProvider.GetUtcNow();
+ }
+
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return true;
+ }, cancellationToken);
+
+ if (!wrote)
{
- vote.Choice = choice;
- vote.Weight = actor.EffectiveVotingWeight;
- vote.Comment = comment?.Trim() ?? string.Empty;
- vote.CastAtUtc = timeProvider.GetUtcNow();
+ return;
}
- await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
actorUser.Id,
nameof(Motion),
@@ -102,6 +120,11 @@ public sealed class MotionGovernanceService(
.Include(x => x.Votes)
.SingleAsync(x => x.Id == motionId, cancellationToken);
+ if (motion.Kind != MotionKind.Standard)
+ {
+ throw new InvalidOperationException("Sealed-ballot motions close only at their deadline.");
+ }
+
if (!actor.CanModerateMotions && motion.CreatedByUserAccountId != actorUser.Id)
{
throw new UnauthorizedAccessException("Only the motion creator or a moderator can close this motion.");
@@ -121,7 +144,21 @@ public sealed class MotionGovernanceService(
? $"Closed with {votesFor:0.##} for and {votesAgainst:0.##} against at a {motion.ApprovalThreshold:P0} threshold."
: "Closed without decisive votes.";
- await dbContext.SaveChangesAsync(cancellationToken);
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException error)
+ {
+ // Status is a concurrency token: another closer won. Adopt its result and record nothing a second time.
+ foreach (var entry in error.Entries)
+ {
+ await entry.ReloadAsync(cancellationToken);
+ }
+
+ return;
+ }
+
await auditTrailService.RecordAsync(
actorUser.Id,
nameof(Motion),
@@ -140,6 +177,7 @@ public sealed class MotionGovernanceService(
.AsNoTracking()
.Include(x => x.Project)
.Include(x => x.Votes)
+ .Where(x => x.Kind == MotionKind.Standard)
.OrderBy(x => x.ClosesAtUtc)
.ToListAsync(cancellationToken);
diff --git a/src/Bifrost.Web/Features/Motions/SealedBallotService.cs b/src/Bifrost.Web/Features/Motions/SealedBallotService.cs
new file mode 100644
index 0000000..7fc3af0
--- /dev/null
+++ b/src/Bifrost.Web/Features/Motions/SealedBallotService.cs
@@ -0,0 +1,462 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace Bifrost.Web.Features.Motions;
+
+///
+/// Sealed-ballot motions: commit, then reveal, then one atomic publication at close.
+/// This is the only code that reads ,
+/// or ; a test fails if any other source file mentions them.
+///
+public sealed class SealedBallotService(
+ BifrostDbContext dbContext,
+ AuditTrailService auditTrailService,
+ TimeProvider timeProvider)
+{
+ public const int MaxReasonLength = 280;
+ private static readonly Regex HexSha256 = new(@"^[0-9a-f]{64}\z", RegexOptions.Compiled);
+ private static readonly Regex HexSalt = new(@"^[0-9a-f]{32,128}\z", RegexOptions.Compiled);
+
+ public async Task OpenAsync(
+ CurrentBifrostActor actor,
+ OpenSealedMotionCommand command,
+ CancellationToken cancellationToken)
+ {
+ var user = RequireMember(actor);
+ if (!actor.CanModerateMotions)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Forbidden, "Only a moderator opens a sealed-ballot motion.");
+ }
+
+ var now = timeProvider.GetUtcNow();
+ var candidates = command.Candidates.Select(x => x.Trim()).Where(x => x.Length > 0).ToList();
+ if (candidates.Count < 2 || candidates.Distinct(StringComparer.Ordinal).Count() != candidates.Count ||
+ candidates.Any(x => x.Contains('\n') || x.Contains('\r')))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "Two or more distinct single-line candidates are required.");
+ }
+
+ var commitCloses = command.CommitClosesAtUtc.ToUniversalTime();
+ var closes = command.ClosesAtUtc.ToUniversalTime();
+ if (commitCloses <= now || closes <= commitCloses)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The commit window must end in the future and the reveal window must end after it.");
+ }
+
+ var motion = new Motion
+ {
+ CreatedByUserAccountId = user.Id,
+ Scope = MotionScope.Management,
+ Category = MotionCategory.Features,
+ Kind = MotionKind.SealedBallot,
+ Title = command.Title.Trim(),
+ Summary = command.Summary.Trim(),
+ Candidates = string.Join('\n', candidates),
+ Round = Math.Max(1, command.Round),
+ PriorMotionId = command.PriorMotionId,
+ ApprovalThreshold = 0m,
+ OpensAtUtc = now,
+ CommitClosesAtUtc = commitCloses,
+ ClosesAtUtc = closes,
+ CreatedAtUtc = now
+ };
+
+ dbContext.Motions.Add(motion);
+ await dbContext.SaveChangesAsync(cancellationToken);
+ await auditTrailService.RecordAsync(
+ user.Id, nameof(Motion), motion.Id, "sealed.opened",
+ $"Opened sealed-ballot motion {motion.Title} (round {motion.Round}, {candidates.Count} candidates).",
+ cancellationToken);
+
+ return BuildState(motion, now, null, user.Id);
+ }
+
+ public async Task CommitAsync(
+ CurrentBifrostActor actor,
+ Guid motionId,
+ string commitment,
+ CancellationToken cancellationToken)
+ {
+ var user = RequireMember(actor);
+ var motion = await LoadAsync(motionId, cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ if (PhaseOf(motion, now) != SealedPhase.Commit)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The commit window is not open.");
+ }
+
+ commitment = (commitment ?? string.Empty).Trim().ToLowerInvariant();
+ if (!HexSha256.IsMatch(commitment))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "A commitment is 64 lowercase hex characters (SHA-256).");
+ }
+
+ var ballot = await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing =>
+ {
+ RequireStanding(standing);
+ var written = await dbContext.SealedBallots
+ .SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken);
+ if (written is null)
+ {
+ written = new SealedBallot { MotionId = motionId, UserAccountId = user.Id };
+ dbContext.SealedBallots.Add(written);
+ }
+ else
+ {
+ written.Revision++;
+ }
+
+ written.Commitment = commitment;
+ written.CommittedAtUtc = now;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return written;
+ }, cancellationToken);
+
+ await auditTrailService.RecordAsync(
+ user.Id, nameof(Motion), motionId, "sealed.committed",
+ $"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
+ cancellationToken);
+
+ return new SealedBallotReceipt(motionId, user.Id, commitment, ballot.Revision, now, Revealed: false);
+ }
+
+ public async Task RevealAsync(
+ CurrentBifrostActor actor,
+ Guid motionId,
+ SealedBallotDocument document,
+ CancellationToken cancellationToken,
+ string persona = "")
+ {
+ var user = RequireMember(actor);
+ var motion = await LoadAsync(motionId, cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ if (PhaseOf(motion, now) != SealedPhase.Reveal)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal window is not open.");
+ }
+
+ var ballot = await dbContext.SealedBallots
+ .SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken)
+ ?? throw new SealedBallotException(SealedBallotFailure.NotFound, "No commitment from this member on this motion.");
+
+ var reason = (document.Reason ?? string.Empty).Trim();
+ var candidate = (document.Candidate ?? string.Empty).Trim();
+ if (document.Schema != SealedBallotDocument.SchemaId || document.MotionId != motionId || (document.Persona ?? string.Empty) != persona || document.Round != motion.Round ||
+ !CandidatesOf(motion).Contains(candidate, StringComparer.Ordinal) ||
+ reason.Length is 0 or > MaxReasonLength || reason.Contains('\n') || reason.Contains('\r') ||
+ !HexSalt.IsMatch(document.Salt ?? string.Empty))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The ballot document does not fit this motion (schema, motion, round, candidate, one-line reason, 128-bit hex salt).");
+ }
+
+ var recomputed = SealedBallotDocument.Commit(document with { Candidate = candidate, Reason = reason }, user.Id);
+ if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(recomputed), Encoding.ASCII.GetBytes(ballot.Commitment)))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The ballot does not match the stored commitment.");
+ }
+
+ // RevealSeq and Status are concurrency tokens. A conflict means either the close froze the set (refuse, truthfully) or
+ // another voter's reveal landed first while the window is still open (re-read the row and write again).
+ // Standing is read once, under the gate's lock, which holds across every attempt: a merge cannot freeze the account between them.
+ await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing =>
+ {
+ RequireStanding(standing);
+ for (var attempt = 0; ; attempt++)
+ {
+ ballot.RevealedCandidate = candidate;
+ ballot.RevealedReason = reason;
+ ballot.Salt = document.Salt;
+ ballot.RevealedAtUtc = now;
+ motion.RevealSeq++;
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ break;
+ }
+ catch (DbUpdateConcurrencyException error)
+ {
+ foreach (var entry in error.Entries)
+ {
+ await entry.ReloadAsync(cancellationToken);
+ }
+
+ if (PhaseOf(motion, now) != SealedPhase.Reveal)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over.");
+ }
+
+ if (attempt >= 4)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal is contended; send it again.");
+ }
+ }
+ }
+
+ return true;
+ }, cancellationToken);
+
+ await auditTrailService.RecordAsync(
+ user.Id, nameof(Motion), motionId, "sealed.revealed",
+ $"{actor.DisplayName} submitted a reveal for commitment {ballot.Commitment}; content stays sealed until close.",
+ cancellationToken);
+
+ return new SealedBallotReceipt(motionId, user.Id, ballot.Commitment, ballot.Revision, ballot.CommittedAtUtc, Revealed: true);
+ }
+
+ /// Phase, times and the caller's own commitment status. Never another member's ballot, never revealed content.
+ public async Task GetStateAsync(
+ CurrentBifrostActor actor,
+ Guid motionId,
+ CancellationToken cancellationToken)
+ {
+ var user = RequireMember(actor);
+ var motion = await LoadAsync(motionId, cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ var own = await dbContext.SealedBallots
+ .AsNoTracking()
+ .Where(x => x.MotionId == motionId && x.UserAccountId == user.Id)
+ .Select(x => new SealedBallotReceipt(x.MotionId, x.UserAccountId, x.Commitment, x.Revision, x.CommittedAtUtc, x.RevealedAtUtc != null))
+ .SingleOrDefaultAsync(cancellationToken);
+
+ return BuildState(motion, now, own, user.Id);
+ }
+
+ /// Finalizes the motion if its deadline has passed, then publishes every ballot at once. Before close it refuses.
+ public async Task GetResultAsync(
+ CurrentBifrostActor actor,
+ Guid motionId,
+ CancellationToken cancellationToken)
+ {
+ RequireMember(actor);
+ var motion = await LoadAsync(motionId, cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ if (PhaseOf(motion, now) != SealedPhase.Closed)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "Ballots stay sealed until the motion closes.");
+ }
+
+ // Freeze: the close counts the reveals it read and succeeds only if no reveal landed since (RevealSeq is a concurrency
+ // token); a conflict re-reads and retries, so the digest always covers exactly the set that is published.
+ for (var attempt = 0; motion.Status == MotionStatus.Open && attempt < 5; attempt++)
+ {
+ var frozen = await dbContext.SealedBallots.AsNoTracking().Where(x => x.MotionId == motionId).ToListAsync(cancellationToken);
+ if (await FinalizeAsync(motion, frozen, now, cancellationToken))
+ {
+ break;
+ }
+ }
+
+ if (motion.Status == MotionStatus.Open)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The close is contended; read again.");
+ }
+
+ var ballots = await dbContext.SealedBallots.AsNoTracking()
+ .Include(x => x.UserAccount).ThenInclude(x => x.MemberProfile)
+ .Where(x => x.MotionId == motionId)
+ .ToListAsync(cancellationToken);
+
+ var revealed = ballots.Where(x => x.RevealedAtUtc != null).OrderBy(x => x.Id).ToList();
+ var tally = CandidatesOf(motion)
+ .Select(c => new SealedTally(c, revealed.Count(x => x.RevealedCandidate == c)))
+ .ToList();
+ var top = tally.Max(x => x.Votes);
+ var leaders = top == 0 ? [] : tally.Where(x => x.Votes == top).Select(x => x.Candidate).ToList();
+
+ var voterIds = ballots.Select(x => x.UserAccountId).ToHashSet();
+ var nonVoters = await dbContext.Memberships
+ .AsNoTracking()
+ .Where(x => x.Status == MembershipStatus.Active && !voterIds.Contains(x.UserAccountId))
+ .Select(x => x.UserAccount.MemberProfile != null ? x.UserAccount.MemberProfile.Nickname : x.UserAccount.DisplayName)
+ .ToListAsync(cancellationToken);
+
+ return new SealedMotionResult(
+ motion.Id,
+ motion.Title,
+ motion.Round,
+ motion.PriorMotionId,
+ SealedBallotDocument.SchemaId,
+ tally,
+ leaders,
+ leaders.Count > 1 ? "tie" : leaders.Count == 1 ? "winner" : "no ballots",
+ revealed.Select(x => new RevealedBallot(
+ NameOf(x.UserAccount), x.UserAccountId, x.RevealedCandidate!, x.RevealedReason!, x.Salt!, x.Commitment)).ToList(),
+ ballots.Where(x => x.RevealedAtUtc == null)
+ .Select(x => new AbstainedMember(NameOf(x.UserAccount), "committed but did not reveal", x.Commitment)).ToList(),
+ nonVoters.Select(n => new AbstainedMember(n, "no commitment", null)).ToList(),
+ motion.ResultDigest);
+ }
+
+ public static SealedPhase PhaseOf(Motion motion, DateTimeOffset now) =>
+ motion.Status != MotionStatus.Open || now >= motion.ClosesAtUtc ? SealedPhase.Closed
+ : now >= motion.CommitClosesAtUtc ? SealedPhase.Reveal
+ : SealedPhase.Commit;
+
+ ///
+ /// Closes the motion once. Motion.Status is a concurrency token, so of two racing closers exactly one SaveChanges wins;
+ /// the loser reloads the winner's result and writes nothing (no second audit event).
+ ///
+ private async Task FinalizeAsync(Motion motion, List ballots, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var lines = ballots.OrderBy(x => x.UserAccountId)
+ .Select(x => $"{x.UserAccountId:D}:{x.Commitment}:{(x.RevealedAtUtc != null ? "revealed" : "unrevealed")}")
+ .Prepend($"reveals:{motion.RevealSeq}");
+ motion.ResultDigest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', lines)))).ToLowerInvariant();
+ motion.Status = MotionStatus.Closed;
+ motion.ResolvedAtUtc = now;
+ motion.ResolutionNote = $"Sealed ballots published: {ballots.Count(x => x.RevealedAtUtc != null)} revealed, {ballots.Count(x => x.RevealedAtUtc == null)} committed but unrevealed.";
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException error)
+ {
+ foreach (var entry in error.Entries)
+ {
+ await entry.ReloadAsync(cancellationToken);
+ }
+
+ return motion.Status != MotionStatus.Open;
+ }
+
+ await auditTrailService.RecordAsync(
+ null, nameof(Motion), motion.Id, "sealed.closed",
+ $"Closed sealed-ballot motion {motion.Title}; commitment digest {motion.ResultDigest}.",
+ cancellationToken);
+ return true;
+ }
+
+ /// Closes every sealed-ballot motion whose deadline has passed, so a motion nobody reads still closes.
+ public async Task FinalizeDueAsync(CancellationToken cancellationToken)
+ {
+ var now = timeProvider.GetUtcNow();
+ var due = await dbContext.Motions
+ .Where(x => x.Kind == MotionKind.SealedBallot && x.Status == MotionStatus.Open && x.ClosesAtUtc <= now)
+ .ToListAsync(cancellationToken);
+ foreach (var motion in due)
+ {
+ var ballots = await dbContext.SealedBallots.AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync(cancellationToken);
+ await FinalizeAsync(motion, ballots, now, cancellationToken);
+ }
+
+ return due.Count;
+ }
+
+ private SealedMotionState BuildState(Motion motion, DateTimeOffset now, SealedBallotReceipt? own, Guid voterId)
+ {
+ var phase = PhaseOf(motion, now);
+ var announcement = phase switch
+ {
+ SealedPhase.Commit => $"Sealed ballot open: {motion.Title}. Commit by {motion.CommitClosesAtUtc:u}; reveal until {motion.ClosesAtUtc:u}.",
+ SealedPhase.Reveal => $"Sealed ballot in reveal: {motion.Title}. Reveal by {motion.ClosesAtUtc:u}.",
+ _ => $"Sealed ballot closed: {motion.Title}."
+ };
+ return new SealedMotionState(
+ motion.Id, motion.Title, motion.Summary, motion.Round, motion.PriorMotionId, SealedBallotDocument.SchemaId,
+ phase.ToString(), CandidatesOf(motion), motion.CommitClosesAtUtc!.Value, motion.ClosesAtUtc, voterId, own, announcement);
+ }
+
+ private async Task LoadAsync(Guid motionId, CancellationToken cancellationToken) =>
+ await dbContext.Motions.SingleOrDefaultAsync(x => x.Id == motionId && x.Kind == MotionKind.SealedBallot, cancellationToken)
+ ?? throw new SealedBallotException(SealedBallotFailure.NotFound, "No such sealed-ballot motion.");
+
+ private static IReadOnlyList CandidatesOf(Motion motion) => motion.Candidates.Split('\n');
+
+ private static string NameOf(UserAccount user) => user.MemberProfile?.Nickname ?? user.DisplayName;
+
+ // A member resolved before a merge froze the account must not write a ballot after it: the write gate reads standing at the write.
+ private static void RequireStanding(MergeStanding? standing)
+ {
+ if (standing is not null)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required.");
+ }
+ }
+
+ private static UserAccount RequireMember(CurrentBifrostActor actor) =>
+ actor is { IsActiveMember: true, UserAccount: { } user }
+ ? user
+ : throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required.");
+}
+
+public enum SealedPhase { Commit, Reveal, Closed }
+
+public enum SealedBallotFailure { Forbidden, NotFound, WrongPhase, Invalid, Unauthorized }
+
+public sealed class SealedBallotException(SealedBallotFailure failure, string message) : Exception(message)
+{
+ public SealedBallotFailure Failure { get; } = failure;
+}
+
+///
+/// The typed ballot document, schema gamecult.sealed_ballot.v0 . A Delphi second round is another motion carrying this
+/// same type with a higher Round. The commitment binds the voter's account id and, for a Mind casting through the signed intake, its persona id (empty for member casts), so a commitment cannot be replayed by another member or persona.
+///
+public sealed record SealedBallotDocument(string Schema, Guid MotionId, int Round, string Candidate, string Reason, string Salt, string Persona = "")
+{
+ public const string SchemaId = "gamecult.sealed_ballot.v0";
+
+ public static string Commit(SealedBallotDocument d, Guid voterUserAccountId) =>
+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
+ $"{SchemaId}\n{d.MotionId:D}\n{voterUserAccountId:D}\n{d.Persona}\n{d.Round}\n{d.Candidate}\n{d.Reason}\n{d.Salt}"))).ToLowerInvariant();
+}
+
+public sealed record OpenSealedMotionCommand(
+ string Title,
+ string Summary,
+ IReadOnlyList Candidates,
+ DateTimeOffset CommitClosesAtUtc,
+ DateTimeOffset ClosesAtUtc,
+ int Round = 1,
+ Guid? PriorMotionId = null);
+
+public sealed record SealedBallotReceipt(Guid MotionId, Guid VoterUserAccountId, string Commitment, int Revision, DateTimeOffset CommittedAtUtc, bool Revealed);
+
+public sealed record SealedMotionState(
+ Guid Id, string Title, string Summary, int Round, Guid? PriorMotionId, string BallotSchema, string Phase,
+ IReadOnlyList Candidates, DateTimeOffset CommitClosesAtUtc, DateTimeOffset ClosesAtUtc,
+ Guid YourVoterId, SealedBallotReceipt? YourCommitment, string Announcement);
+
+public sealed record SealedTally(string Candidate, int Votes);
+
+public sealed record RevealedBallot(string Voter, Guid VoterUserAccountId, string Candidate, string Reason, string Salt, string Commitment);
+
+public sealed record AbstainedMember(string Member, string Why, string? Commitment);
+
+public sealed record SealedMotionResult(
+ Guid Id, string Title, int Round, Guid? PriorMotionId, string BallotSchema,
+ IReadOnlyList Tally, IReadOnlyList Leaders, string Outcome,
+ IReadOnlyList Ballots, IReadOnlyList Unrevealed, IReadOnlyList NonVoters,
+ string CommitmentDigest);
+public sealed record SealedCommitRequest(string Commitment);
+
+/// Sweeps due sealed-ballot motions once a minute. Reads also close on demand; this covers a motion nobody reads.
+public sealed class SealedBallotCloser(IServiceScopeFactory scopes, ILogger logger) : BackgroundService
+{
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
+ do
+ {
+ try
+ {
+ using var scope = scopes.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(stoppingToken);
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ logger.LogWarning(error, "Sealed-ballot close sweep failed; retrying next tick.");
+ }
+ }
+ while (await timer.WaitForNextTickAsync(stoppingToken));
+ }
+}
diff --git a/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs b/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs
new file mode 100644
index 0000000..c393afd
--- /dev/null
+++ b/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs
@@ -0,0 +1,79 @@
+using Bifrost.Web.Configuration;
+using Microsoft.Extensions.Options;
+using OpenIddict.Abstractions;
+using OpenIddict.Server;
+using static OpenIddict.Abstractions.OpenIddictConstants;
+
+namespace Bifrost.Web.Features.Oidc;
+
+///
+/// Makes the provider's one client match configuration at startup, creating it or updating it in place, and removes
+/// every other application (with its authorizations and tokens), so a client left by an older configuration cannot get codes.
+///
+public sealed class OidcClientSeeder(
+ IServiceScopeFactory scopeFactory,
+ OidcIssuerOptions options,
+ OidcKeyMaterial material,
+ IOptions serverOptions,
+ ILogger logger) : IHostedService
+{
+ public async Task StartAsync(CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(options.Clients.Mas.BackchannelLogoutUri))
+ {
+ logger.LogWarning(
+ "Bifrost:Oidc:Clients:Mas:BackchannelLogoutUri is not set: suspending an account stops new sign-ins and token refresh but does not end its existing chat sessions.");
+ }
+
+ // Reading the server options now runs their configuration, so a bad issuer stops startup rather than the first request.
+ _ = serverOptions.Value;
+
+ await using var scope = scopeFactory.CreateAsyncScope();
+ var manager = scope.ServiceProvider.GetRequiredService();
+ var mas = options.Clients.Mas;
+
+ var descriptor = new OpenIddictApplicationDescriptor
+ {
+ ClientId = mas.ClientId,
+ ClientSecret = material.ClientSecret,
+ ClientType = ClientTypes.Confidential,
+ DisplayName = "Matrix Authentication Service",
+ RedirectUris = { new Uri(mas.RedirectUri, UriKind.Absolute) },
+ Permissions =
+ {
+ Permissions.Endpoints.Authorization,
+ Permissions.Endpoints.Token,
+ Permissions.GrantTypes.AuthorizationCode,
+ Permissions.ResponseTypes.Code,
+ Permissions.Scopes.Profile,
+ Permissions.Prefixes.Scope + Scopes.OpenId
+ }
+ };
+
+ var existing = await manager.FindByClientIdAsync(mas.ClientId, cancellationToken);
+ if (existing is null)
+ {
+ await manager.CreateAsync(descriptor, cancellationToken);
+ }
+ else
+ {
+ await manager.UpdateAsync(existing, descriptor, cancellationToken);
+ }
+
+ var applications = new List