Commit Graph
89 Commits
Author SHA1 Message Date
MythEclipseandClaude Opus 4.8 3a7b005d95 fix: resolve architecture disconnects and codebase weaknesses
- Add TEXT_CHANNEL_ID and TEXT_GUILD_ID to config schema (fix silent channel monitoring)
- Remove dead files: message-capture/broadcaster.ts, voice-recording/index.ts
- Fix WebSocket voice_command payload to forward from frontend
- Implement moderation:action handler in commandHandler
- Fix useMascotChat to use canonical request() wrapper
- Fix useAudioPlayback userId hash collision (use string not parseInt)
- Add catch blocks to useMediaControl.skip/stop
- Add typed broadcast functions (messageAnalyzed, voicePcmData, voiceActiveUser)
- Apply Biome formatting and lint fixes

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 16:36:23 +07:00
MythEclipseandClaude Opus 4.8 30c9e86edc test: add placeholder test files for vitest
Prevents vitest from exiting with code 1 when no test files exist.
Adds minimal test files to backend and discord-gateway services.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 15:40:40 +07:00
MythEclipseandClaude Opus 4.8 7d6612bb2d refactor: resolve architecture disconnects and codebase weaknesses
- Consolidate eventTypes.ts as single source of truth for Redis channels:
  - Remove duplicate DiscordGatewayEvent interface from eventBroadcaster.ts
  - Replace all hardcoded channel strings with EventChannels constants
  - eventTypes.ts is no longer an orphan file

- Remove dangerous moderation action feature (selfbot safety):
  - Remove /messages/:id/moderate endpoint from backend
  - Remove moderation:action handler from commandHandler.ts
  - Remove publishFireAndForgetCommand (wrong envelope format)
  - Verified no remaining references to moderation:action in code

- Remove unused getCommandPublisher import from redis-bridge.ts

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:22:09 +07:00
MythEclipseandClaude Opus 4.8 3614d32701 fix: resolve architecture disconnects and codebase weaknesses
- Standardize MessageRecord types — single source of truth from @bete/shared
- Clean up config: remove unused GUILD_ID/TEXT_GUILD_ID/TEXT_CHANNEL_ID, fix WEBSERVER_PORT default (3001), remove default admin password
- Move mascot_chat_messages table to Drizzle schema with proper migration
- Remove runtime DDL (CREATE TABLE IF NOT EXISTS) from mascot-chat repository
- Remove phantom analytics/ module from documentation
- Add better-sqlite3 dependency to root devDependencies
- Replace 'as any' casts with proper type assertions across AI moderation
- Add error logging to silent catch blocks in LLM client
- Apply Biome formatting and import organization

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:07:01 +07:00
MythEclipse 67d66bb5dd refactor(shared): centralize configuration and types
Migrate configuration validation and core moderation types from individual services to the `@bete/shared` package to ensure consistency across the monorepo.

- Move `AppConfig` and moderation-related interfaces to `packages/shared`.
- Replace service-specific Zod schemas with the centralized shared configuration.
- Refactor `services/backend` and `services/discord-gateway` to consume shared config and types.
- Remove redundant type definitions and local configuration logic in services.
- Update `packages/shared` exports to include new `config` and `moderation-types` modules.
- Clean up unused files and deprecated utility functions in `packages/shared`.
2026-06-09 11:56:03 +07:00
MythEclipse f84b380f4f fix: resolve architecture disconnects and codebase weaknesses
- fix(backend): replace raw .parse() with proper loadConfig() + ConfigError
- fix(gateway): connect voice recording uploader to EventBroadcaster
- fix(gateway): remove dead globalThis.moderationBroadcaster path in AI analyzer
- fix(gateway): eliminate audioStream race condition by attaching handlers before pipe
- fix(gateway): enable inlineVolume by default for setMusicVolume to work
- fix(gateway): reuse persistent redisPub for command replies (no new connection per cmd)
- fix(frontend): add missing voice_active_user/voice_pcm_data to WsEventMap
- fix(frontend): correct onAttachmentUploaded handler signature to accept data
- chore: move @types/pg from dependencies to devDependencies
- chore: translate remaining Indonesian comments to English
- chore: remove stale P3 TODO comment
2026-06-09 11:06:14 +07:00
MythEclipseandClaude Opus 4.8 4becf0d6f1 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>
2026-06-09 10:16:04 +07:00
MythEclipseandClaude Opus 4.8 a4c2b93314 fix(voice): correct Express route for voice command
Route was POST /api/command (mounted at /api + /command)
Fixed to POST /api/voice/command (mounted at /api + /voice/command)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 00:13:00 +07:00
MythEclipseandClaude Opus 4.8 52f2968d8f fix(voice): add HTTP API fallback for transmit commands
- Add POST /api/voice/command endpoint in backend
- Frontend transmit now sends commands via dedicated WebSocket connection
  with HTTP API fallback if WebSocket fails
- Fixes issue where transmit start command was never received by discord-gateway

Previously commands were sent via the existing dashboard WebSocket,
which may not be connected when the Transmit button is pressed.
Now each command opens a fresh WebSocket connection with HTTP fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 22:55:11 +07:00
MythEclipseandClaude Opus 4.8 314d2baec4 feat(voice): implement full voice transmit (Browser → Discord)
Frontend (useAudioTransmit.ts):
- Capture microphone via getUserMedia
- Convert Float32 to Int16 PCM at 24kHz mono
- Base64 encode and send as JSON via WebSocket
- Send voice:transmit:start/stop commands on start/stop

Backend (ws/server.ts):
- Handle voice_transmit messages from browser
- Forward PCM data to Redis channel backend:voice:transmit
- Handle voice_command messages and forward to backend:command
- discord-gateway VoiceTransmitter receives and plays to voice channel

Flow:
   Browser Mic → getUserMedia → ScriptProcessor → Int16 PCM → base64 →
   WebSocket JSON → Backend → Redis → VoiceTransmitter → Discord Voice Channel

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:29:41 +07:00
MythEclipseandClaude Opus 4.8 1c7b7e6398 fix(backend): handle voice PCM as JSON instead of binary
- Add discord:voice:pcm to SUBSCRIPTIONS as regular JSON channel
- Remove BINARY_CHANNELS and handleBinaryMessage function
- Discord-gateway sends PCM as JSON with base64, not raw binary
- This fixes PCM data not reaching browser via WebSocket

The issue was backend expected binary format but gateway sends:
{"type":"voice_pcm_data","data":{"userId":"...","pcm":"base64..."}}

Now backend correctly subscribes and broadcasts this to WebSocket clients.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 21:18:11 +07:00
MythEclipseandClaude Opus 4.8 13a75a5101 fix(voice): restore voice features and apply critical optimizations
Voice Feature Restoration:
- Implemented full Redis pub/sub pipeline for real-time voice data
- Added VOICE_PCM and VOICE_ACTIVE_USER Redis channels
- Implemented EventBroadcaster.voicePcmData() and voiceActiveUser() methods
- Extended backend redis-bridge to subscribe to voice channels
- Updated backend WebSocket server for binary PCM broadcast
- Replaced globalThis PcmBroadcaster pattern with proper EventBroadcaster DI
- Fixed root cause: PcmBroadcaster functions were never initialized

Bug Fixes:
- Fixed prism-media version conflict (2.0.0-alpha.0 → 1.3.5)
- Fixed type inconsistency in commandHandler.ts (AudioPlayerStatus → string)

Critical Optimizations:
- P1.1: Fixed unbounded memory growth in aiAnalyzer (added LRU caching, max 10K entries)
- P1.2: Converted sync file I/O to async in audio hot paths (recorder, sessionRecording)
- P1.3: Replaced process.exit(1) with proper error handling (bootstrap, aiAnalysisWorker)

Code Quality:
- Removed unused logger field in EventBroadcaster
- Replaced console.* with structured logger.* calls (player, decoder)
- Fixed typos and removed commented debug code
- Added DatabaseError class for better error handling

Files Modified: 18 (discord-gateway: 14, backend: 3, root: 1)
Architecture: Discord → EventBroadcaster → Redis → Backend WebSocket → Frontend

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 19:14:34 +07:00
MythEclipse e00b23f9b8 fix(concurrency): eliminate all identified double-queue and race conditions
Implements full audit from double_queue_audit.md.

## Critical

fix(backend): reanalyze-batch — per-scope in-flight guard (messages.routes.ts)
  Two concurrent admin sessions clicking 'Retry All Errors' simultaneously now
  get a 409 REANALYZE_BATCH_IN_PROGRESS for the same guildId:channelId scope.
  Prevents the recovery worker from being triggered twice for the same set of
  error messages.

fix(discord-gateway): messageUpdate embed resolution skip (messageCapture.ts)
  Discord fires messageUpdate when link previews resolve 1-2s after send
  even though the message body is unchanged. Compare newContent vs
  existingContent before resetting ai_status to pending and re-queueing LLM.
  Eliminates a spurious duplicate analysis that could overwrite a valid result.

## High

fix(discord-gateway): scheduleAutoDelete idempotency (aiAnalyzer.ts)
  Add autoDeleteInFlight Set. Both processBatch and processIndividualFallback
  call scheduleAutoDelete; without the guard, a message that races through
  both paths launches two concurrent attemptAutoDeleteFlaggedMessage calls,
  producing a duplicate moderation-action log entry and a Discord 10008 error.
  The Set is cleaned up in a .finally() block after each attempt completes.

## Medium

fix(frontend): revert optimistic pending state on HTTP failure (useMessages.ts)
  Capture the prior MessageRecord inside the setMessages functional updater
  (no extra useCallback deps needed). If reanalyzeMessage() throws, restore
  the snapshot so the UI reflects the real DB state instead of lying.

fix(discord-gateway): exclude individual_analysis_exhausted from recovery queries
  Both getConversationKeysWithIncompleteAnalysis and
  getIncompleteMessagesByConversation now add a NOT LIKE guard for
  individual_analysis_exhausted. Prevents an infinite recovery loop if a bug
  ever writes both flags to the same row.

## Low

fix(discord-gateway): unified timer path in scheduleConversationAnalysis
  Remove the separate cooldown-path that created a secondary timer calling
  scheduleConversationAnalysis recursively. Replace with a single
  clear-and-reset pattern where delayMs = max(cooldownRemainder+500, debounce).
  Eliminates the edge case where both timers were live simultaneously.

## Misc

fix(backend): cast req.params.id to String() to satisfy Express typings
  Pre-existing tsc error (string | string[]) exposed by our edit.
  String() is correct; route params are always scalar strings at runtime.
2026-06-05 16:09:23 +07:00
MythEclipse 5c0a837cf0 fix(ai-moderation): eliminate double-queue on failure and spam-retry
Three root causes patched:

1. aiAnalyzer.ts — processBatch apiFailedMessages path:
   After reverting messages to 'pending', suppress shouldScheduleNext
   (was true by default) to prevent scheduleConversationAnalysis from
   firing immediately and racing with the recovery worker that will pick
   up those same pending messages on its next poll cycle.
   Also release the conversationProcessing lock immediately after the
   revert so the cooldown timer (not the full processing-timeout) gates
   the next attempt.

2. messages.routes.ts — POST /messages/:id/reanalyze:
   Add a per-message reanalyzeInFlight Set.  Concurrent requests for
   the same ID now return HTTP 409 instead of issuing duplicate UPDATEs
   and triggering multiple recovery worker activations.
   Also narrow the SQL predicate to 'WHERE id =  AND ai_status != pending'
   so a click that arrives while the recovery worker already picked the
   message up is a no-op at the DB level.
2026-06-05 15:38:31 +07:00
MythEclipse 5d9713b162 chore(config): update TELE_UPLOAD_URL domain across all services 2026-06-04 17:12:02 +07:00
MythEclipse 67daea2f52 fix(analytics): filter out common file extensions from topic words
Excludes image, video, audio, and document file extensions from the
topic word extraction process to improve the quality of generated
analytics topics.
2026-06-03 20:15:24 +07:00
MythEclipse 8918dd09e2 fix(analytics): improve topic word filtering with Indonesian stop words and stricter noise reduction 2026-06-03 20:08:03 +07:00
MythEclipse cbee35c348 fix(analytics): replace regexp_split_to_table with UNNEST+STRING_TO_ARRAY and fix regex escapes 2026-06-03 19:55:43 +07:00
MythEclipse 4e12394168 fix: add error handling to analytics getTopics query and fix mascot tooltip positioning 2026-06-03 19:50:26 +07:00
MythEclipse de0c7927c9 refactor(analytics): update topic analysis to use word frequency
Replaces the previous AI-category based topic analysis with a word-based
frequency analysis using a Common Table Expression (CTE).

- Implements `word_list` CTE to split message content into individual words.
- Adds regex filtering to exclude URLs, Discord stickers, and emojis.
- Implements a stop-word filter to remove common Indonesian and English
  conjunctions, pronouns, and prepositions.
- Filters out words shorter than 3 characters.
- Updates the aggregation to group by word and limit results to the top 10.
2026-06-03 19:37:16 +07:00
MythEclipse ac678e8a88 chore: session auto-commit 2026-06-03 18:52:20 +07:00
MythEclipse ee50afb1c1 feat(mascot-chat): implement LLM-based response generation
Refactor the mascot chat service to use an LLM instead of hardcoded
rule-based responses. This includes building system prompts from
server insights and constructing conversation history for context-aware
interactions.
2026-06-03 18:30:18 +07:00
MythEclipse 58f5d4f7ce style(analytics): reorder imports and apply consistent formatting 2026-06-03 18:20:27 +07:00
MythEclipse f1bc36d6d8 feat(analytics): add moderation actions, AI stats, and attachment stats endpoints 2026-06-03 18:16:55 +07:00
MythEclipse 7904d7f38d ``` 2026-06-03 15:01:34 +07:00
MythEclipseandClaude Opus 4.8 6da8a32c9b feat: add "Retry All Errors" batch reanalyze button
Backend:
- POST /api/messages/reanalyze-batch — bulk reset error messages to pending
- messages.repository.reanalyzeErrorBatch() — scoped by guildId/channelId/messageIds
- messages.service.reanalyzeErrorBatch() — validation layer

Frontend:
- reanalyzeErrorBatch() API client function
- useMessages.reanalyzeAllErrors() — optimistic state + batch call
- MessagesPanel: destructive button visible when error count > 0
- Shows confirmation text with queued count

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:17:51 +07:00
MythEclipse 2d79d8aefd feat(shared): reorder AppError constructor to (message, code, status), add singleton logger, retry and TTL cache utilities 2026-06-02 21:06:42 +07:00
MythEclipse 9045e7e347 chore(backend): switch moduleResolution to bundler and remove baseUrl from tsconfig 2026-06-02 19:14:50 +07:00
MythEclipse 685a6b2ea9 chore: auto-commit task - 2026-06-02 19:04:49 +07:00
MythEclipse d1ad397be6 chore: session auto-commit 2026-06-02 18:57:38 +07:00
MythEclipse 924a6b8819 chore: session auto-commit 2026-06-02 18:57:13 +07:00
MythEclipse 0fa49b3613 chore: session auto-commit 2026-06-02 18:55:48 +07:00
MythEclipseandClaude Opus 4.8 c5c667b147 feat: comprehensive UX improvements — messages, analysis, moderation
Fix #1 (CRITICAL): Wire message_analyzed through Redis EventBroadcaster
- DG aiAnalyzer.ts: Add broadcastAnalysisCompleted() helper that publishes
  to both in-memory WS broadcaster AND Redis EventBroadcaster
- DG bootstrap.ts: Pass eventBroadcaster to startPendingAIAnalysisWorker()
- Fixes broken real-time chain so analysis results appear instantly

Fix #2: Collapsible AI Analysis with Rich Formatting
- MessageCard: AI analysis now collapsible with color-coded severity border
  (red/yellow/blue), summary line showing categories + confidence + severity
- Default collapsed for clean, expanded for warn/flagged

Fix #3: Toast Notifications for Flagged Content
- Wrap app in ToastProvider; ModerationAlertListener component listens for
  moderation_alert custom events and shows toast with emoji + details

Fix #4: Discord-style Message Grouping
- MessageFeed: Group consecutive messages from same user within 5 min
- MessageCard: Compact variant hides avatar, reduces padding for non-first

Fix #5: Moderation Action Buttons in UI
- BE: POST /api/messages/:id/moderate endpoint + publishCommand() for Redis
- FE: Delete/Warn buttons on flagged/warned cards with confirmation dialog

Fix #6: Search Results Include Full Data
- BE analysis.service.ts: SELECT all 26 message columns instead of just 11
- Search results now render with full MessageCard including images/analysis

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 12:17:51 +07:00
MythEclipseandClaude Opus 4.8 5f419a6f0f feat: real guild/channel names from Discord + remove selectors in Messages/Analytics
- discord-gateway: add redis command handlers for guilds:list, guilds:text-channels, voice:channels
- backend: replace postgres synthetic names with redis commands to gateway (with fallback)
- frontend: remove guild/channel dropdowns from messages and analytics tabs
- frontend: auto-load all channels from monitor guild via guildId query param
- frontend: show guild name in messages/analytics headers instead of selector
- live tab: keeps guild/channel selectors with real discord names

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 11:02:54 +07:00
MythEclipseandClaude Opus 4.8 f1ddca5eee fix: false positive gambling detection + route collision + WS events (#1)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 10:44:27 +07:00
MythEclipseandClaude Opus 4.8 3b2709455e feat: implement all real backend endpoints, Redis pub/sub bridge, and gateway command handler
Backend (real implementations, no more stubs):
- Redis pub/sub bridge: subscribes to discord-gateway events (message/attachment/voice) and broadcasts to WS clients
- Redis command channel: backend publishes voice/media commands, discord-gateway executes and replies
- Voice service: connectVoice/disconnectVoice/getVoiceStatus via Redis commands with graceful fallback
- Media service: queue/skip/stop/volume via Redis commands, reads status from Redis cache
- Messages repository: ALL 7 methods now use real PostgreSQL queries (findMany, findById, findByChannel, create, update, delete, getAttachmentsByChannel)
- Analytics: period returns {start,end} epoch millis, overview includes hourly/topics/top_users, worst_flags as string[]
- Health check: actually queries SELECT 1 against database
- VoiceStatus type fixed: {connected, activeGuildId, activeChannelId, activeChannelName}
- Guild type: includes icon: string | null
- asyncHandler: accepts Promise<unknown> instead of Promise<void>

Discord Gateway:
- CommandHandler: subscribes to 'backend:command' Redis channel, executes voice/media commands, publishes replies
- Publishes voice:status and media:status to Redis for backend caching
- Shutdown handler updated to close command handler

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 00:32:38 +07:00
MythEclipseandClaude Opus 4.8 9b41eb9c12 feat(backend): implement all missing endpoints, real analytics queries, and WebSocket server
- Replace stub analytics.repository.ts with real PostgreSQL queries using pg.Pool
- Add /api/guilds, /api/config, /api/auth/login, /api/ui-state (GET/POST)
- Add /api/review, /api/recordings, /api/analysis/search
- Add /api/messages/:id/reanalyze endpoint
- Add /api/analytics/heatmap and /api/analytics/topics
- Implement media routes (stub responses, backend has no Discord voice client)
- Add WebSocket server at /ws with heartbeat and broadcast functions
- Fix analytics route paths to match frontend contract (dual paths for backward compat)
- Export getPool() from database module for raw SQL queries
- Register all new routers in app.ts

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 00:11:29 +07:00
MythEclipseandClaude Opus 4.6 f20c2389a4 refactor(backend): flatten module structure, move routes to .routes.ts files
- Remove empty controllers/, services/, repositories/ subdirectories
- Move routes/index.ts into module.routes.ts (flat naming convention)
- Update imports in http/app.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-01 21:53:08 +07:00
MythEclipseandClaude Opus 4.8 c48a0c5e3b refactor: split monolith into 3 microservices (frontend, backend, discord-gateway)
- Extract services into services/{frontend,backend,discord-gateway}
- Create packages/shared/ for shared logger, errors, utils, types
- Setup Modular MVC pattern in backend (controller→service→repository)
- Setup event-driven architecture in discord-gateway with Redis pub/sub
- Move Docker files to infra/docker/ with per-service Dockerfiles
- Update docker-compose.yml to use Traefik-only routing (no port exposes)
- Update GitHub Actions deploy workflow for multi-service matrix build
- Fix all import paths and resolve type errors across all services
- All 3 services pass tsc --noEmit clean

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 21:44:29 +07:00