Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { scoresRouter } from "./routes/scores";
import { healthRouter } from "./routes/health";
import { aiRouter } from "./routes/ai";
import { guideRouter } from "./routes/guide";
import { gameplayRouter } from "./routes/gameplay";
import { getAiReadiness } from "./lib/ai-config";
import { aiRateLimit } from "./lib/rate-limit";
import { initStorage, shutdownStorage, getStorageBackend } from "./lib/storage";
Expand Down Expand Up @@ -35,6 +36,7 @@ async function main() {
app.use("/api/command", aiRateLimit, commandRouter);
app.use("/api/scenario", aiRateLimit, scenarioRouter);
app.use("/api/scores", scoresRouter);
app.use("/api/gameplay", gameplayRouter);
app.use("/api/ai", aiRouter);
app.use("/api/guide", guideRouter);
app.use("/", healthRouter);
Expand Down
80 changes: 80 additions & 0 deletions backend/src/integration/mssql-stores.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,12 +237,16 @@ describe.skipIf(SKIP)("MssqlMetricsStore (real SQL)", () => {
nickname: nick,
difficulty: "easy",
scenarioTitle: "Master Down",
lifecycleState: "completed",
commandCount: 2,
commandsExecuted: ["oc get nodes", "oc get pods -A"],
scoringEvents: [{ type: "safety", points: 5 }],
chatMessageCount: 8,
aiPromptTokens: 3000,
aiCompletionTokens: 1500,
durationMs: 120_000,
scoreTotal: 88,
grade: "B",
completed: true,
metadata: { version: "test" },
});
Expand All @@ -253,10 +257,14 @@ describe.skipIf(SKIP)("MssqlMetricsStore (real SQL)", () => {
const record = history[0];
expect(record.nickname).toBe(nick);
expect(record.difficulty).toBe("easy");
expect(record.lifecycleState).toBe("completed");
expect(record.commandCount).toBe(2);
expect(record.commandsExecuted).toEqual(["oc get nodes", "oc get pods -A"]);
expect(record.scoringEvents).toEqual([{ type: "safety", points: 5 }]);
expect(record.chatMessageCount).toBe(8);
expect(record.durationMs).toBe(120_000);
expect(record.scoreTotal).toBe(88);
expect(record.grade).toBe("B");
expect(record.completed).toBe(true);
expect(record.metadata).toEqual({ version: "test" });
});
Expand All @@ -272,6 +280,78 @@ describe.skipIf(SKIP)("MssqlMetricsStore (real SQL)", () => {
const history = await store.getPlayerHistory("");
expect(history.length).toBeGreaterThanOrEqual(0);
});

it("aggregates latest-session analytics by lifecycle state", async () => {
const { MssqlMetricsStore } = await import(
"../lib/storage/mssql-metrics-store"
);
const { MssqlSessionStore } = await import(
"../lib/storage/mssql-session-store"
);
const store = new MssqlMetricsStore(pool);
const sessionStore = new MssqlSessionStore(pool);

const completedNick = trackNickname(shortId("ga"));
const abandonedNick = trackNickname(shortId("gb"));
const completedSession = await sessionStore.create("easy", "The Sleeping Cluster");
const abandonedSession = await sessionStore.create("hard", "Etcd Quorum Loss");
createdSessionTokens.push(completedSession, abandonedSession);

await store.recordGameplay({
sessionToken: completedSession,
nickname: completedNick,
difficulty: "easy",
scenarioTitle: "The Sleeping Cluster",
lifecycleState: "started",
});
await store.recordGameplay({
sessionToken: completedSession,
nickname: completedNick,
difficulty: "easy",
scenarioTitle: "The Sleeping Cluster",
lifecycleState: "completed",
commandCount: 4,
chatMessageCount: 6,
durationMs: 80_000,
scoreTotal: 85,
grade: "B",
completed: true,
});

await store.recordGameplay({
sessionToken: abandonedSession,
nickname: abandonedNick,
difficulty: "hard",
scenarioTitle: "Etcd Quorum Loss",
lifecycleState: "started",
});
await store.recordGameplay({
sessionToken: abandonedSession,
nickname: abandonedNick,
difficulty: "hard",
scenarioTitle: "Etcd Quorum Loss",
lifecycleState: "abandoned",
commandCount: 2,
chatMessageCount: 3,
durationMs: 45_000,
completed: false,
});

const analytics = await store.getGameplayAnalytics();
expect(analytics.summary.totalSessions).toBeGreaterThanOrEqual(2);
expect(analytics.summary.completedSessions).toBeGreaterThanOrEqual(1);
expect(analytics.summary.abandonedSessions).toBeGreaterThanOrEqual(1);

const easy = analytics.byDifficulty.find((bucket) => bucket.difficulty === "easy");
expect(easy).toBeDefined();
expect(easy!.completedSessions).toBeGreaterThanOrEqual(1);

const recent = analytics.recentSessions.find(
(session) => session.sessionToken?.toLowerCase() === completedSession.toLowerCase(),
);
expect(recent?.lifecycleState).toBe("completed");
expect(recent?.scoreTotal).toBe(85);
});
});

describe.skipIf(SKIP)("Migration idempotency (real SQL)", () => {
Expand Down
163 changes: 158 additions & 5 deletions backend/src/lib/storage/json-metrics-store.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,168 @@
import type { GameplayAnalytics, GameplayDifficultyAnalytics, GameplayScenarioAnalytics, GameplayLifecycleState } from "../../../../shared/types/gameplay";
import type { Difficulty } from "../../../../shared/types/game";
import type { IMetricsStore, GameplayRecord } from "./types";

const records: GameplayRecord[] = [];
Comment on lines 4 to +5
Copy link

Copilot AI Apr 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JSON metrics backend keeps all GameplayRecords in a process-global records array with no cap/TTL. In long-running json-backend deployments (or dev sessions), this can grow without bound and increase memory usage over time. Consider adding a retention limit (e.g., keep last N records) and/or TTL-based cleanup.

Suggested change
const records: GameplayRecord[] = [];
const MAX_RECORDS = 10000;
function trimRecords(items: GameplayRecord[]): void {
if (items.length <= MAX_RECORDS) return;
items.splice(0, items.length - MAX_RECORDS);
}
const records: GameplayRecord[] = [];
const originalPush = records.push.bind(records);
records.push = (...items: GameplayRecord[]): number => {
const length = originalPush(...items);
trimRecords(records);
return length > MAX_RECORDS ? MAX_RECORDS : length;
};

Copilot uses AI. Check for mistakes.

function sessionKey(record: GameplayRecord): string {
return record.sessionToken ?? record.id ?? crypto.randomUUID();
}

function roundAverage(values: number[]): number | null {
if (values.length === 0) return null;
const total = values.reduce((sum, value) => sum + value, 0);
return Math.round((total / values.length) * 100) / 100;
}

function toRate(part: number, total: number): number {
if (total === 0) return 0;
return Math.round((part / total) * 10000) / 100;
}

function latestSessionRecords(): GameplayRecord[] {
const latest = new Map<string, GameplayRecord>();
const sorted = [...records].sort((a, b) => {
const aTime = a.createdAt?.getTime() ?? 0;
const bTime = b.createdAt?.getTime() ?? 0;
return aTime - bTime;
});

for (const record of sorted) {
latest.set(sessionKey(record), record);
}

return [...latest.values()];
}

function countStates(items: GameplayRecord[]) {
const states: Record<GameplayLifecycleState, number> = {
started: 0,
completed: 0,
abandoned: 0,
};

for (const item of items) {
const state = item.lifecycleState ?? "completed";
states[state] += 1;
}

return states;
}

export class JsonMetricsStore implements IMetricsStore {
async recordGameplay(data: GameplayRecord): Promise<void> {
const record: GameplayRecord = {
...data,
id: data.id ?? crypto.randomUUID(),
lifecycleState: data.lifecycleState ?? "completed",
commandCount: data.commandCount ?? data.commandsExecuted?.length ?? 0,
commandsExecuted: data.commandsExecuted ?? [],
scoringEvents: data.scoringEvents ?? [],
chatMessageCount: data.chatMessageCount ?? 0,
aiPromptTokens: data.aiPromptTokens ?? 0,
aiCompletionTokens: data.aiCompletionTokens ?? 0,
completed: data.completed ?? data.lifecycleState === "completed",
metadata: data.metadata ?? {},
createdAt: data.createdAt ?? new Date(),
};

records.push(record);

console.log(
`[metrics] gameplay recorded (in-memory only): session=${data.sessionToken ?? "unknown"} ` +
`nickname=${data.nickname ?? "unknown"} difficulty=${data.difficulty ?? "unknown"}`
`[metrics] gameplay recorded (in-memory only): session=${record.sessionToken ?? "unknown"} ` +
`state=${record.lifecycleState} difficulty=${record.difficulty ?? "unknown"}`
);
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getPlayerHistory(_nickname: string): Promise<GameplayRecord[]> {
return [];
async getPlayerHistory(nickname: string): Promise<GameplayRecord[]> {
return records
.filter((record) => record.nickname === nickname)
.sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0));
}

async getGameplayAnalytics(): Promise<GameplayAnalytics> {
const latest = latestSessionRecords();
const completed = latest.filter((record) => record.lifecycleState === "completed");
const summaryStates = countStates(latest);

const byDifficulty = (["easy", "medium", "hard"] as Difficulty[])
.map((difficulty): GameplayDifficultyAnalytics => {
const scoped = latest.filter((record) => record.difficulty === difficulty);
const scopedStates = countStates(scoped);
return {
difficulty,
totalSessions: scoped.length,
completedSessions: scopedStates.completed,
abandonedSessions: scopedStates.abandoned,
inProgressSessions: scopedStates.started,
completionRate: toRate(scopedStates.completed, scoped.length),
};
})
.filter((bucket) => bucket.totalSessions > 0);

const scenarioMap = new Map<string, GameplayRecord[]>();
for (const record of latest) {
const key = `${record.difficulty ?? "unknown"}::${record.scenarioTitle ?? "Unknown Scenario"}`;
const existing = scenarioMap.get(key) ?? [];
existing.push(record);
scenarioMap.set(key, existing);
}

const byScenario = [...scenarioMap.entries()]
.map(([key, scoped]): GameplayScenarioAnalytics => {
const [difficulty, scenarioTitle] = key.split("::");
const scopedStates = countStates(scoped);
return {
difficulty: difficulty === "unknown" ? undefined : (difficulty as Difficulty),
scenarioTitle,
totalSessions: scoped.length,
completedSessions: scopedStates.completed,
abandonedSessions: scopedStates.abandoned,
inProgressSessions: scopedStates.started,
completionRate: toRate(scopedStates.completed, scoped.length),
};
})
.sort((a, b) => b.totalSessions - a.totalSessions || a.scenarioTitle.localeCompare(b.scenarioTitle));

return {
summary: {
totalSessions: latest.length,
completedSessions: summaryStates.completed,
abandonedSessions: summaryStates.abandoned,
inProgressSessions: summaryStates.started,
completionRate: toRate(summaryStates.completed, latest.length),
abandonmentRate: toRate(summaryStates.abandoned, latest.length),
avgCompletionDurationMs: roundAverage(
completed.map((record) => record.durationMs).filter((value): value is number => typeof value === "number"),
),
avgCompletionCommandCount: roundAverage(
completed.map((record) => record.commandCount).filter((value): value is number => typeof value === "number"),
),
avgCompletionChatMessageCount: roundAverage(
completed.map((record) => record.chatMessageCount).filter((value): value is number => typeof value === "number"),
),
avgCompletionScoreTotal: roundAverage(
completed.map((record) => record.scoreTotal).filter((value): value is number => typeof value === "number"),
),
},
byDifficulty,
byScenario,
recentSessions: latest
.sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0))
.slice(0, 20)
.map((record) => ({
sessionToken: record.sessionToken,
lifecycleState: record.lifecycleState ?? "completed",
nickname: record.nickname,
difficulty: record.difficulty,
scenarioTitle: record.scenarioTitle,
commandCount: record.commandCount,
chatMessageCount: record.chatMessageCount,
durationMs: record.durationMs,
scoreTotal: record.scoreTotal,
grade: record.grade,
createdAt: (record.createdAt ?? new Date(0)).toISOString(),
})),
};
}
}
5 changes: 5 additions & 0 deletions backend/src/lib/storage/json-session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ export class JsonSessionStore implements ISessionStore {
return token;
}

async get(token: string): Promise<GameSession | null> {
cleanup();
return sessions.get(token) ?? null;
}

async validateAndConsume(token: string): Promise<GameSession | null> {
cleanup();
const session = sessions.get(token);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
IF COL_LENGTH('gameplay_metrics', 'lifecycle_state') IS NULL
BEGIN
ALTER TABLE gameplay_metrics
ADD lifecycle_state VARCHAR(16) NOT NULL
CONSTRAINT df_gameplay_metrics_lifecycle_state DEFAULT 'completed';
END;

IF COL_LENGTH('gameplay_metrics', 'command_count') IS NULL
BEGIN
ALTER TABLE gameplay_metrics
ADD command_count INT NOT NULL
CONSTRAINT df_gameplay_metrics_command_count DEFAULT 0;
END;

IF COL_LENGTH('gameplay_metrics', 'score_total') IS NULL
BEGIN
ALTER TABLE gameplay_metrics
ADD score_total INT NULL;
END;

IF COL_LENGTH('gameplay_metrics', 'grade') IS NULL
BEGIN
ALTER TABLE gameplay_metrics
ADD grade VARCHAR(5) NULL;
END;

IF NOT EXISTS (
SELECT *
FROM sys.check_constraints
WHERE name = 'ck_gameplay_metrics_lifecycle_state'
)
BEGIN
EXEC('
ALTER TABLE gameplay_metrics
ADD CONSTRAINT ck_gameplay_metrics_lifecycle_state
CHECK (lifecycle_state IN (''started'', ''completed'', ''abandoned''))
');
END;

IF NOT EXISTS (
SELECT *
FROM sys.indexes
WHERE name = 'idx_metrics_session_created'
AND object_id = OBJECT_ID('gameplay_metrics')
)
BEGIN
EXEC('
CREATE INDEX idx_metrics_session_created
ON gameplay_metrics (session_token, created_at)
');
END;

IF NOT EXISTS (
SELECT *
FROM sys.indexes
WHERE name = 'idx_metrics_lifecycle_state'
AND object_id = OBJECT_ID('gameplay_metrics')
)
BEGIN
EXEC('
CREATE INDEX idx_metrics_lifecycle_state
ON gameplay_metrics (lifecycle_state, created_at)
');
END;
Loading
Loading