Account merge ledger: AccountMerge receipt, reductions, alias standing, undo and final sweep

AccountMergeLedger owns what a merge does to Bifrost records: PlanAsync (dry run, block codes),
CommitAsync (one save, total, idempotent), UndoLocalAsync (journal replay), FinalizeDueAsync
(AccountMergeSweeper) and StandingAsync/ResolveAsync. Votes and concept appraisals are voided by a
stamp that a model query filter hides from every tally. The actor accessor no longer ORs several
credentials under SingleOrDefault (a latent crash); a frozen or folded account resolves to no
account on every route, the OIDC authorize and chat refusal deny it, and patron intake follows the
alias. Migration AddAccountMerges is additive. No UI, no Heimdall call, nothing deployed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-14 02:31:51 +00:00
commit 84ff2c4578
20 changed files with 2077 additions and 27 deletions

View file

@ -81,6 +81,10 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
public DbSet<ConceptAppraisal> ConceptAppraisals => Set<ConceptAppraisal>();
public DbSet<AccountMerge> AccountMerges => Set<AccountMerge>();
public DbSet<AccountMergeEntry> AccountMergeEntries => Set<AccountMergeEntry>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccount>(entity =>
@ -301,6 +305,8 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
modelBuilder.Entity<Vote>(entity =>
{
entity.HasIndex(x => new { x.MotionId, x.UserAccountId }).IsUnique();
// A merge voids a vote by stamping it; every tally reads through this filter, and only AccountMergeLedger ignores it.
entity.HasQueryFilter(x => x.VoidedByMergeId == null);
entity.Property(x => x.Choice).HasConversion<string>();
entity.Property(x => x.Weight).HasPrecision(18, 2);
entity.HasOne(x => x.Motion)
@ -607,6 +613,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
entity.Property(x => x.NetworkTag).HasMaxLength(64);
entity.Property(x => x.Stance).HasConversion<string>().HasMaxLength(16);
entity.Property(x => x.VoterClass).HasConversion<string>().HasMaxLength(16);
entity.HasQueryFilter(x => x.VoidedByMergeId == null);
entity.HasIndex(x => new { x.SubjectId, x.VoterKey }).IsUnique();
entity.HasIndex(x => new { x.NetworkTag, x.CastAtUtc });
entity.HasOne(x => x.Subject)
@ -618,5 +625,34 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
.HasForeignKey(x => x.UserAccountId)
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity<AccountMerge>(entity =>
{
entity.Property(x => x.State).HasConversion<string>().HasMaxLength(24);
entity.Property(x => x.FailureCode).HasMaxLength(64);
entity.HasIndex(x => new { x.FoldedUserAccountId, x.State });
entity.HasIndex(x => new { x.SurvivorUserAccountId, x.State });
entity.HasIndex(x => new { x.State, x.GraceEndsUtc });
entity.HasOne<UserAccount>()
.WithMany()
.HasForeignKey(x => x.SurvivorUserAccountId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne<UserAccount>()
.WithMany()
.HasForeignKey(x => x.FoldedUserAccountId)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<AccountMergeEntry>(entity =>
{
entity.Property(x => x.Kind).HasConversion<string>().HasMaxLength(24);
entity.Property(x => x.Action).HasConversion<string>().HasMaxLength(24);
entity.Property(x => x.PriorText).HasMaxLength(120);
entity.HasIndex(x => new { x.MergeId, x.Seq }).IsUnique();
entity.HasOne(x => x.Merge)
.WithMany(x => x.Entries)
.HasForeignKey(x => x.MergeId)
.OnDelete(DeleteBehavior.Restrict);
});
}
}

View file

@ -0,0 +1,150 @@
using System;
using Bifrost.Web.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
// Scaffolded by IMigrationsScaffolder against the previous snapshot (no dotnet-ef on the authoring host), the designer file dropped and
// the snapshot edited by hand to match, like AddPasskeyCredentials. Additive only; Down drops what Up adds.
[DbContext(typeof(BifrostDbContext))]
[Migration("20261114120000_AddAccountMerges")]
public partial class AddAccountMerges : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "VoidedByMergeId",
table: "Votes",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "VoidedUtc",
table: "Votes",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "VoidedByMergeId",
table: "ConceptAppraisals",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "VoidedUtc",
table: "ConceptAppraisals",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.CreateTable(
name: "AccountMerges",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
State = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
SurvivorUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
FoldedUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CommittedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
GraceEndsUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
FinalizedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
UndoneUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
FailedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
FailureCode = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AccountMerges", x => x.Id);
table.ForeignKey(
name: "FK_AccountMerges_UserAccounts_FoldedUserAccountId",
column: x => x.FoldedUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AccountMerges_UserAccounts_SurvivorUserAccountId",
column: x => x.SurvivorUserAccountId,
principalTable: "UserAccounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AccountMergeEntries",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
MergeId = table.Column<Guid>(type: "uuid", nullable: false),
Seq = table.Column<int>(type: "integer", nullable: false),
Kind = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
RecordId = table.Column<Guid>(type: "uuid", nullable: false),
Action = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
PriorUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
PriorText = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: true),
PriorAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
AtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AccountMergeEntries", x => x.Id);
table.ForeignKey(
name: "FK_AccountMergeEntries_AccountMerges_MergeId",
column: x => x.MergeId,
principalTable: "AccountMerges",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_AccountMergeEntries_MergeId_Seq",
table: "AccountMergeEntries",
columns: new[] { "MergeId", "Seq" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AccountMerges_FoldedUserAccountId_State",
table: "AccountMerges",
columns: new[] { "FoldedUserAccountId", "State" });
migrationBuilder.CreateIndex(
name: "IX_AccountMerges_State_GraceEndsUtc",
table: "AccountMerges",
columns: new[] { "State", "GraceEndsUtc" });
migrationBuilder.CreateIndex(
name: "IX_AccountMerges_SurvivorUserAccountId_State",
table: "AccountMerges",
columns: new[] { "SurvivorUserAccountId", "State" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AccountMergeEntries");
migrationBuilder.DropTable(
name: "AccountMerges");
migrationBuilder.DropColumn(
name: "VoidedByMergeId",
table: "Votes");
migrationBuilder.DropColumn(
name: "VoidedUtc",
table: "Votes");
migrationBuilder.DropColumn(
name: "VoidedByMergeId",
table: "ConceptAppraisals");
migrationBuilder.DropColumn(
name: "VoidedUtc",
table: "ConceptAppraisals");
}
}
}

View file

@ -22,6 +22,103 @@ namespace Bifrost.Web.Data.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("CommittedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("FailedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("FailureCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("FinalizedUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FoldedUserAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("GraceEndsUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("State")
.IsRequired()
.HasMaxLength(24)
.HasColumnType("character varying(24)");
b.Property<Guid>("SurvivorUserAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("UndoneUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("FoldedUserAccountId", "State");
b.HasIndex("State", "GraceEndsUtc");
b.HasIndex("SurvivorUserAccountId", "State");
b.ToTable("AccountMerges");
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Action")
.IsRequired()
.HasMaxLength(24)
.HasColumnType("character varying(24)");
b.Property<DateTimeOffset>("AtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(24)
.HasColumnType("character varying(24)");
b.Property<Guid>("MergeId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("PriorAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("PriorText")
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<Guid?>("PriorUserAccountId")
.HasColumnType("uuid");
b.Property<Guid>("RecordId")
.HasColumnType("uuid");
b.Property<int>("Seq")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("MergeId", "Seq")
.IsUnique();
b.ToTable("AccountMergeEntries");
});
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
{
b.Property<Guid>("Id")
@ -437,6 +534,12 @@ namespace Bifrost.Web.Data.Migrations
b.Property<Guid?>("UserAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("VoidedByMergeId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("VoidedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("VoterClass")
.IsRequired()
.HasMaxLength(16)
@ -1676,6 +1779,12 @@ namespace Bifrost.Web.Data.Migrations
b.Property<Guid>("UserAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("VoidedByMergeId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("VoidedUtc")
.HasColumnType("timestamp with time zone");
b.Property<decimal>("Weight")
.HasPrecision(18, 2)
.HasColumnType("numeric(18,2)");
@ -2063,6 +2172,32 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("OpenIddictTokens", (string)null);
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("FoldedUserAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("SurvivorUserAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMergeEntry", b =>
{
b.HasOne("Bifrost.Web.Domain.AccountMerge", "Merge")
.WithMany("Entries")
.HasForeignKey("MergeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Merge");
});
modelBuilder.Entity("Bifrost.Web.Domain.AgentDispatchRun", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", "StartedByUserAccount")
@ -2602,6 +2737,11 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("Authorization");
});
modelBuilder.Entity("Bifrost.Web.Domain.AccountMerge", b =>
{
b.Navigation("Entries");
});
modelBuilder.Entity("Bifrost.Web.Domain.Membership", b =>
{
b.Navigation("RoleAssignments");

View file

@ -0,0 +1,93 @@
namespace Bifrost.Web.Domain;
/// <summary>The whole lifecycle of an account merge, declared once; later cuts add columns, not states. Stored as a string.</summary>
public enum AccountMergeState
{
Proposed,
Confirmed,
HeimdallMoved,
Committed,
Final,
UndoRequested,
HeimdallReversed,
Undone,
Failed
}
public enum AccountMergeEntryKind
{
Vote,
ConceptAppraisal,
Membership,
Standing,
PatronSupportEvent
}
public enum AccountMergeEntryAction
{
Voided,
Moved,
Closed,
Suspended,
Restored,
KeptAfterUndo
}
/// <summary>
/// The merge receipt: two Heimdall-backed accounts, one survivor. Whether an account is folded or frozen is derived from this row's
/// State on every request (AccountMergeLedger.StandingAsync); no column on the account says so.
/// </summary>
public sealed class AccountMerge
{
public Guid Id { get; set; } = Guid.NewGuid();
public AccountMergeState State { get; set; } = AccountMergeState.Proposed;
public Guid SurvivorUserAccountId { get; set; }
public Guid FoldedUserAccountId { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset? CommittedUtc { get; set; }
public DateTimeOffset? GraceEndsUtc { get; set; }
public DateTimeOffset? FinalizedUtc { get; set; }
public DateTimeOffset? UndoneUtc { get; set; }
public DateTimeOffset? FailedUtc { get; set; }
public string FailureCode { get; set; } = string.Empty;
public ICollection<AccountMergeEntry> Entries { get; set; } = [];
}
/// <summary>Append-only journal of what a merge did to one record; undo and the later preview read it, tallies and gates never do.</summary>
public sealed class AccountMergeEntry
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid MergeId { get; set; }
public int Seq { get; set; }
public AccountMergeEntryKind Kind { get; set; }
public Guid RecordId { get; set; }
public AccountMergeEntryAction Action { get; set; }
public Guid? PriorUserAccountId { get; set; }
/// <summary>The prior status or prior voter key.</summary>
public string? PriorText { get; set; }
/// <summary>The cast time of a moved vote or appraisal, so undo can tell whether the survivor re-cast it.</summary>
public DateTimeOffset? PriorAtUtc { get; set; }
public DateTimeOffset AtUtc { get; set; }
public AccountMerge Merge { get; set; } = null!;
}

View file

@ -7,7 +7,9 @@ public enum MembershipStatus
Authenticated,
PendingApproval,
Active,
Suspended
Suspended,
/// <summary>Terminal status of a folded membership; written only by the account merge ledger, never read to decide standing.</summary>
Merged
}
public enum MemberRole
@ -776,6 +778,11 @@ public sealed class Vote
public DateTimeOffset CastAtUtc { get; set; }
/// <summary>Set by the account merge ledger when a merge removes this vote from every tally; the model's query filter then hides the row.</summary>
public Guid? VoidedByMergeId { get; set; }
public DateTimeOffset? VoidedUtc { get; set; }
public Motion Motion { get; set; } = null!;
public UserAccount UserAccount { get; set; } = null!;

View file

@ -46,5 +46,10 @@ public sealed class ConceptAppraisal
public DateTimeOffset CastAtUtc { get; set; }
/// <summary>Set by the account merge ledger when a merge removes this appraisal from every tally; the model's query filter then hides the row.</summary>
public Guid? VoidedByMergeId { get; set; }
public DateTimeOffset? VoidedUtc { get; set; }
public ConceptSubject? Subject { get; set; }
}

View file

@ -5,6 +5,7 @@ using System.Text.Json.Serialization;
using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Patronage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
@ -14,6 +15,7 @@ namespace Bifrost.Web.Features.Heimdall;
public sealed class HeimdallPatronSupportIntakeService(
BifrostDbContext dbContext,
PatronageService patronageService,
AccountMergeLedger mergeLedger,
IOptions<HeimdallOptions> heimdallOptions)
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
@ -83,7 +85,7 @@ public sealed class HeimdallPatronSupportIntakeService(
var supportEvent = await patronageService.RecordSupportEventAsync(
actorUserAccountId: null,
userAccountId: user.Id,
userAccountId: await mergeLedger.ResolveAsync(user.Id, cancellationToken), // a folded account's events record on the survivor
request.Kind,
request.Amount,
request.CurrencyCode,

View file

@ -0,0 +1,583 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Patronage;
using Microsoft.EntityFrameworkCore;
namespace Bifrost.Web.Features.Membership;
/// <summary>How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded.</summary>
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);
/// <summary>A dry run: the block codes (never account names), the journal entries a commit would write, and the record counts left untouched.</summary>
public sealed record MergePlan(
IReadOnlyList<string> Blocks,
IReadOnlyList<MergePlanEntry> Entries,
IReadOnlyDictionary<string, int> Left);
/// <summary>
/// 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, StandingAsync and ResolveAsync. 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.
/// </summary>
public sealed class AccountMergeLedger(
BifrostDbContext dbContext,
PatronageService patronageService,
TimeProvider timeProvider)
{
public static readonly TimeSpan Grace = TimeSpan.FromDays(7);
private const int MaxHops = 8;
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<MergeStanding?> StandingAsync(Guid userAccountId, CancellationToken cancellationToken) =>
StandingAsync(dbContext, userAccountId, cancellationToken);
/// <summary>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.</summary>
public static async Task<MergeStanding?> 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);
}
/// <summary>Follows Folded links to the account that now carries the person. Each account is folded once, so the hop cap is only a guard.</summary>
public async Task<Guid> ResolveAsync(Guid userAccountId, CancellationToken cancellationToken)
{
var current = userAccountId;
for (var hop = 0; hop < MaxHops; hop++)
{
if (await StandingAsync(current, cancellationToken) is not MergeStanding.Folded folded)
{
return current;
}
current = folded.SurvivorId;
}
return current;
}
/// <summary>Writes nothing. <paramref name="exceptMergeId"/> lets the saga re-plan a merge it already holds without it blocking itself.</summary>
public async Task<MergePlan> PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null)
{
var blocks = await BlocksAsync(survivorId, foldedId, exceptMergeId, cancellationToken);
var entries = new List<MergePlanEntry>();
var left = new Dictionary<string, int>();
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<IReadOnlyList<string>> BlocksAsync(Guid survivorId, Guid foldedId, Guid? exceptMergeId, CancellationToken cancellationToken)
{
var blocks = new List<string>();
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");
}
// Heimdall could no longer reverse a merge this account survived once it is folded into another.
if (await dbContext.AccountMerges.AnyAsync(
x => x.Id != exceptMergeId && x.State == AccountMergeState.Committed && x.SurvivorUserAccountId == foldedId,
cancellationToken))
{
blocks.Add("folded_survivor_in_grace");
}
if (await dbContext.SealedBallots.AnyAsync(
x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open,
cancellationToken))
{
blocks.Add("sealed_ballot_pending");
}
return blocks;
}
private Task<bool> FoldedLinkAsync(Guid accountId, Guid? exceptMergeId, CancellationToken cancellationToken) =>
dbContext.AccountMerges.AnyAsync(
x => x.Id != exceptMergeId && x.FoldedUserAccountId == accountId && FoldedStates.Contains(x.State),
cancellationToken);
/// <summary>
/// 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.
/// </summary>
public async Task<AccountMerge> CommitAsync(Guid mergeId, CancellationToken cancellationToken)
{
var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, 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);
}
merge.State = AccountMergeState.Committed;
merge.CommittedUtc = now;
merge.GraceEndsUtc = now + Grace;
await dbContext.SaveChangesAsync(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;
}
}
/// <summary>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.</summary>
public async Task<AccountMerge> 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.");
}
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))
{
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;
}
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;
row.VoterKey = entry.PriorText ?? row.VoterKey;
}
Record(entry, restore);
break;
}
case (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed):
{
var restore = folded.Membership is { Status: MembershipStatus.Merged } && Enum.TryParse<MembershipStatus>(entry.PriorText, out _);
if (restore)
{
folded.Membership!.Status = Enum.Parse<MembershipStatus>(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<MembershipStatus>(entry.PriorText, out _);
if (restore)
{
survivor.Membership!.Status = Enum.Parse<MembershipStatus>(entry.PriorText!);
survivor.Membership.SuspensionReason = null;
}
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;
}
}
/// <summary>Committed merges whose grace has ended become Final; returns how many. Undo is never allowed past Final.</summary>
public async Task<int> FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
{
var due = await dbContext.AccountMerges
.Where(x => x.State == AccountMergeState.Committed && x.GraceEndsUtc <= now)
.ToListAsync(cancellationToken);
foreach (var merge in due)
{
merge.State = AccountMergeState.Final;
merge.FinalizedUtc = now;
}
await dbContext.SaveChangesAsync(cancellationToken);
return due.Count;
}
private sealed class Reduction(
UserAccount survivor,
UserAccount folded,
List<MergePlanEntry> entries,
List<Action<Guid, DateTimeOffset>> effects,
bool movedPatronEvents)
{
public UserAccount Survivor { get; } = survivor;
public UserAccount Folded { get; } = folded;
public IReadOnlyList<MergePlanEntry> Entries => entries;
public bool MovedPatronEvents { get; } = movedPatronEvents;
public Guid MergeId { get; set; }
public void Apply(DateTimeOffset now)
{
foreach (var effect in effects)
{
effect(MergeId, now);
}
}
}
/// <summary>
/// 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.
/// </summary>
private async Task<Reduction> ReduceAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? mergeId = null)
{
var survivor = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
.SingleAsync(x => x.Id == survivorId, cancellationToken);
var folded = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
.SingleAsync(x => x.Id == foldedId, cancellationToken);
var entries = new List<MergePlanEntry>();
var effects = new List<Action<Guid, DateTimeOffset>>();
var foldedSuspended = folded.Membership?.Status == MembershipStatus.Suspended;
var survivorSuspendedNow = survivor.Membership?.Status == MembershipStatus.Suspended;
var survivorStanding = survivor.Membership?.Status;
if (foldedSuspended && !survivorSuspendedNow && 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);
});
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, null, vote.CastAtUtc));
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.VoterKey, appraisal.CastAtUtc));
effects.Add((_, _) =>
{
appraisal.UserAccountId = survivorId;
appraisal.VoterKey = survivorKey;
});
}
}
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, 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<PatronSupportEvent> events, DateTimeOffset now, CancellationToken cancellationToken)
{
if (membership is not null)
{
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");
}
/// <summary>Finalizes merges past their grace every five minutes. Copies the SealedBallotCloser shape: a new scope per tick, a warning on failure.</summary>
public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger<AccountMergeSweeper> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
do
{
try
{
using var scope = scopes.CreateScope();
await scope.ServiceProvider.GetRequiredService<AccountMergeLedger>().FinalizeDueAsync(clock.GetUtcNow(), stoppingToken);
}
catch (Exception error) when (error is not OperationCanceledException)
{
logger.LogWarning(error, "Account merge sweep failed; retrying next tick.");
}
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
}

View file

@ -23,6 +23,7 @@ namespace Bifrost.Web.Features.Oidc;
public static class OidcEndpoints
{
public const string SuspendedDescription = "The account is suspended.";
public const string MergedDescription = "The account is part of an account merge and can no longer sign in.";
public const string NoIdentityDescription = "The account has no Bifrost identity.";
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
@ -56,7 +57,7 @@ public static class OidcEndpoints
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
if (actor.UserAccount is null)
{
return Deny(Errors.AccessDenied, NoIdentityDescription);
return Deny(Errors.AccessDenied, actor.Merge is not null ? MergedDescription : NoIdentityDescription);
}
if (actor.Membership?.Status == MembershipStatus.Suspended)
@ -176,6 +177,12 @@ public static class OidcEndpoints
return SuspendedDescription;
}
// A folded or frozen subject's chat sessions end: token, userinfo and the logout reconciler all read this one refusal.
if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
{
return MergedDescription;
}
return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
}

