fix: Ref 게임 로직과 시나리오 풀 호환을 보정

월 경계, 전투 기술 상한, 연감과 베팅·설문·경매 정산 순서를 Ref 계약에 맞춘다.\n\n시나리오 일반 풀을 ENGINE mutation과 logical tick 기반으로 직렬화하고 914·915 catalog 및 조건부 100기 pool 실행 경계를 추가한다.\n\n경매 worker는 세대별 durable event만 만들고 ENGINE이 row lock 후 상태 전이와 정산을 단일 transaction으로 소유한다.
This commit is contained in:
2026-08-23 16:26:14 +00:00
parent bf6b7be7b0
commit 85591c68ad
114 changed files with 13327 additions and 901 deletions
+191 -12
View File
@@ -12,8 +12,9 @@ import {
} from '@sammo-ts/logic';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import { normalizeTurnDaemonCommand } from '../src/turn/commandRegistry.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
import { createTurnDaemonCommandHandler, hasVotePollDeadlinePassed } from '../src/turn/worldCommandHandler.js';
const buildGeneral = (id: number): TurnGeneral => ({
id,
@@ -46,6 +47,39 @@ const buildGeneral = (id: number): TurnGeneral => ({
});
describe('voteReward command', () => {
it('keeps the wall-time fallback open at exact deadline equality', () => {
const deadline = new Date('0180-01-01T00:00:00.000Z');
expect(hasVotePollDeadlinePassed({ endAt: deadline, endTick: null, closedAt: null }, deadline, 0)).toBe(false);
expect(
hasVotePollDeadlinePassed(
{ endAt: deadline, endTick: null, closedAt: null },
new Date(deadline.getTime() + 1),
0
)
).toBe(true);
});
it('preserves the server-accepted game tick through durable command normalization', () => {
expect(
normalizeTurnDaemonCommand({
requestId: 'vote-accepted-tick',
sentAt: '2026-08-23T00:00:00.000Z',
command: {
type: 'voteReward',
voteId: 1,
generalId: 1,
selection: [0],
acceptedGameTick: 100,
},
})
).toMatchObject({
type: 'voteReward',
requestId: 'vote-accepted-tick',
acceptedGameTick: 100,
});
});
it('applies gold, unique item, logs, and idempotency', async () => {
const generals = [buildGeneral(1)];
const snapshot: TurnWorldSnapshot = {
@@ -117,6 +151,7 @@ describe('voteReward command', () => {
iconPath: '',
map: {},
const: {
develCost: 100,
allItems: {
weapon: {
che_무기_12_칠성검: 1,
@@ -141,12 +176,18 @@ describe('voteReward command', () => {
currentMonth: 1,
tickSeconds: 3600,
lastTurnTime: new Date('0180-01-01T00:00:00Z'),
clockBaseTime: new Date('0180-01-01T00:00:00Z'),
clockTick: 10_000,
clockMode: 'manual',
clockWallAnchor: new Date('2026-08-23T00:00:00Z'),
meta: {
hiddenSeed: 'seed',
scenarioId: 200,
initYear: 180,
initMonth: 1,
scenarioMeta: { startYear: 180 },
// Simulate ENGINE processing after the yearly develcost update.
develcost: 120,
},
};
@@ -179,19 +220,42 @@ describe('voteReward command', () => {
expect(itemKey).toBe('che_무기_12_칠성검');
let voteInserted = false;
let voteQueryCount = 0;
const commandDb = {
auction: {
findMany: async () => [],
},
$queryRaw: async (query: { strings: readonly string[] }) => {
voteQueryCount += 1;
if (query.strings.join(' ').includes('SELECT options')) {
return [
{
options: ['찬성'],
multipleOptions: 1,
endAt: null,
endTick: 0n,
closedAt: null,
},
];
}
if (voteInserted) return [];
voteInserted = true;
return [{ id: 11 }];
},
};
const handler = createTurnDaemonCommandHandler({ world });
const command = {
type: 'voteReward' as const,
voteId: 1,
generalId: 1,
goldReward: 500,
unique: {
expected: true,
itemKey,
},
selection: [0],
// Ref accepts the request at exact equality. Engine processing may
// occur after the logical clock has advanced beyond the deadline.
acceptedGameTick: 0,
};
const result = await handler.handle(command);
const result = await handler.handle(command, { db: commandDb as any });
expect(result && result.type).toBe('voteReward');
if (!result || result.type !== 'voteReward' || !result.ok) {
throw new Error('voteReward result missing');
@@ -199,7 +263,9 @@ describe('voteReward command', () => {
expect(result.awardedUnique).toBe(true);
const updated = world.getGeneralById(1);
expect(updated?.gold).toBe(1500);
// ENGINE is the single reward linearization point, so it uses the
// processing world's develcost (120 * 5), not an API projection.
expect(updated?.gold).toBe(1600);
expect(updated?.role.items.weapon).toBe('che_무기_12_칠성검');
const meta = updated?.meta as Record<string, unknown>;
expect(meta.voteRewards).toMatchObject({
@@ -213,7 +279,7 @@ describe('voteReward command', () => {
const logTexts = diff.logs.map((entry) => entry.text);
expect(logTexts.some((text) => text.includes('【설문조사】'))).toBe(true);
const second = await handler.handle(command);
const second = await handler.handle(command, { db: commandDb as any });
expect(second && second.type).toBe('voteReward');
if (!second || second.type !== 'voteReward' || !second.ok) {
throw new Error('voteReward second result missing');
@@ -221,7 +287,108 @@ describe('voteReward command', () => {
expect(second.alreadyApplied).toBe(true);
expect(second.itemKey).toBe('che_무기_12_칠성검');
const afterSecond = world.getGeneralById(1);
expect(afterSecond?.gold).toBe(1500);
expect(afterSecond?.gold).toBe(1600);
expect(voteQueryCount).toBe(2);
const duplicateWorld = new InMemoryTurnWorld(
{ ...state, meta: { ...state.meta } },
{ ...snapshot, generals: [buildGeneral(1)] as any },
{ schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } }
);
const duplicateHandler = createTurnDaemonCommandHandler({ world: duplicateWorld });
const duplicateResult = await duplicateHandler.handle(command, {
db: {
auction: { findMany: async () => [] },
$queryRaw: async (query: { strings: readonly string[] }) => {
const text = query.strings.join(' ');
if (text.includes('SELECT options')) {
return [
{
options: ['찬성'],
multipleOptions: 1,
endAt: null,
endTick: 0n,
closedAt: null,
},
];
}
if (text.includes('SELECT selection')) return [{ selection: [0] }];
return [];
},
} as any,
});
expect(duplicateResult).toMatchObject({
type: 'voteReward',
ok: true,
awardedUnique: true,
});
expect(duplicateWorld.getGeneralById(1)?.gold).toBe(1600);
expect(duplicateWorld.getGeneralById(1)?.role.items.weapon).toBe('che_무기_12_칠성검');
const mismatchWorld = new InMemoryTurnWorld(
{ ...state, meta: { ...state.meta } },
{ ...snapshot, generals: [buildGeneral(1)] as any },
{ schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } }
);
const mismatchHandler = createTurnDaemonCommandHandler({ world: mismatchWorld });
const mismatchResult = await mismatchHandler.handle(command, {
db: {
auction: { findMany: async () => [] },
$queryRaw: async (query: { strings: readonly string[] }) => {
const text = query.strings.join(' ');
if (text.includes('SELECT options')) {
return [
{
options: ['찬성'],
multipleOptions: 1,
endAt: null,
endTick: 0n,
closedAt: null,
},
];
}
if (text.includes('SELECT selection')) return [{ selection: [1] }];
return [];
},
} as any,
});
expect(mismatchResult).toMatchObject({
type: 'voteReward',
ok: false,
reason: '이미 설문조사를 완료하였습니다.',
});
expect(mismatchWorld.getGeneralById(1)?.gold).toBe(1000);
expect(mismatchWorld.getGeneralById(1)?.role.items.weapon).toBeNull();
expect(mismatchWorld.consumeDirtyState().logs).toEqual([]);
const legacyLateWorld = new InMemoryTurnWorld(
{ ...state, meta: { ...state.meta } },
{ ...snapshot, generals: [buildGeneral(1)] as any },
{ schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } }
);
const legacyLateHandler = createTurnDaemonCommandHandler({ world: legacyLateWorld });
const { acceptedGameTick: _acceptedGameTick, ...legacyLateCommand } = command;
const legacyLateResult = await legacyLateHandler.handle(legacyLateCommand, {
db: {
$queryRaw: async (query: { strings: readonly string[] }) =>
query.strings.join(' ').includes('SELECT options')
? [
{
options: ['찬성'],
multipleOptions: 1,
endAt: null,
endTick: 0n,
closedAt: null,
},
]
: [],
} as any,
});
expect(legacyLateResult).toMatchObject({
type: 'voteReward',
ok: false,
reason: '설문조사가 종료되었습니다.',
});
});
it('treats an active unique auction as occupied when revalidating the lottery', async () => {
@@ -245,6 +412,7 @@ describe('voteReward command', () => {
iconPath: '',
map: {},
const: {
develCost: 100,
allItems: { weapon: { che_무기_12_칠성검: 1 } },
maxUniqueItemLimit: [[-1, 1]],
uniqueTrialCoef: 10,
@@ -278,6 +446,18 @@ describe('voteReward command', () => {
auction: {
findMany: async () => [{ targetCode: 'che_무기_12_칠성검' }],
},
$queryRaw: async (query: { strings: readonly string[] }) =>
query.strings.join(' ').includes('SELECT options')
? [
{
options: ['찬성'],
multipleOptions: 1,
endAt: null,
endTick: 0n,
closedAt: null,
},
]
: [{ id: 12 }],
};
const result = await handler.handle(
@@ -285,8 +465,7 @@ describe('voteReward command', () => {
type: 'voteReward',
voteId: 1,
generalId: 1,
goldReward: 500,
unique: { expected: false, itemKey: null },
selection: [0],
},
{ db: commandDb as any }
);