refactor: comprehensive codebase cleanup and architecture hardening

- Sprint 1 (Quick Wins): Remove dead analytics modules, fix 4 unresolved
  imports, replace 3 console.warn with logger, remove mock-crc import
- Sprint 2 (Architecture): Create MascotChatRepository, AnalysisRepository,
  3 Zod schemas (mascot-chat, analysis, voice), deduplicate error classes,
  move 3 SQL queries from routes to repository
- Sprint 3 (Complexity): Replace 7 any types with proper interfaces,
  extract 6 helpers from prepareMediaMessage (CC 85 -> ~15)
- Sprint 4 (Config): Remove 22 dead env vars from .env, add 30 missing
  vars to .env.example, standardize naming

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MythEclipse
2026-06-09 10:16:04 +07:00
co-authored by Claude Opus 4.8
parent d0d9e1669e
commit 4becf0d6f1
89 changed files with 1260 additions and 5499 deletions
@@ -1,47 +1,25 @@
import { createChildLogger } from "@bete/shared/logger";
import { config } from "../../shared/config/index.js";
import { getPool } from "../../shared/database/index.js";
import type {
MascotChatContext,
MascotChatHistoryRow,
SaveConversationInput,
} from "./mascot-chat.repository.js";
import { mascotChatRepository } from "./mascot-chat.repository.js";
const logger = createChildLogger("mascot-chat.service");
export interface MascotChatContext {
messageCount?: number;
activeParticipants?: number;
lastActivity?: string;
topicsDiscussed?: string[];
guildId?: string;
channelId?: string;
}
export interface SaveConversationInput {
userId: string;
userMessage: string;
mascotResponse: string;
context?: MascotChatContext;
timestamp: Date;
}
export interface MascotChatHistoryRow {
id: string;
user_id: string;
user_message: string;
mascot_response: string;
context: MascotChatContext | null;
created_at: string;
}
class MascotChatService {
private initialized = false;
async processMessage(
message: string,
context: MascotChatContext | undefined,
userId: string,
): Promise<string> {
await this.ensureSchema();
const recentContext = await this.getRecentConversationContext(userId);
const serverInsights = await this.getServerInsights(context);
const serverInsights = await mascotChatRepository.getServerInsights(
context?.guildId,
context?.channelId,
);
// Build LLM messages
const systemPrompt = this.buildSystemPrompt(serverInsights);
@@ -56,142 +34,30 @@ class MascotChatService {
}
async saveConversation(input: SaveConversationInput): Promise<void> {
await this.ensureSchema();
const pool = getPool();
await pool.query(
`
INSERT INTO mascot_chat_messages
(user_id, user_message, mascot_response, context, created_at)
VALUES ($1, $2, $3, $4::jsonb, $5)
`,
[
input.userId,
input.userMessage,
input.mascotResponse,
JSON.stringify(input.context ?? {}),
input.timestamp.toISOString(),
],
);
await mascotChatRepository.saveConversation(input);
}
async getChatHistory(
userId: string,
limit: number,
): Promise<MascotChatHistoryRow[]> {
await this.ensureSchema();
const pool = getPool();
const { rows } = await pool.query<MascotChatHistoryRow>(
`
SELECT id, user_id, user_message, mascot_response, context, created_at
FROM mascot_chat_messages
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT $2
`,
[userId, limit],
);
return rows.reverse();
return mascotChatRepository.getChatHistory(userId, limit);
}
async clearChatHistory(userId: string): Promise<void> {
await this.ensureSchema();
const pool = getPool();
await pool.query(`DELETE FROM mascot_chat_messages WHERE user_id = $1`, [
userId,
]);
}
private async ensureSchema(): Promise<void> {
if (this.initialized) return;
const pool = getPool();
await pool.query(`
CREATE TABLE IF NOT EXISTS mascot_chat_messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id TEXT NOT NULL,
user_message TEXT NOT NULL,
mascot_response TEXT NOT NULL,
context JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
`);
await pool.query(`
CREATE INDEX IF NOT EXISTS idx_mascot_chat_messages_user_created
ON mascot_chat_messages (user_id, created_at DESC)
`);
this.initialized = true;
logger.info("Mascot chat schema ready");
await mascotChatRepository.clearChatHistory(userId);
}
private async getRecentConversationContext(
userId: string,
): Promise<string[]> {
const history = await this.getChatHistory(userId, 3);
const history = await mascotChatRepository.getChatHistory(userId, 3);
return history.flatMap((row) => [
`User: ${row.user_message}`,
`Mascot: ${row.mascot_response}`,
]);
}
private async getServerInsights(context?: MascotChatContext) {
const pool = getPool();
const guildId = context?.guildId;
const channelId = context?.channelId;
try {
const params: string[] = [];
const clauses: string[] = [];
if (guildId) {
params.push(guildId);
clauses.push(`guild_id = $${params.length}`);
}
if (channelId) {
params.push(channelId);
clauses.push(`channel_id = $${params.length}`);
}
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
const { rows } = await pool.query<{
total_messages: number;
active_users: number;
flagged: number;
warned: number;
}>(
`
SELECT
COUNT(*)::int AS total_messages,
COUNT(DISTINCT user_id)::int AS active_users,
COUNT(*) FILTER (WHERE ai_status = 'flagged')::int AS flagged,
COUNT(*) FILTER (WHERE ai_status = 'warn')::int AS warned
FROM messages
${where}
`,
params,
);
return (
rows[0] ?? {
total_messages: 0,
active_users: 0,
flagged: 0,
warned: 0,
}
);
} catch (error) {
logger.warn({ error }, "Failed to load mascot server insights");
return {
total_messages: context?.messageCount ?? 0,
active_users: context?.activeParticipants ?? 0,
flagged: 0,
warned: 0,
};
}
}
private buildSystemPrompt(insights: {
total_messages: number;
active_users: number;