From de9f1cbc64d0550c1ed5828c1c11169129b86bd4 Mon Sep 17 00:00:00 2001 From: hided62 Date: Sat, 25 Jul 2026 20:55:34 +0000 Subject: [PATCH] feat: port monthly speciality and betrayal actions --- .../src/turn/monthlySpecialityBetrayAction.ts | 262 +++++++++++++++++ app/game-engine/src/turn/turnDaemon.ts | 16 + .../monthlySpecialityBetrayAction.test.ts | 273 ++++++++++++++++++ ...alityBetrayPersistence.integration.test.ts | 221 ++++++++++++++ 4 files changed, 772 insertions(+) create mode 100644 app/game-engine/src/turn/monthlySpecialityBetrayAction.ts create mode 100644 app/game-engine/test/monthlySpecialityBetrayAction.test.ts create mode 100644 app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts diff --git a/app/game-engine/src/turn/monthlySpecialityBetrayAction.ts b/app/game-engine/src/turn/monthlySpecialityBetrayAction.ts new file mode 100644 index 0000000..830ed0f --- /dev/null +++ b/app/game-engine/src/turn/monthlySpecialityBetrayAction.ts @@ -0,0 +1,262 @@ +import { JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common'; +import { + LogCategory, + LogFormat, + LogScope, + TraitSelector, + WAR_TRAIT_KEYS, + loadDomesticTraitModules, + loadWarTraitModules, + type TraitModule, +} from '@sammo-ts/logic'; +import { simpleSerialize } from '@sammo-ts/logic/war/utils.js'; + +import type { InMemoryTurnWorld } from './inMemoryWorld.js'; +import type { MonthlyEventActionHandler, MonthlyEventEnvironment } from './monthlyEventHandler.js'; +import type { TurnGeneral } from './types.js'; + +const LEGACY_DOMESTIC_SELECTION_KEYS = [ + 'che_경작', + 'che_상재', + 'che_발명', + 'che_축성', + 'che_수비', + 'che_통찰', + 'che_인덕', + 'che_귀모', +] as const; + +const normalizeCode = (value: unknown): string | null => + typeof value === 'string' && value !== '' && value !== 'None' ? value : null; + +const readFiniteNumber = (source: Record, keys: readonly string[]): number | null => { + for (const key of keys) { + const value = source[key]; + if (typeof value === 'number' && Number.isFinite(value)) { + return value; + } + } + return null; +}; + +const readStringList = (source: Record, key: string): string[] => { + const value = source[key]; + return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []; +}; + +const resolveHiddenSeed = (world: InMemoryTurnWorld): string | number => { + const state = world.getState(); + const value = state.meta.hiddenSeed ?? state.meta.seed ?? state.id; + return typeof value === 'string' || typeof value === 'number' ? value : String(value); +}; + +const readRuntimeNumber = (world: InMemoryTurnWorld, key: string, fallback: number): number => { + const value = world.getScenarioConfig().const[key]; + return typeof value === 'number' && Number.isFinite(value) ? value : fallback; +}; + +const buildSpecialityAge = ( + retirementYear: number, + age: number, + relativeYear: number, + divisor: number +): number => Math.max(Math.round((retirementYear - age) / divisor - relativeYear / 2), 3) + age; + +const resolveSpecialityAge = ( + general: TurnGeneral, + environment: MonthlyEventEnvironment, + retirementYear: number, + kind: 'domestic' | 'war' +): number => { + const stored = readFiniteNumber( + general.meta, + kind === 'domestic' ? ['specage', 'specAge'] : ['specage2', 'specAge2'] + ); + if (stored !== null) { + return stored; + } + + const currentRelativeYear = Math.max(environment.year - environment.startyear, 0); + const startAge = + typeof general.startAge === 'number' && Number.isFinite(general.startAge) + ? general.startAge + : general.age - currentRelativeYear; + const yearsSinceCreation = Math.max(general.age - startAge, 0); + const creationRelativeYear = Math.max(currentRelativeYear - yearsSinceCreation, 0); + return buildSpecialityAge(retirementYear, startAge, creationRelativeYear, kind === 'domestic' ? 12 : 6); +}; + +const pushSpecialityLogs = ( + world: InMemoryTurnWorld, + general: TurnGeneral, + traitName: string, + environment: MonthlyEventEnvironment +): void => { + const josaUl = JosaUtil.pick(traitName, '을'); + world.pushLog({ + scope: LogScope.GENERAL, + category: LogCategory.HISTORY, + generalId: general.id, + text: `특기 【${traitName}】${josaUl} 습득`, + format: LogFormat.YEAR_MONTH, + year: environment.year, + month: environment.month, + }); + world.pushLog({ + scope: LogScope.GENERAL, + category: LogCategory.ACTION, + generalId: general.id, + text: `특기 【${traitName}】${josaUl} 익혔습니다!`, + format: LogFormat.PLAIN, + year: environment.year, + month: environment.month, + }); +}; + +const resolveTrait = (modules: readonly TraitModule[], key: string, label: string): TraitModule => { + const module = modules.find((candidate) => candidate.key === key); + if (!module) { + throw new Error(`Unknown ${label} speciality: ${key}`); + } + return module; +}; + +export const createAssignGeneralSpecialityHandler = (options: { + getWorld: () => InMemoryTurnWorld | null; +}): MonthlyEventActionHandler => { + let modulePromise: + | Promise<{ domesticModules: TraitModule[]; warModules: TraitModule[] }> + | undefined; + const loadModules = () => { + modulePromise ??= Promise.all([ + loadDomesticTraitModules([...LEGACY_DOMESTIC_SELECTION_KEYS]), + loadWarTraitModules([...WAR_TRAIT_KEYS]), + ]).then(([domesticModules, warModules]) => ({ domesticModules, warModules })); + return modulePromise; + }; + + return async (_args, environment) => { + const world = options.getWorld(); + if (!world || environment.year < environment.startyear + 3) { + return; + } + const { domesticModules, warModules } = await loadModules(); + const rng = new RandUtil( + new LiteHashDRBG( + simpleSerialize(resolveHiddenSeed(world), 'assignGeneralSpeciality', environment.year, environment.month) + ) + ); + const defaultDomestic = normalizeCode(world.getScenarioConfig().const.defaultSpecialDomestic); + const defaultWar = normalizeCode(world.getScenarioConfig().const.defaultSpecialWar); + const retirementYear = readRuntimeNumber(world, 'retirementYear', 80); + const scenarioStat = world.getScenarioConfig().stat; + // ref SQL에 ORDER BY가 없으므로 loader가 보존한 DB scan 순서를 두 + // domestic/war pass에서 그대로 재사용한다. + const generals = world.listGenerals(); + + for (const general of generals) { + if ( + general.role.specialDomestic !== defaultDomestic || + resolveSpecialityAge(general, environment, retirementYear, 'domestic') > general.age + ) { + continue; + } + const key = TraitSelector.pickDomesticTrait( + rng, + general.stats, + domesticModules, + readStringList(general.meta, 'prev_types_special'), + scenarioStat + ); + if (!key) { + throw new Error(`Unable to assign domestic speciality (generalId=${general.id}).`); + } + const trait = resolveTrait(domesticModules, key, 'domestic'); + world.updateGeneral(general.id, { + role: { ...general.role, specialDomestic: key }, + }); + pushSpecialityLogs(world, general, trait.name, environment); + } + + for (const general of generals) { + const currentGeneral = world.getGeneralById(general.id) ?? general; + if ( + currentGeneral.role.specialWar !== defaultWar || + resolveSpecialityAge(currentGeneral, environment, retirementYear, 'war') > currentGeneral.age + ) { + continue; + } + const inherited = currentGeneral.meta.inheritSpecificSpecialWar; + let key: string | null; + let meta = currentGeneral.meta; + let removeInherited = false; + if (Object.prototype.hasOwnProperty.call(currentGeneral.meta, 'inheritSpecificSpecialWar')) { + if (typeof inherited !== 'string') { + throw new Error(`Invalid inherited war speciality (generalId=${currentGeneral.id}).`); + } + key = inherited; + removeInherited = true; + } else { + key = TraitSelector.pickWarTrait( + rng, + currentGeneral.stats, + [ + readFiniteNumber(currentGeneral.meta, ['dex1']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex2']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex3']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex4']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex5']) ?? 0, + ], + warModules, + readStringList(currentGeneral.meta, 'prev_types_special2'), + scenarioStat + ); + } + if (!key) { + throw new Error(`Unable to assign war speciality (generalId=${currentGeneral.id}).`); + } + const trait = resolveTrait(warModules, key, 'war'); + if (removeInherited) { + delete currentGeneral.meta.inheritSpecificSpecialWar; + meta = { ...currentGeneral.meta }; + } + world.updateGeneral(currentGeneral.id, { + role: { ...currentGeneral.role, specialWar: key }, + meta, + }); + pushSpecialityLogs(world, currentGeneral, trait.name, environment); + } + }; +}; + +const readOptionalInteger = (value: unknown, fallback: number, label: string): number => { + if (value === undefined) { + return fallback; + } + if (typeof value !== 'number' || !Number.isInteger(value)) { + throw new Error(`${label} must be an integer.`); + } + return value; +}; + +export const createAddGlobalBetrayHandler = (options: { + getWorld: () => InMemoryTurnWorld | null; +}): MonthlyEventActionHandler => { + return (args) => { + const world = options.getWorld(); + if (!world) { + return; + } + const count = readOptionalInteger(args[0], 1, 'AddGlobalBetray count'); + const maximum = readOptionalInteger(args[1], 0, 'AddGlobalBetray maximum'); + for (const general of world.listGenerals()) { + const betray = readFiniteNumber(general.meta, ['betray']) ?? 0; + if (betray > maximum) { + continue; + } + world.updateGeneral(general.id, { + meta: { ...general.meta, betray: betray + count }, + }); + } + }; +}; diff --git a/app/game-engine/src/turn/turnDaemon.ts b/app/game-engine/src/turn/turnDaemon.ts index 27955dd..0ff3cd6 100644 --- a/app/game-engine/src/turn/turnDaemon.ts +++ b/app/game-engine/src/turn/turnDaemon.ts @@ -66,6 +66,10 @@ import { createOpenNationBettingHandler, } from './monthlyNationBettingAction.js'; import { createScoutBlockHandler } from './monthlyScoutBlockAction.js'; +import { + createAddGlobalBetrayHandler, + createAssignGeneralSpecialityHandler, +} from './monthlySpecialityBetrayAction.js'; import { buildCommandEnv } from './reservedTurnCommands.js'; import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js'; @@ -358,6 +362,18 @@ const createTurnDaemonRuntimeWithLease = async ( }) ); } + eventActions.set( + 'AssignGeneralSpeciality', + createAssignGeneralSpecialityHandler({ + getWorld: () => worldRef, + }) + ); + eventActions.set( + 'AddGlobalBetray', + createAddGlobalBetrayHandler({ + getWorld: () => worldRef, + }) + ); eventActions.set('ProcessIncome', async (_args, environment) => { await incomeHandler.onMonthChanged?.({ previousYear: environment.month === 1 ? environment.year - 1 : environment.year, diff --git a/app/game-engine/test/monthlySpecialityBetrayAction.test.ts b/app/game-engine/test/monthlySpecialityBetrayAction.test.ts new file mode 100644 index 0000000..04b5d4e --- /dev/null +++ b/app/game-engine/test/monthlySpecialityBetrayAction.test.ts @@ -0,0 +1,273 @@ +import { describe, expect, it } from 'vitest'; +import { LogCategory, LogFormat } from '@sammo-ts/logic'; + +import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js'; +import { + createAddGlobalBetrayHandler, + createAssignGeneralSpecialityHandler, +} from '../src/turn/monthlySpecialityBetrayAction.js'; +import type { TurnEvent, TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js'; + +const event: TurnEvent = { + id: 1, + targetCode: 'month', + priority: 9_000, + condition: true, + action: [], + meta: {}, +}; + +const buildGeneral = (options: { + id: number; + name: string; + nationId: number; + stats: [number, number, number]; + specialDomestic: string | null; + specialWar: string | null; + meta: Record; +}): TurnGeneral => ({ + id: options.id, + userId: null, + name: options.name, + nationId: options.nationId, + cityId: options.id === 1 ? 1 : 2, + troopId: 0, + stats: { + leadership: options.stats[0], + strength: options.stats[1], + intelligence: options.stats[2], + }, + experience: 0, + dedication: 0, + officerLevel: 1, + role: { + personality: null, + specialDomestic: options.specialDomestic, + specialWar: options.specialWar, + items: { horse: null, weapon: null, book: null, item: null }, + }, + injury: 0, + gold: 1_000, + rice: 1_000, + crew: 0, + crewTypeId: 0, + train: 0, + atmos: 0, + age: 30, + startAge: 20, + npcState: 2, + triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, + meta: { ...options.meta, killturn: 24 }, + lastTurn: { command: '휴식' }, + turnTime: new Date('0200-01-01T00:00:00.000Z'), +}); + +const buildWorld = (hiddenSeed = 'monthly-speciality-fixture') => { + const state: TurnWorldState = { + id: 1, + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + lastTurnTime: new Date('0200-01-01T00:00:00.000Z'), + meta: { hiddenSeed }, + }; + const scenarioConfig: TurnWorldSnapshot['scenarioConfig'] = { + stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 75, npcMin: 10, chiefMin: 70 }, + iconPath: '.', + map: {}, + const: { + defaultSpecialDomestic: 'None', + defaultSpecialWar: 'None', + retirementYear: 80, + }, + 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_경작'] }, + }); + 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, + }, + }); + 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 }, + }); + // 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]; + return new InMemoryTurnWorld( + state, + { + scenarioConfig, + map: { id: 'test', name: 'test', cities: [] }, + generals, + cities: [], + nations: [], + troops: [], + diplomacy: [], + events: [event], + initialEvents: [], + }, + { schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } } + ); +}; + +const environment = { + year: 200, + month: 1, + startyear: 190, + currentEventID: 1, + turnTime: new Date('0200-01-01T00:00:00.000Z'), +}; + +describe('monthly speciality and betrayal actions', () => { + it('assigns eligible traits, consumes inherited war choice without RNG, and writes legacy logs', async () => { + const world = buildWorld(); + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + + expect(world.getGeneralById(1)?.role.specialDomestic).not.toBeNull(); + expect(world.getGeneralById(1)?.role.specialDomestic).not.toBe('che_경작'); + expect(world.getGeneralById(2)?.role.specialWar).not.toBeNull(); + expect(world.getGeneralById(2)?.role.specialWar).not.toBe('che_돌격'); + expect(world.getGeneralById(3)?.role.specialWar).toBe('che_의술'); + expect(world.getGeneralById(3)?.meta).toEqual(expect.objectContaining({ marker: 3, killturn: 24 })); + expect(world.getGeneralById(3)?.meta).not.toHaveProperty('inheritSpecificSpecialWar'); + + const logs = world.peekDirtyState().logs; + expect(logs).toHaveLength(6); + expect(logs.slice(2, 4)).toEqual([ + expect.objectContaining({ + generalId: 3, + category: LogCategory.HISTORY, + format: LogFormat.YEAR_MONTH, + text: '특기 【의술】을 습득', + }), + expect.objectContaining({ + generalId: 3, + category: LogCategory.ACTION, + format: LogFormat.PLAIN, + text: '특기 【의술】을 익혔습니다!', + }), + ]); + }); + + it('does nothing before the three-year opening period ends', async () => { + const world = buildWorld(); + await createAssignGeneralSpecialityHandler({ getWorld: () => world })( + [], + { ...environment, year: 192 }, + event + ); + expect(world.peekDirtyState().generals).toEqual([]); + expect(world.peekDirtyState().logs).toEqual([]); + }); + + it('preserves a domestic trait when the same general also receives a war trait', async () => { + const world = buildWorld(); + const general = world.getGeneralById(1)!; + world.updateGeneral(1, { + role: { ...general.role, specialWar: null }, + meta: { ...general.meta, specage2: 30 }, + }); + world.acknowledgeDirtyState(world.peekDirtyState()); + + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + + expect(world.getGeneralById(1)?.role.specialDomestic).not.toBeNull(); + expect(world.getGeneralById(1)?.role.specialWar).not.toBeNull(); + }); + + 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 } }); + world.updateGeneral(2, { meta: { ...world.getGeneralById(2)!.meta, betray: 1 } }); + world.updateGeneral(3, { meta: { ...world.getGeneralById(3)!.meta, betray: 2 } }); + world.acknowledgeDirtyState(world.peekDirtyState()); + const handler = createAddGlobalBetrayHandler({ getWorld: () => world }); + + await handler([1, 0], environment, event); + await handler([1, 1], environment, event); + + expect(world.listGenerals().map((general) => general.meta.betray)).toEqual([2, 2, 2]); + }); + + it.skipIf(!process.env.REF_HIDDEN_SEED)('matches the isolated legacy fixed-seed trait choices', async () => { + const world = buildWorld(process.env.REF_HIDDEN_SEED); + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + + expect(world.getGeneralById(1)?.role.specialDomestic).toBe('che_상재'); + expect(world.getGeneralById(2)?.role.specialWar).toBe('che_필살'); + expect(world.getGeneralById(3)?.role.specialWar).toBe('che_의술'); + expect( + world.peekDirtyState().logs.map((log) => ({ + generalId: log.generalId, + category: log.category, + text: log.text, + format: log.format, + })) + ).toEqual([ + { + generalId: 1, + category: LogCategory.HISTORY, + text: '특기 【상재】를 습득', + format: LogFormat.YEAR_MONTH, + }, + { + generalId: 1, + category: LogCategory.ACTION, + text: '특기 【상재】를 익혔습니다!', + format: LogFormat.PLAIN, + }, + { + generalId: 3, + category: LogCategory.HISTORY, + text: '특기 【의술】을 습득', + format: LogFormat.YEAR_MONTH, + }, + { + generalId: 3, + category: LogCategory.ACTION, + text: '특기 【의술】을 익혔습니다!', + format: LogFormat.PLAIN, + }, + { + generalId: 2, + category: LogCategory.HISTORY, + text: '특기 【필살】을 습득', + format: LogFormat.YEAR_MONTH, + }, + { + generalId: 2, + category: LogCategory.ACTION, + text: '특기 【필살】을 익혔습니다!', + format: LogFormat.PLAIN, + }, + ]); + }); +}); diff --git a/app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts b/app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts new file mode 100644 index 0000000..12c3913 --- /dev/null +++ b/app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts @@ -0,0 +1,221 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Nation } from '@sammo-ts/logic'; +import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra'; + +import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js'; +import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js'; +import { + createAddGlobalBetrayHandler, + createAssignGeneralSpecialityHandler, +} from '../src/turn/monthlySpecialityBetrayAction.js'; +import type { TurnEvent, TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js'; + +const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL; +const integration = describe.skipIf(!databaseUrl); +const nationId = 990_091; +const generalIds = [990_091, 990_092] as const; + +const event: TurnEvent = { + id: 1, + targetCode: 'month', + priority: 9_000, + condition: true, + action: [], + meta: {}, +}; + +const nation: Nation = { + id: nationId, + name: '특기검증국', + color: '#777777', + capitalCityId: null, + chiefGeneralId: null, + gold: 0, + rice: 0, + power: 0, + level: 2, + typeCode: 'che_중립', + meta: {}, +}; + +const buildGeneral = ( + id: number, + options: { domestic: string | null; war: string | null; meta: Record } +): TurnGeneral => ({ + id, + userId: null, + name: id === generalIds[0] ? '영속내정대상' : '영속계승대상', + nationId, + cityId: 0, + troopId: 0, + stats: { leadership: 40, strength: 45, intelligence: 80 }, + experience: 0, + dedication: 0, + officerLevel: 1, + role: { + personality: null, + specialDomestic: options.domestic, + specialWar: options.war, + items: { horse: null, weapon: null, book: null, item: null }, + }, + injury: 0, + gold: 1_000, + rice: 1_000, + crew: 0, + crewTypeId: 0, + train: 0, + atmos: 0, + age: 30, + startAge: 20, + npcState: 2, + triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, + meta: { ...options.meta, killturn: 24 }, + lastTurn: { command: '휴식' }, + turnTime: new Date('2026-07-25T00:00:00.000Z'), +}); + +integration('monthly speciality and betrayal persistence', () => { + let db: GamePrismaClient; + let closeDb: (() => Promise) | undefined; + + beforeAll(async () => { + const connector = createGamePostgresConnector({ url: databaseUrl! }); + await connector.connect(); + db = connector.prisma; + closeDb = () => connector.disconnect(); + await db.logEntry.deleteMany({ where: { generalId: { in: [...generalIds] } } }); + await db.general.deleteMany({ where: { id: { in: [...generalIds] } } }); + await db.nation.deleteMany({ where: { id: nationId } }); + }); + + afterAll(async () => { + await db.logEntry.deleteMany({ where: { generalId: { in: [...generalIds] } } }); + await db.general.deleteMany({ where: { id: { in: [...generalIds] } } }); + await db.nation.deleteMany({ where: { id: nationId } }); + await closeDb?.(); + }); + + it('flushes trait columns, inherited aux removal, betrayal, and four general logs', async () => { + const generals = [ + buildGeneral(generalIds[0], { + domestic: null, + war: 'che_신산', + meta: { specage: 30, specage2: 99, betray: 0 }, + }), + buildGeneral(generalIds[1], { + domestic: 'che_경작', + war: null, + meta: { + specage: 99, + specage2: 30, + betray: 1, + inheritSpecificSpecialWar: 'che_의술', + marker: 2, + }, + }), + ]; + await db.nation.create({ + data: { + id: nation.id, + name: nation.name, + color: nation.color, + level: nation.level, + typeCode: nation.typeCode, + meta: {}, + }, + }); + await db.general.createMany({ + data: generals.map((general) => ({ + id: general.id, + name: general.name, + nationId: general.nationId, + cityId: general.cityId, + leadership: general.stats.leadership, + strength: general.stats.strength, + intel: general.stats.intelligence, + age: general.age, + startAge: general.startAge, + specialCode: general.role.specialDomestic ?? 'None', + special2Code: general.role.specialWar ?? 'None', + turnTime: general.turnTime, + meta: general.meta, + })), + }); + const row = await db.worldState.create({ + data: { + scenarioCode: 'monthly-speciality-betray-persistence', + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + config: {}, + meta: { hiddenSeed: 'monthly-speciality-persistence' }, + }, + }); + const state: TurnWorldState = { + id: row.id, + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + lastTurnTime: new Date('2026-07-25T00:00:00.000Z'), + meta: { hiddenSeed: 'monthly-speciality-persistence' }, + }; + const snapshot: TurnWorldSnapshot = { + scenarioConfig: { + stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 75, npcMin: 10, chiefMin: 70 }, + iconPath: '.', + map: {}, + const: { + defaultSpecialDomestic: 'None', + defaultSpecialWar: 'None', + retirementYear: 80, + }, + environment: { mapName: 'test', unitSet: 'default' }, + }, + map: { id: 'test', name: 'test', cities: [] }, + generals, + cities: [], + nations: [nation], + troops: [], + diplomacy: [], + events: [event], + initialEvents: [], + }; + const world = new InMemoryTurnWorld(state, snapshot, { + schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] }, + }); + const hooks = await createDatabaseTurnHooks(databaseUrl!, world); + const environment = { + year: 200, + month: 1, + startyear: 190, + currentEventID: 1, + turnTime: state.lastTurnTime, + }; + + try { + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + await createAddGlobalBetrayHandler({ getWorld: () => world })([2, 1], environment, event); + await hooks.hooks.flushChanges?.({ + lastTurnTime: state.lastTurnTime.toISOString(), + processedGenerals: 0, + processedTurns: 2, + durationMs: 0, + partial: false, + }); + + const rows = await db.general.findMany({ + where: { id: { in: [...generalIds] } }, + orderBy: { id: 'asc' }, + }); + expect(rows[0]?.specialCode).not.toBe('None'); + expect(rows[0]?.meta).toMatchObject({ betray: 2 }); + expect(rows[1]).toMatchObject({ special2Code: 'che_의술' }); + expect(rows[1]?.meta).toMatchObject({ betray: 3, marker: 2 }); + expect(rows[1]?.meta).not.toHaveProperty('inheritSpecificSpecialWar'); + expect(await db.logEntry.count({ where: { generalId: { in: [...generalIds] } } })).toBe(4); + } finally { + await hooks.close(); + await db.worldState.deleteMany({ where: { id: row.id } }); + } + }); +});