feat: execute MyPage immediate actions in daemon

This commit is contained in:
2026-07-31 01:56:16 +00:00
parent c6a2a0da93
commit d82e493109
13 changed files with 1836 additions and 98 deletions
@@ -0,0 +1,596 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { SystemClock } from '@sammo-ts/common';
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
import type { MapDefinition, ScenarioConfig, ScenarioMeta, TurnSchedule } from '@sammo-ts/logic';
import { DatabaseTurnDaemonCommandQueue } from '../src/lifecycle/databaseCommandQueue.js';
import { TurnDaemonLifecycle } from '../src/lifecycle/turnDaemonLifecycle.js';
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
import { EngineStateManager } from '../src/turn/engineStateManager.js';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import { createReservedTurnStore } from '../src/turn/reservedTurnStore.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
import { loadTurnWorldFromDatabase } from '../src/turn/worldLoader.js';
const databaseUrl = process.env.IMMEDIATE_ACTION_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const worldId = 991_731;
const generalId = 991_731;
const cityId = 991_731;
const existingNationId = 991_730;
const requestId = 'integration:engine:immediate-action-uprising';
const occupiedUniqueItem = 'che_무기_12_칠성검';
const assertDedicatedDatabase = (rawUrl: string): void => {
const schema = new URL(rawUrl).searchParams.get('schema');
if (!schema?.endsWith('immediate_action_integration')) {
throw new Error(`Refusing to mutate non-dedicated schema: ${schema ?? '(missing)'}`);
}
};
const map: MapDefinition = {
id: 'immediate-action-integration',
name: '즉시 행동 통합',
cities: [
{
id: cityId,
name: '낙양',
level: 5,
region: 1,
position: { x: 0, y: 0 },
connections: [],
max: {
population: 100_000,
agriculture: 2_000,
commerce: 2_000,
security: 2_000,
defence: 2_000,
wall: 2_000,
},
initial: {
population: 10_000,
agriculture: 1_000,
commerce: 1_000,
security: 1_000,
defence: 1_000,
wall: 1_000,
},
},
],
};
const scenarioMeta: ScenarioMeta = {
title: '즉시 행동 통합',
startYear: 180,
life: null,
fiction: null,
history: [],
ignoreDefaultEvents: false,
};
const scenarioConfig: ScenarioConfig = {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 65 },
iconPath: '',
map: {},
const: {
openingPartYear: 3,
baseRice: 2_000,
allItems: {
weapon: {
[occupiedUniqueItem]: 1,
},
},
maxUniqueItemLimit: [[-1, 1]],
minMonthToAllowInheritItem: 0,
},
environment: {
mapName: 'che',
unitSet: 'che',
},
};
const state: TurnWorldState = {
id: worldId,
currentYear: 180,
currentMonth: 1,
tickSeconds: 600,
lastTurnTime: new Date('2026-07-31T00:00:00.000Z'),
meta: {
hiddenSeed: 'immediate-action-integration',
killturn: 24,
opentime: '2026-08-01T00:00:00.000Z',
scenarioId: 1000,
},
};
const general: TurnGeneral = {
id: generalId,
userId: 'immediate-action-user',
name: '통합장수',
nationId: 0,
cityId,
troopId: 0,
stats: { leadership: 70, strength: 60, intelligence: 50 },
turnTime: new Date('2026-07-31T00:10:00.000Z'),
recentWarTime: null,
role: {
items: { horse: null, weapon: null, book: null, item: null },
personality: null,
specialDomestic: null,
specialWar: null,
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: {
killturn: 3,
inherit_active_action: 0,
inheritRandomUnique: true,
leadership_exp: 0,
strength_exp: 0,
intel_exp: 0,
},
penalty: {},
officerLevel: 0,
experience: 0,
dedication: 0,
injury: 0,
gold: 1_000,
rice: 1_000,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
age: 20,
npcState: 0,
};
integration('immediate general action persistence', () => {
let db: GamePrismaClient;
let disconnect: (() => Promise<void>) | undefined;
beforeAll(async () => {
assertDedicatedDatabase(databaseUrl!);
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
disconnect = () => connector.disconnect();
await db.inputEvent.deleteMany({ where: { requestId } });
await db.auction.deleteMany({ where: { targetCode: occupiedUniqueItem } });
await db.logEntry.deleteMany({
where: {
OR: [{ generalId }, { nationId: { gte: existingNationId } }, { text: { contains: general.name } }],
},
});
await db.nationTurn.deleteMany({ where: { nationId: { gte: existingNationId } } });
await db.diplomacy.deleteMany({
where: {
OR: [{ srcNationId: { gte: existingNationId } }, { destNationId: { gte: existingNationId } }],
},
});
await db.general.deleteMany({ where: { id: generalId } });
await db.city.deleteMany({ where: { id: cityId } });
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
await db.worldState.deleteMany({ where: { id: worldId } });
await db.worldState.create({
data: {
id: worldId,
scenarioCode: 'immediate-action-integration',
currentYear: state.currentYear,
currentMonth: state.currentMonth,
tickSeconds: state.tickSeconds,
config: JSON.parse(JSON.stringify(scenarioConfig)) as GamePrisma.InputJsonValue,
meta: state.meta as GamePrisma.InputJsonValue,
},
});
await db.nation.create({
data: {
id: existingNationId,
name: general.name,
color: '#111111',
capitalCityId: 0,
chiefGeneralId: 0,
gold: 0,
rice: 0,
tech: 0,
level: 1,
typeCode: 'che_중립',
meta: {},
},
});
await db.city.create({
data: {
id: cityId,
name: '낙양',
level: 5,
nationId: 0,
supplyState: 1,
frontState: 0,
population: 10_000,
populationMax: 100_000,
agriculture: 1_000,
agricultureMax: 2_000,
commerce: 1_000,
commerceMax: 2_000,
security: 1_000,
securityMax: 2_000,
defence: 1_000,
defenceMax: 2_000,
wall: 1_000,
wallMax: 2_000,
region: 1,
},
});
await db.general.create({
data: {
id: general.id,
userId: general.userId,
name: general.name,
nationId: general.nationId,
cityId: general.cityId,
troopId: general.troopId,
npcState: general.npcState,
leadership: general.stats.leadership,
strength: general.stats.strength,
intel: general.stats.intelligence,
officerLevel: general.officerLevel,
experience: general.experience,
dedication: general.dedication,
gold: general.gold,
rice: general.rice,
crew: general.crew,
crewTypeId: general.crewTypeId,
train: general.train,
atmos: general.atmos,
turnTime: general.turnTime,
age: general.age,
meta: general.meta as GamePrisma.InputJsonValue,
penalty: general.penalty as GamePrisma.InputJsonValue,
},
});
});
afterAll(async () => {
if (!db) {
await disconnect?.();
return;
}
await db.inputEvent.deleteMany({ where: { requestId } });
await db.auction.deleteMany({ where: { targetCode: occupiedUniqueItem } });
await db.logEntry.deleteMany({
where: {
OR: [{ generalId }, { nationId: { gte: existingNationId } }, { text: { contains: general.name } }],
},
});
await db.nationTurn.deleteMany({ where: { nationId: { gte: existingNationId } } });
await db.diplomacy.deleteMany({
where: {
OR: [{ srcNationId: { gte: existingNationId } }, { destNationId: { gte: existingNationId } }],
},
});
await db.general.deleteMany({ where: { id: generalId } });
await db.city.deleteMany({ where: { id: cityId } });
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
await db.worldState.deleteMany({ where: { id: worldId } });
await disconnect?.();
});
it('flushes and reloads the nation, diplomacy, officer turns, logs, and general state together', async () => {
const snapshot: TurnWorldSnapshot = {
generals: [general],
cities: [
{
id: cityId,
name: '낙양',
level: 5,
nationId: 0,
state: 0,
supplyState: 1,
frontState: 0,
population: 10_000,
populationMax: 100_000,
agriculture: 1_000,
agricultureMax: 2_000,
commerce: 1_000,
commerceMax: 2_000,
security: 1_000,
securityMax: 2_000,
defence: 1_000,
defenceMax: 2_000,
wall: 1_000,
wallMax: 2_000,
meta: {},
},
],
nations: [
{
id: existingNationId,
name: general.name,
color: '#111111',
capitalCityId: 0,
chiefGeneralId: 0,
gold: 0,
rice: 0,
level: 1,
typeCode: 'che_중립',
power: 0,
meta: {},
},
],
troops: [],
diplomacy: [],
events: [],
initialEvents: [],
scenarioConfig,
scenarioMeta,
map,
};
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
const world = new InMemoryTurnWorld(state, snapshot, { schedule });
const reservedTurns = await createReservedTurnStore({ databaseUrl: databaseUrl! });
const handler = createTurnDaemonCommandHandler({
world,
reservedTurns: reservedTurns.store,
scenarioMeta,
map,
});
const hooks = await createDatabaseTurnHooks(databaseUrl!, world, {
reservedTurns: reservedTurns.store,
});
await db.auction.createMany({
data: (['OPEN', 'FINALIZING'] as const).map((status) => ({
type: 'UNIQUE_ITEM' as const,
targetCode: occupiedUniqueItem,
hostGeneralId: generalId,
hostName: general.name,
detail: {},
status,
closeAt: new Date('2026-08-01T00:00:00.000Z'),
})),
});
await db.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: 'buildNationCandidate',
actorUserId: general.userId,
payload: {
type: 'buildNationCandidate',
requestId,
userId: general.userId,
generalId,
} as GamePrisma.InputJsonValue,
},
});
const stateManager = new EngineStateManager();
stateManager.register('world', {
capture: () => world.captureState(),
restore: (captured) => world.restoreState(captured),
});
stateManager.register('reservedTurns', {
capture: () => reservedTurns.store.captureState(),
restore: (captured) => reservedTurns.store.restoreState(captured),
});
const stateStore = {
loadLastTurnTime: async () => new Date(state.lastTurnTime),
loadNextGeneralTurnTime: async () => null,
saveLastTurnTime: async () => {},
loadCheckpoint: async () => undefined,
saveCheckpoint: async () => {},
};
const processor = {
run: async () => {
throw new Error('scheduled turn must not run in the immediate-action integration test');
},
};
const buildLifecycle = (
queue: DatabaseTurnDaemonCommandQueue,
lifecycleHooks: ConstructorParameters<typeof TurnDaemonLifecycle>[0]['hooks']
) =>
new TurnDaemonLifecycle(
{
clock: new SystemClock(),
controlQueue: queue,
commandResponder: queue,
getNextTickTime: () => new Date(Date.now() + 3_600_000),
stateStore,
processor,
commandHandler: handler,
hooks: lifecycleHooks,
stateManager,
},
{
profile: 'immediate-action-integration',
defaultBudget: { budgetMs: 100, maxGenerals: 1, catchUpCap: 1 },
}
);
const waitForEvent = async (status: 'PENDING' | 'SUCCEEDED') => {
for (let attempt = 0; attempt < 200; attempt += 1) {
const event = await db.inputEvent.findUnique({ where: { requestId } });
if (event?.status === status && (status !== 'SUCCEEDED' || event.lockedBy === null)) {
return event;
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error(`Timed out waiting for ${requestId} to become ${status}.`);
};
try {
const firstQueue = new DatabaseTurnDaemonCommandQueue(db);
await firstQueue.initialize();
let observeInjectedFailure: (() => void) | undefined;
const injectedFailureObserved = new Promise<void>((resolve) => {
observeInjectedFailure = resolve;
});
const firstLifecycle = buildLifecycle(firstQueue, {
...hooks.hooks,
executeCommand: async (_failedRequestId, execute) =>
db.$transaction(async (transaction) => {
await execute({ db: transaction });
throw new Error('injected immediate-action commit failure');
}),
onRunError: async () => {
observeInjectedFailure?.();
},
});
const firstLoop = firstLifecycle.start();
await injectedFailureObserved;
await firstLifecycle.stop('injected failure observed');
await firstLoop;
await expect(waitForEvent('PENDING')).resolves.toMatchObject({
attempts: 1,
error: 'injected immediate-action commit failure',
});
expect(world.getGeneralById(generalId)).toMatchObject({
nationId: 0,
officerLevel: 0,
role: { items: { weapon: null } },
});
expect(world.listNations().map((nation) => nation.id)).toEqual([existingNationId]);
expect(reservedTurns.store.peekDirtyState()).toEqual({
generalIds: [],
generalInitializationIds: [],
generalLeaseIds: [],
nationKeys: [],
nationInitializationKeys: [],
nationLeaseKeys: [],
});
await expect(db.nation.findUnique({ where: { id: existingNationId + 1 } })).resolves.toBeNull();
await expect(db.general.findUniqueOrThrow({ where: { id: generalId } })).resolves.toMatchObject({
nationId: 0,
officerLevel: 0,
});
const retryQueue = new DatabaseTurnDaemonCommandQueue(db);
await retryQueue.initialize();
const retryLifecycle = buildLifecycle(retryQueue, hooks.hooks);
const retryLoop = retryLifecycle.start();
await expect(waitForEvent('SUCCEEDED')).resolves.toMatchObject({
attempts: 2,
actorUserId: general.userId,
result: expect.objectContaining({
type: 'buildNationCandidate',
ok: true,
generalId,
}),
});
await retryLifecycle.stop('retry committed');
await retryLoop;
} finally {
await hooks.close();
await reservedTurns.close();
}
const persistedGeneral = await db.general.findUniqueOrThrow({ where: { id: generalId } });
expect(persistedGeneral).toMatchObject({
nationId: existingNationId + 1,
officerLevel: 12,
experience: 100,
dedication: 100,
turnTime: general.turnTime,
lastTurn: { command: '거병', arg: {} },
weaponCode: 'None',
meta: expect.objectContaining({
inherit_active_action: 1,
killturn: 24,
belong: 1,
officer_city: 0,
}),
});
await expect(db.nation.findUniqueOrThrow({ where: { id: existingNationId + 1 } })).resolves.toMatchObject({
name: `${general.name}`,
chiefGeneralId: generalId,
rice: 2_000,
meta: expect.objectContaining({ gennum: 1, secretlimit: 1 }),
});
await expect(
db.diplomacy.findMany({
where: {
OR: [{ srcNationId: existingNationId + 1 }, { destNationId: existingNationId + 1 }],
},
})
).resolves.toHaveLength(2);
for (const officerLevel of [11, 12]) {
await expect(
db.nationTurn.findMany({
where: {
nationId: existingNationId + 1,
officerLevel,
},
orderBy: { turnIdx: 'asc' },
})
).resolves.toEqual(
Array.from({ length: 12 }, (_, turnIdx) =>
expect.objectContaining({
officerLevel,
turnIdx,
actionCode: '휴식',
arg: {},
})
)
);
}
await expect(
db.logEntry.findMany({
where: {
OR: [
{ scope: 'GENERAL', category: 'ACTION', generalId },
{ scope: 'GENERAL', category: 'HISTORY', generalId },
{ scope: 'NATION', category: 'HISTORY', nationId: existingNationId + 1 },
{ scope: 'SYSTEM', category: 'SUMMARY' },
{ scope: 'SYSTEM', category: 'HISTORY' },
],
},
})
).resolves.toEqual(
expect.arrayContaining([
expect.objectContaining({
scope: 'GENERAL',
category: 'ACTION',
generalId,
text: expect.stringContaining('거병에 성공하였습니다. <1>00:10</>'),
}),
expect.objectContaining({
scope: 'GENERAL',
category: 'HISTORY',
generalId,
text: expect.stringContaining('낙양'),
}),
expect.objectContaining({
scope: 'NATION',
category: 'HISTORY',
nationId: existingNationId + 1,
text: expect.stringContaining('통합장수'),
}),
expect.objectContaining({
scope: 'SYSTEM',
category: 'SUMMARY',
text: expect.stringContaining('거병하였습니다'),
}),
expect.objectContaining({
scope: 'SYSTEM',
category: 'HISTORY',
text: expect.stringContaining('【거병】'),
}),
])
);
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
expect(reloaded.snapshot.generals.find((entry) => entry.id === generalId)).toMatchObject({
nationId: existingNationId + 1,
officerLevel: 12,
experience: 100,
dedication: 100,
turnTime: general.turnTime,
});
expect(reloaded.snapshot.nations.find((entry) => entry.id === existingNationId + 1)).toMatchObject({
name: `${general.name}`,
chiefGeneralId: generalId,
rice: 2_000,
});
});
});
@@ -1,13 +1,42 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import type { ScenarioEffectKey, TurnSchedule } from '@sammo-ts/logic';
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
import type { MapDefinition, ScenarioEffectKey, TurnSchedule } from '@sammo-ts/logic';
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import type { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
import { createImmediateGeneralActionExecutor } from '../src/turn/reservedTurnHandler.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
const buildMapCity = (id: number, connections: number[]): MapDefinition['cities'][number] => ({
id,
name: `도시${id}`,
level: 1,
region: 1,
position: { x: id, y: id },
connections,
max: {
population: 100_000,
agriculture: 1_000,
commerce: 1_000,
security: 1_000,
defence: 1_000,
wall: 1_000,
},
initial: {
population: 10_000,
agriculture: 100,
commerce: 100,
security: 100,
defence: 100,
wall: 100,
},
});
const buildGeneral = (overrides: Partial<TurnGeneral> = {}): TurnGeneral => ({
id: 7,
userId: 'user-7',
@@ -102,6 +131,76 @@ const buildWorld = (
return { world, handler: createTurnDaemonCommandHandler({ world }) };
};
const buildImmediateActionWorld = (options: {
general: TurnGeneral;
cities: TurnWorldSnapshot['cities'];
nations: TurnWorldSnapshot['nations'];
map: MapDefinition;
availableInstantRetreat?: boolean;
lastTurnTime?: Date;
scenarioConst?: Record<string, unknown>;
}) => {
const state: TurnWorldState = {
id: 1,
currentYear: 180,
currentMonth: 1,
tickSeconds: 600,
lastTurnTime: options.lastTurnTime ?? new Date('0180-01-01T00:00:00Z'),
meta: {
hiddenSeed: 'immediate-action-test',
killturn: 24,
opentime: '0180-02-01T00:00:00.000Z',
scenarioId: 1000,
},
};
const scenarioMeta = {
title: '즉시 행동 테스트',
startYear: 180,
life: null,
fiction: null,
history: [],
ignoreDefaultEvents: false,
};
const snapshot: TurnWorldSnapshot = {
generals: [options.general],
cities: options.cities,
nations: options.nations,
troops: [],
diplomacy: [],
events: [],
initialEvents: [],
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 65 },
iconPath: '',
map: {},
const: {
openingPartYear: 3,
baseRice: 2_000,
availableInstantAction: {
instantRetreat: options.availableInstantRetreat ?? false,
},
...(options.scenarioConst ?? {}),
},
environment: {
mapName: 'test',
unitSet: 'test',
},
},
scenarioMeta,
map: options.map,
};
const world = new InMemoryTurnWorld(state, snapshot, { schedule });
const ensureNationTurns = vi.fn();
const reservedTurns = { ensureNationTurns } as unknown as InMemoryReservedTurnStore;
const handler = createTurnDaemonCommandHandler({
world,
reservedTurns,
scenarioMeta,
map: options.map,
});
return { world, handler, ensureNationTurns, reservedTurns, scenarioMeta };
};
describe('my information world commands', () => {
it('normalizes legacy settings and charges myset only when defence mode changes', async () => {
const fixture = buildWorld();
@@ -183,4 +282,474 @@ describe('my information world commands', () => {
).resolves.toMatchObject({ ok: true });
expect(fixture.world.getGeneralById(7)?.role.items.horse).toBeNull();
});
it('executes pre-open uprising through the action stack without advancing the turn clock', async () => {
const general = buildGeneral({
nationId: 0,
cityId: 1,
turnTime: new Date('0180-01-01T00:10:00Z'),
experience: 0,
dedication: 0,
meta: {
killturn: 3,
inherit_active_action: 2,
leadership_exp: 0,
strength_exp: 0,
intel_exp: 0,
},
});
const fixture = buildImmediateActionWorld({
general,
cities: [
{
id: 1,
name: '낙양',
nationId: 0,
supplyState: 1,
meta: {},
} as TurnWorldSnapshot['cities'][number],
],
nations: [
{
id: 1,
name: general.name,
color: '#111111',
typeCode: 'che_중립',
level: 1,
capitalCityId: 0,
chiefGeneralId: 0,
gold: 0,
rice: 0,
power: 0,
meta: {},
},
],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
},
});
await expect(
fixture.handler.handle({
type: 'buildNationCandidate',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({ ok: true });
const createdNation = fixture.world.listNations().find((nation) => nation.id === 2);
expect(createdNation).toMatchObject({
name: `${general.name}`,
color: '#330000',
typeCode: 'che_중립',
level: 0,
capitalCityId: 0,
chiefGeneralId: general.id,
gold: 0,
rice: 2_000,
meta: {
rate: 20,
bill: 100,
strategic_cmd_limit: 12,
surlimit: 72,
secretlimit: 1,
gennum: 1,
},
});
expect(fixture.world.getGeneralById(general.id)).toMatchObject({
nationId: 2,
officerLevel: 12,
experience: 100,
dedication: 100,
turnTime: general.turnTime,
lastTurn: { command: '거병', arg: {} },
meta: {
belong: 1,
officer_city: 0,
inherit_active_action: 3,
killturn: 24,
},
});
expect(fixture.ensureNationTurns.mock.calls).toEqual([
[2, 12],
[2, 11],
]);
expect(fixture.world.getDiplomacyEntry(1, 2)).toMatchObject({ state: 2, term: 0 });
expect(fixture.world.getDiplomacyEntry(2, 1)).toMatchObject({ state: 2, term: 0 });
const { logs } = fixture.world.consumeDirtyState();
expect(logs.map((entry) => entry.text)).toEqual(
expect.arrayContaining([
'거병에 성공하였습니다. <1>00:10</>',
expect.stringContaining('낙양'),
expect.stringContaining('세력을 결성하였습니다.'),
])
);
});
it('rejects a penalized uprising before allocating a nation or writing a log', async () => {
const general = buildGeneral({
nationId: 0,
cityId: 1,
penalty: { noFoundNation: true },
});
const fixture = buildImmediateActionWorld({
general,
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
nations: [],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
},
});
await expect(
fixture.handler.handle({
type: 'buildNationCandidate',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({ ok: false });
expect(fixture.world.listNations()).toEqual([]);
expect(fixture.world.getGeneralById(general.id)).toMatchObject({
nationId: 0,
experience: general.experience,
dedication: general.dedication,
});
expect(fixture.ensureNationTurns).not.toHaveBeenCalled();
expect(fixture.world.consumeDirtyState().logs).toEqual([]);
});
it('uses the Ref generic unique seed independently from the immediate-action RNG', async () => {
const general = buildGeneral({
nationId: 0,
cityId: 1,
meta: {
killturn: 3,
inheritRandomUnique: true,
leadership_exp: 0,
strength_exp: 0,
intel_exp: 0,
},
});
const map = {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
};
const fixture = buildImmediateActionWorld({
general,
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
nations: [],
map,
scenarioConst: {
allItems: {
weapon: {
che_무기_12_칠성검: 1,
},
},
maxUniqueItemLimit: [[-1, 1]],
minMonthToAllowInheritItem: 0,
},
});
const actionRng = new RandUtil(new LiteHashDRBG('immediate-action-main-rng'));
const nextFloat = vi.spyOn(actionRng, 'nextFloat1');
const nextInt = vi.spyOn(actionRng, 'nextInt');
const nextIntInclusive = vi.spyOn(actionRng, 'nextIntInclusive');
const executor = await createImmediateGeneralActionExecutor({
world: fixture.world,
reservedTurns: fixture.reservedTurns,
scenarioMeta: fixture.scenarioMeta,
map,
});
await expect(
executor.execute({
actionKey: 'che_거병',
generalId: general.id,
rng: actionRng,
refreshKillturn: true,
})
).resolves.toEqual({ ok: true });
expect(fixture.world.getGeneralById(general.id)?.role.items.weapon).toBe('che_무기_12_칠성검');
expect(fixture.world.consumeDirtyState().logs.some((entry) => entry.text.includes('【아이템】'))).toBe(true);
expect(nextFloat).not.toHaveBeenCalled();
expect(nextInt).not.toHaveBeenCalled();
expect(nextIntInclusive).not.toHaveBeenCalled();
});
it('preserves the Ref uprising precheck order and messages after the game starts', async () => {
const general = buildGeneral({ nationId: 1, cityId: 1 });
const fixture = buildImmediateActionWorld({
general,
cities: [{ id: 1, name: '낙양', nationId: 1, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
nations: [],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
},
lastTurnTime: new Date('0180-03-01T00:00:00.000Z'),
});
await expect(
fixture.handler.handle({
type: 'buildNationCandidate',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({
ok: false,
reason: '게임이 시작되었습니다.',
});
});
it('executes instant retreat with the legacy seed and leaves the reserved turn untouched', async () => {
const originalLastTurn = { command: '훈련', arg: { marker: 1 } };
const general = buildGeneral({
nationId: 1,
cityId: 2,
turnTime: new Date('0180-01-01T00:10:00Z'),
lastTurn: originalLastTurn,
});
const map = {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [2]), buildMapCity(2, [1])],
};
const cities = [
{ id: 1, name: '낙양', nationId: 1, supplyState: 1, meta: {} },
{ id: 2, name: '장안', nationId: 2, supplyState: 1, meta: {} },
] as TurnWorldSnapshot['cities'];
const nations = [
{
id: 1,
name: '아국',
color: '#111111',
typeCode: 'che_중립',
level: 1,
capitalCityId: 1,
chiefGeneralId: general.id,
gold: 0,
rice: 0,
power: 0,
meta: {},
},
{
id: 2,
name: '타국',
color: '#222222',
typeCode: 'che_중립',
level: 1,
capitalCityId: 2,
chiefGeneralId: 0,
gold: 0,
rice: 0,
power: 0,
meta: {},
},
] as TurnWorldSnapshot['nations'];
const fixture = buildImmediateActionWorld({
general,
cities,
nations,
map,
availableInstantRetreat: true,
});
await expect(
fixture.handler.handle({
type: 'instantRetreat',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({
ok: true,
});
expect(fixture.world.getGeneralById(general.id)).toMatchObject({
cityId: 1,
turnTime: general.turnTime,
lastTurn: originalLastTurn,
});
expect(fixture.world.consumeDirtyState().logs.map((entry) => entry.text)).toContain(
'<G><b>낙양</b></>으로 접경귀환했습니다.'
);
});
it('chooses equal-distance retreat cities in the Ref map BFS connection order', async () => {
const general = buildGeneral({ nationId: 1, cityId: 2 });
const map = {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [2]), buildMapCity(2, [3, 1]), buildMapCity(3, [2])],
};
const fixture = buildImmediateActionWorld({
general,
cities: [
{ id: 1, name: '첫째', nationId: 1, supplyState: 1, meta: {} },
{ id: 3, name: '셋째', nationId: 1, supplyState: 1, meta: {} },
{ id: 2, name: '출발', nationId: 2, supplyState: 1, meta: {} },
] as TurnWorldSnapshot['cities'],
nations: [
{
id: 1,
name: '아국',
color: '#111111',
typeCode: 'che_중립',
level: 1,
capitalCityId: 1,
chiefGeneralId: general.id,
gold: 0,
rice: 0,
power: 0,
meta: {},
},
],
map,
availableInstantRetreat: true,
});
const expectedIndex = new RandUtil(
new LiteHashDRBG(
simpleSerialize('immediate-action-test', 'InstantRetreat', general.id, 180, 1, general.cityId)
)
).nextIntInclusive(1);
await expect(
fixture.handler.handle({
type: 'instantRetreat',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({ ok: true });
expect(fixture.world.getGeneralById(general.id)?.cityId).toBe([3, 1][expectedIndex]);
});
it('rejects an immediate action when the command user does not own the runtime general', async () => {
const general = buildGeneral({ nationId: 0, cityId: 1 });
const fixture = buildImmediateActionWorld({
general,
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
nations: [],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
},
});
await expect(
fixture.handler.handle({
type: 'buildNationCandidate',
userId: 'different-user',
generalId: general.id,
})
).rejects.toThrow('general owner does not match command user');
expect(fixture.world.listNations()).toEqual([]);
});
it('attributes an instant-retreat constraint failure to the session general log', async () => {
const general = buildGeneral({ nationId: 0, cityId: 1 });
const fixture = buildImmediateActionWorld({
general,
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
nations: [],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
},
availableInstantRetreat: true,
});
await expect(
fixture.handler.handle({
type: 'instantRetreat',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({ ok: false });
expect(fixture.world.consumeDirtyState().logs).toEqual([
expect.objectContaining({
scope: 'GENERAL',
category: 'ACTION',
generalId: general.id,
}),
]);
});
it('persists the ref failure log when instant retreat has no reachable supplied city', async () => {
const general = buildGeneral({ nationId: 1, cityId: 2 });
const fixture = buildImmediateActionWorld({
general,
cities: [
{ id: 1, name: '낙양', nationId: 1, supplyState: 0, meta: {} },
{ id: 2, name: '장안', nationId: 2, supplyState: 1, meta: {} },
] as TurnWorldSnapshot['cities'],
nations: [
{
id: 1,
name: '아국',
color: '#111111',
typeCode: 'che_중립',
level: 1,
capitalCityId: 1,
chiefGeneralId: general.id,
gold: 0,
rice: 0,
power: 0,
meta: {},
},
],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [2]), buildMapCity(2, [1])],
},
availableInstantRetreat: true,
});
await expect(
fixture.handler.handle({
type: 'instantRetreat',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({
ok: false,
reason: '가까운 아국 도시가 없습니다.',
});
expect(fixture.world.getGeneralById(general.id)?.cityId).toBe(2);
expect(fixture.world.consumeDirtyState().logs.map((entry) => entry.text)).toContain(
'3칸 이내에 아국 도시가 없습니다.'
);
});
it('checks the Ref instant-retreat scenario gate before looking up the general', async () => {
const general = buildGeneral({ nationId: 1, cityId: 1 });
const fixture = buildImmediateActionWorld({
general,
cities: [{ id: 1, name: '낙양', nationId: 1, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
nations: [],
map: {
id: 'test',
name: 'test',
cities: [buildMapCity(1, [])],
},
availableInstantRetreat: false,
});
fixture.world.removeGeneral(general.id);
await expect(
fixture.handler.handle({
type: 'instantRetreat',
userId: general.userId!,
generalId: general.id,
})
).resolves.toMatchObject({
ok: false,
reason: '접경귀환을 사용할 수 없는 시나리오입니다.',
});
});
});