Deployment and operations
Run with PM2
Install production dependencies on the server, then start Mochi through Bun:
bun install --production
bun run pm2:start
bun run pm2:startup
Run the command printed by pm2:startup with the required system privileges, then save the current process list:
bun run pm2:save
The ecosystem file keeps the process running. It restarts the process after a crash. It writes logs to logs/pm2-out.log and logs/pm2-error.log.
Keep application settings and secrets in .env. After you change them, reload the process:
bun run pm2:restart
Use bun run pm2:logs to view logs. Use bun run pm2:stop to stop the process. Use bun run pm2:delete to remove the PM2 process.
Database model
Mochi uses SQLite with Bun's native bun:sqlite driver and WAL mode. Versioned
migrations in src/database/migrations/ manage the schema. Mochi records
completed migrations in schema_migrations.
The invite lifecycle ledger (invite_events) and bonus adjustment history
(invite_bonus_adjustments) are the source of truth. invite_members,
inviters, and daily_invite_stats are projections. Mochi can rebuild them
from the ledger.
The Discord invite snapshot is authoritative, including an empty snapshot. The
persisted invite_cache is a temporary fallback when Mochi cannot query
Discord. A successful empty fetch clears stale cache rows.
Rebuild projections
After manually changing invite data, rebuild the projections:
bun run rebuild-projections # all guilds
bun run rebuild-projections -- --guild <guildId> # one guild
bun run rebuild-projections -- --guild <guildId> --dry-run # preview only, no writes
Migrations
The current migration sequence is:
| Migration | Contents |
|---|---|
001 | Complete initial schema: invite ledger, projections, invite logs, invite cache and labels, guild settings, and bot attribution |
002 | Namespaced plugin migration metadata |
003 | Per-guild plugin enablement settings |
004–006 | Invite log imports and source evidence |
007 | Dashboard staff role permissions |
008 | Dashboard audit records and request results |
The new bot starts with one complete baseline migration. After deployment, preserve the migration history. Do not edit, combine, or remove a released migration. Add the next numbered migration for each schema change.
Migration 001 must remain unchanged after release.
Development databases are disposable while the bot is being built. Reset one explicitly when changing the baseline; the application never does this at startup:
rm data/mochi.sqlite
Migration 001 will create a clean database on the next start.
Plugin migrations follow the same safety model. Each migration uses the plugin ID as its namespace and is recorded in plugin_schema_migrations.
Migrations run in ascending version order. Each migration and its record are written in one transaction. Mochi does not run down migrations. Disabled plugins do not run migrations. Mochi does not remove their existing tables.
Testing
Run the complete test suite:
bun test
Tests use isolated in-memory databases and never touch data/mochi.sqlite.
Dashboard audit records
Deploying the audit log adds core migration 8. It runs automatically at startup. Restart the bot to load the new page and browser assets. Existing feature histories are not imported. New authenticated server dashboard write requests are recorded from this deployment onward.
The dashboard_audit_events table belongs to the main bot database. Include it in database backups. There is no dashboard delete API. Optional record retention can remove old completed-record detail as described below. Review database size during normal maintenance. A crash can leave pending requests. Verify their feature records before retrying; audit requests are never replayed.
Bot-data backups and recovery
Use bun run backup:create to create a consistent SQLite backup while Mochi runs.
The command uses SQLite VACUUM INTO, checks integrity, and saves a SHA-256
checksum. It does not copy a live WAL database with a raw filesystem copy.
Backups are stored in the backups directory beside the configured bot database.
The directory uses mode 0700. Backup files use mode 0600.
Use bun run backup:list, then bun run backup:verify FILENAME. Keep protected
copies on another host when required. This deployment keeps backups local.
The runtime creates a verified backup at startup when needed and then once per
24 hours. The scheduler checks each minute. It retains 14 days of its own
automatic backups. Manual backups are not removed. Set AUTO_BACKUP_ENABLED=false
to disable the scheduler, or AUTO_BACKUP_RETENTION_DAYS to change its retention.
The Recovery dashboard shows the latest backup and verification times. Backups older than 24 hours are marked stale.
To restore bot data:
- Run
bun run pm2:stop. Stop any other process using the bot database. - Run
bun run backup:verify FILENAME. - Run
bun run backup:restore FILENAME --confirm-stopped --confirm-restore. - Run
bun run pm2:restart. Check PM2,/api/health, and/api/stats. Confirm thatbot.connectedis true.
The restore command verifies PM2 state, checks Linux process file handles, checks
the backup checksum and integrity, and saves a recovery copy before replacement.
It refuses to restore an open database. It preserves old WAL sidecars separately.
The command requires Linux /proc access. Session data and environment secrets
are outside the bot-data backup. Database restoration does not undo Discord
punishments or restore Discord resources.
Discord server snapshots
Open System → Recovery. Administrator is required because snapshots contain private channel names and permission overwrites. Keep up to ten snapshots per server. Export their JSON outside the bot database. Exports are archives; this version restores stored snapshots and does not accept uploaded snapshot files.
Snapshots save ordinary roles, categories, text channels, announcement channels, and voice channels. They include channel settings and permission overwrites. They exclude messages, attachments, bans, managed roles, member role assignments, threads, forums, and stage channels.
Select Preview restore. The preview lists resources to keep or create and any blocked resources. Type the snapshot name to restore. Existing roles and channels are kept. Restoration creates missing resources only. It does not replace settings on existing resources. Missing integration roles block restoration until the integration is available again.
Created resources have new Discord IDs. Recreated roles are below Mochi. Review role order, private access, and member role assignments afterwards. Update bot settings that refer to old IDs. Mochi retains channel access during recovery.
Creation results are recorded one resource at a time. If creation is interrupted, the preview shows the uncertain resource. Check Discord and link its resulting ID with Resolve an interrupted creation. If it does not exist, create the matching resource in Discord first, then link it. Mochi does not repeat an unconfirmed creation. You can then restore the remaining missing resources.
Request protection and readiness
The dashboard applies separate limits to login, API requests, writes, and expensive operations. Limits are local to the single Mochi process and reset after a restart. A limited request returns HTTP 429 and Retry-After.
Browser API writes require a session CSRF token and the configured dashboard origin. The shared browser client obtains the token from /auth/csrf. Requests with a body must use application/json. Authenticated non-browser clients can continue to use JSON without browser headers. Existing feature routes can require an explicit CSRF token as well.
The dashboard sets security response headers. Its content policy allows the existing inline handlers and declared external chart and style sources. Request parsers reject compressed bodies.
Use /api/health for liveness. Use /api/ready for readiness. Readiness requires completed startup, database access, running plugins, fresh scheduled jobs, the production Discord connection, and configured global-protection freshness. Automatic backup failures also make readiness fail. Readiness returns HTTP 503 when a required check fails. Responses contain status flags, not credentials or private records.
Shutdown stops new work and drains active jobs and event handlers before closing SQLite. Cleanup continues after an individual hook fails. The runtime has a 45-second deadline. PM2 allows 60 seconds before forcing termination.
Optional record retention
RECORD_RETENTION_DAYS defaults to 0. This keeps existing records. A positive value enables hourly text cleanup for old completed records. It clears saved transcripts, ticket details, feedback comments, completed application answers and messages, closed report/appeal text and messages, completed audit change details, and completed case evidence. Old successful message-delivery history can also be removed.
Record identifiers, moderation reasons, decisions where required for state, case relationships, and unresolved workflow records remain. Active requests, unconfirmed audit records, and unfinished application role work remain. Closed ticket text is cleared only after its Discord channel was deleted. Existing backup files can still contain earlier text. Backups have a separate retention period. Enable this setting only after choosing the required period.