장시간 Ref 행렬과 NPC 회귀 비용을 줄인다

This commit is contained in:
2026-09-04 08:59:10 +00:00
parent 07897d9765
commit 5d220de739
12 changed files with 253 additions and 11346 deletions
+41
View File
@@ -0,0 +1,41 @@
import type { City, MapDefinition } from '@sammo-ts/logic';
import { LARGE_TEST_MAP } from './largeTestMap.js';
const COMPACT_CITY_IDS = new Set([1, 2, 3, 4, 5]);
export const COMPACT_NPC_TEST_MAP: MapDefinition = {
id: 'compact_npc_test_map',
name: 'NPC 장기 시뮬레이션용 소형 맵',
cities: LARGE_TEST_MAP.cities
.filter((city) => COMPACT_CITY_IDS.has(city.id))
.map((city) => ({
...city,
connections: city.connections.filter((cityId) => COMPACT_CITY_IDS.has(cityId)),
})),
defaults: { ...LARGE_TEST_MAP.defaults },
};
export const buildCompactNpcTestCities = (): City[] =>
COMPACT_NPC_TEST_MAP.cities.map((city) => ({
id: city.id,
name: city.name,
nationId: 0,
level: city.level,
state: 0,
population: city.initial.population,
populationMax: city.max.population,
agriculture: city.initial.agriculture,
agricultureMax: city.max.agriculture,
commerce: city.initial.commerce,
commerceMax: city.max.commerce,
security: city.initial.security,
securityMax: city.max.security,
supplyState: 1,
frontState: 0,
defence: city.initial.defence,
defenceMax: city.max.defence,
wall: city.initial.wall,
wallMax: city.max.wall,
meta: { trust: 95 },
}));
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest';
import type { TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
import { DIPLOMACY_STATE } from '@sammo-ts/logic';
import { getTechLevel } from '@sammo-ts/logic/world/unitSet.js';
import { getTechCost, getTechLevel } from '@sammo-ts/logic/world/unitSet.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
import { COMPACT_NPC_TEST_MAP, buildCompactNpcTestCities } from './fixtures/compactNpcTestScenario.js';
import { createTurnTestHarness } from './helpers/turnTestHarness.js';
const mockDate = new Date('0180-01-01T00:00:00Z');
@@ -45,7 +45,7 @@ const createNpcGeneral = (
npcState,
});
const maxCityStats = (city: ReturnType<typeof buildLargeTestCities>[number]) => ({
const maxCityStats = (city: ReturnType<typeof buildCompactNpcTestCities>[number]) => ({
...city,
population: city.populationMax,
agriculture: city.agricultureMax,
@@ -63,9 +63,9 @@ const readTech = (nation: { meta: Record<string, unknown> }): number => {
describe('NPC 기술 연구 장기 시뮬레이션', () => {
it('기술이 상승하고 기술 등급 및 소모 금이 증가해야 한다', async () => {
const cities = buildLargeTestCities().map(maxCityStats);
const nation1CityIds = [1, 2, 3, 4];
const nation2CityIds = [5, 6, 7, 8, 9];
const cities = buildCompactNpcTestCities().map(maxCityStats);
const nation1CityIds = [1, 2];
const nation2CityIds = [3, 4, 5];
for (const city of cities) {
if (nation1CityIds.includes(city.id)) {
@@ -122,7 +122,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
1
)
);
for (let i = 0; i < 9; i += 1) {
for (let i = 0; i < 3; i += 1) {
generals.push(
createNpcGeneral(nextId++, cityId, nationId, 2, {
leadership: 80,
@@ -131,7 +131,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
})
);
}
for (let i = 0; i < 40; i += 1) {
for (let i = 0; i < 6; i += 1) {
generals.push(
createNpcGeneral(nextId++, cityId, nationId, 2, {
leadership: 70,
@@ -163,7 +163,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
power: 0,
level: 1,
typeCode: 'large_test_map_def',
meta: { tech: 0 },
meta: { tech: 950 },
},
{
id: 2,
@@ -176,7 +176,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
power: 0,
level: 1,
typeCode: 'large_test_map_def',
meta: { tech: 0 },
meta: { tech: 950 },
},
],
troops: [],
@@ -200,7 +200,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
],
events: [],
initialEvents: [],
map: LARGE_TEST_MAP as any,
map: COMPACT_NPC_TEST_MAP as any,
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
@@ -214,7 +214,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
minAvailableRecruitPop: 0,
maxTechLevel: 12000,
},
environment: { mapName: 'large_test_map', unitSet: 'default' },
environment: { mapName: 'compact_npc_test_map', unitSet: 'default' },
},
scenarioMeta: {
startYear: 180,
@@ -239,7 +239,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
snapshot,
state,
schedule,
map: LARGE_TEST_MAP,
map: COMPACT_NPC_TEST_MAP,
});
const controlledGeneralId = nation1ChiefId;
@@ -261,17 +261,14 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
const firstGoldAfter = world.getGeneralById(controlledGeneralId)!.gold;
const firstRecruitCost = firstGoldBefore - firstGoldAfter;
expect(firstRecruitCost).toBeGreaterThan(0);
const firstTechValue = readTech(world.getNationById(1)! as { meta: Record<string, unknown> });
const firstTechLevel = getTechLevel(firstTechValue);
const techSnapshots: Array<{ year: number; tech1: number; tech2: number }> = [];
let pendingRecruit = false;
let pendingGoldBefore = 0;
let secondRecruitCost: number | null = null;
const shouldStop = () => {
const exceededSafetyLimit = () => {
const current = world.getState();
return current.currentYear > 230 || (current.currentYear === 230 && current.currentMonth >= 1);
return current.currentYear > 185 || (current.currentYear === 185 && current.currentMonth >= 1);
};
while (true) {
@@ -294,15 +291,18 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
const tech1 = readTech(nation1 as { meta: Record<string, unknown> });
const tech2 = readTech(nation2 as { meta: Record<string, unknown> });
if (current.currentMonth === 1) {
techSnapshots.push({ year: current.currentYear, tech1, tech2 });
}
techSnapshots.push({ year: current.currentYear, tech1, tech2 });
if (secondRecruitCost === null && getTechLevel(tech1) > firstTechLevel) {
if (secondRecruitCost === null && getTechLevel(tech1) > initialLevel) {
pendingRecruit = true;
}
if (shouldStop()) {
if (
(secondRecruitCost !== null &&
getTechLevel(tech1) > initialLevel &&
getTechLevel(tech2) > initialLevel) ||
exceededSafetyLimit()
) {
break;
}
}
@@ -322,8 +322,12 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
expect(finalTech2).toBeGreaterThan(initialTech2);
expect(getTechLevel(finalTech1)).toBeGreaterThan(initialLevel);
expect(getTechLevel(finalTech2)).toBeGreaterThanOrEqual(initialLevel);
expect(getTechCost(finalTech1)).toBeGreaterThan(getTechCost(initialTech1));
expect(secondRecruitCost).not.toBeNull();
expect(
secondRecruitCost,
`second recruit was not observed (tech1=${finalTech1}, tech2=${finalTech2}, level=${initialLevel})`
).not.toBeNull();
// Nation awards can occur in the same tick and make the general's net
// gold delta smaller than the recruitment price. Exact cost scaling is
// covered by the unit-set/action contract tests rather than this smoke.
@@ -7,7 +7,7 @@ import type { LogEntryDraft, TurnSchedule, UnitSetDefinition } from '@sammo-ts/l
import { DIPLOMACY_STATE, LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../src/turn/inMemoryWorld.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
import { COMPACT_NPC_TEST_MAP, buildCompactNpcTestCities } from './fixtures/compactNpcTestScenario.js';
import { createTurnTestHarness } from './helpers/turnTestHarness.js';
import { NpcUnificationMemoryProfiler } from './helpers/npcUnificationMemoryProfiler.js';
@@ -28,8 +28,8 @@ const createNpcGeneral = (
role: {
items: { horse: null, weapon: null, book: null, item: null },
personality: null,
specialDomestic: null,
specialWar: null,
specialDomestic: id % 2 === 0 ? 'che_경작' : 'che_상재',
specialWar: id % 2 === 0 ? 'che_보병' : 'che_무쌍',
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: { killturn: 800 },
@@ -47,7 +47,7 @@ const createNpcGeneral = (
npcState: 2,
});
const maxCityStats = (city: ReturnType<typeof buildLargeTestCities>[number]) => ({
const maxCityStats = (city: ReturnType<typeof buildCompactNpcTestCities>[number]) => ({
...city,
population: city.populationMax,
agriculture: city.agricultureMax,
@@ -156,7 +156,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
const memoryProfileEnabled = process.env.NPC_UNIFICATION_MEMORY_PROFILE === '1';
const rankingAuditEnabled = process.env.NPC_RANKING_AUDIT === '1';
const profileStartedAtMs = performance.now();
const cities = buildLargeTestCities().map(maxCityStats);
const cities = buildCompactNpcTestCities().map(maxCityStats);
for (const city of cities) {
city.nationId = 0;
}
@@ -208,7 +208,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
};
const generals: TurnGeneral[] = [];
const initialGeneralCount = rankingAuditEnabled ? 150 : 300;
const initialGeneralCount = rankingAuditEnabled ? 150 : 60;
for (let i = 0; i < initialGeneralCount; i += 1) {
const cityId = cities[i % cities.length]!.id;
const stats =
@@ -217,6 +217,10 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
: { leadership: 75, strength: 10, intelligence: 75 };
generals.push(createNpcGeneral(i + 1, cityId, stats));
}
expect(new Set(generals.map((general) => general.role.specialDomestic))).toEqual(
new Set(['che_경작', 'che_상재'])
);
expect(new Set(generals.map((general) => general.role.specialWar))).toEqual(new Set(['che_보병', 'che_무쌍']));
const snapshot: TurnWorldSnapshot = {
generals: generals as any,
@@ -226,7 +230,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
diplomacy: [],
events: [],
initialEvents: [],
map: LARGE_TEST_MAP as any,
map: COMPACT_NPC_TEST_MAP as any,
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
@@ -239,7 +243,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
maxResourceActionAmount: 10000,
minAvailableRecruitPop: 0,
},
environment: { mapName: 'large_test_map', unitSet: 'default' },
environment: { mapName: 'compact_npc_test_map', unitSet: 'default' },
},
scenarioMeta: {
startYear: 180,
@@ -305,45 +309,44 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
getCollectedLogsCount,
getCollectedLogsRange,
getAndClearCollectedLogs,
} =
await createTurnTestHarness({
snapshot,
state,
schedule,
map: LARGE_TEST_MAP,
worldRef,
extraCalendarHandlers: [unificationHandler],
collectLogs: true,
onActionResolved: (payload) => {
const currentWorld = worldRef.current;
if (currentWorld) {
const nationIds = new Set(currentWorld.listNations().map((nation) => nation.id));
const orphanCities = currentWorld
.listCities()
.filter((city) => city.nationId > 0 && !nationIds.has(city.nationId));
if (orphanCities.length > 0) {
throw new Error(
`orphan city ownership after ${lastResolvedAction}, before ${payload.kind}:${payload.actionKey}: ${orphanCities
.map((city) => `${city.id}->${city.nationId}`)
.join(', ')}`
);
}
} = await createTurnTestHarness({
snapshot,
state,
schedule,
map: COMPACT_NPC_TEST_MAP,
worldRef,
extraCalendarHandlers: [unificationHandler],
collectLogs: true,
onActionResolved: (payload) => {
const currentWorld = worldRef.current;
if (currentWorld) {
const nationIds = new Set(currentWorld.listNations().map((nation) => nation.id));
const orphanCities = currentWorld
.listCities()
.filter((city) => city.nationId > 0 && !nationIds.has(city.nationId));
if (orphanCities.length > 0) {
throw new Error(
`orphan city ownership after ${lastResolvedAction}, before ${payload.kind}:${payload.actionKey}: ${orphanCities
.map((city) => `${city.id}->${city.nationId}`)
.join(', ')}`
);
}
lastResolvedAction = `${payload.kind}:${payload.actionKey}`;
if (payload.kind === 'general') {
if (payload.actionKey === 'che_출병') {
sortieCount += 1;
}
return;
}
lastResolvedAction = `${payload.kind}:${payload.actionKey}`;
if (payload.kind === 'general') {
if (payload.actionKey === 'che_출병') {
sortieCount += 1;
}
if (payload.nationId) {
lastNationAiState.set(payload.nationId, payload.aiState ?? null);
}
if (payload.actionKey === 'che_선전포고') {
declarationCount += 1;
}
},
});
return;
}
if (payload.nationId) {
lastNationAiState.set(payload.nationId, payload.aiState ?? null);
}
if (payload.actionKey === 'che_선전포고') {
declarationCount += 1;
}
},
});
const memoryProfiler =
memoryProfileEnabled && worldRef.current
? new NpcUnificationMemoryProfiler(worldRef.current, reservedTurnStore)
@@ -410,6 +413,9 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
const foundedNations = world.listNations().filter((nation) => nation.level > 0);
expect(foundedNations.length).toBeGreaterThanOrEqual(2);
const foundedNationCount = foundedNations.length;
const foundedGenerals = world.listGenerals().filter((general) => general.nationId > 0);
expect(foundedGenerals.some((general) => general.role.specialDomestic !== null)).toBe(true);
expect(foundedGenerals.some((general) => general.role.specialWar !== null)).toBe(true);
memoryProfiler?.sample('nations-founded');
await runUntil(
@@ -436,7 +442,8 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
if (declarationCount === 0) {
await runUntil(
(current) => current.currentYear > 190 || (current.currentYear === 190 && current.currentMonth >= 1),
(current) =>
current.currentYear > 190 || (current.currentYear === 190 && current.currentMonth >= 1),
undefined,
observeProfileMonth
);
@@ -614,6 +621,9 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
const logs = getCollectedLogs();
const hasUnificationLog =
unificationLogObserved || logs.some((log) => log.text.includes('전토를 통일하였습니다.'));
if (!rankingAuditEnabled) {
expect(unifiedAt).not.toBeNull();
}
if (unifiedAt) {
expect(meta.isUnited).toBe(2);
expect(hasUnificationLog).toBe(true);
@@ -714,8 +724,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
startMonth: state.currentMonth,
});
const reportPath = resolve(
process.env.NPC_UNIFICATION_MEMORY_REPORT_PATH ??
'test-results/npc-unification-memory.json'
process.env.NPC_UNIFICATION_MEMORY_REPORT_PATH ?? 'test-results/npc-unification-memory.json'
);
mkdirSync(dirname(reportPath), { recursive: true });
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
+3 -4
View File
@@ -109,7 +109,6 @@ source입니다. 현재 이벤트는 장비 구매·판매, 계략 성공, 도
`actionModuleEvents.test.ts`는 표준 순서, 이벤트 brand와 잘못된 context의
compile 실패를 검증합니다. `itemActionEvents.test.ts`는 도기 분기와
연차 경계, 충차·환약 초기 충전, 계략 성공 소비를 검증합니다.
`warAftermath.test.ts`는 도시 점령 대상과 공유 RNG 소비 순서를 검증합니다.
ref↔core 실제 명령 차등은
`turnCommandGeneralMatrix.integration.test.ts`의 도기 판매 fixture가
담당합니다.
`warAftermath.test.ts`는 도시 점령 대상과 공유 RNG 소비 순서를 검증합니다. 도기 판매는
`itemActionEvents.test.ts`의 고정 seed Core 계약으로 검증하며, 실제 Ref 재조사가 필요한
회귀만 command 단위의 좁은 차등 fixture로 추가합니다.
@@ -65,13 +65,13 @@ pnpm check:legacy:nation
`instantDiplomacyCoreReference.integration.test.ts`에서 실제 Ref API entry와 Core
router 결과를 별도로 비교합니다.
장수·수뇌 registry 전수 성공 case는 각각
`turnCommandGeneralMatrix.integration.test.ts`
`turnCommandNationMatrix.integration.test.ts`가 registry와 exact-set으로 닫습니다.
두 matrix의 `includeLifecycle`은 요청 scope의 queue shift와 tail lifecycle까지이며,
같은 actor의 수뇌→장수 제품 outer loop를 뜻하지 않습니다. 결합 outer lifecycle은
장수·수뇌 명령 전체를 case마다 임시 MariaDB와 PHP Ref에 실행하던 matrix는 운영
서비스가 안정화된 뒤 상시 회귀 비용이 각각 약 1시간에 달해 제거했습니다. 명령 key,
constraint와 log의 정적 계약은 위 `check:legacy:*` 명령이 계속 검사하고, 계산·RNG와
오류 경계는 command별 logic/engine unit이 담당합니다. 결합 outer lifecycle
`turnCommandFullLifecycle.integration.test.ts`, 실제 PostgreSQL flush/reload는
`turnCommandFullLifecyclePersistence.integration.test.ts` 대표 fixture로 검증합니다.
`turnCommandFullLifecyclePersistence.integration.test.ts` 대표 fixture로 검증합니다.
새 호환성 의심은 전수 matrix를 복원하지 않고 해당 command의 좁은 fixture로 재현합니다.
기본 Core canonical/projection 계약:
@@ -139,6 +139,22 @@
"side": "php",
"name": "alwaysFail",
"note": "core preserves the legacy completed-false action in resolve-time handling"
},
{
"id": "non-aggression invalid term becomes legacy dynamic AlwaysFail",
"command": "Nation/che_불가침제의",
"kind": "full",
"side": "php",
"name": "alwaysFail",
"note": "legacy inserts AlwaysFail for a term shorter than six months"
},
{
"id": "non-aggression term range is explicit in core constraints",
"command": "Nation/che_불가침제의",
"kind": "full",
"side": "ts",
"name": "reqTreatyTermRange",
"note": "core exposes the equivalent six-month validation as a named constraint"
}
]
}
@@ -4,8 +4,6 @@ test/instantDiplomacyReference.integration.test.ts reference_command
test/monthlyDisasterCoreReference.integration.test.ts reference_monthly
test/turnCommandCoreReference.integration.test.ts reference_command
test/turnCommandFullLifecycle.integration.test.ts reference_full_lifecycle
test/turnCommandGeneralMatrix.integration.test.ts reference_command
test/turnCommandNationMatrix.integration.test.ts reference_command
test/turnCommandReference.integration.test.ts reference_command
test/turnSnapshotReference.integration.test.ts reference_snapshot
test/turnTraceFiles.integration.test.ts saved_trace_pair
1 # Test file Environment requirement
4 test/monthlyDisasterCoreReference.integration.test.ts reference_monthly
5 test/turnCommandCoreReference.integration.test.ts reference_command
6 test/turnCommandFullLifecycle.integration.test.ts reference_full_lifecycle
test/turnCommandGeneralMatrix.integration.test.ts reference_command
test/turnCommandNationMatrix.integration.test.ts reference_command
7 test/turnCommandReference.integration.test.ts reference_command
8 test/turnSnapshotReference.integration.test.ts reference_snapshot
9 test/turnTraceFiles.integration.test.ts saved_trace_pair
-2
View File
@@ -17,8 +17,6 @@ test/troopStaticEvent.integration.test.ts conditional
test/turnCommandCoreReference.integration.test.ts reference
test/turnCommandFullLifecycle.integration.test.ts reference
test/turnCommandFullLifecyclePersistence.integration.test.ts conditional
test/turnCommandGeneralMatrix.integration.test.ts reference
test/turnCommandNationMatrix.integration.test.ts reference
test/turnCommandReference.integration.test.ts reference
test/turnCommandRiskDurabilityMatrix.integration.test.ts conditional
test/turnLogProjection.test.ts core
1 # Test file Lane
17 test/turnCommandCoreReference.integration.test.ts reference
18 test/turnCommandFullLifecycle.integration.test.ts reference
19 test/turnCommandFullLifecyclePersistence.integration.test.ts conditional
test/turnCommandGeneralMatrix.integration.test.ts reference
test/turnCommandNationMatrix.integration.test.ts reference
20 test/turnCommandReference.integration.test.ts reference
21 test/turnCommandRiskDurabilityMatrix.integration.test.ts conditional
22 test/turnLogProjection.test.ts core
@@ -869,6 +869,77 @@ const assertRngParity = (reference: ReferenceTrace, coreRng: TracingRng | null):
assertCanonicalValue(coreRng?.boolCalls ?? [], reference.boolRng, 'boolRng');
};
const FINAL_GENERAL_INTEGER_FIELDS = ['rice', 'experience', 'dedication'] as const;
const roundLikePhp = (value: number): number => {
const corrected = value + Math.sign(value) * Number.EPSILON * Math.max(1, Math.abs(value)) * 4;
return corrected < 0 ? Math.ceil(corrected - 0.5) : Math.floor(corrected + 0.5);
};
const projectReferenceBattleEndToCoreRounding = (
coreEvents: WarBattleTraceEvent[],
reference: ReferenceTrace
): ReferenceTrace => {
const projected = structuredClone(reference);
const coreFinal = coreEvents.at(-1);
const referenceFinal = projected.events.at(-1);
if (coreFinal?.event !== 'battle_end' || referenceFinal?.event !== 'battle_end') {
return projected;
}
for (const side of ['attacker', 'defender'] as const) {
const coreUnit = coreFinal[side];
const referenceUnit = referenceFinal[side];
if (!coreUnit || !referenceUnit || coreUnit.kind !== 'general' || referenceUnit.kind !== 'general') {
continue;
}
const coreBeforeFinish = coreEvents
.slice(0, -1)
.reverse()
.flatMap((event) => [event.attacker, event.defender])
.find((unit) => unit?.kind === 'general' && unit.id === coreUnit.id);
const referenceBeforeFinish = reference.events
.slice(0, -1)
.reverse()
.flatMap((event) => [event.attacker, event.defender])
.find((unit) => unit?.kind === 'general' && unit.id === referenceUnit.id);
if (!coreBeforeFinish || !referenceBeforeFinish) {
continue;
}
for (const field of FINAL_GENERAL_INTEGER_FIELDS) {
const coreValue = coreUnit.general?.[field];
const referenceValue = referenceUnit.general?.[field];
if (coreValue === referenceValue || coreValue === undefined || referenceValue === undefined) {
continue;
}
const coreRaw = coreBeforeFinish.general?.[field];
const referenceRaw = referenceBeforeFinish.general?.[field];
expectNearlyEqual(coreRaw, referenceRaw, `battle_end.${side}.${field}.raw`);
expect(coreValue, `battle_end.${side}.${field}: Core Math.round policy`).toBe(Math.round(coreRaw!));
expect(referenceValue, `battle_end.${side}.${field}: Ref PHP round policy`).toBe(
roundLikePhp(referenceRaw!)
);
referenceUnit.general![field] = coreValue;
}
}
projected.attacker = referenceFinal.attacker;
projected.finishedDefenders = projected.finishedDefenders.map((unit) => {
if (unit.kind !== 'general') {
return unit;
}
for (const side of ['attacker', 'defender'] as const) {
const finalUnit = referenceFinal[side];
if (finalUnit?.kind === 'general' && finalUnit.id === unit.id) {
return finalUnit;
}
}
return unit;
});
return projected;
};
const assertTraceParity = (
coreEvents: WarBattleTraceEvent[],
reference: ReferenceTrace,
@@ -910,8 +981,9 @@ const assertTraceParity = (
}
}
assertRngParity(reference, coreRng);
assertCanonicalValue(comparableCoreEvents, reference.events, 'events');
assertFinalOutcomeParity(coreOutcome, coreEvents, reference);
const projectedReference = projectReferenceBattleEndToCoreRounding(comparableCoreEvents, reference);
assertCanonicalValue(comparableCoreEvents, projectedReference.events, 'events');
assertFinalOutcomeParity(coreOutcome, coreEvents, projectedReference);
};
const outcomeMetaNumber = (general: WarBattleOutcome['attacker'], key: string): number => {
@@ -267,15 +267,26 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
const proposalBefore = structuredClone(messages[0]!);
const findGeneral = (id: number) => (id === actor.id ? actor : id === proposer.id ? proposer : null);
const queryRaw = vi.fn(async (strings: TemplateStringsArray, ...values: unknown[]) => {
const queryRaw = vi.fn(async (query: unknown, ...taggedValues: unknown[]) => {
const queryObject = query as { strings?: readonly string[]; values?: readonly unknown[] };
const strings = Array.isArray(query) ? query.map(String) : (queryObject.strings ?? []);
const values = Array.isArray(query)
? taggedValues
: Array.isArray(queryObject.values)
? [...queryObject.values]
: taggedValues;
const sql = strings.join('?');
if (sql.includes('FROM message') && sql.includes('WHERE id =')) {
if (sql.includes('FROM message') && (sql.includes('WHERE id =') || sql.includes('WHERE m.id ='))) {
const id = Number(values[0]);
const row = messages.find((message) => message.id === id);
return row && row.valid_until.getTime() > Date.now() ? [row] : [];
}
if (sql.includes('INSERT INTO message')) {
const payload = JSON.parse(String(values[8])) as Record<string, unknown>;
const payloadValue = [...values]
.reverse()
.find((value) => typeof value === 'string' && value.startsWith('{'));
if (payloadValue === undefined) throw new Error('Inserted message payload was not captured.');
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
const row: CoreMessageRow = {
id: messages.at(-1)!.id + 1,
mailbox: Number(values[0]),
@@ -359,11 +370,14 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
currentYear: 190,
currentMonth: 3,
config: { environment: { mapName: 'che' } },
clockBaseTime: null,
clockTick: null,
clockMode: null,
clockWallAnchor: null,
tickSeconds: 60,
clockBaseTime: new Date('0190-03-01T00:00:00.000Z'),
clockTick: 1_000n,
clockMode: 'manual',
clockWallAnchor: new Date('2026-09-04T00:00:00.000Z'),
tickSeconds: 600,
clockPhase: 'RUNNING',
clockRevision: 1n,
deadlineGeneration: 1n,
})),
},
logEntry: {
@@ -382,6 +396,9 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
}
),
},
messageAction: {
updateMany: vi.fn(async () => ({ count: 0 })),
},
$queryRaw: queryRaw,
};
@@ -404,7 +421,9 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
auth,
profile: { id: 'che', scenario: 'default', name: 'che:default' },
redis: {},
turnDaemon: {},
turnDaemon: {
requestCommand: vi.fn(async () => ({ type: 'syncDiplomaticResponse', ok: true })),
},
battleSim: {},
uploadDir: 'uploads',
uploadPath: '/uploads',
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff