감사 수집과 저장 장애를 게임 진행에서 분리한다

This commit is contained in:
2026-09-26 16:26:02 +00:00
parent daf7a87799
commit 6b65633324
22 changed files with 1108 additions and 550 deletions
@@ -0,0 +1,34 @@
import { asRecord } from '@sammo-ts/common';
import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js';
/** A bounded, sticky notice: later successful writes cannot make history complete again. */
export const markAuditGap = (world: InMemoryTurnWorld, stage: string): void => {
const state = world.getState();
const previous = asRecord(state.meta.playAuditGap);
world.updateWorldMeta({
playAuditGap: {
serverId: state.meta.serverId ?? null,
firstYear:
previous.serverId === state.meta.serverId
? (previous.firstYear ?? state.currentYear)
: state.currentYear,
firstMonth:
previous.serverId === state.meta.serverId
? (previous.firstMonth ?? state.currentMonth)
: state.currentMonth,
lastYear: state.currentYear,
lastMonth: state.currentMonth,
stage,
},
});
console.warn(`[play-audit] ${stage}: history gap recorded; gameplay continues.`);
};
export const collectPlayAudit = <T>(world: InMemoryTurnWorld, stage: string, collect: () => T, fallback: T): T => {
try {
return collect();
} catch {
markAuditGap(world, stage);
return fallback;
}
};
+92 -73
View File
@@ -1,3 +1,4 @@
import { collectPlayAudit } from './bestEffort.js';
import { asRecord } from '@sammo-ts/common';
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../turn/inMemoryWorld.js';
import { buildAuditSnapshot, type AuditSettlement } from './snapshot.js';
@@ -32,86 +33,104 @@ const readFlows = (world: InMemoryTurnWorld): MonthlyFlows => {
return { year: state.currentYear, month: state.currentMonth, complete: matches && raw.complete === true, entries };
};
export const recordAuditSettlement = (world: InMemoryTurnWorld, settlement: AuditSettlement): void => {
if (typeof world.getState().meta.serverId !== 'string') return;
const flows = readFlows(world);
const key = `${settlement.nationId}:${settlement.resource}`;
const previous = flows.entries[key];
flows.entries[key] = {
...settlement,
income: (previous?.income ?? 0) + settlement.income,
paid: (previous?.paid ?? 0) + settlement.paid,
};
// 월내 flush/reload에도 누적값을 잃지 않도록 작은 국가별 합계만 world meta에 보존한다.
world.updateWorldMeta({ playAuditFlows: flows });
};
export const recordAuditSettlement = (world: InMemoryTurnWorld, settlement: AuditSettlement): void =>
collectPlayAudit(
world,
'recordAuditSettlement',
() => {
if (typeof world.getState().meta.serverId !== 'string') return;
const flows = readFlows(world);
const key = `${settlement.nationId}:${settlement.resource}`;
const previous = flows.entries[key];
flows.entries[key] = {
...settlement,
income: (previous?.income ?? 0) + settlement.income,
paid: (previous?.paid ?? 0) + settlement.paid,
};
// 월내 flush/reload에도 누적값을 잃지 않도록 작은 국가별 합계만 world meta에 보존한다.
world.updateWorldMeta({ playAuditFlows: flows });
},
undefined
);
export const queueAuditMonth = (
world: InMemoryTurnWorld,
kind: 'MONTH_END' | 'FINAL' | 'INITIAL' = 'MONTH_END'
): void => {
const state = world.getState();
const serverId = state.meta.serverId;
// identity 없는 레거시 fixture/설치에서 profile명으로 가짜 기수를 만들지 않는다.
if (typeof serverId !== 'string' || !serverId.trim()) return;
const flows = readFlows(world);
const snapshot = buildAuditSnapshot({
nations: world.listNations(),
cities: world.listCities(),
generals: world.listGenerals(),
settlements: Object.values(flows.entries),
settlementsComplete: flows.complete,
});
world.queueAuditMonth({
...snapshot,
serverId,
year: state.currentYear,
month: state.currentMonth,
tick: kind === 'INITIAL' ? world.getGameClockState().tick : (state.lastTurnTick ?? null),
kind,
settlementsComplete: flows.complete,
});
};
): void =>
collectPlayAudit(
world,
'queueAuditMonth',
() => {
const state = world.getState();
const serverId = state.meta.serverId;
// identity 없는 레거시 fixture/설치에서 profile명으로 가짜 기수를 만들지 않는다.
if (typeof serverId !== 'string' || !serverId.trim()) return;
const flows = readFlows(world);
const snapshot = buildAuditSnapshot({
nations: world.listNations(),
cities: world.listCities(),
generals: world.listGenerals(),
settlements: Object.values(flows.entries),
settlementsComplete: flows.complete,
});
world.queueAuditMonth({
...snapshot,
serverId,
year: state.currentYear,
month: state.currentMonth,
tick: kind === 'INITIAL' ? world.getGameClockState().tick : (state.lastTurnTick ?? null),
kind,
settlementsComplete: flows.complete,
});
},
undefined
);
/** 도입 당시 상태는 월말로 가장하지 않고 기수별 최초 기준으로 한 번 고정한다. */
export const initializeAuditCollection = (world: InMemoryTurnWorld, observedAt = new Date()): boolean => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return false;
const previous = asRecord(state.meta.playAuditCollection);
if (previous.serverId === serverId) {
if (
previous.schemaVersion !== 1 ||
typeof previous.year !== 'number' ||
!Number.isInteger(previous.year) ||
previous.year < 0 ||
typeof previous.month !== 'number' ||
!Number.isInteger(previous.month) ||
previous.month < 1 ||
previous.month > 12 ||
typeof previous.tick !== 'number' ||
!Number.isSafeInteger(previous.tick) ||
previous.tick < 0 ||
typeof previous.observedAt !== 'string' ||
!Number.isFinite(Date.parse(previous.observedAt)) ||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth
)
throw new Error('Invalid play audit collection boundary');
return false;
}
queueAuditMonth(world, 'INITIAL');
world.updateWorldMeta({
playAuditCollection: {
schemaVersion: 1,
serverId,
year: state.currentYear,
month: state.currentMonth,
tick: world.getGameClockState().tick,
observedAt: observedAt.toISOString(),
export const initializeAuditCollection = (world: InMemoryTurnWorld, observedAt = new Date()): boolean =>
collectPlayAudit(
world,
'initializeAuditCollection',
() => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return false;
const previous = asRecord(state.meta.playAuditCollection);
if (previous.serverId === serverId) {
if (
previous.schemaVersion !== 1 ||
typeof previous.year !== 'number' ||
!Number.isInteger(previous.year) ||
previous.year < 0 ||
typeof previous.month !== 'number' ||
!Number.isInteger(previous.month) ||
previous.month < 1 ||
previous.month > 12 ||
typeof previous.tick !== 'number' ||
!Number.isSafeInteger(previous.tick) ||
previous.tick < 0 ||
typeof previous.observedAt !== 'string' ||
!Number.isFinite(Date.parse(previous.observedAt)) ||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth
)
throw new Error('Invalid play audit collection boundary');
return false;
}
queueAuditMonth(world, 'INITIAL');
world.updateWorldMeta({
playAuditCollection: {
schemaVersion: 1,
serverId,
year: state.currentYear,
month: state.currentMonth,
tick: world.getGameClockState().tick,
observedAt: observedAt.toISOString(),
},
});
return true;
},
});
return true;
};
false
);
export const createPlayAuditHandler = (getWorld: () => InMemoryTurnWorld | null): TurnCalendarHandler => ({
beforeMonthChanged: (context) => {
+221 -191
View File
@@ -1,3 +1,4 @@
import { collectPlayAudit } from './bestEffort.js';
import { asRecord } from '@sammo-ts/common';
import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js';
import type { TurnDiplomacy } from '../turn/types.js';
@@ -7,46 +8,52 @@ export const recordMonthlyAuditDiplomacy = (
world: InMemoryTurnWorld,
before: readonly TurnDiplomacy[],
afterByKey: ReadonlyMap<string, TurnDiplomacy>
): void => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return;
const clock = world.getGameClockState();
const project = (entry: TurnDiplomacy) => ({ state: entry.state, term: entry.term, dead: entry.dead });
let ordinal = 0;
for (const entry of [...before].sort(
(left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId
)) {
const next = afterByKey.get(`${entry.fromNationId}:${entry.toNationId}`);
if (!next) continue;
const previousState = project(entry);
const nextState = project(next);
if (JSON.stringify(previousState) === JSON.stringify(nextState)) continue;
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
category: 'RELATION',
source: 'ENGINE',
eventType: 'MONTHLY_RELATION_CHANGED',
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(clock.tick),
clockRevision: BigInt(clock.revision),
executionId: `monthly:${state.currentYear}:${state.currentMonth}:${clock.revision}`,
ordinal: ++ordinal,
requestId: null,
inputSequence: null,
actor: null,
before: previousState,
after: nextState,
});
}
};
): void =>
collectPlayAudit(
world,
'recordMonthlyAuditDiplomacy',
() => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return;
const clock = world.getGameClockState();
const project = (entry: TurnDiplomacy) => ({ state: entry.state, term: entry.term, dead: entry.dead });
let ordinal = 0;
for (const entry of [...before].sort(
(left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId
)) {
const next = afterByKey.get(`${entry.fromNationId}:${entry.toNationId}`);
if (!next) continue;
const previousState = project(entry);
const nextState = project(next);
if (JSON.stringify(previousState) === JSON.stringify(nextState)) continue;
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
category: 'RELATION',
source: 'ENGINE',
eventType: 'MONTHLY_RELATION_CHANGED',
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(clock.tick),
clockRevision: BigInt(clock.revision),
executionId: `monthly:${state.currentYear}:${state.currentMonth}:${clock.revision}`,
ordinal: ++ordinal,
requestId: null,
inputSequence: null,
actor: null,
before: previousState,
after: nextState,
});
}
},
undefined
);
export interface AuditDiplomacyAction {
actionKey: string;
@@ -68,116 +75,133 @@ export const recordTurnAuditDiplomacy = (
after: TurnDiplomacy,
action: AuditDiplomacyAction,
turn: { generalId: number; tick: number; ordinal: number }
): void => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return;
const previousState = { state: before.state, term: before.term, dead: before.dead };
const nextState = { state: after.state, term: after.term, dead: after.dead };
if (JSON.stringify(previousState) === JSON.stringify(nextState)) return;
const clock = world.getGameClockState();
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: before.fromNationId,
destNationId: before.toNationId,
category: 'RELATION',
source: 'ENGINE',
eventType: 'TURN_RELATION_CHANGED',
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(turn.tick),
clockRevision: BigInt(clock.revision),
executionId: `turn:${turn.generalId}:${turn.tick}:${clock.revision}`,
ordinal: turn.ordinal,
requestId: null,
inputSequence: null,
actor: { ...action.actor, actionKey: action.actionKey, kind: action.kind, actionOrdinal: action.actionOrdinal },
before: previousState,
after: nextState,
});
};
): void =>
collectPlayAudit(
world,
'recordTurnAuditDiplomacy',
() => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return;
const previousState = { state: before.state, term: before.term, dead: before.dead };
const nextState = { state: after.state, term: after.term, dead: after.dead };
if (JSON.stringify(previousState) === JSON.stringify(nextState)) return;
const clock = world.getGameClockState();
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: before.fromNationId,
destNationId: before.toNationId,
category: 'RELATION',
source: 'ENGINE',
eventType: 'TURN_RELATION_CHANGED',
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(turn.tick),
clockRevision: BigInt(clock.revision),
executionId: `turn:${turn.generalId}:${turn.tick}:${clock.revision}`,
ordinal: turn.ordinal,
requestId: null,
inputSequence: null,
actor: {
...action.actor,
actionKey: action.actionKey,
kind: action.kind,
actionOrdinal: action.actionOrdinal,
},
before: previousState,
after: nextState,
});
},
undefined
);
/** 현재 로드된 관계를 도입 시 한 번만 고정한다. 과거 발생 원인/주체는 추정하지 않는다. */
export const initializeAuditDiplomacy = (world: InMemoryTurnWorld, observedAt = new Date()): boolean => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return false;
const previous = asRecord(state.meta.playAuditDiplomacy);
if (previous.serverId === serverId) {
if (
previous.schemaVersion !== 1 ||
typeof previous.year !== 'number' ||
previous.year < 0 ||
!Number.isInteger(previous.year) ||
!Number.isInteger(previous.month) ||
typeof previous.month !== 'number' ||
previous.month < 1 ||
previous.month > 12 ||
typeof previous.tick !== 'number' ||
!Number.isSafeInteger(previous.tick) ||
previous.tick < 0 ||
typeof previous.clockRevision !== 'number' ||
!Number.isSafeInteger(previous.clockRevision) ||
previous.clockRevision < 0 ||
typeof previous.relationCount !== 'number' ||
!Number.isInteger(previous.relationCount) ||
previous.relationCount < 0 ||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth ||
typeof previous.observedAt !== 'string' ||
!Number.isFinite(Date.parse(previous.observedAt))
)
throw new Error('Invalid play audit diplomacy boundary');
return false;
}
const clock = world.getGameClockState();
const observedAtIso = observedAt.toISOString();
const relations = world
.listDiplomacy()
.filter((entry) => entry.fromNationId > 0 && entry.toNationId > 0)
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
for (const [index, entry] of relations.entries()) {
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
category: 'RELATION',
source: 'BASELINE',
eventType: 'RELATION_BASELINE',
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(clock.tick),
clockRevision: BigInt(clock.revision),
executionId: 'relation-baseline',
ordinal: index + 1,
requestId: null,
inputSequence: null,
actor: null,
before: null,
after: { state: entry.state, term: entry.term, dead: entry.dead },
});
}
world.updateWorldMeta({
playAuditDiplomacy: {
schemaVersion: 1,
serverId,
year: state.currentYear,
month: state.currentMonth,
tick: clock.tick,
clockRevision: clock.revision,
observedAt: observedAtIso,
relationCount: relations.length,
export const initializeAuditDiplomacy = (world: InMemoryTurnWorld, observedAt = new Date()): boolean =>
collectPlayAudit(
world,
'initializeAuditDiplomacy',
() => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return false;
const previous = asRecord(state.meta.playAuditDiplomacy);
if (previous.serverId === serverId) {
if (
previous.schemaVersion !== 1 ||
typeof previous.year !== 'number' ||
previous.year < 0 ||
!Number.isInteger(previous.year) ||
!Number.isInteger(previous.month) ||
typeof previous.month !== 'number' ||
previous.month < 1 ||
previous.month > 12 ||
typeof previous.tick !== 'number' ||
!Number.isSafeInteger(previous.tick) ||
previous.tick < 0 ||
typeof previous.clockRevision !== 'number' ||
!Number.isSafeInteger(previous.clockRevision) ||
previous.clockRevision < 0 ||
typeof previous.relationCount !== 'number' ||
!Number.isInteger(previous.relationCount) ||
previous.relationCount < 0 ||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth ||
typeof previous.observedAt !== 'string' ||
!Number.isFinite(Date.parse(previous.observedAt))
)
throw new Error('Invalid play audit diplomacy boundary');
return false;
}
const clock = world.getGameClockState();
const observedAtIso = observedAt.toISOString();
const relations = world
.listDiplomacy()
.filter((entry) => entry.fromNationId > 0 && entry.toNationId > 0)
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
for (const [index, entry] of relations.entries()) {
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
category: 'RELATION',
source: 'BASELINE',
eventType: 'RELATION_BASELINE',
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(clock.tick),
clockRevision: BigInt(clock.revision),
executionId: 'relation-baseline',
ordinal: index + 1,
requestId: null,
inputSequence: null,
actor: null,
before: null,
after: { state: entry.state, term: entry.term, dead: entry.dead },
});
}
world.updateWorldMeta({
playAuditDiplomacy: {
schemaVersion: 1,
serverId,
year: state.currentYear,
month: state.currentMonth,
tick: clock.tick,
clockRevision: clock.revision,
observedAt: observedAtIso,
relationCount: relations.length,
},
});
return true;
},
});
return true;
};
false
);
/** 국가 생멸로 생성/제거된 관계를 기록한다. 행위자나 명령은 관측하지 못했다면 추정하지 않는다. */
export const recordNationAuditDiplomacy = (
@@ -186,47 +210,53 @@ export const recordNationAuditDiplomacy = (
relations: readonly TurnDiplomacy[],
operation: 'CREATED' | 'REMOVED',
observedTick?: number
): void => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return;
const targets = new Set(nationIds.filter((id) => id > 0));
const observed = relations
.filter(
(entry) =>
entry.fromNationId > 0 &&
entry.toNationId > 0 &&
(targets.has(entry.fromNationId) || targets.has(entry.toNationId))
)
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
if (!observed.length) return;
// 전역 순번은 실행 identity에만 사용한다. 한 사건 묶음 안의 순서는 방향별 local ordinal이다.
const executionId = `nation-relations:${world.nextAuditOrdinal()}`;
const clock = world.getGameClockState();
for (const [index, entry] of observed.entries()) {
const value = { state: entry.state, term: entry.term, dead: entry.dead };
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
category: 'RELATION',
source: 'ENGINE',
eventType: `NATION_RELATION_${operation}`,
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(observedTick ?? clock.tick),
clockRevision: BigInt(clock.revision),
executionId,
ordinal: index + 1,
requestId: null,
inputSequence: null,
actor: null,
before: operation === 'REMOVED' ? value : null,
after: operation === 'CREATED' ? value : null,
});
}
};
): void =>
collectPlayAudit(
world,
'recordNationAuditDiplomacy',
() => {
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return;
const targets = new Set(nationIds.filter((id) => id > 0));
const observed = relations
.filter(
(entry) =>
entry.fromNationId > 0 &&
entry.toNationId > 0 &&
(targets.has(entry.fromNationId) || targets.has(entry.toNationId))
)
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
if (!observed.length) return;
// 전역 순번은 실행 identity에만 사용한다. 한 사건 묶음 안의 순서는 방향별 local ordinal이다.
const executionId = `nation-relations:${world.nextAuditOrdinal()}`;
const clock = world.getGameClockState();
for (const [index, entry] of observed.entries()) {
const value = { state: entry.state, term: entry.term, dead: entry.dead };
world.queueAuditDiplomacy({
schemaVersion: 1,
serverId,
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
category: 'RELATION',
source: 'ENGINE',
eventType: `NATION_RELATION_${operation}`,
documentId: null,
documentHash: null,
previousDocumentId: null,
year: state.currentYear,
month: state.currentMonth,
tick: BigInt(observedTick ?? clock.tick),
clockRevision: BigInt(clock.revision),
executionId,
ordinal: index + 1,
requestId: null,
inputSequence: null,
actor: null,
before: operation === 'REMOVED' ? value : null,
after: operation === 'CREATED' ? value : null,
});
}
},
undefined
);
+91 -78
View File
@@ -1,3 +1,4 @@
import { collectPlayAudit } from './bestEffort.js';
import { createHash } from 'node:crypto';
import { asRecord } from '@sammo-ts/common';
import type { Nation } from '@sammo-ts/logic';
@@ -70,85 +71,97 @@ export const recordAuditPolicyChange = (options: {
actor?: TurnGeneral;
permission?: number;
requestId?: string;
}): { _playAuditPolicy?: Record<string, PolicyHead> } => {
const { world, nation, area } = options;
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return {};
const rawHeads = asRecord(nation.meta._playAuditPolicy);
const heads: Record<string, PolicyHead> = {};
for (const key of AUDIT_POLICY_AREAS) {
const value = asRecord(rawHeads[key]);
if (
value.serverId === serverId &&
typeof value.id === 'string' &&
typeof value.revision === 'number' &&
Number.isSafeInteger(value.revision) &&
value.revision > 0 &&
typeof value.hash === 'string' &&
value.id === auditPolicyHash([serverId, nation.id, key, value.revision])
) {
heads[key] = { id: value.id, revision: value.revision, hash: value.hash, serverId };
}
}
let head: PolicyHead | null = heads[area] ?? null;
const before = projectAuditPolicy(nation.meta, area);
const after = projectAuditPolicy(options.nextMeta, area);
const append = (source: PendingAuditPolicy['source'], old: PolicyData | null, value: PolicyData) => {
const revision = (head?.revision ?? 0) + 1;
const id = auditPolicyHash([serverId, nation.id, area, revision]);
const actor = options.actor;
world.queueAuditPolicy({
schemaVersion: 1,
id,
serverId,
nationId: nation.id,
area,
revision,
previousId: head?.id ?? null,
source,
year: state.currentYear,
month: state.currentMonth,
tick: world.getGameClockState().tick,
requestId: source === 'CHANGE' ? (options.requestId ?? null) : null,
ordinal: world.nextAuditOrdinal(),
actor:
source === 'CHANGE' && actor
? {
userId: actor.userId ?? null,
generalId: actor.id,
name: actor.name,
nationId: actor.nationId,
officerLevel: actor.officerLevel,
npcState: actor.npcState,
permission: options.permission ?? 0,
}
: null,
before: old,
after: value,
});
head = { id, revision, hash: auditPolicyHash(value), serverId };
};
if (!head) append('BASELINE', null, before);
else if (head.hash !== auditPolicyHash(before)) append('OBSERVED_GAP', null, before);
if (auditPolicyHash(before) !== auditPolicyHash(after)) append('CHANGE', before, after);
if (!head) throw new Error('Play audit policy baseline missing');
return { _playAuditPolicy: { ...heads, [area]: head } };
};
}): { _playAuditPolicy?: Record<string, PolicyHead> } =>
collectPlayAudit(
options.world,
'recordAuditPolicyChange',
() => {
const { world, nation, area } = options;
const state = world.getState();
const serverId = state.meta.serverId;
if (typeof serverId !== 'string' || !serverId.trim()) return {};
const rawHeads = asRecord(nation.meta._playAuditPolicy);
const heads: Record<string, PolicyHead> = {};
for (const key of AUDIT_POLICY_AREAS) {
const value = asRecord(rawHeads[key]);
if (
value.serverId === serverId &&
typeof value.id === 'string' &&
typeof value.revision === 'number' &&
Number.isSafeInteger(value.revision) &&
value.revision > 0 &&
typeof value.hash === 'string' &&
value.id === auditPolicyHash([serverId, nation.id, key, value.revision])
) {
heads[key] = { id: value.id, revision: value.revision, hash: value.hash, serverId };
}
}
let head: PolicyHead | null = heads[area] ?? null;
const before = projectAuditPolicy(nation.meta, area);
const after = projectAuditPolicy(options.nextMeta, area);
const append = (source: PendingAuditPolicy['source'], old: PolicyData | null, value: PolicyData) => {
const revision = (head?.revision ?? 0) + 1;
const id = auditPolicyHash([serverId, nation.id, area, revision]);
const actor = options.actor;
world.queueAuditPolicy({
schemaVersion: 1,
id,
serverId,
nationId: nation.id,
area,
revision,
previousId: head?.id ?? null,
source,
year: state.currentYear,
month: state.currentMonth,
tick: world.getGameClockState().tick,
requestId: source === 'CHANGE' ? (options.requestId ?? null) : null,
ordinal: world.nextAuditOrdinal(),
actor:
source === 'CHANGE' && actor
? {
userId: actor.userId ?? null,
generalId: actor.id,
name: actor.name,
nationId: actor.nationId,
officerLevel: actor.officerLevel,
npcState: actor.npcState,
permission: options.permission ?? 0,
}
: null,
before: old,
after: value,
});
head = { id, revision, hash: auditPolicyHash(value), serverId };
};
if (!head) append('BASELINE', null, before);
else if (head.hash !== auditPolicyHash(before)) append('OBSERVED_GAP', null, before);
if (auditPolicyHash(before) !== auditPolicyHash(after)) append('CHANGE', before, after);
if (!head) throw new Error('Play audit policy baseline missing');
return { _playAuditPolicy: { ...heads, [area]: head } };
},
{}
);
export const initializeNationAuditPolicies = (world: InMemoryTurnWorld, nationId: number): void => {
let nation = world.getNationById(nationId);
if (!nation) return;
for (const area of AUDIT_POLICY_AREAS) {
const patch = recordAuditPolicyChange({ world, nation, area, nextMeta: nation.meta });
if (
Object.keys(patch).length &&
auditPolicyHash(patch._playAuditPolicy) !== auditPolicyHash(nation.meta._playAuditPolicy ?? {})
) {
nation = world.updateNation(nation.id, { meta: { ...nation.meta, ...patch } })!;
}
}
};
export const initializeNationAuditPolicies = (world: InMemoryTurnWorld, nationId: number): void =>
collectPlayAudit(
world,
'initializeNationAuditPolicies',
() => {
let nation = world.getNationById(nationId);
if (!nation) return;
for (const area of AUDIT_POLICY_AREAS) {
const patch = recordAuditPolicyChange({ world, nation, area, nextMeta: nation.meta });
if (
Object.keys(patch).length &&
auditPolicyHash(patch._playAuditPolicy) !== auditPolicyHash(nation.meta._playAuditPolicy ?? {})
) {
nation = world.updateNation(nation.id, { meta: { ...nation.meta, ...patch } })!;
}
}
},
undefined
);
export const initializeAuditPolicies = (world: InMemoryTurnWorld): void => {
for (const nation of world.listNations()) initializeNationAuditPolicies(world, nation.id);