Pairwise faction attitudes were hand-typed into a per-faction array, so the two directions of one relationship lived in different documents and could disagree with each other. Add `faction-relation-entries`: one row per event that moved one faction's attitude toward another, with the score computed on read instead of stored. Entries are directed by default with a mutual flag for shared events; severity tiers set the delta with a custom override; decaying entries halve per half-life (new GameRules knob, 30 days default) while lasting shifts never fade; voiding retires an entry with a stamped reason instead of deleting it; hidden entries still move the score but never explain it to players. `factionRelations.ts` holds the pure math (severity presets, decay, directed and mutual scores, bands), and `factionRelationLedger.ts` is the single read path so the voided, hidden and undiscovered-faction rules exist in one place. Reads run as the caller, never with `overrideAccess`; GM notes are gated by field read access, and hidden rows are censored by an `afterRead` hook. Includes the permission group, the `admin:faction-relation-entries:manage` page gate, the integration spec, and the migration that creates the table and its enums.
479 lines
16 KiB
TypeScript
479 lines
16 KiB
TypeScript
import { getTestPayload } from "../helpers/get-test-payload";
|
|
import type { Payload } from "payload";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
import type { Faction, FactionRelationEntry, Role, User } from "@/payload-types";
|
|
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
|
import {
|
|
directedScore,
|
|
directedScoreMap,
|
|
effectiveDelta,
|
|
relationBand,
|
|
RELATION_MIN,
|
|
RELATION_MAX,
|
|
type RelationEntryLike,
|
|
} from "@/lib/intelligence/factionRelations";
|
|
import { getRelationContext, historyFor } from "@/lib/intelligence/factionRelationLedger";
|
|
|
|
let payload: Payload;
|
|
|
|
const RUN = `frel-${Date.now().toString(36)}`;
|
|
const TIMEOUT = 30_000;
|
|
const DAY = 86_400_000;
|
|
|
|
describe("Faction relation ledger", () => {
|
|
const roleIds: number[] = [];
|
|
const userIds: number[] = [];
|
|
const factionIds: number[] = [];
|
|
const entryIds: number[] = [];
|
|
|
|
let reader: User;
|
|
let gm: User;
|
|
let revealer: User;
|
|
|
|
// One pair of factions per test keeps every score assertion independent of
|
|
// the entries other tests leave behind.
|
|
let a: number;
|
|
let b: number;
|
|
let secret: number;
|
|
|
|
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
|
|
const role = (await payload.create({
|
|
collection: "roles",
|
|
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Role;
|
|
roleIds.push(role.id);
|
|
return role;
|
|
};
|
|
|
|
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
|
const user = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-${label}`,
|
|
discordUsername: `${RUN}-${label}`,
|
|
displayName: label.toUpperCase(),
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
roleDocs: [roleId],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User;
|
|
userIds.push(user.id);
|
|
return user;
|
|
};
|
|
|
|
const makeFaction = async (label: string, discovered = true): Promise<number> => {
|
|
const faction = (await payload.create({
|
|
collection: "factions",
|
|
data: { name: `${RUN}-${label}`, type: "minorFaction", discovered },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Faction;
|
|
factionIds.push(faction.id);
|
|
return faction.id;
|
|
};
|
|
|
|
const makeEntry = async (
|
|
data: Record<string, unknown>,
|
|
user: User = gm,
|
|
): Promise<FactionRelationEntry> => {
|
|
const entry = (await payload.create({
|
|
collection: "faction-relation-entries",
|
|
data: {
|
|
severity: "notable",
|
|
polarity: "detrimental",
|
|
category: "other",
|
|
summary: "A test event.",
|
|
occurredAt: new Date().toISOString(),
|
|
...data,
|
|
} as never,
|
|
user: user as never,
|
|
overrideAccess: false,
|
|
depth: 0,
|
|
})) as unknown as FactionRelationEntry;
|
|
entryIds.push(entry.id);
|
|
return entry;
|
|
};
|
|
|
|
/** Live entries for one direction, as the math expects them. */
|
|
const entriesFor = async (subjectId: number, targetId: number): Promise<RelationEntryLike[]> => {
|
|
const res = await payload.find({
|
|
collection: "faction-relation-entries",
|
|
where: {
|
|
and: [{ subject: { equals: subjectId } }, { target: { equals: targetId } }],
|
|
},
|
|
limit: 100,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
return (res.docs as FactionRelationEntry[]).map((doc) => ({
|
|
subjectId: doc.subject as number,
|
|
targetId: doc.target as number,
|
|
delta: doc.delta ?? 0,
|
|
mutual: doc.mutual,
|
|
decays: doc.decays,
|
|
occurredAt: doc.occurredAt,
|
|
voided: doc.voided,
|
|
}));
|
|
};
|
|
|
|
const readEntriesAs = async (
|
|
user: User | undefined,
|
|
where: Record<string, unknown>,
|
|
): Promise<FactionRelationEntry[]> => {
|
|
const res = await payload.find({
|
|
collection: "faction-relation-entries",
|
|
where: where as never,
|
|
limit: 100,
|
|
depth: 0,
|
|
user: user as never,
|
|
overrideAccess: false,
|
|
});
|
|
return res.docs as FactionRelationEntry[];
|
|
};
|
|
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
invalidatePermissionCache();
|
|
|
|
const readerRole = await makeRole("reader", {
|
|
permissions: ["factions:read", "faction-relation-entries:read"],
|
|
});
|
|
const gmRole = await makeRole("gm", {
|
|
permissions: [
|
|
"factions:read",
|
|
"faction-relation-entries:read",
|
|
"faction-relation-entries:create",
|
|
"faction-relation-entries:update",
|
|
"admin:faction-relation-entries:manage",
|
|
],
|
|
});
|
|
const revealerRole = await makeRole("revealer", {
|
|
permissions: [
|
|
"factions:read",
|
|
"factions:view-undiscovered",
|
|
"faction-relation-entries:read",
|
|
],
|
|
});
|
|
|
|
reader = await makeUser("reader", readerRole.id);
|
|
gm = await makeUser("gm", gmRole.id);
|
|
revealer = await makeUser("revealer", revealerRole.id);
|
|
|
|
a = await makeFaction("Alpha");
|
|
b = await makeFaction("Bravo");
|
|
secret = await makeFaction("Covert", false);
|
|
}, TIMEOUT);
|
|
|
|
afterAll(async () => {
|
|
for (const id of entryIds) {
|
|
await payload
|
|
.delete({ collection: "faction-relation-entries", id, overrideAccess: true })
|
|
.catch(() => null);
|
|
}
|
|
for (const id of factionIds) {
|
|
await payload.delete({ collection: "factions", id, overrideAccess: true }).catch(() => null);
|
|
}
|
|
for (const id of userIds) {
|
|
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => null);
|
|
}
|
|
for (const id of roleIds) {
|
|
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => null);
|
|
}
|
|
invalidatePermissionCache();
|
|
}, TIMEOUT);
|
|
|
|
describe("entry model", () => {
|
|
it("derives the delta from the severity tier and the polarity", async () => {
|
|
const major = await makeEntry({ subject: a, target: b, severity: "major" });
|
|
expect(major.delta).toBe(-20);
|
|
|
|
const decisive = await makeEntry({
|
|
subject: a,
|
|
target: b,
|
|
severity: "decisive",
|
|
polarity: "beneficial",
|
|
});
|
|
expect(decisive.delta).toBe(40);
|
|
});
|
|
|
|
it("keeps a custom delta and derives its polarity from the sign", async () => {
|
|
const gain = await makeEntry({
|
|
subject: a,
|
|
target: b,
|
|
severity: "custom",
|
|
delta: 7,
|
|
polarity: "detrimental",
|
|
});
|
|
expect(gain.delta).toBe(7);
|
|
expect(gain.polarity).toBe("beneficial");
|
|
|
|
const loss = await makeEntry({ subject: a, target: b, severity: "custom", delta: -3 });
|
|
expect(loss.delta).toBe(-3);
|
|
expect(loss.polarity).toBe("detrimental");
|
|
});
|
|
|
|
it("refuses a custom severity without a usable delta", async () => {
|
|
await expect(
|
|
makeEntry({ subject: a, target: b, severity: "custom", delta: 0 }),
|
|
).rejects.toThrow();
|
|
});
|
|
|
|
it("refuses an entry whose subject and target are the same faction", async () => {
|
|
await expect(makeEntry({ subject: a, target: a })).rejects.toThrow();
|
|
});
|
|
|
|
it("stamps who voided an entry and clears the stamps when unvoided", async () => {
|
|
const entry = await makeEntry({ subject: a, target: b });
|
|
const voided = (await payload.update({
|
|
collection: "faction-relation-entries",
|
|
id: entry.id,
|
|
data: { voided: true, voidedReason: "Never happened." },
|
|
user: gm as never,
|
|
overrideAccess: false,
|
|
depth: 0,
|
|
})) as unknown as FactionRelationEntry;
|
|
expect(voided.voided).toBe(true);
|
|
expect(voided.voidedAt).toBeTruthy();
|
|
expect(typeof voided.voidedBy).toBe("number");
|
|
expect(voided.recordedBy).toBe(gm.id);
|
|
|
|
const restored = (await payload.update({
|
|
collection: "faction-relation-entries",
|
|
id: entry.id,
|
|
data: { voided: false },
|
|
user: gm as never,
|
|
overrideAccess: false,
|
|
depth: 0,
|
|
})) as unknown as FactionRelationEntry;
|
|
expect(restored.voidedAt ?? null).toBeNull();
|
|
expect(restored.voidedBy ?? null).toBeNull();
|
|
expect(restored.voidedReason ?? null).toBeNull();
|
|
});
|
|
|
|
it("refuses deletion, so the ledger cannot lose history", async () => {
|
|
const entry = await makeEntry({ subject: a, target: b });
|
|
await expect(
|
|
payload.delete({
|
|
collection: "faction-relation-entries",
|
|
id: entry.id,
|
|
user: gm as never,
|
|
overrideAccess: false,
|
|
}),
|
|
).rejects.toThrow();
|
|
});
|
|
});
|
|
|
|
describe("score math", () => {
|
|
it("sums directed entries and ignores the opposite direction", () => {
|
|
const entries: RelationEntryLike[] = [
|
|
{
|
|
subjectId: 1,
|
|
targetId: 2,
|
|
delta: -20,
|
|
occurredAt: new Date().toISOString(),
|
|
},
|
|
{
|
|
subjectId: 2,
|
|
targetId: 1,
|
|
delta: 30,
|
|
occurredAt: new Date().toISOString(),
|
|
},
|
|
];
|
|
const now = new Date();
|
|
expect(directedScore(entries, 1, 2, now)).toBe(-20);
|
|
expect(directedScore(entries, 2, 1, now)).toBe(30);
|
|
});
|
|
|
|
it("counts a mutual entry in both directions", () => {
|
|
const now = new Date();
|
|
const entries: RelationEntryLike[] = [
|
|
{ subjectId: 1, targetId: 2, delta: 15, mutual: true, occurredAt: now.toISOString() },
|
|
];
|
|
expect(directedScore(entries, 1, 2, now)).toBe(15);
|
|
expect(directedScore(entries, 2, 1, now)).toBe(15);
|
|
});
|
|
|
|
it("excludes voided entries from every direction", () => {
|
|
const now = new Date();
|
|
const entries: RelationEntryLike[] = [
|
|
{
|
|
subjectId: 1,
|
|
targetId: 2,
|
|
delta: -60,
|
|
voided: true,
|
|
mutual: true,
|
|
occurredAt: now.toISOString(),
|
|
},
|
|
{ subjectId: 1, targetId: 2, delta: -10, occurredAt: now.toISOString() },
|
|
];
|
|
expect(directedScore(entries, 1, 2, now)).toBe(-10);
|
|
expect(directedScore(entries, 2, 1, now)).toBe(0);
|
|
});
|
|
|
|
it("clamps the sum to the documented range", () => {
|
|
const now = new Date();
|
|
const entries: RelationEntryLike[] = Array.from({ length: 5 }, () => ({
|
|
subjectId: 1,
|
|
targetId: 2,
|
|
delta: -40,
|
|
occurredAt: now.toISOString(),
|
|
}));
|
|
expect(directedScore(entries, 1, 2, now)).toBe(RELATION_MIN);
|
|
const positive = entries.map((entry) => ({ ...entry, delta: 40 }));
|
|
expect(directedScore(positive, 1, 2, now)).toBe(RELATION_MAX);
|
|
});
|
|
|
|
it("halves a decaying entry per half-life and leaves others untouched", () => {
|
|
const now = new Date("2026-03-01T00:00:00.000Z");
|
|
const fading: RelationEntryLike = {
|
|
subjectId: 1,
|
|
targetId: 2,
|
|
delta: 20,
|
|
decays: true,
|
|
occurredAt: new Date(now.getTime() - 31 * DAY).toISOString(),
|
|
};
|
|
const lasting: RelationEntryLike = {
|
|
subjectId: 1,
|
|
targetId: 2,
|
|
delta: 20,
|
|
occurredAt: new Date(now.getTime() - 400 * DAY).toISOString(),
|
|
};
|
|
expect(effectiveDelta(fading, now, 30)).toBe(10);
|
|
expect(effectiveDelta(lasting, now, 30)).toBe(20);
|
|
|
|
// Not a full period yet: decay has not started.
|
|
const fresh: RelationEntryLike = {
|
|
...fading,
|
|
occurredAt: new Date(now.getTime() - 5 * DAY).toISOString(),
|
|
};
|
|
expect(effectiveDelta(fresh, now, 30)).toBe(20);
|
|
});
|
|
|
|
it("maps every directed pair in one pass, mutuals included", () => {
|
|
const now = new Date();
|
|
const scores = directedScoreMap(
|
|
[
|
|
{ subjectId: 1, targetId: 2, delta: -25, occurredAt: now.toISOString() },
|
|
{
|
|
subjectId: 3,
|
|
targetId: 1,
|
|
delta: 10,
|
|
mutual: true,
|
|
occurredAt: now.toISOString(),
|
|
},
|
|
],
|
|
now,
|
|
);
|
|
expect(scores.get("1:2")).toBe(-25);
|
|
expect(scores.get("3:1")).toBe(10);
|
|
expect(scores.get("1:3")).toBe(10);
|
|
expect(scores.get("2:1")).toBeUndefined();
|
|
});
|
|
|
|
it("labels bands on the thresholds the UI has always used", () => {
|
|
expect(relationBand(50).label).toBe("Allied");
|
|
expect(relationBand(20).label).toBe("Friendly");
|
|
expect(relationBand(0).label).toBe("Neutral");
|
|
expect(relationBand(-20).label).toBe("Tense");
|
|
expect(relationBand(-50).label).toBe("Hostile");
|
|
});
|
|
});
|
|
|
|
describe("visibility", () => {
|
|
it("hides a voided entry from a plain reader but keeps it for a manager", async () => {
|
|
const entry = await makeEntry({ subject: a, target: b, voided: true });
|
|
|
|
const asReader = await readEntriesAs(reader, { id: { equals: entry.id } });
|
|
expect(asReader).toHaveLength(0);
|
|
|
|
const asManager = await readEntriesAs(gm, { id: { equals: entry.id } });
|
|
expect(asManager).toHaveLength(1);
|
|
});
|
|
|
|
it("still counts a hidden entry while censoring what explains it", async () => {
|
|
const hidden = await makeEntry({
|
|
subject: a,
|
|
target: b,
|
|
severity: "major",
|
|
hiddenFromPlayers: true,
|
|
summary: "Worldmark paid us off.",
|
|
notes: "Players must not learn this yet.",
|
|
});
|
|
|
|
const asReader = await readEntriesAs(reader, { id: { equals: hidden.id } });
|
|
expect(asReader).toHaveLength(1);
|
|
expect(asReader[0].delta).toBe(-20);
|
|
expect(asReader[0].summary).toBe("");
|
|
expect(asReader[0].notes ?? null).toBeNull();
|
|
|
|
const asManager = await readEntriesAs(gm, { id: { equals: hidden.id } });
|
|
expect(asManager[0].summary).toBe("Worldmark paid us off.");
|
|
expect(asManager[0].notes).toBe("Players must not learn this yet.");
|
|
});
|
|
|
|
it("never exposes GM notes on an ordinary entry", async () => {
|
|
const entry = await makeEntry({
|
|
subject: a,
|
|
target: b,
|
|
summary: "We helped them.",
|
|
notes: "They do not know why yet.",
|
|
});
|
|
|
|
const asReader = await readEntriesAs(reader, { id: { equals: entry.id } });
|
|
expect(asReader).toHaveLength(1);
|
|
expect(asReader[0].summary).toBe("We helped them.");
|
|
expect(asReader[0].notes ?? null).toBeNull();
|
|
expect(asReader[0].recordedBy ?? null).toBeNull();
|
|
|
|
const asManager = await readEntriesAs(gm, { id: { equals: entry.id } });
|
|
expect(asManager[0].notes).toBe("They do not know why yet.");
|
|
expect(asManager[0].recordedBy).toBe(gm.id);
|
|
});
|
|
|
|
it("gives a player the same score a manager computes from a hidden entry", async () => {
|
|
const subject = await makeFaction("HiddenSubject");
|
|
const target = await makeFaction("HiddenTarget");
|
|
await makeEntry({ subject, target, severity: "major" });
|
|
await makeEntry({ subject, target, severity: "decisive", hiddenFromPlayers: true });
|
|
|
|
const asReader = await getRelationContext(payload, reader as never);
|
|
const asManager = await getRelationContext(payload, gm as never);
|
|
|
|
expect(asReader.scores.get(`${subject}:${target}`)).toBe(-60);
|
|
expect(asManager.scores.get(`${subject}:${target}`)).toBe(-60);
|
|
// The hidden row moves the number but never appears in the timeline.
|
|
expect(asManager.rows.filter((row) => row.subjectId === subject)).toHaveLength(1);
|
|
expect(asReader.rows.filter((row) => row.subjectId === subject)).toHaveLength(1);
|
|
});
|
|
|
|
it("keeps entries naming an undiscovered faction away from plain readers", async () => {
|
|
const visible = await makeFaction("Discovered");
|
|
await makeEntry({ subject: visible, target: secret, severity: "major" });
|
|
|
|
const asReader = await getRelationContext(payload, reader as never);
|
|
expect(asReader.scores.get(`${visible}:${secret}`)).toBeUndefined();
|
|
|
|
const asRevealer = await getRelationContext(payload, revealer as never);
|
|
expect(asRevealer.scores.get(`${visible}:${secret}`)).toBe(-20);
|
|
});
|
|
|
|
it("splits a faction's history into inbound and outbound rows", async () => {
|
|
const subject = await makeFaction("HistSubject");
|
|
const target = await makeFaction("HistTarget");
|
|
await makeEntry({ subject, target, severity: "notable" });
|
|
await makeEntry({ subject: target, target: subject, severity: "major", polarity: "beneficial" });
|
|
|
|
const context = await getRelationContext(payload, gm as never);
|
|
const history = historyFor(context, subject);
|
|
expect(history.outbound).toHaveLength(1);
|
|
expect(history.inbound).toHaveLength(1);
|
|
expect(history.outbound[0].delta).toBe(-10);
|
|
expect(history.inbound[0].delta).toBe(20);
|
|
});
|
|
});
|
|
});
|