View file

@ -146,35 +146,7 @@ public sealed class PatronageService(
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
}
var summary = CalculatePatronPoints(user.PatronSupportEvents, timeProvider.GetUtcNow());
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
var now = timeProvider.GetUtcNow();
var currentPatronSnapshots = await dbContext.TierSnapshots
.Where(x => x.MembershipId == user.Membership.Id &&
x.Kind == TierSnapshotKind.Patron &&
x.IsCurrent)
.ToListAsync(cancellationToken);
foreach (var snapshot in currentPatronSnapshots)
{
snapshot.IsCurrent = false;
}
if (tier is not null)
{
dbContext.TierSnapshots.Add(new TierSnapshot
{
MembershipId = user.Membership.Id,
Kind = TierSnapshotKind.Patron,
Label = PatronTierPolicy.SnapshotLabel(tier),
Weight = tier.VotingWeight,
IsCurrent = true,
EffectiveFromUtc = now,
CapturedAtUtc = now,
Notes = PatronTierPolicy.SnapshotNote(summary.EffectivePoints, now)
});
}
var (summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
@ -190,6 +162,49 @@ public sealed class PatronageService(
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
}
/// <summary>
/// Derives the membership's patron tier from the events once and stages it on the tracker: demotes the current Patron snapshots
/// and adds the new one. It never saves and never clears the tracker, so a caller can stage it inside a larger single save
/// (the account merge ledger does).
/// </summary>
public async Task<(PatronPointSummary Summary, PatronTierDefinition? Tier)> StageTierSnapshotAsync(
Bifrost.Web.Domain.Membership membership,
IEnumerable<PatronSupportEvent> events,
DateTimeOffset now,
CancellationToken cancellationToken)
{
var summary = CalculatePatronPoints(events, now);
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
var currentPatronSnapshots = await dbContext.TierSnapshots
.Where(x => x.MembershipId == membership.Id &&
x.Kind == TierSnapshotKind.Patron &&
x.IsCurrent)
.ToListAsync(cancellationToken);
foreach (var snapshot in currentPatronSnapshots)
{
snapshot.IsCurrent = false;
}
if (tier is not null)
{
dbContext.TierSnapshots.Add(new TierSnapshot
{
MembershipId = membership.Id,
Kind = TierSnapshotKind.Patron,
Label = PatronTierPolicy.SnapshotLabel(tier),
Weight = tier.VotingWeight,
IsCurrent = true,
EffectiveFromUtc = now,
CapturedAtUtc = now,
Notes = PatronTierPolicy.SnapshotNote(summary.EffectivePoints, now)
});
}
return (summary, tier);
}
public static PatronPointSummary CalculatePatronPoints(
IEnumerable<PatronSupportEvent> supportEvents,
DateTimeOffset nowUtc)

View file

@ -1,9 +1,13 @@
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Membership;
namespace Bifrost.Web.Features.Shared;
public sealed record CurrentBifrostActor(bool IsAuthenticated, UserAccount? UserAccount)
{
/// <summary>Set when the account behind this sign-in is frozen or folded by an account merge; the actor then has no account.</summary>
public MergeStanding? Merge { get; init; }
public static readonly CurrentBifrostActor Anonymous = new(false, null);
public Bifrost.Web.Domain.Membership? Membership => UserAccount?.Membership;

View file

@ -12,7 +12,8 @@ public interface ICurrentBifrostActorAccessor
public sealed class CurrentBifrostActorAccessor(
IHttpContextAccessor httpContextAccessor,
BifrostDbContext dbContext) : ICurrentBifrostActorAccessor
BifrostDbContext dbContext,
AccountMergeLedger ledger) : ICurrentBifrostActorAccessor
{
private const string CacheKey = "Bifrost.CurrentActor";
@ -45,18 +46,41 @@ public sealed class CurrentBifrostActorAccessor(
return Cache(httpContext, CurrentBifrostActor.Anonymous);
}
var userAccount = await dbContext.UserAccounts
// One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
// one principal (a merge can leave a login on either side) must never throw or pick by luck.
var accounts = dbContext.UserAccounts
.AsNoTracking()
.Include(x => x.MemberProfile)
.Include(x => x.Membership!)
.ThenInclude(x => x.RoleAssignments)
.Include(x => x.Membership!)
.ThenInclude(x => x.TierSnapshots)
.SingleOrDefaultAsync(
x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
(!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
(hasGitHubUserId && x.GitHubUserId == gitHubUserId),
cancellationToken);
.ThenInclude(x => x.TierSnapshots);
Bifrost.Web.Domain.UserAccount? userAccount = null;
if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
{
userAccount = await accounts.SingleOrDefaultAsync(x => x.NormalizedBifrostIdentity == normalizedBifrostIdentity, cancellationToken);
}
if (userAccount is null && !string.IsNullOrWhiteSpace(heimdallAccountId))
{
userAccount = await accounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, cancellationToken);
}
if (userAccount is null && hasGitHubUserId)
{
userAccount = await accounts.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
}
// A folded or frozen account acts as nobody on every route: this is the one gate (merge ledger standing, derived per request).
if (userAccount is not null)
{
var standing = await ledger.StandingAsync(userAccount.Id, cancellationToken);
if (standing is not null)
{
return Cache(httpContext, new CurrentBifrostActor(true, null) { Merge = standing });
}
}
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
}

View file

@ -139,6 +139,8 @@ builder.Services.AddSingleton<RegistrationChallengeService>();
builder.Services.AddSingleton<RegistrationRateLimit>();
builder.Services.AddScoped<NativeRegistration>();
builder.Services.AddHostedService<SealedBallotCloser>();
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeLedger>();
builder.Services.AddHostedService<Bifrost.Web.Features.Membership.AccountMergeSweeper>();
builder.Services.AddScoped<MotionEveSurfaceService>();
builder.Services.AddScoped<PatronageService>();
builder.Services.AddScoped<StripeWebhookService>();