1
0
Fork 0
polaris-task-force/src/lib/intelligence/factionRelationLedger.ts
Z8MB1E 2384c7f5a4 feat(intelligence): add the faction relation ledger collection and score math
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.
2026-11-18 14:13:20 -05:00

237 lines
6.9 KiB
TypeScript

/**
* Server-side reads over the faction relation ledger.
*
* Every surface that shows a relationship goes through here so the visibility
* rules exist in exactly one place:
* - Reads run with the caller's user (never `overrideAccess: true`), so the
* collection's own read access drops voided entries, and its afterRead hook
* censors hidden ones.
* - Undiscovered factions are masked on the Factions collection, not on this
* ledger, so entries naming an undiscovered faction are filtered here for
* readers without `factions:view-undiscovered`.
*
* The math itself lives in `./factionRelations` and stays pure.
*/
import type { Payload } from "payload";
import { canViewUndiscoveredFactions } from "@/lib/intelligence/factionDiscovery";
import {
DEFAULT_DECAY_HALF_LIFE_DAYS,
directedScoreMap,
effectiveDelta,
type RelationEntryLike,
} from "@/lib/intelligence/factionRelations";
type UserLike = { id: number | string; roleDocs?: unknown } | null | undefined;
export interface RelationFactionRef {
id: number;
name: string;
type: string;
discovered: boolean;
}
export interface RelationLedgerRow {
id: number;
subjectId: number;
targetId: number;
/** Effective amount right now, decayed when the entry fades. */
delta: number;
mutual: boolean;
severity: string;
category: string;
summary: string;
occurredAt: string;
decays: boolean;
missionId: number | null;
campaignId: number | null;
}
export interface RelationContext {
factions: RelationFactionRef[];
/** Player-safe entries, newest first. Voided and hidden rows excluded. */
rows: RelationLedgerRow[];
/** Directed scores keyed by `subjectId:targetId`. */
scores: Map<string, number>;
halfLifeDays: number;
}
const EMPTY: RelationContext = {
factions: [],
rows: [],
scores: new Map(),
halfLifeDays: DEFAULT_DECAY_HALF_LIFE_DAYS,
};
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value && typeof value === "object" && "id" in value) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
interface RawEntry {
id: number;
subject: unknown;
target: unknown;
delta: number;
mutual?: boolean | null;
severity?: string | null;
category?: string | null;
summary?: string | null;
occurredAt?: string | null;
decays?: boolean | null;
hiddenFromPlayers?: boolean | null;
voided?: boolean | null;
mission?: unknown;
campaign?: unknown;
}
interface RawFaction {
id: number;
name?: string | null;
type?: string | null;
discovered?: boolean | null;
}
/** Configured decay half-life, falling back to the documented default. */
export async function getRelationHalfLifeDays(payload: Payload): Promise<number> {
const rules = await payload
.findGlobal({ slug: "game-rules", depth: 0 })
.catch(() => null);
const configured = (rules as { factionRelations?: { decayHalfLifeDays?: number | null } } | null)
?.factionRelations?.decayHalfLifeDays;
const value = Number(configured);
return Number.isFinite(value) && value >= 1 ? value : DEFAULT_DECAY_HALF_LIFE_DAYS;
}
/**
* One read for both relation surfaces: the faction list, the player-safe
* entries, and every directed score computed from them.
*/
export async function getRelationContext(
payload: Payload,
user: UserLike,
now: Date = new Date(),
): Promise<RelationContext> {
if (!user) return EMPTY;
const [halfLifeDays, factionsRes, entriesRes, canSeeUndiscovered] = await Promise.all([
getRelationHalfLifeDays(payload),
payload.find({
collection: "factions",
limit: 200,
depth: 0,
sort: "name",
pagination: false,
user,
overrideAccess: false,
}),
payload.find({
collection: "faction-relation-entries",
limit: 500,
depth: 0,
sort: "-occurredAt",
pagination: false,
user,
overrideAccess: false,
}),
canViewUndiscoveredFactions(payload, user),
]);
const factions: RelationFactionRef[] = (factionsRes.docs as RawFaction[]).map((doc) => ({
id: doc.id,
name: doc.name ?? `Faction #${doc.id}`,
type: doc.type ?? "minorFaction",
discovered: doc.discovered !== false,
}));
const undiscoveredIds = new Set(
factions.filter((faction) => !faction.discovered).map((faction) => faction.id),
);
const displayRows: RelationLedgerRow[] = [];
const mathEntries: RelationEntryLike[] = [];
for (const doc of entriesRes.docs as RawEntry[]) {
const voided = doc.voided === true;
if (voided) continue;
// Hidden entries still move the score; they are censored by the
// collection's afterRead hook and excluded here from the list the players
// read, so the effect shows up while the cause does not.
const hidden = doc.hiddenFromPlayers === true;
const subjectId = relId(doc.subject);
const targetId = relId(doc.target);
if (subjectId == null || targetId == null) continue;
// Never let the ledger name a faction the reader has not discovered.
if (!canSeeUndiscovered && (undiscoveredIds.has(subjectId) || undiscoveredIds.has(targetId))) {
continue;
}
const occurredAt = doc.occurredAt ?? new Date(0).toISOString();
const entry: RelationEntryLike = {
subjectId,
targetId,
delta: doc.delta,
mutual: doc.mutual === true,
decays: doc.decays === true,
occurredAt,
voided,
};
mathEntries.push(entry);
if (!hidden) {
displayRows.push({
id: doc.id,
subjectId,
targetId,
delta: effectiveDelta(entry, now, halfLifeDays),
mutual: entry.mutual === true,
severity: doc.severity ?? "custom",
category: doc.category ?? "other",
summary: doc.summary ?? "",
occurredAt,
decays: entry.decays === true,
missionId: relId(doc.mission),
campaignId: relId(doc.campaign),
});
}
}
return {
factions,
rows: displayRows,
scores: directedScoreMap(mathEntries, now, halfLifeDays),
halfLifeDays,
};
}
export interface FactionRelationHistory {
inbound: RelationLedgerRow[];
outbound: RelationLedgerRow[];
}
/**
* Entries touching one faction, split by direction: what others did to this
* faction's standing with them, and what this faction's own events were.
* Mutual entries appear in both lists.
*/
export function historyFor(
context: RelationContext,
factionId: number,
): FactionRelationHistory {
const inbound: RelationLedgerRow[] = [];
const outbound: RelationLedgerRow[] = [];
for (const row of context.rows) {
if (row.subjectId === factionId) outbound.push(row);
if (row.targetId === factionId) inbound.push(row);
}
return { inbound, outbound };
}
/** Faction display names by id, for entry rendering. */
export function factionNameMap(context: RelationContext): Map<number, string> {
return new Map(context.factions.map((faction) => [faction.id, faction.name]));
}