merge: scenario 2400 long-run parity

This commit is contained in:
2026-08-04 18:19:53 +00:00
30 changed files with 517 additions and 183 deletions
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import type { TurnCommandEnv } from '@sammo-ts/logic';
import { resolveConstraintEnv } from '../src/turn/ai/generalAi/constraint.js';
describe('general AI constraint environment', () => {
it('passes the current development cost into candidate validation', () => {
const env = resolveConstraintEnv(
{
id: 1,
currentYear: 182,
currentMonth: 5,
tickSeconds: 600,
lastTurnTime: new Date('2026-08-02T05:47:00.000Z'),
meta: { develcost: 24 },
},
{
title: 'test',
startYear: 180,
life: null,
fiction: 1,
history: [],
ignoreDefaultEvents: false,
},
{ develCost: 24, openingPartYear: 3, minAvailableRecruitPop: 30_000 } as TurnCommandEnv
);
expect(env).toMatchObject({ currentYear: 182, currentMonth: 5, develCost: 24 });
});
});
@@ -521,13 +521,11 @@ describe('legacy NPC AI final-decision parity', () => {
rice: 10_000,
meta: { killturn: 100, fullLeadership: 70, rank_killcrew: 0, rank_deathcrew: 1 },
},
generalActionModules: singleActionModuleStack(
{
eventHandlers: {},
onCalcDomestic: (_context, turnType, varType, value) =>
turnType === '징병' && varType === 'cost' ? value * 1.2 : value,
}
),
generalActionModules: singleActionModuleStack({
eventHandlers: {},
onCalcDomestic: (_context, turnType, varType, value) =>
turnType === '징병' && varType === 'cost' ? value * 1.2 : value,
}),
rng: makeRng([], [0, 0]),
});
@@ -698,6 +696,17 @@ describe('legacy NPC AI final-decision parity', () => {
expect(do금쌀구매(ai)).toBeNull();
});
it('uses only the additional same-type crew when estimating the recruit gold reserve', () => {
const ai = makeAi({
general: { gold: 500, rice: 3000, crew: 6900, crewTypeId: 1 },
disabledPolicyActions: ['상인무시'],
});
// A full 7,000-person estimate would make this branch sell rice. Ref's
// recruitment calculator prices only the remaining 100 people.
expect(do금쌀구매(ai)).toBeNull();
});
it('randomly chooses between supply and search when national resources are sufficient', () => {
const ai = makeAi({ rng: makeRng([], [1]) });
expect(do중립(ai)?.action).toBe('che_인재탐색');
@@ -936,13 +945,11 @@ describe('legacy NPC AI final-decision parity', () => {
dipState: 4,
rng,
generals: [baseGeneral(), specialist],
generalActionModules: singleActionModuleStack(
{
eventHandlers: {},
onCalcDomestic: (context, turnType, varType, value) =>
context.general.id === 2 && turnType === '징집인구' && varType === 'score' ? 0 : value,
}
),
generalActionModules: singleActionModuleStack({
eventHandlers: {},
onCalcDomestic: (context, turnType, varType, value) =>
context.general.id === 2 && turnType === '징집인구' && varType === 'score' ? 0 : value,
}),
});
ai.frontCities = { 1: { ...baseCity(), frontState: 3, dev: 1, important: 1 } };
ai.supplyCities = {
@@ -994,4 +1001,32 @@ describe('legacy NPC AI final-decision parity', () => {
ai.npcWarGenerals = { 2: warGeneral };
expect(doNPC몰수(ai)?.action).toBe('che_몰수');
});
it('carries the Ref gold sort order into equal-rice NPC seizure candidates', () => {
const rng = makeRng();
const ai = makeAi({ nation: { gold: 1_000, rice: 1_000 }, rng });
ai.nationPolicy.reqNationGold = 10_000;
ai.nationPolicy.reqNationRice = 10_000;
ai.nationPolicy.reqNpcWarGold = 1_000;
ai.nationPolicy.reqNpcWarRice = 1_000;
const candidate = (id: number, gold: number) => ({
...baseGeneral(),
id,
gold,
rice: 5_000,
meta: { killturn: 100, fullLeadership: 70 },
});
ai.npcCivilGenerals = {};
ai.npcWarGenerals = {
77: candidate(77, 4_000),
534: candidate(534, 5_000),
};
expect(doNPC몰수(ai)?.action).toBe('che_몰수');
const riceCandidates = (rng.weightedPairs[0] ?? [])
.map(([args]) => args as { isGold: boolean; destGeneralId: number })
.filter((args) => !args.isGold)
.map((args) => args.destGeneralId);
expect(riceCandidates).toEqual([534, 77]);
});
});
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { TurnSchedule } from '@sammo-ts/logic/turn/calendar.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { createTurnTestHarness } from './helpers/turnTestHarness.js';
import { applyLegacyGeneralProgression } from '../src/turn/reservedTurnHandler.js';
const start = new Date('0200-01-01T00:00:00.000Z');
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
@@ -152,6 +153,29 @@ const makeState = (): TurnWorldState => ({
});
describe('legacy general-turn execution contract', () => {
it('preserves the battle-computed level across legacy INT rounding', () => {
const previous = makeGeneral({
experience: 6_700,
dedication: 5_800,
meta: { killturn: 24, explevel: 25, dedlevel: 8 },
});
const roundedAfterBattle = makeGeneral({
experience: 6_760,
dedication: 5_871,
meta: { killturn: 24, explevel: 25, dedlevel: 8 },
});
const resolved = applyLegacyGeneralProgression(
roundedAfterBattle,
previous,
'che_출병',
{ maxStatLevel: 255, maxDedicationLevel: 30 } as never,
[]
);
expect(resolved.meta).toMatchObject({ explevel: 25, dedlevel: 8 });
});
it('quantizes integer general columns at each in-memory DB mutation boundary', async () => {
const harness = await createTurnTestHarness({
snapshot: makeSnapshot(makeGeneral()),
@@ -3,9 +3,9 @@ import { describe, expect, it } from 'vitest';
import { buildJoinCreateGeneralSeed, cutJoinTurnTime } from '../src/turn/joinCreateGeneralService.js';
describe('generic join legacy time contracts', () => {
it('builds the Ref MakeGeneral seed from the Seoul whole-second timestamp', () => {
expect(buildJoinCreateGeneralSeed('seed', 42, new Date('2026-07-30T23:59:58.987Z'))).toBe(
'str(4,seed)|str(11,MakeGeneral)|int(42)|str(19,2026-07-31 08:59:58)'
it('builds the Ref MakeGeneral seed from the logical game tick', () => {
expect(buildJoinCreateGeneralSeed('seed', 42, 72_000_000)).toBe(
'str(4,seed)|str(11,MakeGeneral)|int(42)|int(72000000)'
);
});
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { LogCategory, LogFormat, LogScope, type City, type MapDefinition, type Nation } from '@sammo-ts/logic';
import { createIncomeHandler } from '../src/turn/incomeHandler.js';
import { createIncomeHandler, resolveLegacyIncomeCityTrust } from '../src/turn/incomeHandler.js';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import { calculateNpcNationFinance } from '../src/turn/npcTaxHandler.js';
import {
@@ -146,6 +146,10 @@ const buildWorld = (
};
describe('core monthly event actions at the real month boundary', () => {
it('reads income trust through the PHP six-significant-digit FLOAT representation', () => {
expect(resolveLegacyIncomeCityTrust(98.12674)).toBe(98.1267);
});
it('preserves notice format, NewYear month log, age/belong, and officer lock reset', async () => {
const world = buildWorld(
[
@@ -2,10 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { City, Nation, NationTraitModule } from '@sammo-ts/logic';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import {
createProcessSemiAnnualHandler,
storeLegacySemiAnnualTrust,
} from '../src/turn/monthlySemiAnnualAction.js';
import { createProcessSemiAnnualHandler, storeLegacySemiAnnualTrust } from '../src/turn/monthlySemiAnnualAction.js';
import type { TurnEvent, TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
const buildCity = (id: number, patch: Partial<City> = {}): City => ({
@@ -83,41 +83,41 @@ const buildWorld = (hiddenSeed = 'monthly-speciality-fixture') => {
environment: { mapName: 'test', unitSet: 'default' },
};
const domesticGeneral = buildGeneral({
id: 1,
name: '내정대상',
nationId: 1,
stats: [40, 45, 80],
specialDomestic: null,
specialWar: 'che_신산',
meta: { specage: 30, specage2: 99, prev_types_special: ['che_경작'] },
});
id: 1,
name: '내정대상',
nationId: 1,
stats: [40, 45, 80],
specialDomestic: null,
specialWar: 'che_신산',
meta: { specage: 30, specage2: 99, prev_types_special: ['che_경작'] },
});
const warGeneral = buildGeneral({
id: 2,
name: '전투대상',
nationId: 1,
stats: [80, 75, 40],
specialDomestic: 'che_인덕',
specialWar: null,
meta: {
specage: 99,
specage2: 30,
prev_types_special2: ['che_돌격'],
dex1: 200,
dex2: 10,
dex3: 10,
dex4: 10,
dex5: 10,
},
});
id: 2,
name: '전투대상',
nationId: 1,
stats: [80, 75, 40],
specialDomestic: 'che_인덕',
specialWar: null,
meta: {
specage: 99,
specage2: 30,
prev_types_special2: ['che_돌격'],
dex1: 200,
dex2: 10,
dex3: 10,
dex4: 10,
dex5: 10,
},
});
const inheritedGeneral = buildGeneral({
id: 3,
name: '계승대상',
nationId: 2,
stats: [50, 50, 50],
specialDomestic: 'che_경작',
specialWar: null,
meta: { specage: 99, specage2: 30, inheritSpecificSpecialWar: 'che_의술', marker: 3 },
});
id: 3,
name: '계승대상',
nationId: 2,
stats: [50, 50, 50],
specialDomestic: 'che_경작',
specialWar: null,
meta: { specage: 99, specage2: 30, inheritSpecificSpecialWar: 'che_의술', marker: 3 },
});
// The isolated Aria fixture scans eligible war rows as 3, 2 because the
// legacy query has no ORDER BY. Preserve that input order in this trace.
const generals = [domesticGeneral, inheritedGeneral, warGeneral];
@@ -179,11 +179,7 @@ describe('monthly speciality and betrayal actions', () => {
it('does nothing before the three-year opening period ends', async () => {
const world = buildWorld();
await createAssignGeneralSpecialityHandler({ getWorld: () => world })(
[],
{ ...environment, year: 192 },
event
);
await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], { ...environment, year: 192 }, event);
expect(world.peekDirtyState().generals).toEqual([]);
expect(world.peekDirtyState().logs).toEqual([]);
});
@@ -203,6 +199,59 @@ describe('monthly speciality and betrayal actions', () => {
expect(world.getGeneralById(1)?.role.specialWar).not.toBeNull();
});
it('persists creation scan order for speciality RNG across a reload', async () => {
const world = buildWorld();
const laterId = buildGeneral({
id: 5,
name: '먼저생성',
nationId: 0,
stats: [55, 55, 55],
specialDomestic: null,
specialWar: 'che_신산',
meta: { specage: 30, specage2: 99 },
});
const earlierId = buildGeneral({
id: 4,
name: '나중생성',
nationId: 0,
stats: [55, 55, 55],
specialDomestic: null,
specialWar: 'che_신산',
meta: { specage: 30, specage2: 99 },
});
expect(world.addGeneral(laterId)).toBe(true);
expect(world.addGeneral(earlierId)).toBe(true);
const persisted = world.listGenerals().sort((left, right) => left.id - right.id);
expect(persisted.find((general) => general.id === 5)?.meta.legacyScanOrder).toBeLessThan(
persisted.find((general) => general.id === 4)?.meta.legacyScanOrder as number
);
const reloaded = new InMemoryTurnWorld(
world.getState(),
{
scenarioConfig: world.getScenarioConfig(),
map: { id: 'test', name: 'test', cities: [] },
generals: persisted,
cities: [],
nations: [],
troops: [],
diplomacy: [],
events: [event],
initialEvents: [],
},
{ schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } }
);
await createAssignGeneralSpecialityHandler({ getWorld: () => reloaded })([], environment, event);
expect(
reloaded
.peekDirtyState()
.logs.filter((log) => log.category === LogCategory.HISTORY)
.map((log) => log.generalId)
).toEqual([1, 5, 4, 3, 2]);
});
it('applies the two default scenario betrayal steps only to values within each threshold', async () => {
const world = buildWorld();
world.updateGeneral(1, { meta: { ...world.getGeneralById(1)!.meta, betray: 0 } });
+4 -1
View File
@@ -239,7 +239,10 @@ describeDb('scenario database seed', () => {
expect(config.tournamentTrig).toBe(false);
const meta = (worldState.meta ?? {}) as Record<string, unknown>;
expect(meta.develcost).toBe((worldState.currentYear - (scenario.startYear ?? worldState.currentYear) + 10) * 2);
expect(meta.develcost).toBe(
(worldState.currentYear - (scenario.startYear ?? worldState.currentYear) + 10) * 2
);
expect(meta.killturn).toBe(80);
const autorun = (meta.autorun_user ?? {}) as Record<string, unknown>;
const autorunOptions = (autorun.options ?? {}) as Record<string, unknown>;
expect(autorunOptions.develop).toBe(true);
@@ -0,0 +1,20 @@
import { GameClock } from '@sammo-ts/common';
import { describe, expect, test } from 'vitest';
import { calculateInitialTurnTick } from '../src/scenario/scenarioSeeder.js';
describe('scenario seeder general turn tick', () => {
test('preserves Ref-compatible sub-millisecond RNG precision', () => {
const now = new Date('2026-08-02T00:03:44.000Z');
const clock = new GameClock({
baseTime: new Date('2026-08-02T01:00:00.000Z'),
tick: 0,
mode: 'manual',
wallAnchor: now,
turnSeconds: 600,
});
const baseTick = clock.dateToTick(now);
expect(calculateInitialTurnTick(clock, baseTick, 235_265_319)).toBe(baseTick + 14_115_919);
expect(clock.dateToTick(new Date(now.getTime() + 235_265))).toBe(baseTick + 14_115_900);
});
});