merge: 최신 main을 NPC 천통 계측 브랜치에 통합

This commit is contained in:
2026-08-15 19:36:56 +00:00
53 changed files with 2379 additions and 1304 deletions
@@ -914,6 +914,7 @@ export const createDatabaseTurnHooks = async (
let persistedVisibleLogs: PersistedVisibleLogRow[] = [];
let visibleLogFloor = directLogFloor;
const {
accessScoreResetGeneralIds,
generals,
cities,
nations,
@@ -1012,6 +1013,13 @@ export const createDatabaseTurnHooks = async (
world.gameTickToDate(state.clockTick ?? state.lastTurnTick ?? 0)
);
if (accessScoreResetGeneralIds.length > 0) {
await prisma.generalAccessLog.updateMany({
where: { generalId: { in: accessScoreResetGeneralIds } },
data: { refreshScore: 0 },
});
}
if (inheritancePointAdjustments.length > 0) {
const grouped = new Map<string, { userId: string; key: string; amount: number }>();
for (const entry of inheritancePointAdjustments) {
@@ -2,7 +2,7 @@ import type { TurnCheckpoint, TurnProcessor, TurnRunBudget, TurnRunResult } from
import { getNextTickTime } from '../lifecycle/getNextTickTime.js';
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
import type { TurnGeneral } from './types.js';
import { asNumber, asRecord } from '@sammo-ts/common';
import { asNumber, asRecord, calculateAccessRefreshLimit } from '@sammo-ts/common';
export interface InMemoryTurnProcessorOptions {
tickMinutes?: number;
@@ -50,6 +50,9 @@ export class InMemoryTurnProcessor implements TurnProcessor {
const isBudgetExpired = () => Date.now() >= deadlineMs;
this.world.setCheckpoint(checkpoint);
this.world.updateWorldMeta({
refreshLimit: calculateAccessRefreshLimit(this.world.getState().tickSeconds),
});
let processedGenerals = 0;
let processedTurns = 0;
@@ -97,6 +100,9 @@ export class InMemoryTurnProcessor implements TurnProcessor {
if (executionError !== undefined) {
throw executionError;
}
// Ref의 updateTurnTime()은 장수 명령이 성공한 뒤 그 장수의
// 순간 벌점을 같은 턴 flush에서 초기화한다.
this.world.markGeneralAccessScoreReset(general.id);
processedGenerals += 1;
nextCheckpoint = {
turnTime: executedAt.toISOString(),
+16
View File
@@ -115,6 +115,7 @@ export interface InMemoryGameClockState {
}
export interface TurnWorldChanges {
accessScoreResetGeneralIds: number[];
generals: TurnGeneral[];
cities: City[];
nations: Nation[];
@@ -156,6 +157,7 @@ export interface InMemoryTurnWorldStateSnapshot {
dirtyNationIds: number[];
dirtyTroopIds: number[];
dirtyDiplomacyKeys: string[];
accessScoreResetGeneralIds: number[];
createdGeneralIds: number[];
createdNationIds: number[];
createdTroopIds: number[];
@@ -419,6 +421,7 @@ export class InMemoryTurnWorld {
private readonly dirtyNationIds = new Set<number>();
private readonly dirtyTroopIds = new Set<number>();
private readonly dirtyDiplomacyKeys = new Set<string>();
private readonly accessScoreResetGeneralIds = new Set<number>();
private readonly createdGeneralIds = new Set<number>();
private nextLegacyGeneralScanOrder = 0;
private readonly createdNationIds = new Set<number>();
@@ -606,6 +609,7 @@ export class InMemoryTurnWorld {
dirtyNationIds: Array.from(this.dirtyNationIds),
dirtyTroopIds: Array.from(this.dirtyTroopIds),
dirtyDiplomacyKeys: Array.from(this.dirtyDiplomacyKeys),
accessScoreResetGeneralIds: Array.from(this.accessScoreResetGeneralIds),
createdGeneralIds: Array.from(this.createdGeneralIds),
createdNationIds: Array.from(this.createdNationIds),
createdTroopIds: Array.from(this.createdTroopIds),
@@ -644,6 +648,7 @@ export class InMemoryTurnWorld {
this.replaceSet(this.dirtyNationIds, restored.dirtyNationIds);
this.replaceSet(this.dirtyTroopIds, restored.dirtyTroopIds);
this.replaceSet(this.dirtyDiplomacyKeys, restored.dirtyDiplomacyKeys);
this.replaceSet(this.accessScoreResetGeneralIds, restored.accessScoreResetGeneralIds ?? []);
this.replaceSet(this.createdGeneralIds, restored.createdGeneralIds);
this.replaceSet(this.createdNationIds, restored.createdNationIds);
this.replaceSet(this.createdTroopIds, restored.createdTroopIds);
@@ -693,6 +698,12 @@ export class InMemoryTurnWorld {
};
}
markGeneralAccessScoreReset(generalId: number): void {
if (Number.isSafeInteger(generalId) && generalId > 0) {
this.accessScoreResetGeneralIds.add(generalId);
}
}
changeTurnTerm(tickMinutes: number): void {
if (!Number.isInteger(tickMinutes) || tickMinutes <= 0) {
throw new Error('Turn term must be a positive integer.');
@@ -1512,8 +1523,12 @@ export class InMemoryTurnWorld {
}));
const pendingYearbookSnapshots = structuredClone(this.pendingYearbookSnapshots);
const pendingUnificationFinalizations = structuredClone(this.pendingUnificationFinalizations);
const accessScoreResetGeneralIds = Array.from(this.accessScoreResetGeneralIds).sort(
(left, right) => left - right
);
return {
accessScoreResetGeneralIds,
generals,
cities,
nations,
@@ -1542,6 +1557,7 @@ export class InMemoryTurnWorld {
}
acknowledgeDirtyState(changes: TurnWorldChanges): void {
for (const id of changes.accessScoreResetGeneralIds) this.accessScoreResetGeneralIds.delete(id);
for (const general of changes.generals) this.dirtyGeneralIds.delete(general.id);
for (const city of changes.cities) this.dirtyCityIds.delete(city.id);
for (const nation of changes.nations) this.dirtyNationIds.delete(nation.id);
@@ -330,8 +330,8 @@ export const cutJoinTurnTime = (value: Date, tickSeconds: number): Date => {
return new Date(baseTime + alignedSeconds * 1000);
};
const resolveTurnTime = (
rng: RandUtil,
export const resolveJoinTurnTime = (
rng: Pick<RandUtil, 'nextRangeInt'>,
worldState: WorldStateRow,
acceptedAt: Date,
runtimeTurnTime: Date,
@@ -348,7 +348,12 @@ const resolveTurnTime = (
offsetSeconds = inheritTurntimeZone * legacyTurnTermMinutes + rng.nextRangeInt(0, legacyTurnTermMinutes - 1);
offsetMicros = rng.nextRangeInt(0, 999_999);
} else {
turnTimeBase = base;
// Ref normally uses game_env.turntime as a near-current cursor. Core's
// durable daemon can legitimately be catching up from an older cursor,
// so scheduling from runtimeTurnTime may put a newly created general
// hours behind the game clock. The accepted game time is the equivalent
// current-time boundary for a new general.
turnTimeBase = acceptedAt;
offsetSeconds = rng.nextRangeInt(0, tickSeconds - 1);
offsetMicros = rng.nextRangeInt(0, 999_999);
}
@@ -662,7 +667,7 @@ export const createGeneralFromJoin = async (options: {
}
const experience = await resolveCatchupExperience(db, relativeYear);
const turnTime = resolveTurnTime(
const turnTime = resolveJoinTurnTime(
rng,
worldState,
acceptedAt,
@@ -87,6 +87,9 @@ const LEGACY_STAT_CHANGE_GENERAL_ACTIONS = new Set([
'che_견문',
'che_무작위건국',
'che_화계',
'che_선동',
'che_파괴',
'che_탈취',
'che_집합',
'cr_건국',
'che_이동',
@@ -18,15 +18,23 @@ const GENERAL_AI_ACTIONS = [
const NATION_AI_ACTIONS = ['che_몰수', 'che_발령', 'che_선전포고', 'che_천도', 'che_포상'] as const;
const GENERAL_REF_EDITOR_ACTIONS = [
'che_은퇴',
'che_임관',
'che_랜덤임관',
'che_강행',
'che_징병',
'che_출병',
'che_농지개간',
'che_선동',
'che_탈취',
'che_파괴',
'che_화계',
'che_증여',
'che_하야',
'che_장비매매',
] as const;
const GENERAL_REF_STRATEGY_ACTIONS = ['che_선동', 'che_탈취', 'che_파괴', 'che_화계'] as const;
const GENERAL_REF_STRATEGY_ACTION_SET = new Set<string>(GENERAL_REF_STRATEGY_ACTIONS);
const NATION_REF_EDITOR_ACTIONS = ['che_포상', 'che_발령', 'che_증축', 'che_필사즉생'] as const;
describe('default turn command profile AI coverage', () => {
@@ -41,6 +49,9 @@ describe('default turn command profile AI coverage', () => {
const profile = await loadTurnCommandProfile();
expect(profile.general).toEqual(expect.arrayContaining([...GENERAL_REF_EDITOR_ACTIONS]));
expect(profile.general.filter((action) => GENERAL_REF_STRATEGY_ACTION_SET.has(action))).toEqual(
GENERAL_REF_STRATEGY_ACTIONS
);
expect(profile.nation).toEqual(expect.arrayContaining([...NATION_REF_EDITOR_ACTIONS]));
});
});
@@ -0,0 +1,120 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import type { TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const generalId = 991_815;
const scenarioCode = 'general-access-score-reset-persistence';
integration('general access score reset persistence', () => {
let db: GamePrismaClient;
let closeDb: (() => Promise<void>) | undefined;
const cleanup = async () => {
await db.generalAccessLog.deleteMany({ where: { generalId } });
await db.general.deleteMany({ where: { id: generalId } });
await db.worldState.deleteMany({ where: { scenarioCode } });
};
beforeAll(async () => {
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
closeDb = () => connector.disconnect();
await cleanup();
});
afterAll(async () => {
await cleanup();
await closeDb?.();
});
it('commits the own-turn reset marker in the same world flush', async () => {
const turnTime = new Date('2026-08-15T00:10:00.000Z');
await db.general.create({
data: {
id: generalId,
userId: 'access-reset-persistence-user',
name: '접속점수초기화장수',
turnTime,
},
});
await db.generalAccessLog.create({
data: {
generalId,
userId: 'access-reset-persistence-user',
lastRefresh: new Date('2026-08-15T00:09:59.000Z'),
refresh: 120,
refreshTotal: 500,
refreshScore: 351,
refreshScoreTotal: 999,
},
});
const row = await db.worldState.create({
data: {
scenarioCode,
currentYear: 200,
currentMonth: 1,
tickSeconds: 600,
config: {},
meta: {},
},
});
const state: TurnWorldState = {
id: row.id,
currentYear: 200,
currentMonth: 1,
tickSeconds: 600,
lastTurnTime: new Date('2026-08-15T00:00:00.000Z'),
meta: {},
};
const scenarioConfig: TurnWorldSnapshot['scenarioConfig'] = {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 75, npcMin: 10, chiefMin: 70 },
iconPath: '.',
map: {},
const: {},
environment: { mapName: 'test', unitSet: 'default' },
};
const world = new InMemoryTurnWorld(
state,
{
scenarioConfig,
map: { id: 'test', name: 'test', cities: [] },
generals: [],
cities: [],
nations: [],
troops: [],
diplomacy: [],
events: [],
initialEvents: [],
},
{ schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } }
);
world.markGeneralAccessScoreReset(generalId);
const hooks = await createDatabaseTurnHooks(databaseUrl!, world);
try {
await hooks.hooks.flushChanges?.({
lastTurnTime: state.lastTurnTime.toISOString(),
processedGenerals: 1,
processedTurns: 1,
durationMs: 0,
partial: false,
});
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).toMatchObject({
refresh: 120,
refreshTotal: 500,
refreshScore: 0,
refreshScoreTotal: 999,
});
expect(world.peekDirtyState().accessScoreResetGeneralIds).toEqual([]);
} finally {
await hooks.close();
}
});
});
@@ -4,6 +4,7 @@ import {
buildJoinCreateGeneralSeed,
cutJoinTurnTime,
JOIN_WELCOME_MESSAGE,
resolveJoinTurnTime,
} from '../src/turn/joinCreateGeneralService.js';
describe('generic join legacy time contracts', () => {
@@ -19,6 +20,35 @@ describe('generic join legacy time contracts', () => {
);
});
it('schedules a new general within one turn of the accepted game time even when the daemon cursor is stale', () => {
const calls: Array<[number, number]> = [];
const values = [59, 250_000];
const rng = {
nextRangeInt(min: number, max: number) {
calls.push([min, max]);
return values.shift() ?? min;
},
};
const acceptedAt = new Date('2026-08-15T17:57:05.837Z');
const staleRuntimeTurnTime = new Date('2026-08-15T07:10:00.000Z');
const turnTime = resolveJoinTurnTime(
rng,
{ tickSeconds: 120 } as Parameters<typeof resolveJoinTurnTime>[1],
acceptedAt,
staleRuntimeTurnTime,
undefined
);
expect(turnTime.toISOString()).toBe('2026-08-15T17:58:05.087Z');
expect(turnTime.getTime()).toBeGreaterThan(acceptedAt.getTime());
expect(turnTime.getTime()).toBeLessThanOrEqual(acceptedAt.getTime() + 120_000);
expect(calls).toEqual([
[0, 119],
[0, 999_999],
]);
});
it('uses the HiDCHe product name without the legacy PHP runtime label', () => {
expect(JOIN_WELCOME_MESSAGE).toBe('삼국지 모의전투 HiDCHe의 세계에 오신 것을 환영합니다 ^o^');
expect(JOIN_WELCOME_MESSAGE).not.toContain('PHP');
+2
View File
@@ -174,6 +174,8 @@ describe('InMemoryTurnProcessor ordering', () => {
const tiedGeneralResult = await processor.run(new Date(addMinutes(baseTime, 10).getTime() + 1), budget);
expect(tiedGeneralResult.processedTurns).toBe(0);
expect(executed).toEqual([3, 2]);
expect(world.peekDirtyState().accessScoreResetGeneralIds).toEqual([2, 3]);
expect(world.getState().meta).toMatchObject({ refreshLimit: 350 });
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);