Rename mentor matching to similar players

This commit is contained in:
dahyeon committed 2026-07-03 03:18:59 -07:00
1 parent cfbc74d882
commit ce00bc84b5
14 files changed
+529 -388

No files matched your search

@@ -3,9 +3,9 @@ import {
FEATURE_SCHEMA_VERSION,
METRICS,
type AnalysisJobStatusDto,
type MentorMatchesDto,
type MetricValueDto,
type PlayerAnalysisDto,
type SimilarPlayersDto,
} from '@persona-lenz/shared';
import { ConnectionService } from '../global/database/connection.service';
import type {
@@ -14,8 +14,8 @@ import type {
PlayerProfile,
TierInfo,
} from '../global/database/schemas';
import { MentorMatchService } from './mentor-match.service';
import type { MentorMatch } from './analysis.types';
import { SimilarPlayerService } from './similar-player.service';
import type { SimilarPlayer } from './analysis.types';
type JobStatusRecord = Pick<
AnalysisJob,
@@ -27,7 +27,7 @@ type AccountSummaryRecord = Pick<
'gameName' | 'profileIconId' | 'tagLine' | 'tiers'
>;
type MentorAccountRecord = Pick<Account, 'gameName' | 'puuid' | 'tagLine'>;
type CounterpartAccountRecord = Pick<Account, 'gameName' | 'puuid' | 'tagLine'>;
type PlayerProfileRecord = Pick<
PlayerProfile,
@@ -45,7 +45,7 @@ type PlayerProfileRecord = Pick<
export class AnalysisReadService {
constructor(
private readonly connectionService: ConnectionService,
private readonly mentorMatchService?: MentorMatchService,
private readonly similarPlayerService?: SimilarPlayerService,
) {}
public async getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
@@ -113,34 +113,27 @@ export class AnalysisReadService {
};
}
public async getMentorMatches(
public async getSimilarPlayers(
puuid: string,
queueId: number,
limit: number,
): Promise<MentorMatchesDto> {
if (!this.mentorMatchService) {
throw new Error('MentorMatchService is not configured.');
): Promise<SimilarPlayersDto> {
if (!this.similarPlayerService) {
throw new Error('SimilarPlayerService is not configured.');
}
const mentorMatchesResult = await this.mentorMatchService.findMentorMatches(
puuid,
queueId,
limit,
);
const mentorAccountsByPuuid = await this.findMentorAccounts(
mentorMatchesResult.matches.map((match) => match.puuid),
const similarPlayersResult =
await this.similarPlayerService.findSimilarPlayers(puuid, queueId, limit);
const accountsByPuuid = await this.findCounterpartAccounts(
similarPlayersResult.matches.map((match) => match.puuid),
);
return {
puuid: mentorMatchesResult.puuid,
queueId: mentorMatchesResult.queueId,
profileUpdatedAt: mentorMatchesResult.profileUpdatedAt.toISOString(),
matches: mentorMatchesResult.matches.map((match, index) =>
this.toMentorMatchDto(
match,
mentorAccountsByPuuid.get(match.puuid),
index,
),
puuid: similarPlayersResult.puuid,
queueId: similarPlayersResult.queueId,
profileUpdatedAt: similarPlayersResult.profileUpdatedAt.toISOString(),
matches: similarPlayersResult.matches.map((match, index) =>
this.toSimilarPlayerDto(match, accountsByPuuid.get(match.puuid), index),
),
};
}
@@ -152,16 +145,16 @@ export class AnalysisReadService {
return accountModel.findOne({ puuid }).lean<AccountSummaryRecord>().exec();
}
private async findMentorAccounts(
private async findCounterpartAccounts(
puuids: string[],
): Promise<Map<string, MentorAccountRecord>> {
): Promise<Map<string, CounterpartAccountRecord>> {
const uniquePuuids = Array.from(new Set(puuids));
if (uniquePuuids.length === 0) return new Map();
const accountModel = await this.connectionService.getModel('account');
const accounts = await accountModel
.find({ puuid: { $in: uniquePuuids } })
.lean<MentorAccountRecord[]>()
.lean<CounterpartAccountRecord[]>()
.exec();
return new Map(accounts.map((account) => [account.puuid, account]));
@@ -224,13 +217,13 @@ export class AnalysisReadService {
};
}
private toMentorMatchDto(
match: MentorMatch,
account: MentorAccountRecord | undefined,
private toSimilarPlayerDto(
match: SimilarPlayer,
account: CounterpartAccountRecord | undefined,
index: number,
): MentorMatchesDto['matches'][number] {
): SimilarPlayersDto['matches'][number] {
return {
mentorDisplayId: `mentor-${index + 1}`,
displayId: `similar-${index + 1}`,
riotId: account
? {
gameName: account.gameName,
@@ -242,11 +235,13 @@ export class AnalysisReadService {
tier: match.tier,
division: match.division,
leaguePoints: match.leaguePoints,
tierComparison: match.tierComparison,
mainRole: match.mainRole,
mainChampions: match.mainChampions,
sampleGameCount: match.sampleGameCount,
similarMetrics: match.similarMetrics,
gapMetrics: match.gapMetrics,
strongerMetrics: match.strongerMetrics,
weakerMetrics: match.weakerMetrics,
};
}
@@ -12,8 +12,8 @@ import {
import type {
AnalysisJobStatusDto,
AnalysisRequestAcceptedDto,
MentorMatchesDto,
PlayerAnalysisDto,
SimilarPlayersDto,
} from '@persona-lenz/shared';
import {
RIOT_PLATFORM_ROUTES,
@@ -70,16 +70,16 @@ export class AnalysisController {
);
}
@Get('players/:puuid/mentor-matches')
public async getMentorMatches(
@Get('players/:puuid/similar-players')
public async getSimilarPlayers(
@Param('puuid') puuid: string,
@Query('queueId') rawQueueId?: string,
@Query('limit') rawLimit?: string,
): Promise<MentorMatchesDto> {
return this.analysisReadService.getMentorMatches(
): Promise<SimilarPlayersDto> {
return this.analysisReadService.getSimilarPlayers(
this.parsePuuid(puuid),
this.parseQueueId(rawQueueId),
this.parseMentorMatchLimit(rawLimit),
this.parseSimilarPlayersLimit(rawLimit),
);
}
@@ -165,7 +165,7 @@ export class AnalysisController {
return queueId;
}
private parseMentorMatchLimit(value?: string): number {
private parseSimilarPlayersLimit(value?: string): number {
if (value === undefined) return 10;
const limit = Number(value);
if (!Number.isInteger(limit) || limit < 1) {
@@ -20,10 +20,10 @@ import { createBullMqOptions } from './bullmq.config';
import { FeatureExtractorService } from './feature-extractor.service';
import { MetricBaselineService } from './metric-baseline.service';
import { MetricNormalizationService } from './metric-normalization.service';
import { MentorMatchService } from './mentor-match.service';
import { ProfileBuilderService } from './profile-builder.service';
import { SeedCollectionProcessor } from './seed-collection.processor';
import { SeedCollectionService } from './seed-collection.service';
import { SimilarPlayerService } from './similar-player.service';
import { TimelineDerivedService } from './timeline-derived.service';
import { TimelineMetricService } from './timeline-metric.service';
@@ -61,9 +61,9 @@ import { TimelineMetricService } from './timeline-metric.service';
FeatureExtractorService,
MetricBaselineService,
MetricNormalizationService,
MentorMatchService,
ProfileBuilderService,
SeedCollectionService,
SimilarPlayerService,
TimelineDerivedService,
TimelineMetricService,
],
@@ -73,8 +73,8 @@ import { TimelineMetricService } from './timeline-metric.service';
AnalysisPipelineService,
MetricBaselineService,
MetricNormalizationService,
MentorMatchService,
SeedCollectionService,
SimilarPlayerService,
],
})
export class AnalysisModule {}
+15 -13
View File
@@ -1,4 +1,4 @@
import type { MetricId, Role } from '@persona-lenz/shared';
import type { MetricId, Role, TierComparison } from '@persona-lenz/shared';
import type {
BaselineCohort,
LaneOpponentRef,
@@ -97,43 +97,45 @@ export interface BuiltPlayerProfile {
leaguePoints?: number;
}
export interface MentorChampionPoolEntry {
export interface ChampionPoolEntry {
championId: number;
games: number;
wins: number;
}
export interface SimilarMentorMetric {
export interface SimilarMetric {
metricId: MetricId;
currentValue: number;
mentorValue: number;
otherValue: number;
absoluteGap: number;
}
export interface GapMentorMetric {
export interface LeadMetric {
metricId: MetricId;
currentValue: number;
mentorValue: number;
mentorAdvantage: number;
otherValue: number;
lead: number;
}
export interface MentorMatch {
export interface SimilarPlayer {
puuid: string;
similarityScore: number;
finalScore: number;
tier?: string;
division?: string;
leaguePoints?: number;
tierComparison: TierComparison;
mainRole: Role;
mainChampions: MentorChampionPoolEntry[];
mainChampions: ChampionPoolEntry[];
sampleGameCount: number;
similarMetrics: SimilarMentorMetric[];
gapMetrics: GapMentorMetric[];
similarMetrics: SimilarMetric[];
strongerMetrics: LeadMetric[];
weakerMetrics: LeadMetric[];
}
export interface MentorMatchesResult {
export interface SimilarPlayersResult {
puuid: string;
queueId: number;
profileUpdatedAt: Date;
matches: MentorMatch[];
matches: SimilarPlayer[];
}
@@ -1,6 +1,6 @@
import { FEATURE_SCHEMA_VERSION, VECTOR_DIMENSION } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import { MentorMatchService } from './mentor-match.service';
import { SimilarPlayerService } from './similar-player.service';
function createLeanExec<T>(value: T) {
return {
@@ -64,7 +64,7 @@ function createProfile(overrides: Record<string, unknown> = {}) {
};
}
describe('MentorMatchService', () => {
describe('SimilarPlayerService', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-03T00:00:00.000Z'));
});
@@ -73,7 +73,7 @@ describe('MentorMatchService', () => {
jest.useRealTimers();
});
it('queries high-tier seed profiles with Atlas Vector Search and reranks candidates', async () => {
it('queries similar profiles without tier filters and ranks by style similarity', async () => {
const currentProfile = createProfile();
const findOne = jest.fn(() => createLeanExec(currentProfile));
const recommendationFindOne = jest.fn(() => createSortedLeanExec(null));
@@ -81,7 +81,7 @@ describe('MentorMatchService', () => {
const aggregate = jest.fn(() =>
createAggregateExec([
createProfile({
puuid: 'mentor-low-style-better-context',
puuid: 'lower-style-better-context',
championPool: [
{ championId: 103, games: 12, wins: 8 },
{ championId: 84, games: 5, wins: 4 },
@@ -101,7 +101,7 @@ describe('MentorMatchService', () => {
score: 0.8,
}),
createProfile({
puuid: 'mentor-high-style-weaker-context',
puuid: 'higher-style-similar-player',
championPool: [{ championId: 222, games: 30, wins: 20 }],
profile: {
kda: 0.4,
@@ -111,13 +111,13 @@ describe('MentorMatchService', () => {
deathsPerMin: 0.6,
},
sampleGameCount: 30,
tier: 'MASTER',
tier: 'PLATINUM',
lastMatchAt: new Date('2026-06-19T00:00:00.000Z'),
score: 0.9,
}),
]),
);
const service = new MentorMatchService({
const service = new SimilarPlayerService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerProfile'
@@ -127,7 +127,7 @@ describe('MentorMatchService', () => {
),
} as unknown as ConnectionService);
const result = await service.findMentorMatches('target-puuid', 420, 2);
const result = await service.findSimilarPlayers('target-puuid', 420, 2);
expect(findOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
@@ -145,8 +145,6 @@ describe('MentorMatchService', () => {
filter: {
mainRole: 'MIDDLE',
queueId: 420,
tier: { $in: ['MASTER', 'GRANDMASTER', 'CHALLENGER'] },
isSeed: true,
sampleGameCount: { $gte: 20 },
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
@@ -173,63 +171,89 @@ describe('MentorMatchService', () => {
expect(result.profileUpdatedAt).toEqual(
new Date('2026-07-02T00:00:00.000Z'),
);
// 스타일 유사도(0.9)가 컨텍스트(챔피언 풀·최근성)보다 랭킹을 지배한다.
expect(result.matches.map((match) => match.puuid)).toEqual([
'mentor-low-style-better-context',
'mentor-high-style-weaker-context',
]);
expect(result.matches[0].finalScore).toBeGreaterThan(
result.matches[1].finalScore,
);
expect(result.matches[0].mainChampions).toEqual([
{ championId: 103, games: 12, wins: 8 },
{ championId: 84, games: 5, wins: 4 },
{ championId: 777, games: 5, wins: 3 },
'higher-style-similar-player',
'lower-style-better-context',
]);
expect(result.matches[0].finalScore).toBeCloseTo(0.69, 6);
expect(result.matches[1].finalScore).toBeCloseTo(0.67, 6);
expect(result.matches[0].tierComparison).toBe('lower');
expect(result.matches[1].tierComparison).toBe('higher');
expect(result.matches[0].similarMetrics).toEqual([
{
metricId: 'killParticipation',
currentValue: 0.5,
mentorValue: 0.49,
absoluteGap: 0.01,
},
{
metricId: 'csPerMin',
currentValue: 0.5,
mentorValue: 0.51,
absoluteGap: 0.01,
otherValue: 0.52,
absoluteGap: 0.02,
},
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
absoluteGap: 0.3,
otherValue: 0.55,
absoluteGap: 0.05,
},
]);
expect(result.matches[0].gapMetrics).toEqual([
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.9,
mentorAdvantage: 0.6,
otherValue: 0.4,
absoluteGap: 0.1,
},
]);
expect(result.matches[0].strongerMetrics).toEqual([
{
metricId: 'csPerMin',
currentValue: 0.5,
otherValue: 0.7,
lead: 0.2,
},
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.4,
lead: 0.1,
},
{
metricId: 'deathsPerMin',
currentValue: 0.7,
mentorValue: 0.2,
mentorAdvantage: 0.5,
otherValue: 0.6,
lead: 0.1,
},
]);
expect(result.matches[0].weakerMetrics).toEqual([]);
expect(result.matches[1].strongerMetrics).toEqual([
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.9,
lead: 0.6,
},
{
metricId: 'deathsPerMin',
currentValue: 0.7,
otherValue: 0.2,
lead: 0.5,
},
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
]);
expect(result.matches[1].weakerMetrics).toEqual([
{
metricId: 'killParticipation',
currentValue: 0.5,
otherValue: 0.49,
lead: 0.01,
},
]);
expect(updateOne).toHaveBeenCalledWith(
{
puuid: 'target-puuid',
queueId: 420,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
},
@@ -237,7 +261,7 @@ describe('MentorMatchService', () => {
$set: {
puuid: 'target-puuid',
queueId: 420,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
result: { matches: result.matches },
@@ -252,13 +276,14 @@ describe('MentorMatchService', () => {
);
});
it('returns a fresh cached mentor recommendation without running vector search', async () => {
it('returns a fresh cached similar-player recommendation without running vector search', async () => {
const currentProfile = createProfile();
const cachedMatch = {
puuid: 'cached-mentor',
puuid: 'cached-similar-player',
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
@@ -266,18 +291,19 @@ describe('MentorMatchService', () => {
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.31,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
gapMetrics: [
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [],
};
const findOne = jest.fn(() => createLeanExec(currentProfile));
const aggregate = jest.fn();
@@ -288,7 +314,7 @@ describe('MentorMatchService', () => {
}),
);
const updateOne = jest.fn();
const service = new MentorMatchService({
const service = new SimilarPlayerService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerProfile'
@@ -298,12 +324,12 @@ describe('MentorMatchService', () => {
),
} as unknown as ConnectionService);
const result = await service.findMentorMatches('target-puuid', 420, 10);
const result = await service.findSimilarPlayers('target-puuid', 420, 10);
expect(recommendationFindOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
queueId: 420,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
});
@@ -320,12 +346,12 @@ describe('MentorMatchService', () => {
it('throws when the player profile has not been built yet', async () => {
const findOne = jest.fn(() => createLeanExec(null));
const aggregate = jest.fn();
const service = new MentorMatchService({
const service = new SimilarPlayerService({
getModel: jest.fn().mockResolvedValue({ findOne, aggregate }),
} as unknown as ConnectionService);
await expect(
service.findMentorMatches('missing-puuid', 420),
service.findSimilarPlayers('missing-puuid', 420),
).rejects.toThrow('Player profile not found.');
expect(aggregate).not.toHaveBeenCalled();
});
@@ -6,33 +6,51 @@ import {
VECTOR_DIMENSION,
type MetricDefinition,
type Role,
type TierComparison,
} from '@persona-lenz/shared';
import type { PipelineStage } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
GapMentorMetric,
MentorChampionPoolEntry,
MentorMatch,
MentorMatchesResult,
SimilarMentorMetric,
ChampionPoolEntry,
LeadMetric,
SimilarMetric,
SimilarPlayer,
SimilarPlayersResult,
} from './analysis.types';
const MENTOR_VECTOR_SEARCH_INDEX_NAME = 'player_profile_vector_index';
const MENTOR_VECTOR_SEARCH_NUM_CANDIDATES = 200;
const MENTOR_VECTOR_SEARCH_LIMIT = 50;
const DEFAULT_MENTOR_MATCH_LIMIT = 10;
const MINIMUM_MENTOR_SAMPLE_GAME_COUNT = 20;
const SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME = 'player_profile_vector_index';
const SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES = 200;
const SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT = 50;
const DEFAULT_SIMILAR_PLAYER_LIMIT = 10;
const MINIMUM_SAMPLE_GAME_COUNT = 20;
const LOW_SAMPLE_GAME_COUNT_THRESHOLD = 30;
const LOW_SAMPLE_PENALTY = 0.1;
const RECENCY_HALF_LIFE_MS = 14 * 24 * 60 * 60 * 1000;
const HIGH_TIER_MENTOR_TIERS = ['MASTER', 'GRANDMASTER', 'CHALLENGER'];
const TIER_ORDER = [
'IRON',
'BRONZE',
'SILVER',
'GOLD',
'PLATINUM',
'EMERALD',
'DIAMOND',
'MASTER',
'GRANDMASTER',
'CHALLENGER',
];
const TIER_COMPARISONS: TierComparison[] = [
'higher',
'same',
'lower',
'unknown',
];
interface MentorProfileRecord {
interface PlayerProfileRecord {
puuid: string;
queueId: number;
mainRole: Role;
sampleGameCount: number;
championPool: MentorChampionPoolEntry[];
championPool: ChampionPoolEntry[];
profile: Record<string, number>;
vector: number[];
updatedAt: Date;
@@ -42,23 +60,29 @@ interface MentorProfileRecord {
leaguePoints?: number;
}
interface MentorVectorSearchRecord extends Omit<MentorProfileRecord, 'vector'> {
interface VectorSearchRecord extends Omit<PlayerProfileRecord, 'vector'> {
score?: number;
}
interface MentorRecommendationCacheRecord {
interface RecommendationCacheRecord {
result?: Record<string, unknown>;
}
/**
* 나와 플레이스타일 벡터가 가까운 유저를 찾는다. 목적은 "따라 할 멘토"가 아니라
* "스타일은 비슷한데 왜 점수(티어)가 다른가"라는 인사이트 제공이므로,
* 후보를 티어로 거르지 않고 유사도 중심으로 랭킹한 뒤 티어 관계와
* 지표 우위(양방향)를 함께 반환한다.
*/
@Injectable()
export class MentorMatchService {
export class SimilarPlayerService {
constructor(private readonly connectionService: ConnectionService) {}
public async findMentorMatches(
public async findSimilarPlayers(
puuid: string,
queueId: number,
requestedLimit = DEFAULT_MENTOR_MATCH_LIMIT,
): Promise<MentorMatchesResult> {
requestedLimit = DEFAULT_SIMILAR_PLAYER_LIMIT,
): Promise<SimilarPlayersResult> {
const playerProfileModel =
await this.connectionService.getModel('playerProfile');
const recommendationModel =
@@ -66,14 +90,14 @@ export class MentorMatchService {
const normalizedLimit = this.normalizeLimit(requestedLimit);
const currentProfile = await playerProfileModel
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
.lean<MentorProfileRecord>()
.lean<PlayerProfileRecord>()
.exec();
if (!currentProfile) {
throw new NotFoundException('Player profile not found.');
}
const cacheFilter = this.createMentorRecommendationFilter(
const cacheFilter = this.createRecommendationFilter(
puuid,
queueId,
currentProfile.updatedAt,
@@ -81,9 +105,9 @@ export class MentorMatchService {
const cachedRecommendation = await recommendationModel
.findOne(cacheFilter)
.sort({ generatedAt: -1 })
.lean<MentorRecommendationCacheRecord>()
.lean<RecommendationCacheRecord>()
.exec();
const cachedMatches = this.extractCachedMentorMatches(cachedRecommendation);
const cachedMatches = this.extractCachedMatches(cachedRecommendation);
if (cachedMatches) {
return {
puuid,
@@ -103,13 +127,13 @@ export class MentorMatchService {
}
const candidates = await playerProfileModel
.aggregate<MentorVectorSearchRecord>(
this.createMentorCandidatePipeline(currentProfile, puuid, queueId),
.aggregate<VectorSearchRecord>(
this.createCandidatePipeline(currentProfile, puuid, queueId),
)
.exec();
const matches = candidates
.map((candidate) => this.toMentorMatch(currentProfile, candidate))
.map((candidate) => this.toSimilarPlayer(currentProfile, candidate))
.sort((left, right) => right.finalScore - left.finalScore)
.slice(0, normalizedLimit);
@@ -120,13 +144,13 @@ export class MentorMatchService {
$set: {
puuid,
queueId,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: currentProfile.updatedAt,
result: { matches },
evidence: {
candidateCount: candidates.length,
vectorSearchIndex: MENTOR_VECTOR_SEARCH_INDEX_NAME,
vectorSearchIndex: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
},
generatedAt: new Date(),
},
@@ -143,45 +167,43 @@ export class MentorMatchService {
};
}
private createMentorRecommendationFilter(
private createRecommendationFilter(
puuid: string,
queueId: number,
profileUpdatedAt: Date,
): {
puuid: string;
queueId: number;
type: 'mentor-match';
type: 'similar-player';
featureSchemaVersion: number;
profileUpdatedAt: Date;
} {
return {
puuid,
queueId,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt,
};
}
private createMentorCandidatePipeline(
currentProfile: MentorProfileRecord,
private createCandidatePipeline(
currentProfile: PlayerProfileRecord,
puuid: string,
queueId: number,
): PipelineStage[] {
return [
{
$vectorSearch: {
index: MENTOR_VECTOR_SEARCH_INDEX_NAME,
index: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
path: 'vector',
queryVector: currentProfile.vector,
numCandidates: MENTOR_VECTOR_SEARCH_NUM_CANDIDATES,
limit: MENTOR_VECTOR_SEARCH_LIMIT,
numCandidates: SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES,
limit: SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT,
filter: {
mainRole: currentProfile.mainRole,
queueId,
tier: { $in: HIGH_TIER_MENTOR_TIERS },
isSeed: true,
sampleGameCount: { $gte: MINIMUM_MENTOR_SAMPLE_GAME_COUNT },
sampleGameCount: { $gte: MINIMUM_SAMPLE_GAME_COUNT },
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
},
@@ -206,81 +228,99 @@ export class MentorMatchService {
];
}
private toMentorMatch(
currentProfile: MentorProfileRecord,
mentorProfile: MentorVectorSearchRecord,
): MentorMatch {
const similarityScore = this.clamp01(mentorProfile.score ?? 0);
private toSimilarPlayer(
currentProfile: PlayerProfileRecord,
candidate: VectorSearchRecord,
): SimilarPlayer {
const similarityScore = this.clamp01(candidate.score ?? 0);
return {
puuid: mentorProfile.puuid,
puuid: candidate.puuid,
similarityScore,
finalScore: this.calculateFinalScore(
currentProfile,
mentorProfile,
candidate,
similarityScore,
),
tier: mentorProfile.tier,
division: mentorProfile.division,
leaguePoints: mentorProfile.leaguePoints,
mainRole: mentorProfile.mainRole,
mainChampions: mentorProfile.championPool.slice(0, 3),
sampleGameCount: mentorProfile.sampleGameCount,
tier: candidate.tier,
division: candidate.division,
leaguePoints: candidate.leaguePoints,
tierComparison: this.compareTier(currentProfile.tier, candidate.tier),
mainRole: candidate.mainRole,
mainChampions: candidate.championPool.slice(0, 3),
sampleGameCount: candidate.sampleGameCount,
similarMetrics: this.resolveSimilarMetrics(
currentProfile.profile,
mentorProfile.profile,
candidate.profile,
),
gapMetrics: this.resolveGapMetrics(
strongerMetrics: this.resolveLeadMetrics(
currentProfile.profile,
mentorProfile.profile,
candidate.profile,
'other',
),
weakerMetrics: this.resolveLeadMetrics(
currentProfile.profile,
candidate.profile,
'current',
),
};
}
private calculateFinalScore(
currentProfile: MentorProfileRecord,
mentorProfile: MentorVectorSearchRecord,
currentProfile: PlayerProfileRecord,
candidate: VectorSearchRecord,
similarityScore: number,
): number {
const championPoolSimilarity = this.calculateChampionPoolSimilarity(
currentProfile.championPool,
mentorProfile.championPool,
candidate.championPool,
);
const recencyScore = this.calculateRecencyScore(mentorProfile.lastMatchAt);
const tierScore = this.resolveTierScore(mentorProfile.tier);
const recencyScore = this.calculateRecencyScore(candidate.lastMatchAt);
const lowSamplePenalty =
mentorProfile.sampleGameCount < LOW_SAMPLE_GAME_COUNT_THRESHOLD
candidate.sampleGameCount < LOW_SAMPLE_GAME_COUNT_THRESHOLD
? LOW_SAMPLE_PENALTY
: 0;
// 유사도가 랭킹을 지배해야 한다 — 티어는 랭킹 요소가 아니라 인사이트(tierComparison)로만 쓴다.
return this.clamp01(
0.6 * similarityScore +
0.2 * championPoolSimilarity +
0.12 * recencyScore +
0.08 * tierScore -
0.7 * similarityScore +
0.18 * championPoolSimilarity +
0.12 * recencyScore -
lowSamplePenalty,
);
}
private compareTier(
currentTier: string | undefined,
otherTier: string | undefined,
): TierComparison {
const currentTierRank = TIER_ORDER.indexOf(currentTier ?? '');
const otherTierRank = TIER_ORDER.indexOf(otherTier ?? '');
if (currentTierRank < 0 || otherTierRank < 0) return 'unknown';
if (otherTierRank > currentTierRank) return 'higher';
if (otherTierRank < currentTierRank) return 'lower';
return 'same';
}
private calculateChampionPoolSimilarity(
currentChampionPool: MentorChampionPoolEntry[],
mentorChampionPool: MentorChampionPoolEntry[],
currentChampionPool: ChampionPoolEntry[],
otherChampionPool: ChampionPoolEntry[],
): number {
const currentChampionIds = new Set(
currentChampionPool.slice(0, 5).map((entry) => entry.championId),
);
const mentorChampionIds = new Set(
mentorChampionPool.slice(0, 5).map((entry) => entry.championId),
const otherChampionIds = new Set(
otherChampionPool.slice(0, 5).map((entry) => entry.championId),
);
const unionChampionIds = new Set([
...currentChampionIds,
...mentorChampionIds,
...otherChampionIds,
]);
if (unionChampionIds.size === 0) return 0;
let sharedChampionCount = 0;
currentChampionIds.forEach((championId) => {
if (mentorChampionIds.has(championId)) sharedChampionCount += 1;
if (otherChampionIds.has(championId)) sharedChampionCount += 1;
});
return sharedChampionCount / unionChampionIds.size;
@@ -293,21 +333,14 @@ export class MentorMatchService {
return this.clamp01(Math.pow(0.5, ageMs / RECENCY_HALF_LIFE_MS));
}
private resolveTierScore(tier: string | undefined): number {
if (tier === 'CHALLENGER') return 1;
if (tier === 'GRANDMASTER') return 0.8;
if (tier === 'MASTER') return 0.6;
return 0;
}
private resolveSimilarMetrics(
currentProfile: Record<string, number>,
mentorProfile: Record<string, number>,
): SimilarMentorMetric[] {
otherProfile: Record<string, number>,
): SimilarMetric[] {
return METRICS.flatMap((metric) => {
const comparison = this.createMetricValues(
currentProfile,
mentorProfile,
otherProfile,
metric,
);
if (!comparison) return [];
@@ -315,9 +348,9 @@ export class MentorMatchService {
return {
metricId: metric.id,
currentValue: comparison.currentValue,
mentorValue: comparison.mentorValue,
otherValue: comparison.otherValue,
absoluteGap: this.roundMetricGap(
Math.abs(comparison.mentorValue - comparison.currentValue),
Math.abs(comparison.otherValue - comparison.currentValue),
),
};
})
@@ -325,57 +358,59 @@ export class MentorMatchService {
.slice(0, 3);
}
private resolveGapMetrics(
private resolveLeadMetrics(
currentProfile: Record<string, number>,
mentorProfile: Record<string, number>,
): GapMentorMetric[] {
otherProfile: Record<string, number>,
leader: 'current' | 'other',
): LeadMetric[] {
return METRICS.flatMap((metric) => {
const comparison = this.createMetricValues(
currentProfile,
mentorProfile,
otherProfile,
metric,
);
if (!comparison) return [];
const rawMentorAdvantage =
const otherAdvantage =
metric.direction === 'lowerIsBetter'
? comparison.currentValue - comparison.mentorValue
: comparison.mentorValue - comparison.currentValue;
if (rawMentorAdvantage <= 0) return [];
? comparison.currentValue - comparison.otherValue
: comparison.otherValue - comparison.currentValue;
const lead = leader === 'other' ? otherAdvantage : -otherAdvantage;
if (lead <= 0) return [];
return {
metricId: metric.id,
currentValue: comparison.currentValue,
mentorValue: comparison.mentorValue,
mentorAdvantage: this.roundMetricGap(rawMentorAdvantage),
otherValue: comparison.otherValue,
lead: this.roundMetricGap(lead),
};
})
.sort((left, right) => right.mentorAdvantage - left.mentorAdvantage)
.sort((left, right) => right.lead - left.lead)
.slice(0, 3);
}
private createMetricValues(
currentProfile: Record<string, number>,
mentorProfile: Record<string, number>,
otherProfile: Record<string, number>,
metric: MetricDefinition,
): { currentValue: number; mentorValue: number } | null {
): { currentValue: number; otherValue: number } | null {
const currentValue = currentProfile[metric.id];
const mentorValue = mentorProfile[metric.id];
if (!Number.isFinite(currentValue) || !Number.isFinite(mentorValue)) {
const otherValue = otherProfile[metric.id];
if (!Number.isFinite(currentValue) || !Number.isFinite(otherValue)) {
return null;
}
return {
currentValue: this.clamp01(currentValue),
mentorValue: this.clamp01(mentorValue),
otherValue: this.clamp01(otherValue),
};
}
private normalizeLimit(requestedLimit: number): number {
if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
return DEFAULT_MENTOR_MATCH_LIMIT;
return DEFAULT_SIMILAR_PLAYER_LIMIT;
}
return Math.min(requestedLimit, DEFAULT_MENTOR_MATCH_LIMIT);
return Math.min(requestedLimit, DEFAULT_SIMILAR_PLAYER_LIMIT);
}
private roundMetricGap(value: number): number {
@@ -387,18 +422,18 @@ export class MentorMatchService {
return Math.max(0, Math.min(1, value));
}
private extractCachedMentorMatches(
recommendation: MentorRecommendationCacheRecord | null,
): MentorMatch[] | null {
private extractCachedMatches(
recommendation: RecommendationCacheRecord | null,
): SimilarPlayer[] | null {
const matches = recommendation?.result?.matches;
if (!Array.isArray(matches)) return null;
if (!matches.every((match) => this.isCachedMentorMatch(match))) {
if (!matches.every((match) => this.isCachedSimilarPlayer(match))) {
return null;
}
return matches;
}
private isCachedMentorMatch(value: unknown): value is MentorMatch {
private isCachedSimilarPlayer(value: unknown): value is SimilarPlayer {
const record = this.asRecord(value);
if (!record) return false;
@@ -406,6 +441,8 @@ export class MentorMatchService {
typeof record.puuid === 'string' &&
this.isFiniteNumber(record.similarityScore) &&
this.isFiniteNumber(record.finalScore) &&
typeof record.tierComparison === 'string' &&
TIER_COMPARISONS.includes(record.tierComparison as TierComparison) &&
typeof record.mainRole === 'string' &&
ROLES.includes(record.mainRole as Role) &&
Array.isArray(record.mainChampions) &&
@@ -414,13 +451,14 @@ export class MentorMatchService {
record.similarMetrics,
'absoluteGap',
) &&
this.isCachedMetricComparisonArray(record.gapMetrics, 'mentorAdvantage')
this.isCachedMetricComparisonArray(record.strongerMetrics, 'lead') &&
this.isCachedMetricComparisonArray(record.weakerMetrics, 'lead')
);
}
private isCachedMetricComparisonArray(
value: unknown,
scoreFieldName: 'absoluteGap' | 'mentorAdvantage',
scoreFieldName: 'absoluteGap' | 'lead',
): boolean {
return (
Array.isArray(value) &&
@@ -430,7 +468,7 @@ export class MentorMatchService {
record !== null &&
typeof record.metricId === 'string' &&
this.isFiniteNumber(record.currentValue) &&
this.isFiniteNumber(record.mentorValue) &&
this.isFiniteNumber(record.otherValue) &&
this.isFiniteNumber(record[scoreFieldName])
);
})
@@ -107,7 +107,7 @@ export const PlayerProfileSchema = new Schema<PlayerProfile>(
);
PlayerProfileSchema.index({ puuid: 1, queueId: 1 }, { unique: true });
// 운영 조회용 (멘토 검색 자체는 Atlas Vector Search 인덱스 사용)
// 운영 조회용 (유사 유저 검색 자체는 Atlas Vector Search 인덱스 사용)
PlayerProfileSchema.index({ isSeed: 1, mainRole: 1, tier: 1 });
export type PlayerProfileDocument = HydratedDocument<PlayerProfile>;
@@ -2,14 +2,14 @@ import { HydratedDocument, Schema } from 'mongoose';
import { MongooseTimestamps } from './common';
/**
* - mentor-match: 유사 고티어 유저 Top-K (MVP 3)
* - similar-player: 플레이스타일이 비슷한 유저 Top-K (MVP 3)
* - champion-recommendation: Fit/Growth/Stretch 챔피언 추천 (MVP 4)
* - llm-feedback: LLM 생성 피드백 (MVP 5)
*/
export type RecommendationType =
'mentor-match' | 'champion-recommendation' | 'llm-feedback';
'similar-player' | 'champion-recommendation' | 'llm-feedback';
export const RECOMMENDATION_TYPES: RecommendationType[] = [
'mentor-match',
'similar-player',
'champion-recommendation',
'llm-feedback',
];
+43 -25
View File
@@ -3,8 +3,8 @@ import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import {
FEATURE_SCHEMA_VERSION,
type MentorMatchesDto,
type PlayerAnalysisDto,
type SimilarPlayersDto,
} from '@persona-lenz/shared';
import request from 'supertest';
import { App } from 'supertest/types';
@@ -15,7 +15,7 @@ import {
ANALYSIS_QUEUE_NAME,
SEED_COLLECTION_QUEUE_NAME,
} from './../src/modules/analysis/analysis.constants';
import { MentorMatchService } from './../src/modules/analysis/mentor-match.service';
import { SimilarPlayerService } from './../src/modules/analysis/similar-player.service';
import { ConnectionService } from './../src/modules/global/database/connection.service';
import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants';
import { SecretService } from './../src/modules/global/secret/secret.service';
@@ -25,8 +25,8 @@ describe('AppController (e2e)', () => {
let analysisQueueService: {
enqueueUserAnalysis: jest.Mock;
};
let mentorMatchService: {
findMentorMatches: jest.Mock;
let similarPlayerService: {
findSimilarPlayers: jest.Mock;
};
let connectionService: {
getModel: jest.Mock;
@@ -44,8 +44,8 @@ describe('AppController (e2e)', () => {
analysisQueueService = {
enqueueUserAnalysis: jest.fn(),
};
mentorMatchService = {
findMentorMatches: jest.fn(),
similarPlayerService = {
findSimilarPlayers: jest.fn(),
};
connectionService = {
getModel: jest.fn(),
@@ -57,8 +57,8 @@ describe('AppController (e2e)', () => {
.useValue(connectionService)
.overrideProvider(AnalysisQueueService)
.useValue(analysisQueueService)
.overrideProvider(MentorMatchService)
.useValue(mentorMatchService)
.overrideProvider(SimilarPlayerService)
.useValue(similarPlayerService)
.overrideProvider(SecretService)
.useValue({
get: jest.fn((key: string) => {
@@ -446,18 +446,19 @@ describe('AppController (e2e)', () => {
});
});
it('/api/players/:puuid/mentor-matches (GET) returns mentor matches with display Riot IDs', async () => {
mentorMatchService.findMentorMatches.mockResolvedValue({
it('/api/players/:puuid/similar-players (GET) returns similar players with display Riot IDs', async () => {
similarPlayerService.findSimilarPlayers.mockResolvedValue({
puuid: 'target-puuid',
queueId: 420,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
matches: [
{
puuid: 'mentor-puuid',
puuid: 'similar-player-puuid',
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
leaguePoints: 900,
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
@@ -465,16 +466,24 @@ describe('AppController (e2e)', () => {
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.31,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
gapMetrics: [
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [
{
metricId: 'visionScorePerMin',
currentValue: 0.6,
otherValue: 0.4,
lead: 0.2,
},
],
},
@@ -483,7 +492,7 @@ describe('AppController (e2e)', () => {
const accountFind = jest.fn(() =>
createLeanExec([
{
puuid: 'mentor-puuid',
puuid: 'similar-player-puuid',
gameName: '프리리',
tagLine: 'KR1',
},
@@ -494,17 +503,17 @@ describe('AppController (e2e)', () => {
});
const response = await request(app.getHttpServer())
.get('/api/players/target-puuid/mentor-matches?limit=3')
.get('/api/players/target-puuid/similar-players?limit=3')
.expect(200);
const responseBody = response.body as MentorMatchesDto;
const responseBody = response.body as SimilarPlayersDto;
expect(mentorMatchService.findMentorMatches).toHaveBeenCalledWith(
expect(similarPlayerService.findSimilarPlayers).toHaveBeenCalledWith(
'target-puuid',
420,
3,
);
expect(accountFind).toHaveBeenCalledWith({
puuid: { $in: ['mentor-puuid'] },
puuid: { $in: ['similar-player-puuid'] },
});
expect(responseBody).toEqual({
puuid: 'target-puuid',
@@ -512,7 +521,7 @@ describe('AppController (e2e)', () => {
profileUpdatedAt: '2026-07-02T00:00:00.000Z',
matches: [
{
mentorDisplayId: 'mentor-1',
displayId: 'similar-1',
riotId: {
gameName: '프리리',
tagLine: 'KR1',
@@ -521,6 +530,7 @@ describe('AppController (e2e)', () => {
finalScore: 0.81,
tier: 'CHALLENGER',
leaguePoints: 900,
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
@@ -528,16 +538,24 @@ describe('AppController (e2e)', () => {
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.31,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
gapMetrics: [
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [
{
metricId: 'visionScorePerMin',
currentValue: 0.6,
otherValue: 0.4,
lead: 0.2,
},
],
},
+41 -30
View File
@@ -107,7 +107,7 @@
.chart-section,
.champion-section,
.insight-section,
.mentor-section,
.similar-section,
.dashboard-summary {
border: 1px solid var(--border);
border-radius: 8px;
@@ -344,7 +344,7 @@
.chart-section,
.champion-section,
.insight-section,
.mentor-section {
.similar-section {
padding: 24px;
}
@@ -466,28 +466,28 @@
line-height: 1.55;
}
.mentor-message {
.similar-message {
margin-top: 16px;
}
.mentor-table-wrap {
.similar-table-wrap {
margin-top: 18px;
overflow-x: auto;
}
.mentor-table-wrap:focus-visible {
.similar-table-wrap:focus-visible {
outline: 3px solid color-mix(in srgb, var(--accent) 42%, transparent);
outline-offset: 3px;
}
.mentor-table {
.similar-table {
width: 100%;
min-width: 780px;
border-collapse: separate;
border-spacing: 0 10px;
}
.mentor-table th {
.similar-table th {
padding: 0 12px;
color: var(--text-subtle);
font-size: 12px;
@@ -497,7 +497,7 @@
text-transform: uppercase;
}
.mentor-table td {
.similar-table td {
min-width: 0;
padding: 14px 12px;
border-block: 1px solid var(--border);
@@ -505,51 +505,51 @@
vertical-align: top;
}
.mentor-table td:first-child {
.similar-table td:first-child {
border-left: 1px solid var(--border);
border-radius: 8px 0 0 8px;
}
.mentor-table td:last-child {
.similar-table td:last-child {
border-right: 1px solid var(--border);
border-radius: 0 8px 8px 0;
}
.mentor-player,
.mentor-score,
.mentor-metric-groups,
.mentor-metric-group {
.similar-player,
.similar-score,
.similar-metric-groups,
.similar-metric-group {
min-width: 0;
display: grid;
gap: 6px;
}
.mentor-player strong,
.mentor-score strong,
.mentor-chip strong {
.similar-player strong,
.similar-score strong,
.similar-chip strong {
overflow: hidden;
color: var(--text-strong);
text-overflow: ellipsis;
white-space: nowrap;
}
.mentor-player span,
.mentor-score span,
.mentor-chip span,
.mentor-metric-group > span,
.mentor-empty {
.similar-player span,
.similar-score span,
.similar-chip span,
.similar-metric-group > span,
.similar-empty {
color: var(--text-subtle);
font-size: 12px;
font-weight: 700;
line-height: 1.35;
}
.mentor-score strong {
.similar-score strong {
font-size: 22px;
line-height: 1;
}
.mentor-chip-list {
.similar-chip-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
@@ -558,7 +558,7 @@
list-style: none;
}
.mentor-chip {
.similar-chip {
max-width: 100%;
display: inline-flex;
align-items: center;
@@ -569,23 +569,34 @@
padding: 5px 8px;
}
.mentor-chip strong {
.similar-chip strong {
min-width: 0;
}
.mentor-chip span {
.similar-chip span {
flex: 0 0 auto;
white-space: nowrap;
}
.mentor-chip-accent {
.similar-chip-accent {
border-color: color-mix(in srgb, var(--accent) 48%, var(--border));
}
.mentor-chip-muted {
.similar-chip-muted {
background: color-mix(in srgb, var(--surface) 74%, var(--surface-soft));
}
.similar-tier-badge {
justify-self: start;
border: 1px solid color-mix(in srgb, var(--accent) 48%, var(--border));
border-radius: 999px;
padding: 3px 8px;
color: var(--text-strong);
font-size: 11px;
font-weight: 700;
line-height: 1.2;
}
.empty-view {
min-height: calc(100svh - 240px);
display: grid;
@@ -685,7 +696,7 @@
.chart-section,
.champion-section,
.insight-section,
.mentor-section,
.similar-section,
.dashboard-summary {
padding: 18px;
}
+5 -5
View File
@@ -2,8 +2,8 @@ import type {
AnalysisJobStatusDto,
AnalysisRequestAcceptedDto,
AnalysisRequestDto,
MentorMatchesDto,
PlayerAnalysisDto,
SimilarPlayersDto,
} from '@persona-lenz/shared';
export class ApiClientError extends Error {
@@ -99,12 +99,12 @@ export async function getLatestPlayerAnalysis(
);
}
export async function getMentorMatches(
export async function getSimilarPlayers(
puuid: string,
limit = 10,
): Promise<MentorMatchesDto> {
): Promise<SimilarPlayersDto> {
const params = new URLSearchParams({ limit: String(limit) });
return fetchJson<MentorMatchesDto>(
`/api/players/${encodeURIComponent(puuid)}/mentor-matches?${params}`,
return fetchJson<SimilarPlayersDto>(
`/api/players/${encodeURIComponent(puuid)}/similar-players?${params}`,
);
}
+112 -73
View File
@@ -3,13 +3,14 @@ import { Link, useParams } from 'react-router-dom';
import {
METRICS,
type ChampionPoolEntryDto,
type GapMentorMetricDto,
type MentorMatchDto,
type MentorMatchesDto,
type LeadMetricDto,
type MetricId,
type MetricValueDto,
type PlayerAnalysisDto,
type SimilarMentorMetricDto,
type SimilarMetricDto,
type SimilarPlayerDto,
type SimilarPlayersDto,
type TierComparison,
type TierInfoDto,
} from '@persona-lenz/shared';
import {
@@ -23,8 +24,8 @@ import {
} from 'recharts';
import {
getLatestPlayerAnalysis,
getMentorMatches,
getReadableErrorMessage,
getSimilarPlayers,
} from '../api/analysis';
import {
loadChampionCatalog,
@@ -45,19 +46,18 @@ interface RadarMetricDatum {
value: number;
}
const MENTOR_MATCH_LIMIT = 10;
const SIMILAR_PLAYER_LIMIT = 10;
export function DashboardPage() {
const { puuid } = useParams<{ puuid: string }>();
const [analysis, setAnalysis] = useState<PlayerAnalysisDto | null>(null);
const [championCatalog, setChampionCatalog] =
useState<ChampionCatalog | null>(null);
const [mentorMatches, setMentorMatches] =
useState<MentorMatchesDto | null>(null);
const [similarPlayers, setSimilarPlayers] =
useState<SimilarPlayersDto | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [mentorErrorMessage, setMentorErrorMessage] = useState<string | null>(
null,
);
const [similarPlayersErrorMessage, setSimilarPlayersErrorMessage] =
useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const missingPuuidMessage = puuid ? null : '플레이어 식별자가 없습니다.';
@@ -73,12 +73,12 @@ export function DashboardPage() {
setIsLoading(true);
setAnalysis(null);
setErrorMessage(null);
setMentorErrorMessage(null);
setMentorMatches(null);
setSimilarPlayersErrorMessage(null);
setSimilarPlayers(null);
const mentorMatchesResultPromise = getMentorMatches(
const similarPlayersResultPromise = getSimilarPlayers(
currentPuuid,
MENTOR_MATCH_LIMIT,
SIMILAR_PLAYER_LIMIT,
).then(
(value) => ({ status: 'fulfilled', value }) as const,
(reason: unknown) => ({ status: 'rejected', reason }) as const,
@@ -105,17 +105,17 @@ export function DashboardPage() {
setIsLoading(false);
}
const mentorMatchesResult = await mentorMatchesResultPromise;
const similarPlayersResult = await similarPlayersResultPromise;
if (!isActive) {
return;
}
if (mentorMatchesResult.status === 'fulfilled') {
setMentorMatches(mentorMatchesResult.value);
if (similarPlayersResult.status === 'fulfilled') {
setSimilarPlayers(similarPlayersResult.value);
} else {
setMentorErrorMessage(
getReadableErrorMessage(mentorMatchesResult.reason),
setSimilarPlayersErrorMessage(
getReadableErrorMessage(similarPlayersResult.reason),
);
}
}
@@ -289,10 +289,10 @@ export function DashboardPage() {
)}
</section>
<MentorMatchSection
<SimilarPlayerSection
catalog={championCatalog}
errorMessage={mentorErrorMessage}
mentorMatches={mentorMatches}
errorMessage={similarPlayersErrorMessage}
similarPlayers={similarPlayers}
/>
</article>
);
@@ -380,87 +380,104 @@ function ChampionPoolRow({
);
}
function MentorMatchSection({
function SimilarPlayerSection({
catalog,
errorMessage,
mentorMatches,
similarPlayers,
}: {
catalog: ChampionCatalog | null;
errorMessage: string | null;
mentorMatches: MentorMatchesDto | null;
similarPlayers: SimilarPlayersDto | null;
}) {
const matches = mentorMatches?.matches ?? [];
const matches = similarPlayers?.matches ?? [];
return (
<section className="mentor-section" aria-labelledby="mentor-title">
<section className="similar-section" aria-labelledby="similar-title">
<div className="section-heading">
<div>
<h2 id="mentor-title">유사 상위 티어 비교</h2>
<h2 id="similar-title">나와 비슷한 플레이어</h2>
<p className="section-copy">
당신과 비슷한 상위 티어 그룹은 이런 경향을 보입니다.
플레이스타일 벡터가 가장 가까운 유저들입니다. 티어가 다르다면 어떤
지표에서 차이가 나는지 확인해보세요.
</p>
</div>
<span className="status-pill">
{mentorMatches ? `${matches.length} matches` : 'mentor match'}
{similarPlayers ? `${matches.length} players` : 'similar players'}
</span>
</div>
{errorMessage ? (
<p className="message message-warning mentor-message" role="status">
멘토 비교를 불러오지 못했습니다. {errorMessage}
<p className="message message-warning similar-message" role="status">
비슷한 플레이어 목록을 불러오지 못했습니다. {errorMessage}
</p>
) : null}
{!errorMessage && mentorMatches && matches.length === 0 ? (
{!errorMessage && similarPlayers && matches.length === 0 ? (
<p className="empty-copy">
조건에 맞는 상위 티어 seed 프로필이 아직 없습니다.
비교 가능한 프로필이 아직 충분히 수집되지 않았습니다.
</p>
) : null}
{!errorMessage && !mentorMatches ? (
<p className="empty-copy">멘토 비교 결과를 준비 중입니다.</p>
{!errorMessage && !similarPlayers ? (
<p className="empty-copy">비슷한 플레이어를 찾는 중입니다.</p>
) : null}
{matches.length > 0 ? (
<div
aria-label="유사 상위 티어 비교 테이블"
className="mentor-table-wrap"
aria-label="나와 비슷한 플레이어 테이블"
className="similar-table-wrap"
role="region"
tabIndex={0}
>
<table className="mentor-table">
<table className="similar-table">
<thead>
<tr>
<th scope="col">플레이어</th>
<th scope="col">점수</th>
<th scope="col">유사도</th>
<th scope="col">주요 챔피언</th>
<th scope="col">비교 지표</th>
</tr>
</thead>
<tbody>
{matches.map((match) => (
<tr key={match.mentorDisplayId}>
<tr key={match.displayId}>
<td>
<div className="mentor-player">
<strong>{formatMentorName(match)}</strong>
<div className="similar-player">
<strong>{formatSimilarPlayerName(match)}</strong>
<span>
{formatMentorTier(match)} · {ROLE_LABELS[match.mainRole]} ·{' '}
{formatSimilarPlayerTier(match)} ·{' '}
{ROLE_LABELS[match.mainRole]} ·{' '}
{match.sampleGameCount}게임
</span>
{formatTierComparison(match.tierComparison) ? (
<span className="similar-tier-badge">
{formatTierComparison(match.tierComparison)}
</span>
) : null}
</div>
</td>
<td>
<div className="mentor-score">
<strong>{formatPercent(match.finalScore)}</strong>
<span>스타일 {formatPercent(match.similarityScore)}</span>
<div className="similar-score">
<strong>{formatPercent(match.similarityScore)}</strong>
<span>종합 {formatPercent(match.finalScore)}</span>
</div>
</td>
<td>
<MentorChampionList catalog={catalog} match={match} />
<SimilarPlayerChampionList catalog={catalog} match={match} />
</td>
<td>
<div className="mentor-metric-groups">
<GapMetricChips values={match.gapMetrics} />
<div className="similar-metric-groups">
<LeadMetricChips
accent
emptyLabel="이 유저가 앞서는 지표 없음"
title="이 유저가 앞서는 지표"
values={match.strongerMetrics}
/>
<LeadMetricChips
emptyLabel={null}
title="내가 앞서는 지표"
values={match.weakerMetrics}
/>
<SimilarMetricChips values={match.similarMetrics} />
</div>
</td>
@@ -474,21 +491,21 @@ function MentorMatchSection({
);
}
function MentorChampionList({
function SimilarPlayerChampionList({
catalog,
match,
}: {
catalog: ChampionCatalog | null;
match: MentorMatchDto;
match: SimilarPlayerDto;
}) {
if (match.mainChampions.length === 0) {
return <span className="mentor-empty">챔피언 기록 없음</span>;
return <span className="similar-empty">챔피언 기록 없음</span>;
}
return (
<ul className="mentor-chip-list">
<ul className="similar-chip-list">
{match.mainChampions.map((entry) => (
<li className="mentor-chip" key={entry.championId}>
<li className="similar-chip" key={entry.championId}>
<strong>{formatChampionName(catalog, entry.championId)}</strong>
<span>{entry.games}게임</span>
</li>
@@ -497,19 +514,34 @@ function MentorChampionList({
);
}
function GapMetricChips({ values }: { values: GapMentorMetricDto[] }) {
function LeadMetricChips({
accent = false,
emptyLabel,
title,
values,
}: {
accent?: boolean;
emptyLabel: string | null;
title: string;
values: LeadMetricDto[];
}) {
if (values.length === 0) {
return <span className="mentor-empty">뚜렷한 우위 지표 없음</span>;
return emptyLabel ? (
<span className="similar-empty">{emptyLabel}</span>
) : null;
}
return (
<div className="mentor-metric-group">
<span>앞서는 지표</span>
<ul className="mentor-chip-list">
<div className="similar-metric-group">
<span>{title}</span>
<ul className="similar-chip-list">
{values.map((value) => (
<li className="mentor-chip mentor-chip-accent" key={value.metricId}>
<li
className={`similar-chip ${accent ? 'similar-chip-accent' : ''}`}
key={value.metricId}
>
<strong>{getMetricLabel(value.metricId)}</strong>
<span>+{formatPercent(value.mentorAdvantage)}</span>
<span>+{formatPercent(value.lead)}</span>
</li>
))}
</ul>
@@ -517,17 +549,17 @@ function GapMetricChips({ values }: { values: GapMentorMetricDto[] }) {
);
}
function SimilarMetricChips({ values }: { values: SimilarMentorMetricDto[] }) {
function SimilarMetricChips({ values }: { values: SimilarMetricDto[] }) {
if (values.length === 0) {
return null;
}
return (
<div className="mentor-metric-group">
<div className="similar-metric-group">
<span>비슷한 지표</span>
<ul className="mentor-chip-list">
<ul className="similar-chip-list">
{values.map((value) => (
<li className="mentor-chip mentor-chip-muted" key={value.metricId}>
<li className="similar-chip similar-chip-muted" key={value.metricId}>
<strong>{getMetricLabel(value.metricId)}</strong>
<span>차이 {formatPercent(value.absoluteGap)}</span>
</li>
@@ -537,21 +569,28 @@ function SimilarMetricChips({ values }: { values: SimilarMentorMetricDto[] }) {
);
}
function formatMentorName(match: MentorMatchDto): string {
function formatSimilarPlayerName(match: SimilarPlayerDto): string {
if (match.riotId) {
return `${match.riotId.gameName}#${match.riotId.tagLine}`;
}
return formatMentorDisplayId(match.mentorDisplayId);
return formatSimilarPlayerDisplayId(match.displayId);
}
function formatMentorDisplayId(mentorDisplayId: string): string {
const numericSuffix = mentorDisplayId.match(/^mentor-(\d+)$/)?.[1];
function formatSimilarPlayerDisplayId(displayId: string): string {
const numericSuffix = displayId.match(/^similar-(\d+)$/)?.[1];
return numericSuffix ? `상위 티어 멘토 #${numericSuffix}` : '상위 티어 멘토';
return numericSuffix ? `비슷한 플레이어 #${numericSuffix}` : '비슷한 플레이어';
}
function formatMentorTier(match: MentorMatchDto): string {
function formatTierComparison(tierComparison: TierComparison): string | null {
if (tierComparison === 'higher') return '나보다 높은 티어';
if (tierComparison === 'lower') return '나보다 낮은 티어';
if (tierComparison === 'same') return '같은 티어';
return null;
}
function formatSimilarPlayerTier(match: SimilarPlayerDto): string {
const tier = [match.tier, match.division].filter(Boolean).join(' ');
if (!tier) {
+25 -21
View File
@@ -319,7 +319,7 @@ interface MetricBaseline extends MongooseTimestamps {
```ts
type RecommendationType =
| "mentor-match" // MVP 3
| "similar-player" // MVP 3
| "champion-recommendation" // MVP 4
| "llm-feedback"; // MVP 5
@@ -675,8 +675,8 @@ DB 스키마가 이 단계를 미리 견디도록 상세화한 스펙이다. 구
지표를 전부 유사도 벡터에 넣으면 희귀 이벤트 기반의 노이즈 축이 코사인 유사도를 오염시킨다. 두 계층으로 나눈다:
- **vector 지표** (`includeInVector: true`): 게임마다 안정적으로 관측되는 핵심 스타일 축. 벡터·레이더 차트·멘토 매칭에 사용
- **insight 지표** (`includeInVector: false`): 희귀 이벤트 기반 비율. 강점/약점 분석, 멘토와의 gap 비교, LLM evidence에 사용. 벡터에는 미포함
- **vector 지표** (`includeInVector: true`): 게임마다 안정적으로 관측되는 핵심 스타일 축. 벡터·레이더 차트·유사 유저 탐색에 사용
- **insight 지표** (`includeInVector: false`): 희귀 이벤트 기반 비율. 강점/약점 분석, 유사 유저와의 gap 비교, LLM evidence에 사용. 벡터에는 미포함
**ratio 지표 저장 규칙**: 게임당 발생 횟수가 적은 비율 지표는 매치 단위 rate가 0/1로 튄다. 매치의 `features`에는 `{metricId}Numerator` / `{metricId}Denominator`로 **횟수만** 저장하고, rate는 profile builder가 `Σ분자/Σ분모`로 계산해 `profile`에 저장한다. registry의 `kind: 'scalar' | 'ratio'`가 이를 결정한다 (§5.1).
@@ -759,7 +759,9 @@ DB 스키마가 이 단계를 미리 견디도록 상세화한 스펙이다. 구
---
## 12. MVP 3 상세 — 고티어 pool · percentile 정규화 · 멘토 매칭
## 12. MVP 3 상세 — 고티어 pool · percentile 정규화 · 유사 유저 탐색
> **컨셉 (2026-07-03 재정의)**: 이 기능은 "멘토 매칭"이 아니라 **나와 플레이스타일이 비슷한 유저 찾기**다. 목적은 따라 할 상위 티어 유저를 지정해주는 것이 아니라, "스타일은 비슷한데 왜 저 유저는 점수(티어)가 더 높거나/낮은가"라는 인사이트를 주는 것. 따라서 후보를 티어로 거르지 않고 유사도 중심으로 랭킹하며, 티어 관계(tierComparison)와 지표 우위(양방향)를 함께 제공한다. seed pool(§12.1)은 필터 조건이 아니라 **비교 후보군의 주 공급원**이다.
### 12.1 고티어 seed pool 수집
@@ -800,35 +802,37 @@ DB 스키마가 이 단계를 미리 견디도록 상세화한 스펙이다. 구
filter로 쓰는 필드(tier, isSeed 등)가 `player_profile`에 **비정규화되어 있어야** `$vectorSearch` 단계에서 join 없이 거를 수 있다 — §4.4 스키마가 이를 전제한다.
### 12.4 멘토 매칭 파이프라인
### 12.4 유사 유저 탐색 파이프라인
```text
1. 내 player_profile 조회 (없으면 404)
2. $vectorSearch:
queryVector = 내 vector, numCandidates = 200, limit = 50
filter: { mainRole: eq 내 mainRole, queueId: eq 420,
tier: in [MASTER, GRANDMASTER, CHALLENGER], isSeed: eq true,
sampleGameCount: gte 20, featureSchemaVersion: eq 현재 버전 }
※ tier/isSeed 필터 없음 — "비슷한 유저"가 목적이므로 어느 티어든 후보.
(인덱스의 tier/isSeed filter 필드는 유지 — 추후 옵션 필터용)
3. 앱 레벨 re-rank (Top 50 → Top K):
final = 0.60 * styleSim # $vectorSearch score (cosine)
+ 0.20 * championPoolSim # 양쪽 championPool 상위 5개 Jaccard
final = 0.70 * styleSim # $vectorSearch score (cosine) — 유사도가 랭킹을 지배
+ 0.18 * championPoolSim # 양쪽 championPool 상위 5개 Jaccard
+ 0.12 * recencyScore # lastMatchAt 지수 감쇠 (half-life 14일)
+ 0.08 * tierScore # CHALLENGER 1.0 / GM 0.8 / MASTER 0.6
- lowSamplePenalty # sampleGameCount < 30이면 0.1
(mainRole은 filter로 보장되므로 별도 가중치 없음)
4. 각 멘토에 대해 지표 비교 계산:
- 비슷한 지표 Top 3: |내 profile[m] - 멘토 profile[m]| 최소
- 멘토가 앞서는 지표 Top 3: direction 반영 gap 최대 (lowerIsBetter는 반전)
5. recommendation 컬렉션에 캐시 (type: 'mentor-match', profileUpdatedAt 기록)
(tierScore 없음 — 티어는 랭킹 요소가 아니라 인사이트. mainRole은 filter로 보장)
4. 각 유사 유저에 대해 비교 계산:
- tierComparison: 내 tier 대비 higher | same | lower | unknown
- 비슷한 지표 Top 3: |내 profile[m] - 상대 profile[m]| 최소
- 상대가 앞서는 지표 Top 3 (strongerMetrics): direction 반영 gap 최대 (lowerIsBetter는 반전)
- 내가 앞서는 지표 Top 3 (weakerMetrics): 위와 대칭 — 상대가 나보다 낮은 티어일 때의 인사이트
5. recommendation 컬렉션에 캐시 (type: 'similar-player', profileUpdatedAt 기록)
→ 내 프로필이 갱신되면 stale로 보고 재계산
```
### 12.5 API / UI
- `GET /api/players/:puuid/mentor-matches?limit=10` — 캐시 있으면 캐시, stale이면 재계산
- 응답 항목: similarityScore, finalScore, Riot ID(표시용), tier, mainRole, mainChampions(top 3), sampleGameCount, similarMetrics[3], gapMetrics[3]
- 대시보드에 멘토 비교 테이블 추가. 화법: "따라 하라"가 아니라 "당신과 비슷한 상위 티어 그룹은 이런 경향" 유지 (§1.3, §14)
- seed 유저의 Riot ID 표시는 공개 데이터이지만, 표시 형식은 전적 사이트 관례 수준으로 유지
- `GET /api/players/:puuid/similar-players?limit=10` — 캐시 있으면 캐시, stale이면 재계산
- 응답 항목: similarityScore, finalScore, Riot ID(표시용), tier, tierComparison, mainRole, mainChampions(top 3), sampleGameCount, similarMetrics[3], strongerMetrics[3], weakerMetrics[3]
- 대시보드에 "나와 비슷한 플레이어" 테이블 추가. 화법: "따라 하라"가 아니라 "나와 비슷한 이 유저는 이런 지표에서 차이가 난다" 유지 (§1.3, §14). 상대가 높은 티어면 strongerMetrics가, 낮은 티어면 weakerMetrics가 인사이트의 중심
- 유저 Riot ID 표시는 공개 데이터이지만, 표시 형식은 전적 사이트 관례 수준으로 유지
---
@@ -837,13 +841,13 @@ filter로 쓰는 필드(tier, isSeed 등)가 `player_profile`에 **비정규화
### MVP 4: 챔피언 추천
- 챔피언 스타일 벡터: 초기엔 수동 taxonomy(주요 챔피언 ~60개), 이후 seed 유저 match data 기반 자동화. **스키마는 `champion_style_profile`(§4.8)로 이미 준비됨**
- Fit(현 스타일 유사) / Growth(약점 보완) / Stretch(폭 확장) 3종 추천 + 근거(유사도, 유사 고티어 유저 pool 등장 빈도) 표시. 결과는 `recommendation`(type: 'champion-recommendation')에 캐시
- Fit(현 스타일 유사) / Growth(약점 보완) / Stretch(폭 확장) 3종 추천 + 근거(유사도, 유사 유저 pool 등장 빈도) 표시. 결과는 `recommendation`(type: 'champion-recommendation')에 캐시
- Data Dragon 연동 (챔피언 이름/이미지, 패치별 static data)
### MVP 5: LLM 피드백
- `FeedbackGenerator` 인터페이스로 provider 추상화 (provider는 이 시점에 결정)
- 입력: 백엔드가 만든 evidence JSON만 (user profile 지표, 멘토 그룹과의 gap Top-N, `derived`의 데스 위치 요약). raw match JSON 입력 금지
- 입력: 백엔드가 만든 evidence JSON만 (user profile 지표, 유사 유저와의 gap Top-N, `derived`의 데스 위치 요약). raw match JSON 입력 금지
- 출력: strict JSON schema 검증. 모든 피드백 항목은 metricId 참조 필수, 검증 실패/LLM 장애 시 rule-based fallback 문장 사용. 결과는 `recommendation`(type: 'llm-feedback')에 캐시
- 화법 규칙: 비난 금지, "다음 5게임에서 실험할 행동" 형태, 실시간 지시·MMR 추정 표현 금지
@@ -853,5 +857,5 @@ filter로 쓰는 필드(tier, isSeed 등)가 `player_profile`에 **비정규화
- **데이터 품질이 AI보다 중요하다.** feature extraction이 틀리면 앱 전체 신뢰가 무너진다. 파이프라인 안정화가 항상 우선.
- **비교군 설계가 핵심이다.** 전체 평균이 아니라 같은 포지션·유사 챔피언·비슷한 패치·충분한 sample size 기준으로 비교한다.
- **결과는 항상 근거와 함께.** "운영이 약합니다"(X) → "10분 골드 리드 게임에서 첫 전령 관여율이 유사 고티어 그룹보다 낮습니다"(O).
- **결과는 항상 근거와 함께.** "운영이 약합니다"(X) → "10분 골드 리드 게임에서 첫 전령 관여율이 유사 유저 그룹보다 낮습니다"(O).
- **추천은 단정하지 않는다.** "이 챔피언을 해야 티어가 오릅니다"(X) → "현재 스타일과 잘 맞을 가능성이 높은 후보입니다. 다음 10게임에서 비교해보세요"(O).
+21 -13
View File
@@ -97,43 +97,51 @@ export interface PlayerAnalysisDto {
updatedAt: string;
}
export interface MentorRiotIdDto {
export interface SimilarPlayerRiotIdDto {
gameName: string;
tagLine: string;
}
export interface SimilarMentorMetricDto {
/** 상대 유저의 티어가 내 티어 대비 어느 쪽인지. 티어 정보가 없으면 unknown. */
export type TierComparison = 'higher' | 'same' | 'lower' | 'unknown';
export interface SimilarMetricDto {
metricId: MetricId;
currentValue: number;
mentorValue: number;
otherValue: number;
absoluteGap: number;
}
export interface GapMentorMetricDto {
export interface LeadMetricDto {
metricId: MetricId;
currentValue: number;
mentorValue: number;
mentorAdvantage: number;
otherValue: number;
/** direction 반영 우위 폭. 항상 양수. */
lead: number;
}
export interface MentorMatchDto {
mentorDisplayId: string;
riotId: MentorRiotIdDto | null;
export interface SimilarPlayerDto {
displayId: string;
riotId: SimilarPlayerRiotIdDto | null;
similarityScore: number;
finalScore: number;
tier?: string;
division?: string;
leaguePoints?: number;
tierComparison: TierComparison;
mainRole: Role;
mainChampions: ChampionPoolEntryDto[];
sampleGameCount: number;
similarMetrics: SimilarMentorMetricDto[];
gapMetrics: GapMentorMetricDto[];
similarMetrics: SimilarMetricDto[];
/** 이 유저가 나보다 앞서는 지표 Top 3 */
strongerMetrics: LeadMetricDto[];
/** 내가 이 유저보다 앞서는 지표 Top 3 */
weakerMetrics: LeadMetricDto[];
}
export interface MentorMatchesDto {
export interface SimilarPlayersDto {
puuid: string;
queueId: number;
profileUpdatedAt: string;
matches: MentorMatchDto[];
matches: SimilarPlayerDto[];
}