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.
This commit is contained in:
parent
e15b0923ad
commit
2384c7f5a4
12 changed files with 48214 additions and 74 deletions
|
|
@ -313,6 +313,27 @@ export const GameRules: GlobalConfig = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "factionRelations",
|
||||
type: "group",
|
||||
label: "Faction Relations",
|
||||
admin: {
|
||||
description:
|
||||
"Tunables for the faction relations ledger (faction-relation-entries). Every pairwise score is computed on read from the ledger; nothing is stored on the faction records.",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "decayHalfLifeDays",
|
||||
type: "number",
|
||||
min: 1,
|
||||
defaultValue: 30,
|
||||
admin: {
|
||||
description:
|
||||
"Half-life, in days, of a decaying relation entry. A decaying entry keeps full weight until one period elapses, then halves per completed period. Entries without the Decays flag never fade.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "zonePressureEnabled",
|
||||
type: "checkbox",
|
||||
|
|
|
|||
374
src/collections/intelligence/FactionRelationEntries.ts
Normal file
374
src/collections/intelligence/FactionRelationEntries.ts
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
import type { CollectionConfig, Payload, PayloadRequest, Where } from "payload";
|
||||
import { hasPermission, requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import {
|
||||
RELATION_POLARITIES,
|
||||
RELATION_SEVERITY_DELTAS,
|
||||
relationCategoryOptions,
|
||||
relationSeverityOptions,
|
||||
} from "@/lib/intelligence/factionRelations";
|
||||
|
||||
const readOnly = { admin: { readOnly: true } } as const;
|
||||
|
||||
/** Ledger managers: the admin-page permission holder or a superuser tier user. */
|
||||
async function canManageLedger(
|
||||
payload: Payload,
|
||||
user: PayloadRequest["user"],
|
||||
): Promise<boolean> {
|
||||
if (!user) return false;
|
||||
const [manages, adminTier] = await Promise.all([
|
||||
hasPermission(payload, user, "admin:faction-relation-entries:manage"),
|
||||
hasPermission(payload, user, "system:admin-access"),
|
||||
]);
|
||||
return manages || adminTier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Field-level read gate for GM-only columns. Payload hides a field whose read
|
||||
* access denies, which is what keeps `notes` out of every non-manager response
|
||||
* (REST, local API and the ledger module).
|
||||
*/
|
||||
const managerOnlyField = {
|
||||
access: {
|
||||
read: async ({ req }: { req: PayloadRequest }) => canManageLedger(req.payload, req.user),
|
||||
},
|
||||
};
|
||||
|
||||
function relationId(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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append-only ledger of events that move faction relationships.
|
||||
*
|
||||
* Nothing on the faction records stores a pairwise score any more: every
|
||||
* relationship value shown anywhere is computed from these rows by
|
||||
* `src/lib/intelligence/factionRelations.ts`. That keeps a single source of
|
||||
* truth, so a score can never disagree with the history that produced it.
|
||||
*
|
||||
* Write semantics:
|
||||
* - Entries are editable, because fixing a wrong delta should not cost two
|
||||
* rows.
|
||||
* - Deletion is denied outright. An event that never happened is voided: the
|
||||
* row stays visible in the admin panel, is excluded from every sum, and is
|
||||
* hidden from players.
|
||||
*
|
||||
* Visibility:
|
||||
* - `summary` is player-facing. `notes` is GM-only and never leaves the admin
|
||||
* panel.
|
||||
* - `hiddenFromPlayers` entries still move the score; they are excluded from
|
||||
* the player-facing list only, which is how a covert cause can have a
|
||||
* visible effect.
|
||||
*/
|
||||
export const FactionRelationEntries: CollectionConfig = {
|
||||
slug: "faction-relation-entries",
|
||||
labels: { singular: "Relation Entry", plural: "Relation Entries" },
|
||||
admin: {
|
||||
group: "Intelligence",
|
||||
useAsTitle: "summary",
|
||||
defaultColumns: ["subject", "target", "delta", "severity", "category", "occurredAt", "voided"],
|
||||
description:
|
||||
"Ledger behind every faction relationship score. Add an entry for each thing that changed one faction's attitude toward another; scores are computed from these rows, never typed in.",
|
||||
},
|
||||
access: {
|
||||
// Managers (and the superuser tier) see the whole ledger, voided rows
|
||||
// included, which is also the admin-panel path. Everyone else sees live
|
||||
// entries only; the Factions collection is readable by any logged-in user,
|
||||
// so this matches it.
|
||||
//
|
||||
// Hidden entries are NOT filtered here: they have to reach the score, since
|
||||
// a covert cause is supposed to move a score the players can see. The
|
||||
// `afterRead` hook censors their content instead, and the read module keeps
|
||||
// them out of the player-facing timeline.
|
||||
read: async ({ req }): Promise<boolean | Where> => {
|
||||
if (!req.user) return false;
|
||||
if (await canManageLedger(req.payload, req.user)) return true;
|
||||
return { voided: { not_equals: true } };
|
||||
},
|
||||
create: requirePermission("faction-relation-entries:create"),
|
||||
update: requirePermission("faction-relation-entries:update"),
|
||||
// Voiding is the only removal path: an audit trail is the point of a ledger.
|
||||
delete: () => false,
|
||||
},
|
||||
hooks: {
|
||||
// Strip a hidden entry down to what the score needs for anyone who is not a
|
||||
// ledger manager. The faction pair, delta, date and decay flag stay (all of
|
||||
// them are needed for an identical score on both sides, and the score is
|
||||
// public anyway); everything that explains the event goes: summary, notes,
|
||||
// category, mission, campaign and the admin-only audit stamps.
|
||||
afterRead: [
|
||||
async ({ doc, req }) => {
|
||||
if (!doc || doc.hiddenFromPlayers !== true) return doc;
|
||||
if (await canManageLedger(req.payload, req.user)) return doc;
|
||||
return {
|
||||
...doc,
|
||||
summary: "",
|
||||
notes: null,
|
||||
category: "other",
|
||||
mission: null,
|
||||
campaign: null,
|
||||
voidedReason: null,
|
||||
voidedAt: null,
|
||||
voidedBy: null,
|
||||
recordedBy: null,
|
||||
};
|
||||
},
|
||||
],
|
||||
beforeValidate: [
|
||||
async ({ data, originalDoc }) => {
|
||||
if (!data) return data;
|
||||
const merged = { ...(originalDoc ?? {}), ...data } as Record<string, unknown>;
|
||||
|
||||
const subjectId = relationId(merged.subject);
|
||||
const targetId = relationId(merged.target);
|
||||
if (subjectId != null && targetId != null && subjectId === targetId) {
|
||||
throw new Error(
|
||||
"A relation entry needs two different factions: the one whose attitude changes and the one it is about.",
|
||||
);
|
||||
}
|
||||
|
||||
const severity = merged.severity as string | undefined;
|
||||
const polarity = merged.polarity as string | undefined;
|
||||
|
||||
if (severity && severity !== "custom") {
|
||||
const magnitude = RELATION_SEVERITY_DELTAS[severity as keyof typeof RELATION_SEVERITY_DELTAS];
|
||||
if (magnitude == null) return data;
|
||||
data.delta = polarity === "detrimental" ? -magnitude : magnitude;
|
||||
return data;
|
||||
}
|
||||
|
||||
if (severity === "custom") {
|
||||
const delta = Number(merged.delta);
|
||||
if (!Number.isFinite(delta) || delta === 0) {
|
||||
throw new Error("A custom severity needs a non-zero delta.");
|
||||
}
|
||||
// Keep the two fields honest: the sign of the number IS the polarity.
|
||||
data.polarity = delta > 0 ? "beneficial" : "detrimental";
|
||||
}
|
||||
|
||||
return data;
|
||||
},
|
||||
],
|
||||
beforeChange: [
|
||||
async ({ data, originalDoc, operation, req }) => {
|
||||
const wasVoided = Boolean((originalDoc as { voided?: boolean } | undefined)?.voided);
|
||||
const isVoided = Boolean(data.voided);
|
||||
|
||||
if (!wasVoided && isVoided) {
|
||||
data.voidedAt = new Date().toISOString();
|
||||
data.voidedBy = req.user?.id ?? null;
|
||||
} else if (wasVoided && !isVoided) {
|
||||
data.voidedAt = null;
|
||||
data.voidedBy = null;
|
||||
data.voidedReason = null;
|
||||
}
|
||||
|
||||
if (operation === "create" && req.user) {
|
||||
data.recordedBy = req.user.id;
|
||||
}
|
||||
|
||||
return data;
|
||||
},
|
||||
],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
type: "row",
|
||||
fields: [
|
||||
{
|
||||
name: "subject",
|
||||
type: "relationship",
|
||||
relationTo: "factions",
|
||||
required: true,
|
||||
index: true,
|
||||
admin: {
|
||||
width: "50%",
|
||||
description: "The faction whose attitude changes.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "target",
|
||||
type: "relationship",
|
||||
relationTo: "factions",
|
||||
required: true,
|
||||
index: true,
|
||||
admin: {
|
||||
width: "50%",
|
||||
description: "The faction the attitude is about.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "mutual",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Count this event for both directions (a shared battle, a treaty both sides signed). Leave unchecked when only the subject's attitude moves.",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "row",
|
||||
fields: [
|
||||
{
|
||||
name: "polarity",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "detrimental",
|
||||
options: [
|
||||
{ label: "Beneficial (improves the relationship)", value: RELATION_POLARITIES[0] },
|
||||
{ label: "Detrimental (worsens the relationship)", value: RELATION_POLARITIES[1] },
|
||||
],
|
||||
admin: {
|
||||
width: "50%",
|
||||
description: "Which way the attitude moves. Ignored for a custom delta, derived from its sign.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "severity",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "notable",
|
||||
options: relationSeverityOptions(),
|
||||
admin: {
|
||||
width: "50%",
|
||||
description:
|
||||
"How large the move is. The tier sets the delta; pick Custom to type an exact number.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "delta",
|
||||
type: "number",
|
||||
required: true,
|
||||
min: -100,
|
||||
max: 100,
|
||||
admin: {
|
||||
condition: (data) => data?.severity === "custom",
|
||||
description:
|
||||
"Signed exact amount for a custom entry, -100 to 100. Positive improves the relationship.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
type: "select",
|
||||
required: true,
|
||||
index: true,
|
||||
defaultValue: "other",
|
||||
options: relationCategoryOptions(),
|
||||
admin: {
|
||||
description: "What kind of event this was. Labels the entry; never changes the score.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "summary",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: {
|
||||
description:
|
||||
"One line the players will read, in plain language. This is the explanation attached to the score change.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "notes",
|
||||
type: "textarea",
|
||||
...managerOnlyField,
|
||||
admin: {
|
||||
description:
|
||||
"GM-only reasoning. Never shown to players, so it is safe for speculation and spoilers.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "occurredAt",
|
||||
type: "date",
|
||||
required: true,
|
||||
index: true,
|
||||
defaultValue: () => new Date().toISOString(),
|
||||
admin: {
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
description:
|
||||
"When it happened in the fiction. Drives the timeline order and, for decaying entries, how far it has faded.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "decays",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Transient events fade: the delta halves per half-life (GameRules > Faction Relations). Leave unchecked for lasting shifts like a treaty or a betrayal.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "hiddenFromPlayers",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Counts toward the score but never appears in the player-facing list. Use it when the effect is visible but the cause is not.",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "row",
|
||||
fields: [
|
||||
{
|
||||
name: "mission",
|
||||
type: "relationship",
|
||||
relationTo: "missions",
|
||||
index: true,
|
||||
admin: { width: "50%", description: "Optional: the operation that caused it." },
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
type: "relationship",
|
||||
relationTo: "campaigns",
|
||||
index: true,
|
||||
admin: { width: "50%", description: "Optional: the campaign arc it belongs to." },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "collapsible",
|
||||
label: "Voiding",
|
||||
admin: {
|
||||
description:
|
||||
"Void an entry that should never have counted. It stays here for the record, struck through, and is excluded from every score.",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "voided",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
index: true,
|
||||
admin: { description: "Excluded from every score and hidden from players." },
|
||||
},
|
||||
{ name: "voidedAt", type: "date", ...readOnly, ...managerOnlyField },
|
||||
{
|
||||
name: "voidedBy",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
...readOnly,
|
||||
...managerOnlyField,
|
||||
},
|
||||
{
|
||||
name: "voidedReason",
|
||||
type: "textarea",
|
||||
...managerOnlyField,
|
||||
admin: { description: "Why it was voided." },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "recordedBy",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
...readOnly,
|
||||
...managerOnlyField,
|
||||
},
|
||||
],
|
||||
};
|
||||
237
src/lib/intelligence/factionRelationLedger.ts
Normal file
237
src/lib/intelligence/factionRelationLedger.ts
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
/**
|
||||
* 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]));
|
||||
}
|
||||
240
src/lib/intelligence/factionRelations.ts
Normal file
240
src/lib/intelligence/factionRelations.ts
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
/**
|
||||
* Faction relation math (pure, client-safe).
|
||||
*
|
||||
* Pairwise faction attitudes are derived, never stored: every value rendered
|
||||
* anywhere comes from summing the live entries of `faction-relation-entries`
|
||||
* for one direction. This module holds the whole model so both read surfaces
|
||||
* (the faction detail page and the relations matrix) agree by construction.
|
||||
*
|
||||
* Two axes that must not be confused:
|
||||
* - `factions.reputation` is a faction's standing in the world at large. It is
|
||||
* still hand-edited and does not appear here.
|
||||
* - A relation entry moves ONE faction's attitude toward ONE other faction
|
||||
* (or both, when the entry is flagged `mutual`).
|
||||
*
|
||||
* Deltas are signed: positive means the attitude improved (more favorable),
|
||||
* negative means it worsened. Scores are clamped to +/-100 so the existing bar
|
||||
* and badge treatments keep meaning what they meant.
|
||||
*/
|
||||
|
||||
/** Magnitude applied by each severity tier. `custom` takes a typed number. */
|
||||
export const RELATION_SEVERITY_DELTAS = {
|
||||
minor: 5,
|
||||
notable: 10,
|
||||
major: 20,
|
||||
decisive: 40,
|
||||
} as const;
|
||||
|
||||
export type RelationSeverityTier = keyof typeof RELATION_SEVERITY_DELTAS;
|
||||
|
||||
export const RELATION_SEVERITIES = [
|
||||
"minor",
|
||||
"notable",
|
||||
"major",
|
||||
"decisive",
|
||||
"custom",
|
||||
] as const;
|
||||
|
||||
export type RelationSeverity = (typeof RELATION_SEVERITIES)[number];
|
||||
|
||||
export const RELATION_POLARITIES = ["beneficial", "detrimental"] as const;
|
||||
|
||||
export type RelationPolarity = (typeof RELATION_POLARITIES)[number];
|
||||
|
||||
/**
|
||||
* What kind of event moved the score. Bookkeeping only: the category never
|
||||
* changes the number, it exists so the ledger can be filtered and so the
|
||||
* player-facing list can show a meaningful chip.
|
||||
*/
|
||||
export const RELATION_CATEGORIES = [
|
||||
"aid",
|
||||
"betrayal",
|
||||
"combat",
|
||||
"diplomacy",
|
||||
"espionage",
|
||||
"trade",
|
||||
"other",
|
||||
] as const;
|
||||
|
||||
export type RelationCategory = (typeof RELATION_CATEGORIES)[number];
|
||||
|
||||
export const RELATION_MIN = -100;
|
||||
export const RELATION_MAX = 100;
|
||||
|
||||
/** Fallback when the GameRules global has no value set. */
|
||||
export const DEFAULT_DECAY_HALF_LIFE_DAYS = 30;
|
||||
|
||||
/** The minimum shape the math needs. Payload documents are adapted to this. */
|
||||
export interface RelationEntryLike {
|
||||
subjectId: number;
|
||||
targetId: number;
|
||||
delta: number;
|
||||
mutual?: boolean | null;
|
||||
decays?: boolean | null;
|
||||
occurredAt: string;
|
||||
voided?: boolean | null;
|
||||
}
|
||||
|
||||
export interface RelationBand {
|
||||
key: "allied" | "friendly" | "neutral" | "tense" | "hostile";
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const RELATION_BANDS: RelationBand[] = [
|
||||
{ key: "allied", label: "Allied" },
|
||||
{ key: "friendly", label: "Friendly" },
|
||||
{ key: "neutral", label: "Neutral" },
|
||||
{ key: "tense", label: "Tense" },
|
||||
{ key: "hostile", label: "Hostile" },
|
||||
];
|
||||
|
||||
/** Tailwind classes per band, shared so both surfaces look the same. */
|
||||
export const RELATION_BAND_CLASSES: Record<RelationBand["key"], { bar: string; text: string }> =
|
||||
{
|
||||
allied: { bar: "bg-emerald-500", text: "text-emerald-400" },
|
||||
friendly: { bar: "bg-green-500", text: "text-green-400" },
|
||||
neutral: { bar: "bg-muted-foreground", text: "text-muted-foreground" },
|
||||
tense: { bar: "bg-amber-500", text: "text-amber-400" },
|
||||
hostile: { bar: "bg-red-500", text: "text-red-400" },
|
||||
};
|
||||
|
||||
/** Clamp a computed score into the documented range. */
|
||||
export function clampScore(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.max(RELATION_MIN, Math.min(RELATION_MAX, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Weight of a decaying entry: full until one half-life period has elapsed, then
|
||||
* halved per completed period. Same shape as the zone-pressure decay so the two
|
||||
* systems age the same way.
|
||||
*/
|
||||
export function decayWeight(
|
||||
occurredAt: string,
|
||||
now: Date,
|
||||
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
|
||||
): number {
|
||||
const period = Math.max(1, halfLifeDays);
|
||||
const occurred = new Date(occurredAt).getTime();
|
||||
if (!Number.isFinite(occurred)) return 1;
|
||||
const elapsedDays = Math.max(0, (now.getTime() - occurred) / 86_400_000);
|
||||
const periods = Math.floor(elapsedDays / period);
|
||||
return 1 / 2 ** periods;
|
||||
}
|
||||
|
||||
/**
|
||||
* The amount one entry contributes to a score right now. Voided entries
|
||||
* contribute nothing at all; non-decaying entries keep their full delta.
|
||||
*/
|
||||
export function effectiveDelta(
|
||||
entry: RelationEntryLike,
|
||||
now: Date,
|
||||
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
|
||||
): number {
|
||||
if (entry.voided) return 0;
|
||||
if (!entry.decays) return entry.delta;
|
||||
return entry.delta * decayWeight(entry.occurredAt, now, halfLifeDays);
|
||||
}
|
||||
|
||||
/**
|
||||
* How `subjectId` currently regards `targetId`, clamped to the documented
|
||||
* range. Mutual entries count for both directions, so a shared event moves
|
||||
* both attitudes by the same amount.
|
||||
*/
|
||||
export function directedScore(
|
||||
entries: RelationEntryLike[],
|
||||
subjectId: number,
|
||||
targetId: number,
|
||||
now: Date,
|
||||
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
|
||||
): number {
|
||||
if (subjectId === targetId) return 0;
|
||||
let total = 0;
|
||||
for (const entry of entries) {
|
||||
const forward = entry.subjectId === subjectId && entry.targetId === targetId;
|
||||
const backward =
|
||||
entry.mutual === true && entry.subjectId === targetId && entry.targetId === subjectId;
|
||||
if (!forward && !backward) continue;
|
||||
total += effectiveDelta(entry, now, halfLifeDays);
|
||||
}
|
||||
return Math.round(clampScore(total) * 10) / 10;
|
||||
}
|
||||
|
||||
/** Stable key for the directed pair map. */
|
||||
export function pairKey(subjectId: number, targetId: number): string {
|
||||
return `${subjectId}:${targetId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every directed score in one pass, keyed by `subjectId:targetId`. Used by the
|
||||
* matrix so it never issues a query (or a nested loop) per pair.
|
||||
*/
|
||||
export function directedScoreMap(
|
||||
entries: RelationEntryLike[],
|
||||
now: Date,
|
||||
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
|
||||
): Map<string, number> {
|
||||
const totals = new Map<string, number>();
|
||||
const add = (subjectId: number, targetId: number, amount: number) => {
|
||||
if (subjectId === targetId) return;
|
||||
const key = pairKey(subjectId, targetId);
|
||||
totals.set(key, (totals.get(key) ?? 0) + amount);
|
||||
};
|
||||
|
||||
for (const entry of entries) {
|
||||
const amount = effectiveDelta(entry, now, halfLifeDays);
|
||||
if (amount === 0) continue;
|
||||
add(entry.subjectId, entry.targetId, amount);
|
||||
if (entry.mutual === true) add(entry.targetId, entry.subjectId, amount);
|
||||
}
|
||||
|
||||
for (const [key, value] of totals) {
|
||||
totals.set(key, Math.round(clampScore(value) * 10) / 10);
|
||||
}
|
||||
return totals;
|
||||
}
|
||||
|
||||
/** Band label for a score. Thresholds match the pre-ledger UI. */
|
||||
export function relationBand(score: number): RelationBand {
|
||||
if (score >= 50) return RELATION_BANDS[0];
|
||||
if (score >= 20) return RELATION_BANDS[1];
|
||||
if (score > -20) return RELATION_BANDS[2];
|
||||
if (score > -50) return RELATION_BANDS[3];
|
||||
return RELATION_BANDS[4];
|
||||
}
|
||||
|
||||
/** Select options for the ledger form, with the magnitude spelled out. */
|
||||
export function relationSeverityOptions(): { label: string; value: RelationSeverity }[] {
|
||||
return [
|
||||
{ label: `Minor (+/-${RELATION_SEVERITY_DELTAS.minor})`, value: "minor" },
|
||||
{ label: `Notable (+/-${RELATION_SEVERITY_DELTAS.notable})`, value: "notable" },
|
||||
{ label: `Major (+/-${RELATION_SEVERITY_DELTAS.major})`, value: "major" },
|
||||
{ label: `Decisive (+/-${RELATION_SEVERITY_DELTAS.decisive})`, value: "decisive" },
|
||||
{ label: "Custom (type a number)", value: "custom" },
|
||||
];
|
||||
}
|
||||
|
||||
const CATEGORY_LABELS: Record<RelationCategory, string> = {
|
||||
aid: "Aid",
|
||||
betrayal: "Betrayal",
|
||||
combat: "Combat",
|
||||
diplomacy: "Diplomacy",
|
||||
espionage: "Espionage",
|
||||
trade: "Trade",
|
||||
other: "Other",
|
||||
};
|
||||
|
||||
export function relationCategoryOptions(): { label: string; value: RelationCategory }[] {
|
||||
return RELATION_CATEGORIES.map((value) => ({ label: CATEGORY_LABELS[value], value }));
|
||||
}
|
||||
|
||||
export function relationCategoryLabel(value: string | null | undefined): string {
|
||||
if (!value) return CATEGORY_LABELS.other;
|
||||
return CATEGORY_LABELS[value as RelationCategory] ?? value;
|
||||
}
|
||||
|
||||
/** Signed score for display: `+12`, `-100`, `0`. */
|
||||
export function formatScore(score: number): string {
|
||||
const rounded = Math.round(score * 10) / 10;
|
||||
return rounded > 0 ? `+${rounded}` : `${rounded}`;
|
||||
}
|
||||
46418
src/migrations/20261118_184813_add_faction_relation_entries.json
Normal file
46418
src/migrations/20261118_184813_add_faction_relation_entries.json
Normal file
File diff suppressed because it is too large
Load diff
File diff suppressed because one or more lines are too long
|
|
@ -159,6 +159,7 @@ import * as migration_20261101_210013_add_mission_command_links from './20261101
|
|||
import * as migration_20261112_171955_add_npc_dialogue_generation_provenance from './20261112_171955_add_npc_dialogue_generation_provenance';
|
||||
import * as migration_20261117_212337_add_faction_discovered_field from './20261117_212337_add_faction_discovered_field';
|
||||
import * as migration_20261118_143000_add_wiki_pages_draft_and_created_by from './20261118_143000_add_wiki_pages_draft_and_created_by';
|
||||
import * as migration_20261118_184813_add_faction_relation_entries from './20261118_184813_add_faction_relation_entries';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -959,11 +960,16 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261117_212337_add_faction_discovered_field.up,
|
||||
down: migration_20261117_212337_add_faction_discovered_field.down,
|
||||
name: '20261117_212337_add_faction_discovered_field'
|
||||
name: '20261117_212337_add_faction_discovered_field',
|
||||
},
|
||||
{
|
||||
up: migration_20261118_143000_add_wiki_pages_draft_and_created_by.up,
|
||||
down: migration_20261118_143000_add_wiki_pages_draft_and_created_by.down,
|
||||
name: '20261118_143000_add_wiki_pages_draft_and_created_by'
|
||||
name: '20261118_143000_add_wiki_pages_draft_and_created_by',
|
||||
},
|
||||
{
|
||||
up: migration_20261118_184813_add_faction_relation_entries.up,
|
||||
down: migration_20261118_184813_add_faction_relation_entries.down,
|
||||
name: '20261118_184813_add_faction_relation_entries',
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -208,9 +208,14 @@ export const enum_game_event_logs_required_permissions = pgEnum(
|
|||
"campaigns:manage",
|
||||
"factions:create",
|
||||
"factions:read",
|
||||
"factions:view-undiscovered",
|
||||
"factions:update",
|
||||
"factions:delete",
|
||||
"admin:factions:manage",
|
||||
"faction-relation-entries:create",
|
||||
"faction-relation-entries:read",
|
||||
"faction-relation-entries:update",
|
||||
"admin:faction-relation-entries:manage",
|
||||
"technologies:create",
|
||||
"technologies:read",
|
||||
"technologies:update",
|
||||
|
|
@ -773,9 +778,14 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
|
|||
"campaigns:manage",
|
||||
"factions:create",
|
||||
"factions:read",
|
||||
"factions:view-undiscovered",
|
||||
"factions:update",
|
||||
"factions:delete",
|
||||
"admin:factions:manage",
|
||||
"faction-relation-entries:create",
|
||||
"faction-relation-entries:read",
|
||||
"faction-relation-entries:update",
|
||||
"admin:faction-relation-entries:manage",
|
||||
"technologies:create",
|
||||
"technologies:read",
|
||||
"technologies:update",
|
||||
|
|
@ -1253,6 +1263,18 @@ export const enum_factions_type = pgEnum("enum_factions_type", [
|
|||
"corporation",
|
||||
"special",
|
||||
]);
|
||||
export const enum_faction_relation_entries_polarity = pgEnum(
|
||||
"enum_faction_relation_entries_polarity",
|
||||
["beneficial", "detrimental"],
|
||||
);
|
||||
export const enum_faction_relation_entries_severity = pgEnum(
|
||||
"enum_faction_relation_entries_severity",
|
||||
["minor", "notable", "major", "decisive", "custom"],
|
||||
);
|
||||
export const enum_faction_relation_entries_category = pgEnum(
|
||||
"enum_faction_relation_entries_category",
|
||||
["aid", "betrayal", "combat", "diplomacy", "espionage", "trade", "other"],
|
||||
);
|
||||
export const enum_technologies_approval_status = pgEnum("enum_technologies_approval_status", [
|
||||
"in_progress",
|
||||
"ready_for_review",
|
||||
|
|
@ -2514,6 +2536,15 @@ export const npc_dialogues = pgTable(
|
|||
entryGate_op: enum_npc_dialogues_entry_gate_op("entry_gate_op").default("is_true"),
|
||||
entryGate_amount: numeric("entry_gate_amount", { mode: "number" }),
|
||||
flowData: jsonb("flow_data").notNull(),
|
||||
generation_model: varchar("generation_model"),
|
||||
generation_promptVersion: varchar("generation_prompt_version"),
|
||||
generation_attempts: numeric("generation_attempts", { mode: "number" }),
|
||||
generation_generatedAt: timestamp("generation_generated_at", {
|
||||
mode: "string",
|
||||
withTimezone: true,
|
||||
precision: 3,
|
||||
}),
|
||||
generation_brief: jsonb("generation_brief"),
|
||||
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
|
|
@ -4832,38 +4863,13 @@ export const campaigns = pgTable(
|
|||
],
|
||||
);
|
||||
|
||||
export const factions_relationships = pgTable(
|
||||
"factions_relationships",
|
||||
{
|
||||
_order: integer("_order").notNull(),
|
||||
_parentID: integer("_parent_id").notNull(),
|
||||
id: varchar("id").primaryKey(),
|
||||
targetFaction: integer("target_faction_id")
|
||||
.notNull()
|
||||
.references(() => factions.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
value: numeric("value", { mode: "number" }).notNull().default(0),
|
||||
notes: varchar("notes"),
|
||||
},
|
||||
(columns) => [
|
||||
index("factions_relationships_order_idx").on(columns._order),
|
||||
index("factions_relationships_parent_id_idx").on(columns._parentID),
|
||||
index("factions_relationships_target_faction_idx").on(columns.targetFaction),
|
||||
foreignKey({
|
||||
columns: [columns["_parentID"]],
|
||||
foreignColumns: [factions.id],
|
||||
name: "factions_relationships_parent_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
],
|
||||
);
|
||||
|
||||
export const factions = pgTable(
|
||||
"factions",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
name: varchar("name").notNull(),
|
||||
type: enum_factions_type("type").notNull().default("minorFaction"),
|
||||
discovered: boolean("discovered").default(true),
|
||||
description: jsonb("description"),
|
||||
reputation: numeric("reputation", { mode: "number" }).default(0),
|
||||
playableFaction: boolean("playable_faction"),
|
||||
|
|
@ -4880,6 +4886,7 @@ export const factions = pgTable(
|
|||
},
|
||||
(columns) => [
|
||||
uniqueIndex("factions_name_idx").on(columns.name),
|
||||
index("factions_discovered_idx").on(columns.discovered),
|
||||
index("factions_cover_image_idx").on(columns.coverImage),
|
||||
index("factions_updated_at_idx").on(columns.updatedAt),
|
||||
index("factions_created_at_idx").on(columns.createdAt),
|
||||
|
|
@ -4913,6 +4920,71 @@ export const factions_rels = pgTable(
|
|||
],
|
||||
);
|
||||
|
||||
export const faction_relation_entries = pgTable(
|
||||
"faction_relation_entries",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
subject: integer("subject_id")
|
||||
.notNull()
|
||||
.references(() => factions.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
target: integer("target_id")
|
||||
.notNull()
|
||||
.references(() => factions.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
mutual: boolean("mutual").default(false),
|
||||
polarity: enum_faction_relation_entries_polarity("polarity").notNull().default("detrimental"),
|
||||
severity: enum_faction_relation_entries_severity("severity").notNull().default("notable"),
|
||||
delta: numeric("delta", { mode: "number" }),
|
||||
category: enum_faction_relation_entries_category("category").notNull().default("other"),
|
||||
summary: varchar("summary").notNull(),
|
||||
notes: varchar("notes"),
|
||||
occurredAt: timestamp("occurred_at", {
|
||||
mode: "string",
|
||||
withTimezone: true,
|
||||
precision: 3,
|
||||
}).notNull(),
|
||||
decays: boolean("decays").default(false),
|
||||
hiddenFromPlayers: boolean("hidden_from_players").default(false),
|
||||
mission: integer("mission_id").references(() => missions.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
campaign: integer("campaign_id").references(() => campaigns.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
voided: boolean("voided").default(false),
|
||||
voidedAt: timestamp("voided_at", { mode: "string", withTimezone: true, precision: 3 }),
|
||||
voidedBy: integer("voided_by_id").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
voidedReason: varchar("voided_reason"),
|
||||
recordedBy: integer("recorded_by_id").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
},
|
||||
(columns) => [
|
||||
index("faction_relation_entries_subject_idx").on(columns.subject),
|
||||
index("faction_relation_entries_target_idx").on(columns.target),
|
||||
index("faction_relation_entries_category_idx").on(columns.category),
|
||||
index("faction_relation_entries_occurred_at_idx").on(columns.occurredAt),
|
||||
index("faction_relation_entries_mission_idx").on(columns.mission),
|
||||
index("faction_relation_entries_campaign_idx").on(columns.campaign),
|
||||
index("faction_relation_entries_voided_idx").on(columns.voided),
|
||||
index("faction_relation_entries_voided_by_idx").on(columns.voidedBy),
|
||||
index("faction_relation_entries_recorded_by_idx").on(columns.recordedBy),
|
||||
index("faction_relation_entries_updated_at_idx").on(columns.updatedAt),
|
||||
index("faction_relation_entries_created_at_idx").on(columns.createdAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const technologies_requirements_prerequisite_technologies = pgTable(
|
||||
"technologies_requirements_prerequisite_technologies",
|
||||
{
|
||||
|
|
@ -7221,6 +7293,10 @@ export const wiki_pages = pgTable(
|
|||
}),
|
||||
curation_featured: boolean("curation_featured").default(false),
|
||||
curation_featuredOrder: numeric("curation_featured_order", { mode: "number" }),
|
||||
draft: boolean("draft").default(false),
|
||||
createdBy: integer("created_by_id").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
|
|
@ -7233,6 +7309,7 @@ export const wiki_pages = pgTable(
|
|||
index("wiki_pages_category_idx").on(columns.category),
|
||||
index("wiki_pages_locked_by_idx").on(columns.lockedBy),
|
||||
index("wiki_pages_last_editor_idx").on(columns.lastEditor),
|
||||
index("wiki_pages_created_by_idx").on(columns.createdBy),
|
||||
index("wiki_pages_updated_at_idx").on(columns.updatedAt),
|
||||
index("wiki_pages_created_at_idx").on(columns.createdAt),
|
||||
],
|
||||
|
|
@ -9288,6 +9365,10 @@ export const payload_mcp_api_keys = pgTable(
|
|||
factions_create: boolean("factions_create").default(false),
|
||||
factions_update: boolean("factions_update").default(false),
|
||||
factions_delete: boolean("factions_delete").default(false),
|
||||
factionRelationEntries_find: boolean("faction_relation_entries_find").default(false),
|
||||
factionRelationEntries_create: boolean("faction_relation_entries_create").default(false),
|
||||
factionRelationEntries_update: boolean("faction_relation_entries_update").default(false),
|
||||
factionRelationEntries_delete: boolean("faction_relation_entries_delete").default(false),
|
||||
technologies_find: boolean("technologies_find").default(false),
|
||||
technologies_create: boolean("technologies_create").default(false),
|
||||
technologies_update: boolean("technologies_update").default(false),
|
||||
|
|
@ -9616,6 +9697,7 @@ export const payload_locked_documents_rels = pgTable(
|
|||
"mission-command-linksID": integer("mission_command_links_id"),
|
||||
campaignsID: integer("campaigns_id"),
|
||||
factionsID: integer("factions_id"),
|
||||
"faction-relation-entriesID": integer("faction_relation_entries_id"),
|
||||
technologiesID: integer("technologies_id"),
|
||||
"tech-categoriesID": integer("tech_categories_id"),
|
||||
"tech-researchesID": integer("tech_researches_id"),
|
||||
|
|
@ -9751,6 +9833,9 @@ export const payload_locked_documents_rels = pgTable(
|
|||
),
|
||||
index("payload_locked_documents_rels_campaigns_id_idx").on(columns.campaignsID),
|
||||
index("payload_locked_documents_rels_factions_id_idx").on(columns.factionsID),
|
||||
index("payload_locked_documents_rels_faction_relation_entries_i_idx").on(
|
||||
columns["faction-relation-entriesID"],
|
||||
),
|
||||
index("payload_locked_documents_rels_technologies_id_idx").on(columns.technologiesID),
|
||||
index("payload_locked_documents_rels_tech_categories_id_idx").on(columns["tech-categoriesID"]),
|
||||
index("payload_locked_documents_rels_tech_researches_id_idx").on(columns["tech-researchesID"]),
|
||||
|
|
@ -10056,6 +10141,11 @@ export const payload_locked_documents_rels = pgTable(
|
|||
foreignColumns: [factions.id],
|
||||
name: "payload_locked_documents_rels_factions_fk",
|
||||
}).onDelete("cascade"),
|
||||
foreignKey({
|
||||
columns: [columns["faction-relation-entriesID"]],
|
||||
foreignColumns: [faction_relation_entries.id],
|
||||
name: "payload_locked_documents_rels_faction_relation_entries_fk",
|
||||
}).onDelete("cascade"),
|
||||
foreignKey({
|
||||
columns: [columns["technologiesID"]],
|
||||
foreignColumns: [technologies.id],
|
||||
|
|
@ -10501,6 +10591,9 @@ export const game_rules = pgTable(
|
|||
interior_decayEnabled: boolean("interior_decay_enabled").default(false),
|
||||
interior_decayMultiplier: numeric("interior_decay_multiplier", { mode: "number" }).default(1),
|
||||
interior_assetOutputsEnabled: boolean("interior_asset_outputs_enabled").default(false),
|
||||
factionRelations_decayHalfLifeDays: numeric("faction_relations_decay_half_life_days", {
|
||||
mode: "number",
|
||||
}).default(30),
|
||||
zonePressureEnabled: boolean("zone_pressure_enabled").default(true),
|
||||
statisticsEnabled: boolean("statistics_enabled").default(true),
|
||||
helpdeskEnabled: boolean("helpdesk_enabled").default(true),
|
||||
|
|
@ -11904,18 +11997,6 @@ export const relations_campaigns = relations(campaigns, ({ one }) => ({
|
|||
relationName: "owner",
|
||||
}),
|
||||
}));
|
||||
export const relations_factions_relationships = relations(factions_relationships, ({ one }) => ({
|
||||
_parentID: one(factions, {
|
||||
fields: [factions_relationships._parentID],
|
||||
references: [factions.id],
|
||||
relationName: "relationships",
|
||||
}),
|
||||
targetFaction: one(factions, {
|
||||
fields: [factions_relationships.targetFaction],
|
||||
references: [factions.id],
|
||||
relationName: "targetFaction",
|
||||
}),
|
||||
}));
|
||||
export const relations_factions_rels = relations(factions_rels, ({ one }) => ({
|
||||
parent: one(factions, {
|
||||
fields: [factions_rels.parent],
|
||||
|
|
@ -11929,9 +12010,6 @@ export const relations_factions_rels = relations(factions_rels, ({ one }) => ({
|
|||
}),
|
||||
}));
|
||||
export const relations_factions = relations(factions, ({ one, many }) => ({
|
||||
relationships: many(factions_relationships, {
|
||||
relationName: "relationships",
|
||||
}),
|
||||
coverImage: one(media, {
|
||||
fields: [factions.coverImage],
|
||||
references: [media.id],
|
||||
|
|
@ -11941,6 +12019,41 @@ export const relations_factions = relations(factions, ({ one, many }) => ({
|
|||
relationName: "_rels",
|
||||
}),
|
||||
}));
|
||||
export const relations_faction_relation_entries = relations(
|
||||
faction_relation_entries,
|
||||
({ one }) => ({
|
||||
subject: one(factions, {
|
||||
fields: [faction_relation_entries.subject],
|
||||
references: [factions.id],
|
||||
relationName: "subject",
|
||||
}),
|
||||
target: one(factions, {
|
||||
fields: [faction_relation_entries.target],
|
||||
references: [factions.id],
|
||||
relationName: "target",
|
||||
}),
|
||||
mission: one(missions, {
|
||||
fields: [faction_relation_entries.mission],
|
||||
references: [missions.id],
|
||||
relationName: "mission",
|
||||
}),
|
||||
campaign: one(campaigns, {
|
||||
fields: [faction_relation_entries.campaign],
|
||||
references: [campaigns.id],
|
||||
relationName: "campaign",
|
||||
}),
|
||||
voidedBy: one(users, {
|
||||
fields: [faction_relation_entries.voidedBy],
|
||||
references: [users.id],
|
||||
relationName: "voidedBy",
|
||||
}),
|
||||
recordedBy: one(users, {
|
||||
fields: [faction_relation_entries.recordedBy],
|
||||
references: [users.id],
|
||||
relationName: "recordedBy",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
export const relations_technologies_requirements_prerequisite_technologies = relations(
|
||||
technologies_requirements_prerequisite_technologies,
|
||||
({ one }) => ({
|
||||
|
|
@ -13134,6 +13247,11 @@ export const relations_wiki_pages = relations(wiki_pages, ({ one, many }) => ({
|
|||
references: [users.id],
|
||||
relationName: "lastEditor",
|
||||
}),
|
||||
createdBy: one(users, {
|
||||
fields: [wiki_pages.createdBy],
|
||||
references: [users.id],
|
||||
relationName: "createdBy",
|
||||
}),
|
||||
_texts: many(wiki_pages_texts, {
|
||||
relationName: "_texts",
|
||||
}),
|
||||
|
|
@ -14003,6 +14121,11 @@ export const relations_payload_locked_documents_rels = relations(
|
|||
references: [factions.id],
|
||||
relationName: "factions",
|
||||
}),
|
||||
"faction-relation-entriesID": one(faction_relation_entries, {
|
||||
fields: [payload_locked_documents_rels["faction-relation-entriesID"]],
|
||||
references: [faction_relation_entries.id],
|
||||
relationName: "faction-relation-entries",
|
||||
}),
|
||||
technologiesID: one(technologies, {
|
||||
fields: [payload_locked_documents_rels.technologiesID],
|
||||
references: [technologies.id],
|
||||
|
|
@ -14500,6 +14623,9 @@ type DatabaseSchema = {
|
|||
enum_campaigns_status: typeof enum_campaigns_status;
|
||||
enum_campaigns_campaign_mode: typeof enum_campaigns_campaign_mode;
|
||||
enum_factions_type: typeof enum_factions_type;
|
||||
enum_faction_relation_entries_polarity: typeof enum_faction_relation_entries_polarity;
|
||||
enum_faction_relation_entries_severity: typeof enum_faction_relation_entries_severity;
|
||||
enum_faction_relation_entries_category: typeof enum_faction_relation_entries_category;
|
||||
enum_technologies_approval_status: typeof enum_technologies_approval_status;
|
||||
enum_technologies_type: typeof enum_technologies_type;
|
||||
enum_tech_researches_status: typeof enum_tech_researches_status;
|
||||
|
|
@ -14676,9 +14802,9 @@ type DatabaseSchema = {
|
|||
mission_ratings: typeof mission_ratings;
|
||||
mission_command_links: typeof mission_command_links;
|
||||
campaigns: typeof campaigns;
|
||||
factions_relationships: typeof factions_relationships;
|
||||
factions: typeof factions;
|
||||
factions_rels: typeof factions_rels;
|
||||
faction_relation_entries: typeof faction_relation_entries;
|
||||
technologies_requirements_prerequisite_technologies: typeof technologies_requirements_prerequisite_technologies;
|
||||
technologies_research_costs_resources: typeof technologies_research_costs_resources;
|
||||
technologies: typeof technologies;
|
||||
|
|
@ -14917,9 +15043,9 @@ type DatabaseSchema = {
|
|||
relations_mission_ratings: typeof relations_mission_ratings;
|
||||
relations_mission_command_links: typeof relations_mission_command_links;
|
||||
relations_campaigns: typeof relations_campaigns;
|
||||
relations_factions_relationships: typeof relations_factions_relationships;
|
||||
relations_factions_rels: typeof relations_factions_rels;
|
||||
relations_factions: typeof relations_factions;
|
||||
relations_faction_relation_entries: typeof relations_faction_relation_entries;
|
||||
relations_technologies_requirements_prerequisite_technologies: typeof relations_technologies_requirements_prerequisite_technologies;
|
||||
relations_technologies_research_costs_resources: typeof relations_technologies_research_costs_resources;
|
||||
relations_technologies_rels: typeof relations_technologies_rels;
|
||||
|
|
|
|||
|
|
@ -107,6 +107,7 @@ export interface Config {
|
|||
'mission-command-links': MissionCommandLink;
|
||||
campaigns: Campaign;
|
||||
factions: Faction;
|
||||
'faction-relation-entries': FactionRelationEntry;
|
||||
technologies: Technology;
|
||||
'tech-categories': TechCategory;
|
||||
'tech-researches': TechResearch;
|
||||
|
|
@ -223,6 +224,7 @@ export interface Config {
|
|||
'mission-command-links': MissionCommandLinksSelect<false> | MissionCommandLinksSelect<true>;
|
||||
campaigns: CampaignsSelect<false> | CampaignsSelect<true>;
|
||||
factions: FactionsSelect<false> | FactionsSelect<true>;
|
||||
'faction-relation-entries': FactionRelationEntriesSelect<false> | FactionRelationEntriesSelect<true>;
|
||||
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
|
||||
'tech-categories': TechCategoriesSelect<false> | TechCategoriesSelect<true>;
|
||||
'tech-researches': TechResearchesSelect<false> | TechResearchesSelect<true>;
|
||||
|
|
@ -746,6 +748,10 @@ export interface Role {
|
|||
| 'factions:update'
|
||||
| 'factions:delete'
|
||||
| 'admin:factions:manage'
|
||||
| 'faction-relation-entries:create'
|
||||
| 'faction-relation-entries:read'
|
||||
| 'faction-relation-entries:update'
|
||||
| 'admin:faction-relation-entries:manage'
|
||||
| 'technologies:create'
|
||||
| 'technologies:read'
|
||||
| 'technologies:update'
|
||||
|
|
@ -2587,7 +2593,7 @@ export interface Faction {
|
|||
*/
|
||||
type: 'playerFaction' | 'majorFaction' | 'minorFaction' | 'corporation' | 'special';
|
||||
/**
|
||||
* Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, relationships, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.
|
||||
* Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.
|
||||
*/
|
||||
discovered?: boolean | null;
|
||||
description?: {
|
||||
|
|
@ -2609,26 +2615,6 @@ export interface Faction {
|
|||
* This faction's standing in the world, from -100 (reviled) to 100 (revered). 0 is neutral. Adjusted manually by admins/GMs as campaign events unfold.
|
||||
*/
|
||||
reputation?: number | null;
|
||||
/**
|
||||
* Pairwise standing between this faction and another faction, from -100 (hostile) to 100 (allied). 0 is neutral. One entry per counterpart faction.
|
||||
*/
|
||||
relationships?:
|
||||
| {
|
||||
/**
|
||||
* The other faction in this pairwise relationship.
|
||||
*/
|
||||
targetFaction: number | Faction;
|
||||
/**
|
||||
* Standing from -100 (hostile) to 100 (allied). 0 is neutral.
|
||||
*/
|
||||
value: number;
|
||||
/**
|
||||
* Optional context for why this relationship stands where it does.
|
||||
*/
|
||||
notes?: string | null;
|
||||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
/**
|
||||
* Whether or not this faction is playable. Some factions may be specifically intended to be unplayable based on narrative requirements.
|
||||
*/
|
||||
|
|
@ -3316,6 +3302,10 @@ export interface GameEventLog {
|
|||
| 'factions:update'
|
||||
| 'factions:delete'
|
||||
| 'admin:factions:manage'
|
||||
| 'faction-relation-entries:create'
|
||||
| 'faction-relation-entries:read'
|
||||
| 'faction-relation-entries:update'
|
||||
| 'admin:faction-relation-entries:manage'
|
||||
| 'technologies:create'
|
||||
| 'technologies:read'
|
||||
| 'technologies:update'
|
||||
|
|
@ -5076,6 +5066,84 @@ export interface MissionCommandLink {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Ledger behind every faction relationship score. Add an entry for each thing that changed one faction's attitude toward another; scores are computed from these rows, never typed in.
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "faction-relation-entries".
|
||||
*/
|
||||
export interface FactionRelationEntry {
|
||||
id: number;
|
||||
/**
|
||||
* The faction whose attitude changes.
|
||||
*/
|
||||
subject: number | Faction;
|
||||
/**
|
||||
* The faction the attitude is about.
|
||||
*/
|
||||
target: number | Faction;
|
||||
/**
|
||||
* Count this event for both directions (a shared battle, a treaty both sides signed). Leave unchecked when only the subject's attitude moves.
|
||||
*/
|
||||
mutual?: boolean | null;
|
||||
/**
|
||||
* Which way the attitude moves. Ignored for a custom delta, derived from its sign.
|
||||
*/
|
||||
polarity: 'beneficial' | 'detrimental';
|
||||
/**
|
||||
* How large the move is. The tier sets the delta; pick Custom to type an exact number.
|
||||
*/
|
||||
severity: 'minor' | 'notable' | 'major' | 'decisive' | 'custom';
|
||||
/**
|
||||
* Signed exact amount for a custom entry, -100 to 100. Positive improves the relationship.
|
||||
*/
|
||||
delta?: number | null;
|
||||
/**
|
||||
* What kind of event this was. Labels the entry; never changes the score.
|
||||
*/
|
||||
category: 'aid' | 'betrayal' | 'combat' | 'diplomacy' | 'espionage' | 'trade' | 'other';
|
||||
/**
|
||||
* One line the players will read, in plain language. This is the explanation attached to the score change.
|
||||
*/
|
||||
summary: string;
|
||||
/**
|
||||
* GM-only reasoning. Never shown to players, so it is safe for speculation and spoilers.
|
||||
*/
|
||||
notes?: string | null;
|
||||
/**
|
||||
* When it happened in the fiction. Drives the timeline order and, for decaying entries, how far it has faded.
|
||||
*/
|
||||
occurredAt: string;
|
||||
/**
|
||||
* Transient events fade: the delta halves per half-life (GameRules > Faction Relations). Leave unchecked for lasting shifts like a treaty or a betrayal.
|
||||
*/
|
||||
decays?: boolean | null;
|
||||
/**
|
||||
* Counts toward the score but never appears in the player-facing list. Use it when the effect is visible but the cause is not.
|
||||
*/
|
||||
hiddenFromPlayers?: boolean | null;
|
||||
/**
|
||||
* Optional: the operation that caused it.
|
||||
*/
|
||||
mission?: (number | null) | Mission;
|
||||
/**
|
||||
* Optional: the campaign arc it belongs to.
|
||||
*/
|
||||
campaign?: (number | null) | Campaign;
|
||||
/**
|
||||
* Excluded from every score and hidden from players.
|
||||
*/
|
||||
voided?: boolean | null;
|
||||
voidedAt?: string | null;
|
||||
voidedBy?: (number | null) | User;
|
||||
/**
|
||||
* Why it was voided.
|
||||
*/
|
||||
voidedReason?: string | null;
|
||||
recordedBy?: (number | null) | User;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-researches".
|
||||
|
|
@ -8145,6 +8213,24 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
factionRelationEntries?: {
|
||||
/**
|
||||
* Allow clients to find faction-relation-entries.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create faction-relation-entries.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update faction-relation-entries.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete faction-relation-entries.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
technologies?: {
|
||||
/**
|
||||
* Allow clients to find technologies.
|
||||
|
|
@ -9394,6 +9480,10 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'factions';
|
||||
value: number | Faction;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'faction-relation-entries';
|
||||
value: number | FactionRelationEntry;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'technologies';
|
||||
value: number | Technology;
|
||||
|
|
@ -10927,14 +11017,6 @@ export interface FactionsSelect<T extends boolean = true> {
|
|||
discovered?: T;
|
||||
description?: T;
|
||||
reputation?: T;
|
||||
relationships?:
|
||||
| T
|
||||
| {
|
||||
targetFaction?: T;
|
||||
value?: T;
|
||||
notes?: T;
|
||||
id?: T;
|
||||
};
|
||||
playableFaction?: T;
|
||||
startingFaction?: T;
|
||||
associatedCampaigns?: T;
|
||||
|
|
@ -10942,6 +11024,33 @@ export interface FactionsSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "faction-relation-entries_select".
|
||||
*/
|
||||
export interface FactionRelationEntriesSelect<T extends boolean = true> {
|
||||
subject?: T;
|
||||
target?: T;
|
||||
mutual?: T;
|
||||
polarity?: T;
|
||||
severity?: T;
|
||||
delta?: T;
|
||||
category?: T;
|
||||
summary?: T;
|
||||
notes?: T;
|
||||
occurredAt?: T;
|
||||
decays?: T;
|
||||
hiddenFromPlayers?: T;
|
||||
mission?: T;
|
||||
campaign?: T;
|
||||
voided?: T;
|
||||
voidedAt?: T;
|
||||
voidedBy?: T;
|
||||
voidedReason?: T;
|
||||
recordedBy?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "technologies_select".
|
||||
|
|
@ -13069,6 +13178,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
factionRelationEntries?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
technologies?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -13720,6 +13837,15 @@ export interface GameRule {
|
|||
*/
|
||||
assetOutputsEnabled?: boolean | null;
|
||||
};
|
||||
/**
|
||||
* Tunables for the faction relations ledger (faction-relation-entries). Every pairwise score is computed on read from the ledger; nothing is stored on the faction records.
|
||||
*/
|
||||
factionRelations?: {
|
||||
/**
|
||||
* Half-life, in days, of a decaying relation entry. A decaying entry keeps full weight until one period elapses, then halves per completed period. Entries without the Decays flag never fade.
|
||||
*/
|
||||
decayHalfLifeDays?: number | null;
|
||||
};
|
||||
/**
|
||||
* When off, the Zone Pressure feature is hidden from the Operations feed (the overview card and the AAR section).
|
||||
*/
|
||||
|
|
@ -13933,6 +14059,11 @@ export interface GameRulesSelect<T extends boolean = true> {
|
|||
decayMultiplier?: T;
|
||||
assetOutputsEnabled?: T;
|
||||
};
|
||||
factionRelations?:
|
||||
| T
|
||||
| {
|
||||
decayHalfLifeDays?: T;
|
||||
};
|
||||
zonePressureEnabled?: T;
|
||||
statisticsEnabled?: T;
|
||||
helpdeskEnabled?: T;
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ import { OperationReservations } from "@/collections/operations/OperationReserva
|
|||
import { OperationReadiness } from "@/collections/operations/OperationReadiness";
|
||||
import { ZonePressure } from "@/collections/operations/ZonePressure";
|
||||
import { Factions } from "@/collections/intelligence/Factions";
|
||||
import { FactionRelationEntries } from "@/collections/intelligence/FactionRelationEntries";
|
||||
import { Assets } from "@/collections/logistics/Assets";
|
||||
import { NarrativeEvents } from "@/collections/world/NarrativeEvents";
|
||||
import { Resources } from "@/collections/logistics/Resources";
|
||||
|
|
@ -275,6 +276,7 @@ const collections = [
|
|||
MissionCommandLinks,
|
||||
Campaigns,
|
||||
Factions,
|
||||
FactionRelationEntries,
|
||||
Technologies,
|
||||
TechCategories,
|
||||
TechResearches,
|
||||
|
|
|
|||
|
|
@ -268,6 +268,15 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:factions:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Faction Relations",
|
||||
permissions: [
|
||||
{ value: "faction-relation-entries:create", label: "Create" },
|
||||
{ value: "faction-relation-entries:read", label: "Read" },
|
||||
{ value: "faction-relation-entries:update", label: "Update" },
|
||||
{ value: "admin:faction-relation-entries:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Technologies",
|
||||
permissions: [
|
||||
|
|
@ -1012,6 +1021,10 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"factions:update",
|
||||
"factions:delete",
|
||||
"admin:factions:manage",
|
||||
"faction-relation-entries:create",
|
||||
"faction-relation-entries:read",
|
||||
"faction-relation-entries:update",
|
||||
"admin:faction-relation-entries:manage",
|
||||
"technologies:create",
|
||||
"technologies:read",
|
||||
"technologies:update",
|
||||
|
|
|
|||
479
tests/int/faction-relations.int.spec.ts
Normal file
479
tests/int/faction-relations.int.spec.ts
Normal file
|
|
@ -0,0 +1,479 @@
|
|||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue