fix(parity): preserve legacy monthly turn ordering
This commit is contained in:
@@ -13,6 +13,7 @@ import { do일반내정, do전쟁내정 } from '../src/turn/ai/generalAi/general
|
||||
import { do금쌀구매 } from '../src/turn/ai/generalAi/general/economyActions.js';
|
||||
import { do거병, do건국, do국가선택, do중립 } from '../src/turn/ai/generalAi/general/politicsActions.js';
|
||||
import { do징병 } from '../src/turn/ai/generalAi/general/recruitActions.js';
|
||||
import { doNPC헌납 } from '../src/turn/ai/generalAi/general/npcActions.js';
|
||||
import { do전투준비, do출병 } from '../src/turn/ai/generalAi/general/warActions.js';
|
||||
import { do내정워프, do전방워프, do집합, do후방워프 } from '../src/turn/ai/generalAi/general/warpActions.js';
|
||||
import { doNPC몰수, doNPC포상, do유저장포상 } from '../src/turn/ai/generalAi/nation/rewards.js';
|
||||
@@ -22,6 +23,10 @@ import {
|
||||
doNPC전방발령,
|
||||
doNPC후방발령,
|
||||
} from '../src/turn/ai/generalAi/nation/assignments/npcAssignments.js';
|
||||
import {
|
||||
do부대구출발령,
|
||||
do부대후방발령,
|
||||
} from '../src/turn/ai/generalAi/nation/assignments/troopAssignments.js';
|
||||
|
||||
type Candidate = {
|
||||
action: string;
|
||||
@@ -398,6 +403,24 @@ const makeAi = (
|
||||
* selection and RNG-sensitive gates, not TypeScript implementation details.
|
||||
*/
|
||||
describe('legacy NPC AI final-decision parity', () => {
|
||||
it('rejects the malformed Ref low-rice donation candidate and continues the priority loop', () => {
|
||||
const rng = makeRng([false], [0]);
|
||||
const ai = makeAi({
|
||||
general: { rice: 2_200, gold: 0 },
|
||||
nation: { rice: 400, gold: 20_000 },
|
||||
genType: 4,
|
||||
rng,
|
||||
});
|
||||
ai.nationPolicy.reqNpcWarRice = 1_000;
|
||||
ai.buildGeneralCandidate = ((_action: string, args: Record<string, unknown>) =>
|
||||
typeof args.isGold === 'boolean'
|
||||
? { action: 'che_헌납', args, reason: 'NPC헌납' }
|
||||
: null) as GeneralAI['buildGeneralCandidate'];
|
||||
|
||||
expect(doNPC헌납(ai)).toBeNull();
|
||||
expect(rng.weightedPairs).toEqual([[[{ isGold: 'rice', amount: 1_100 }, 1_100]]]);
|
||||
});
|
||||
|
||||
it('blocks another officer from starting a capital move within half a turn', () => {
|
||||
const base = makeAi({ general: { officerLevel: 10, turnTick: 36_000_100 } });
|
||||
const ai = Object.assign(Object.create(GeneralAI.prototype), base, {
|
||||
@@ -1054,6 +1077,67 @@ describe('legacy NPC AI final-decision parity', () => {
|
||||
expect(rng.weightedPairs[0]).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('uses target action modules for the full leadership in NPC reward costs', () => {
|
||||
const ai = makeAi({
|
||||
nation: { rice: 100_000 },
|
||||
generalActionModules: singleActionModuleStack({
|
||||
eventHandlers: {},
|
||||
onCalcStat: (_context, statName, value) =>
|
||||
statName === 'leadership' ? Number(value) + 30 : value,
|
||||
}),
|
||||
});
|
||||
ai.maxResourceActionAmount = 100_000;
|
||||
const crewType = ai.unitSet?.crewTypes?.[0];
|
||||
if (!crewType) throw new Error('missing test crew type');
|
||||
crewType.cost = 100;
|
||||
ai.npcWarGenerals = {
|
||||
2: {
|
||||
...baseGeneral(),
|
||||
id: 2,
|
||||
rice: 0,
|
||||
crewTypeId: crewType.id,
|
||||
meta: { killturn: 100 },
|
||||
},
|
||||
};
|
||||
ai.npcCivilGenerals = {};
|
||||
|
||||
expect(doNPC포상(ai)).toMatchObject({
|
||||
action: 'che_포상',
|
||||
args: { destGeneralId: 2, isGold: false, amount: 88_000 },
|
||||
});
|
||||
});
|
||||
|
||||
it('uses target action modules when classifying NPC war generals', () => {
|
||||
const specialist = {
|
||||
...baseGeneral(),
|
||||
id: 2,
|
||||
stats: { ...baseGeneral().stats, leadership: 32 },
|
||||
meta: { killturn: 100 },
|
||||
};
|
||||
const base = makeAi({
|
||||
generals: [baseGeneral(), specialist],
|
||||
generalActionModules: singleActionModuleStack({
|
||||
eventHandlers: {},
|
||||
onCalcStat: (context, statName, value) =>
|
||||
context.general.id === 2 && statName === 'leadership' ? Number(value) + 10 : value,
|
||||
}),
|
||||
});
|
||||
const ai = Object.assign(Object.create(GeneralAI.prototype), base, {
|
||||
categorizedCities: false,
|
||||
categorizedGenerals: false,
|
||||
nationCities: {},
|
||||
frontCities: {},
|
||||
supplyCities: {},
|
||||
backupCities: {},
|
||||
}) as GeneralAI;
|
||||
ai.nationPolicy.minNpcWarLeadership = 40;
|
||||
|
||||
ai.categorizeNationGeneral();
|
||||
|
||||
expect(ai.npcWarGenerals[2]?.id).toBe(2);
|
||||
expect(ai.npcCivilGenerals[2]).toBeUndefined();
|
||||
});
|
||||
|
||||
it('excludes no-population recruitment specialists before NPC rear assignment draws RNG', () => {
|
||||
const rng = makeRng([], [0, 0]);
|
||||
const specialist = {
|
||||
@@ -1128,6 +1212,48 @@ describe('legacy NPC AI final-decision parity', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('draws a rear-assignment troop leader before its destination city', () => {
|
||||
const rng = makeRng([], [1, 0]);
|
||||
const first = { ...baseGeneral(), id: 979, cityId: 2 };
|
||||
const second = { ...baseGeneral(), id: 980, cityId: 2 };
|
||||
const ai = makeAi({ rng });
|
||||
ai.troopLeaders = { 979: first, 980: second };
|
||||
ai.nationPolicy.supportForce = [979, 980];
|
||||
ai.frontCities = { 1: { ...baseCity(), frontState: 3, dev: 1, important: 1 } };
|
||||
ai.supplyCities = {
|
||||
2: { ...baseCity(), id: 2, population: 10_000, dev: 1, important: 1 },
|
||||
3: { ...baseCity(), id: 3, dev: 1, important: 1 },
|
||||
};
|
||||
ai.backupCities = { 3: ai.supplyCities[3]! };
|
||||
|
||||
expect(do부대후방발령(ai)).toMatchObject({
|
||||
action: 'che_발령',
|
||||
args: { destGeneralId: 980, destCityId: 3 },
|
||||
});
|
||||
expect(rng.choices).toEqual([]);
|
||||
});
|
||||
|
||||
it('draws a rescue-assignment troop leader before its destination city', () => {
|
||||
const rng = makeRng([], [1, 0]);
|
||||
const first = { ...baseGeneral(), id: 979, cityId: 99 };
|
||||
const second = { ...baseGeneral(), id: 980, cityId: 99 };
|
||||
const ai = makeAi({ rng });
|
||||
ai.troopLeaders = { 979: first, 980: second };
|
||||
ai.nationPolicy.supportForce = [];
|
||||
ai.nationPolicy.combatForce = {};
|
||||
ai.frontCities = {
|
||||
20: { ...baseCity(), id: 20, frontState: 3, dev: 1, important: 1 },
|
||||
21: { ...baseCity(), id: 21, frontState: 3, dev: 1, important: 1 },
|
||||
};
|
||||
ai.supplyCities = {};
|
||||
|
||||
expect(do부대구출발령(ai)).toMatchObject({
|
||||
action: 'che_발령',
|
||||
args: { destGeneralId: 980, destCityId: 20 },
|
||||
});
|
||||
expect(rng.choices).toEqual([]);
|
||||
});
|
||||
|
||||
it('seizes a small war-NPC surplus while the treasury is below 1.5x reserve', () => {
|
||||
const ai = makeAi({ nation: { gold: 12_000, rice: 100_000 } });
|
||||
const warGeneral = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConstantRNG, RandUtil } from '@sammo-ts/common';
|
||||
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';
|
||||
@@ -201,6 +202,67 @@ describe('legacy general-turn execution contract', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps fractional nation rewards in the same general object until the following command is persisted', async () => {
|
||||
const twoCityMap = {
|
||||
...map,
|
||||
cities: [
|
||||
{ ...map.cities[0]!, connections: [2] },
|
||||
{ ...map.cities[0]!, id: 2, name: '두번째성', position: { x: 1, y: 0 }, connections: [1] },
|
||||
],
|
||||
};
|
||||
const general = makeGeneral({
|
||||
officerLevel: 12,
|
||||
stats: { leadership: 80, strength: 70, intelligence: 52 },
|
||||
role: {
|
||||
personality: 'che_출세',
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
},
|
||||
});
|
||||
const snapshot = makeSnapshot(general);
|
||||
snapshot.map = twoCityMap;
|
||||
snapshot.cities.push({
|
||||
...snapshot.cities[0]!,
|
||||
id: 2,
|
||||
name: '두번째성',
|
||||
});
|
||||
snapshot.nations[0] = {
|
||||
...snapshot.nations[0]!,
|
||||
chiefGeneralId: 1,
|
||||
meta: {
|
||||
gennum: 1,
|
||||
tech: 0,
|
||||
capset: 0,
|
||||
turn_last_12: {
|
||||
command: '천도',
|
||||
arg: { destCityID: 2 },
|
||||
term: 2,
|
||||
seq: 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
const harness = await createTurnTestHarness({
|
||||
snapshot,
|
||||
state: makeState(),
|
||||
schedule,
|
||||
map: twoCityMap,
|
||||
commandRngFactory: () => new RandUtil(new ConstantRNG(0)),
|
||||
});
|
||||
harness.reservedTurnStore.getNationTurns(1, 12)[0] = {
|
||||
action: 'che_천도',
|
||||
args: { destCityID: 2 },
|
||||
};
|
||||
harness.reservedTurnStore.getGeneralTurns(1)[0] = { action: 'che_상업투자', args: {} };
|
||||
|
||||
await harness.runOneTick();
|
||||
|
||||
// 천도 15 * 1.1 = 16.5, 상업 투자 6 * 0.7 * 1.1 = 4.62.
|
||||
// Ref keeps 21.12 in the PHP object and rounds it once at persistence.
|
||||
expect(harness.world.getGeneralById(1)?.experience).toBe(21);
|
||||
expect(harness.world.getNationById(1)?.capitalCityId).toBe(2);
|
||||
});
|
||||
|
||||
it('applies inherited domestic stat progression after farming', async () => {
|
||||
const general = makeGeneral({ meta: { killturn: 24, intel_exp: 29 } });
|
||||
const harness = await createTurnTestHarness({
|
||||
|
||||
@@ -68,14 +68,16 @@ integration('monthly catalog boundary persistence', () => {
|
||||
security: 1_000,
|
||||
securityMax: 2_000,
|
||||
trust: 50,
|
||||
trade: 100,
|
||||
trade: null,
|
||||
defence: 1_000,
|
||||
defenceMax: 2_000,
|
||||
wall: 1_000,
|
||||
wallMax: 2_000,
|
||||
region: 1,
|
||||
conflict: {},
|
||||
meta: { state: 31, term: 1, officer_set: 1 },
|
||||
// Projected columns are deliberately stale in JSON. The
|
||||
// dedicated nullable columns remain authoritative.
|
||||
meta: { state: 31, term: 1, officer_set: 1, trust: 1, trade: 0, region: 99 },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
@@ -248,6 +250,8 @@ integration('monthly catalog boundary persistence', () => {
|
||||
enableLeaseHeartbeat: false,
|
||||
});
|
||||
try {
|
||||
expect(runtime.world.getCityById(1)?.meta).toMatchObject({ trust: 50, region: 1 });
|
||||
expect(runtime.world.getCityById(1)?.meta).not.toHaveProperty('trade');
|
||||
await runtime.world.advanceMonth(new Date('2026-07-25T02:00:00.000Z'));
|
||||
await runtime.hooks?.flushChanges?.({
|
||||
lastTurnTime: runtime.world.getState().lastTurnTime.toISOString(),
|
||||
@@ -271,6 +275,10 @@ integration('monthly catalog boundary persistence', () => {
|
||||
{ id: 1, age: 31, gold: 1_400, meta: expect.objectContaining({ belong: 4, makelimit: 1 }) },
|
||||
{ id: 2, age: 26, gold: 500, meta: expect.objectContaining({ belong: 4, makelimit: 0 }) },
|
||||
]);
|
||||
const persistedCityMeta = (await db.city.findUniqueOrThrow({ where: { id: 1 } })).meta;
|
||||
expect(persistedCityMeta).not.toHaveProperty('trust');
|
||||
expect(persistedCityMeta).not.toHaveProperty('trade');
|
||||
expect(persistedCityMeta).not.toHaveProperty('region');
|
||||
expect(
|
||||
await db.city.findMany({
|
||||
orderBy: { id: 'asc' },
|
||||
|
||||
@@ -194,6 +194,9 @@ describe('CreateManyNPC monthly action', () => {
|
||||
"turnTime": "0200-05-01T00:05:45.821Z",
|
||||
}
|
||||
`);
|
||||
expect(created.turnTick).toBeTypeOf('number');
|
||||
expect(created.turnTick! - world.dateToGameTick(created.turnTime)).toBeGreaterThan(0);
|
||||
expect(created.turnTick! - world.dateToGameTick(created.turnTime)).toBeLessThan(60);
|
||||
expect(reservedTurns.getGeneralTurns(created.id)).toHaveLength(30);
|
||||
expect(reservedTurns.peekDirtyState()).toEqual({
|
||||
generalIds: [],
|
||||
|
||||
@@ -210,6 +210,10 @@ describe('RaiseNPCNation monthly action', () => {
|
||||
const dirty = world.peekDirtyState();
|
||||
expect(dirty.createdNations).toHaveLength(1);
|
||||
expect(dirty.createdGenerals).toHaveLength(1);
|
||||
const created = dirty.createdGenerals[0]!;
|
||||
expect(created.turnTick).toBeTypeOf('number');
|
||||
expect(created.turnTick! - world.dateToGameTick(created.turnTime)).toBeGreaterThan(0);
|
||||
expect(created.turnTick! - world.dateToGameTick(created.turnTime)).toBeLessThan(60);
|
||||
expect(dirty.createdNations[0]).toMatchInlineSnapshot(`
|
||||
{
|
||||
"capitalCityId": 4,
|
||||
|
||||
@@ -141,6 +141,9 @@ describe('RegNPC and RegNeutralNPC monthly actions', () => {
|
||||
);
|
||||
|
||||
const created = world.peekDirtyState().createdGenerals[0]!;
|
||||
expect(created.turnTick).toBeTypeOf('number');
|
||||
expect(created.turnTick! - world.dateToGameTick(created.turnTime)).toBeGreaterThan(0);
|
||||
expect(created.turnTick! - world.dateToGameTick(created.turnTime)).toBeLessThan(60);
|
||||
expect(created).toMatchObject({
|
||||
name: 'ⓝ등장장수',
|
||||
nationId: 1,
|
||||
|
||||
@@ -37,7 +37,7 @@ const buildGeneral = (id: number, turnTime: Date): TurnGeneral => ({
|
||||
});
|
||||
|
||||
describe('InMemoryTurnProcessor ordering', () => {
|
||||
it('executes generals by turnTime then id, not insertion order', async () => {
|
||||
it('executes generals by logical turn tick then id, not projected millisecond or insertion order', async () => {
|
||||
const baseTime = new Date('0189-01-01T00:00:00Z');
|
||||
|
||||
const generals: TurnGeneral[] = [
|
||||
@@ -169,17 +169,18 @@ describe('InMemoryTurnProcessor ordering', () => {
|
||||
const boundaryResult = await processor.run(addMinutes(baseTime, 10), budget);
|
||||
expect(boundaryResult.processedTurns).toBe(1);
|
||||
expect(executed).toEqual([]);
|
||||
expect(world.listDueGenerals(addMinutes(baseTime, 10)).map((general) => general.id)).toEqual([3]);
|
||||
|
||||
const tiedGeneralResult = await processor.run(new Date(addMinutes(baseTime, 10).getTime() + 1), budget);
|
||||
expect(tiedGeneralResult.processedTurns).toBe(0);
|
||||
expect(executed).toEqual([2, 3]);
|
||||
expect(executed).toEqual([3, 2]);
|
||||
expect(world.getGeneralById(2)?.recentWarTime?.getTime()).toBe(baseTime.getTime());
|
||||
expect(world.getGeneralById(2)?.recentWarTick).not.toBeNull();
|
||||
expect(Number(world.getGeneralById(2)?.turnTick) % 10).toBe(4);
|
||||
|
||||
await processor.run(addMinutes(baseTime, 30), budget);
|
||||
|
||||
expect(executed).toEqual([2, 3, 1, 2, 3]);
|
||||
expect(executed).toEqual([3, 2, 1, 3, 2]);
|
||||
expect(world.getNextGeneralId()).toBe(4);
|
||||
expect(world.getNextGeneralId()).toBe(5);
|
||||
expect(world.getState().meta).toMatchObject({ lastGeneralId: 5 });
|
||||
@@ -187,6 +188,7 @@ describe('InMemoryTurnProcessor ordering', () => {
|
||||
const overdue = world.getGeneralById(1);
|
||||
expect(overdue).toBeDefined();
|
||||
overdue!.turnTime = addMinutes(baseTime, 5);
|
||||
overdue!.turnTick = undefined;
|
||||
const overdueResult = await processor.run(addMinutes(baseTime, 5), budget);
|
||||
expect(overdueResult.processedGenerals).toBe(1);
|
||||
expect(executed.at(-1)).toBe(1);
|
||||
|
||||
Reference in New Issue
Block a user