Repository navigation
feat: let a server create several auto-moderation rules - #262
Conversation
GuildAutoModerationZalgo has the columns of the other rule tables and `maximum`, the most combining marks a character may carry. Its settings are automodZalgo*.
A message infringes the rule when one of its characters carries more combining marks than automod.zalgo.maximum (4 by default): the text is decomposed first, so precomposed and combining accents count the same, and the languages that stack marks by design (Thai, Vietnamese, Arabic, Devanagari) stay under it. It is a rule like the others: /automod-zalgo show, edit and reset, the soft actions, the punishment with its threshold, ignored roles and channels.
A guild had one fixed configuration per type of rule, each in its own table. They are replaced by GuildAutoModerationRule: one row per rule, with a name, a type, the actions, the threshold, the exemptions and the options of its type as typed JSON, so a guild can have several rules of the same type. The unused Mentions rule and its overrides table are dropped.
The listeners apply the first enabled rule of their type a message infringes, each rule with its own counter, word list and exemptions. /automod creates, edits, lists and deletes the rules, and replaces the /automod-<type> commands; the guilds/:guild/automod/rules routes do the same for the dashboard. The automod<Type>* settings are removed.
|
Note This drawing shows
4 findings · reviewed 🔴 Rule reads have no database migration ·
|
There was a problem hiding this comment.
Important
A few behavior regressions and a rollout hazard worth addressing before merge; the core design (rules as rows, per-rule state, first-rule-wins per type) reads well.
Reviewed changes
Full review of the two commits that move auto-moderation from per-type settings to GuildAutoModerationRule rows.
- Database layer —
GuildAutoModerationRulemodel,automod/types.ts(limits, option normalization) andautomod/storage.ts(CRUD). - Rule runtime —
lib/moderation/automod/rules.ts(per-guild cache, shard broadcast, per-rule adder/regex/mention state) andModerationMessageListenernow applying the first infringed rule of a type. /automodcommand family —create|edit|delete|list|show|add|remove|ignorereplacing the/automod-<type>commands.- Dashboard API —
GET/POST /guilds/:guild/automod/rulesandGET/PATCH/DELETE .../rules/:rule, withvalidation.tsreading request bodies. - Cleanup — removed settings keys,
AdderManager,SettingsContextword filter and mention limiter, the word serializer, locales and tests.
⚠️ The "run the SQL before the deploy" migration breaks the running bot, and cannot be undone
The migration drops the nine GuildAutoModeration<Type> tables in the same transaction that creates the new one. The old build's fetchGuildData queries every table in Tables, so from the moment the SQL commits until the new build is live, every guild-settings cache miss on the old instances fails. Deploying first fails the other way, because the new build needs GuildAutoModerationRule. The drop is also irreversible: a rollback of the bot has no tables to read.
Technical details
# Split the migration so old and new builds can overlap
## Affected sites
- PR description SQL — `DROP TABLE "GuildAutoModerationMentionsOverrides"` and the nine-table `DROP TABLE` run in the same transaction as `CREATE TABLE "GuildAutoModerationRule"`.
- `projects/database/src/settings/storage.ts` `fetchGuildData` — reads every entry of `Tables` for the old build.
## Required outcome
- There is a window where both the old build and the new build work against the database, and a way back after the deploy.
## Suggested approach
- Step 1 (before deploy): `CREATE TYPE`, `CREATE TABLE`, `INSERT ... SELECT` only. Old build keeps working, new build works.
- Step 2 (after the deploy is verified): the `DROP TABLE` statements, as a separate follow-up.
## Open questions for the human
- Is a brief settings outage during the switch acceptable? If so, say so in the PR body so the person running the SQL expects it.ℹ️ Nitpicks
projects/bot/src/locales/en-US/serializers.json:36—wordIncludedis now unused, sinceserializers/word.tswas deleted, and the generatedi18next.d.tsstill carries it.- There are no tests for
rules.ts(the 25 rule limit,validateNameincluding digit-only and case-insensitive duplicates) or for the "first infringed rule of a type wins" loop inModerationMessageListener.run; those are the two new behaviors users will notice.
claude-sonnet-5-5 | 𝕏
The writes of a guild are queued and read the rule from the database, so two edits made at once no longer overwrite each other, and a query that started before a change does not cache what it read. A unique index on the name is reported as a taken name. The words of a rule are 2 to 32 characters again, lowercased and stripped of look-alike characters on every path, and /automod add refuses a word another word already catches. A rule ID that is not a number answers 404 instead of 500.
Tibetan, Devanagari with a nukta and pointed Hebrew stay at 3 or 4, so the default maximum of 4 does not flag them.
|
On the points that have no thread:
|
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Incremental review of 8ce5013 since the prior pullfrog review at 593256a; it addresses the earlier feedback.
- Serialized rule writes per guild with an
AsyncQueue, each running on the rules read from the database, and letupdateAutoModerationRuletake a function so/automod edit|add|remove|ignoreandroleDeleteno longer overwrite each other. - Guarded the rule cache with a per-guild version so a query that started before a change does not repopulate it, and mapped the unique name index to
nameTaken. - Made
deleteAutoModerationRuleanswerunknownfor an ID that is not a number, so the delete route returns 404 instead of 500. - Restored word validation: 2 to 32 characters, lowercased and confusables-free entries, and the "already caught by another word" check, shared by the command and API paths.
- Split the migration in the PR body into a pre-deploy step and a post-verification
DROP, and removed the unusedwordIncludedlocale key. - Added tests for
rules.ts(names, limit, concurrent writes, ID guard) and foreditRuleListEntry.
ℹ️ Nitpicks
- There is still no test for the "first infringed rule of a type wins" loop in
ModerationMessageListener.run.
claude-sonnet-5-5 | 𝕏
| const { data, errors } = parseAutoModerationRulePatch(rule.type, await request.readBodyJson(), rule.options); | ||
| if (errors) return response.status(HttpCodes.BadRequest).json(errors); | ||
|
|
||
| try { | ||
| return response.json(await updateAutoModerationRule(guildId, rule.id, data)); |
There was a problem hiding this comment.
PATCH merges options from the cached rule before joining the write queue. Two requests changing minimum and maximum can both copy the old options. The second write then restores the first field's old value, even though both requests succeed. This happens within one process despite the queued writes and needs fixing before merging.
Read the body once, then merge its options inside the function passed to updateAutoModerationRule, using the current rule.
Artifacts
- Ran two partial-option PATCH requests with the pre-queue manager and parser, capturing full HTTP statuses, response bodies, storage traces, and the failed assertion; both requests succeeded but one edit was lost.
- Ran the same requests through the current queued manager, capturing full HTTP statuses, response bodies, storage traces, and the failed assertion; serialized writes still lost the minimum edit.
- Contains the complete executed HTTP harness, infrastructure mocks, real-parser tracing, deterministic request barrier, and regression assertions; it reproduces F1 without changing production code.
- Contains the configuration used to select the extracted prior manager and parser for the before run and production modules for the after run; both runs exercise the same test and route.
- Contains the executed revision extraction, route-equivalence check, exact test commands, and output capture logic; each behavior log records its command, working directory, and exit code.
- Contains the complete manager source extracted by git show from revision 593256a and executed in the before run; it provides the historical implementation used for comparison.
- Contains the complete parser source extracted by git show from revision 593256a and executed in the before run; it provides the historical partial-option merge implementation.
Ran code and verified through T-Rex
Prompt To Fix With AI
This is a comment left during a code review.
Path: projects/bot/src/routes/guilds/[guild]/automod/rules/[rule].patch.ts
Line: 24-28
Comment:
**Edits undo each other**
`PATCH` merges options from the cached rule before joining the write queue. Two requests changing `minimum` and `maximum` can both copy the old options. The second write then restores the first field's old value, even though both requests succeed. This happens within one process despite the queued writes and needs fixing before merging.
Read the body once, then merge its options inside the function passed to `updateAutoModerationRule`, using the current rule.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| .filter((entry): entry is string => typeof entry === 'string') | ||
| .map((entry) => (type === 'Invites' ? entry.trim() : entry.trim().toLowerCase())) | ||
| .filter((entry) => entry.length > 0 && (type !== 'Words' || isAutoModerationRuleWord(entry))); | ||
| options[key] = [...new Set(list)].slice(0, MaximumAutoModerationRuleListLength); |
There was a problem hiding this comment.
normalizeAutoModerationRuleOptions cuts stored lists to 200 entries on every read. The supplied migration copies the full old lists, and the old word command allowed more than 200 words. An enabled filter with 201 distinct words therefore stops checking the last word after deployment, without a warning. Preserving existing moderation coverage needs to be addressed before merging.
Keep existing stored entries and enforce the cap when adding new entries, or provide a migration that preserves them.
Artifacts
- The test executes the base command and both matcher paths with the same 201-word fixture, proving that the current storage read removes the last word from enforcement.
- The configuration reuses repository aliases and setup for the explicitly selected test, allowing the reproduction to run without production changes.
- The runner executes both test modes and saves their actual output with command, working directory, and exit code, making the comparison reproducible.
- The base command successfully adds 201 words and the base settings matcher catches all of them, establishing that the oversized legacy policy was valid and effective.
- The actual storage reader loads an enabled row containing 201 words but returns 200 to the actual matcher, proving that the final migrated word silently stops matching.
- The command output captures the PR migration, relevant production source, and complete reproduction source with line numbers, linking the full-array migration to truncation during storage reads.
Ran code and verified through T-Rex
Prompt To Fix With AI
This is a comment left during a code review.
Path: projects/database/src/automod/types.ts
Line: 186
Comment:
**Existing filters lose words**
`normalizeAutoModerationRuleOptions` cuts stored lists to 200 entries on every read. The supplied migration copies the full old lists, and the old word command allowed more than 200 words. An enabled filter with 201 distinct words therefore stops checking the last word after deployment, without a warning. Preserving existing moderation coverage needs to be addressed before merging.
Keep existing stored entries and enforce the cap when adding new entries, or provide a migration that preserves them.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| if (rule.ignoredRoles.length > 0) { | ||
| embed.addFields({ name: translateKey(t, `${Root}:showIgnoredRoles`), value: rule.ignoredRoles.map((id) => roleMention(id)).join(' ') }); | ||
| } | ||
| if (rule.ignoredChannels.length > 0) { | ||
| embed.addFields({ | ||
| name: translateKey(t, `${Root}:showIgnoredChannels`), | ||
| value: rule.ignoredChannels.map((id) => channelMention(id)).join(' ') |
There was a problem hiding this comment.
renderRule puts every exempt role and channel into one field each. The API accepts 100 IDs, but 50 role mentions with 18-digit IDs already take 1,149 characters. The embed builder rejects that field because Discord allows only 1,024 characters, so /automod show fails before sending a reply for a valid rule. This is a non-blocking display problem; the saved rule remains usable for moderation.
Split these lists into smaller fields or shorten them with a hidden-entry count, as the main list already does.
Artifacts
- Executed actual input validation, embed construction, and the show handler with narrow mocks, proving accepted role exemptions can prevent a reply.
- Used repository aliases and setup to execute only the F3 test, keeping validation narrowly scoped.
- Ran the 44-role and 50-role conditions and captured each command, working directory, exit code, and output, making the comparison reproducible.
- Executed the real handler with 44 accepted IDs and recorded a 1,011-character field and one reply, establishing the successful control.
- Executed the real handler with 50 accepted IDs and captured the 1,149-character field, validator errors, and zero replies, confirming F3.
- Saved the actual returned embed and runtime measurements from the successful test, showing the field fits.
- Saved the actual caught render and show errors with runtime measurements, showing accepted input cannot be displayed.
- Rendered captured execution output in Chromium and emphasized the actual embed or validator errors, producing evidence videos rather than a fictional Discord interface.
- Recorded the successful control output and generated embed JSON in Chromium, showing 1,011 characters and one reply.
Poster of successful 44-role runtime evidence
- Captured the Chromium view of the actual successful runtime observation, showing the control stays within the field limit.
- Recorded the failing candidate output and actual validator errors in Chromium, showing 1,149 characters and zero replies.
Poster of rejected 50-role runtime evidence
- Captured the Chromium view of the actual rejected runtime observation, showing the candidate exceeds the field limit.
- Recorded the capture command and successful exit with both videos and posters saved, confirming the capture script completed.
Ran code and verified through T-Rex
Prompt To Fix With AI
This is a comment left during a code review.
Path: projects/bot/src/lib/moderation/automod/commands.ts
Line: 334-340
Comment:
**Long rules cannot be shown**
`renderRule` puts every exempt role and channel into one field each. The API accepts 100 IDs, but 50 role mentions with 18-digit IDs already take 1,149 characters. The embed builder rejects that field because Discord allows only 1,024 characters, so `/automod show` fails before sending a reply for a valid rule. This is a non-blocking display problem; the saved rule remains usable for moderation.
Split these lists into smaller fields or shorten them with a hidden-entry count, as the main list already does.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
The tables are @@control(external), so the baseline only has what the contract controls: the schema and the two enums. A database that already has the tables is signed at this contract with prisma db sign.
GuildAutoModerationZalgo is controlled by the contract instead of external, so prisma migration plan derives its table and foreign key. The db ref is the baseline contract.
# Conflicts: # projects/database/src/contract.prisma
GuildAutoModerationRule is controlled by the contract, so its table, enum and foreign key come from prisma migration plan. The same migration copies the enabled configurations of the old tables into rules and adds the unique index on the lowercase name, which PSL cannot say. A second migration drops the old tables, so the deploy can be verified before they go: prisma db migrate --to stops after the first.
There was a problem hiding this comment.
ℹ️ No critical issues — two minor points about what the copy SQL carries over.
Reviewed changes
Incremental review of 599eab4 since the prior pullfrog review at 8ce5013, which also merges feat/automod-zalgo.
- Prisma 8 migration
20261007T1312_add_automod_rules— creates theGuildAutoModerationRuleTypeenum, theGuildAutoModerationRuletable, its index and foreign key, copies the enabled configurations of the old tables, and adds the unique index on(guild_id, lower(name)). - Prisma 8 migration
20261007T1313_drop_old_automod_tables— drops the ten old tables, the overrides table before the mentions table, as the second, post-verification step. - Contract and snapshots —
GuildAutoModerationRuleis no longer@@control(external),AutoModerationRuleOptionsis atyped.Jsontype, andrefs/db.jsonpoints at the new end contract. Thefrom/tohashes chain correctly from the baseline through the zalgo migration. AGENTS.md— documents the Prisma 8 migration workflow.
claude-sonnet-5-5 | 𝕏
| jsonb_build_object('alerts', alerts, 'mentionsAllowed', mentions_allowed, 'timePeriod', time_period) | ||
| FROM "GuildAutoModerationNoMentionSpam" WHERE enabled | ||
| UNION ALL | ||
| SELECT id, 'Words', 'Words'::"GuildAutoModerationRuleType", true, soft_action, hard_action, hard_action_duration, threshold_maximum, threshold_duration, ignored_roles, ignored_channels, jsonb_build_object('words', to_jsonb(words)) |
There was a problem hiding this comment.
The old words, allowed, allowed_codes and allowed_guilds columns had no cap, but normalizeAutoModerationRuleOptions cuts every list to 200 entries when a row is read. A guild with a longer word list is migrated intact, then enforces only the first 200 from the first message on, and loses the rest on the next write to that rule.
Technical details
# Migrated lists longer than 200 are silently truncated
## Affected sites
- `migration.ts:131` (and the `Links`/`Invites` selects) — copies the full arrays.
- `projects/database/src/automod/types.ts` `normalizeAutoModerationRuleOptions` — `.slice(0, MaximumAutoModerationRuleListLength)` applies to rows read from storage, not only to new input.
## Required outcome
- A guild whose old list is over the cap is not silently shortened by the migration.
## Open questions for the human
- Check the largest `cardinality(words)` in `GuildAutoModerationWords` before running step 1. If any guild is over 200, either raise `MaximumAutoModerationRuleListLength` or split such a list into several `Words` rules in the copy.| description: 'copy the enabled configurations', | ||
| sql: `INSERT INTO "GuildAutoModerationRule" (guild_id, name, type, enabled, soft_action, hard_action, hard_action_duration, threshold_maximum, threshold_duration, ignored_roles, ignored_channels, options) | ||
| SELECT id, 'Attachments', 'Attachments'::"GuildAutoModerationRuleType", true, soft_action, hard_action, hard_action_duration, threshold_maximum, threshold_duration, ignored_roles, ignored_channels, '{}'::jsonb | ||
| FROM "GuildAutoModerationAttachments" WHERE enabled |
There was a problem hiding this comment.
WHERE enabled skips every configuration that is switched off, and the DROP step then removes those rows for good. A guild that turned its word filter off but kept the list and exemptions loses them, although the new rule has an enabled column to hold them. Copying rows that are disabled but customised (non-empty list, exemptions or a changed action) as enabled = false would keep that data without creating a rule for every guild that never used the filter.
# Conflicts: # projects/bot/src/@types/i18next.d.ts # projects/bot/src/lib/database/settings/configuration.ts # projects/bot/src/lib/database/settings/structures/AdderManager.ts # projects/bot/src/lib/moderation/structures/AutoModerationRules.ts # projects/bot/src/listeners/guilds/roles/roleDelete.ts # projects/bot/src/listeners/moderation/messages/guildUserMessageZalgoHandler.ts # projects/bot/src/locales/en-US/commands/auto-moderation.json # projects/bot/src/locales/en-US/settings.json # projects/bot/tests/lib/structures/settings-menu/settings-menu.test.ts # projects/database/migrations/app/refs/db.json # projects/database/src/settings/columns.ts # projects/database/src/settings/constants.ts
| export const AutoModerationRuleOptionLimits = { | ||
| Capitals: { minimum: { minimum: 5, maximum: 2000 }, maximum: { minimum: 10, maximum: 100 } }, | ||
| Newlines: { maximum: { minimum: 1, maximum: 100 } }, | ||
| NoMentionSpam: { mentionsAllowed: { minimum: 1, maximum: 200 }, timePeriod: { minimum: 1, maximum: 3600 } }, |
There was a problem hiding this comment.
NoMentionSpam settings change silently after migration. The old settings allowed mentionsAllowed above 200 and timePeriod above 3600. The migration copies those values, but every read clamps them to the new limits. A server allowing 500 mention points now bans members when the count exceeds 200 rather than 500, without an administrator changing the rule.
Preserve migrated values on reads and apply the new limits only to new inputs.
Artifacts
- Loads source from the exact base and HEAD revisions, executes PostgreSQL fixtures and real storage/listener code with isolated boundaries, and asserts the observed saved-limit regression.
- Runs the baseline followed by the candidate and records each command, working directory, exit code, and captured output, making the comparison reproducible.
- Captures the initial baseline-only attempt failing because the installed TypeScript package did not expose the expected transpilation API, so candidate code was not executed in this attempt.
- Captures the second baseline-only attempt failing on an export generated during isolated transpilation, so candidate code was not executed in this attempt.
- Executes four legacy fixtures through real settings and listener code, showing allowance 500 bans at point 501 and period 7200 retains counts after 3601 idle seconds.
- Executes the exact mention migration SELECT and real HEAD read/listener code, showing preserved JSON is clamped to 200/3600 and allowance 500 now bans at point 201.
- Captures a narrow shared-contract search across supplied related repositories and the final Git checks, showing no relevant external consumer matches or tracked production changes.
Ran code and verified through T-Rex
Prompt To Fix With AI
This is a comment left during a code review.
Path: projects/database/src/automod/types.ts
Line: 96
Comment:
**Saved mention limits change**
`NoMentionSpam` settings change silently after migration. The old settings allowed `mentionsAllowed` above 200 and `timePeriod` above 3600. The migration copies those values, but every read clamps them to the new limits. A server allowing 500 mention points now bans members when the count exceeds 200 rather than 500, without an administrator changing the rule.
Preserve migrated values on reads and apply the new limits only to new inputs.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| enabled: true, | ||
| softAction: 0, | ||
| hardAction: 'Warning', | ||
| hardActionDuration: null, | ||
| thresholdMaximum: 10, | ||
| thresholdDuration: 60_000, |
There was a problem hiding this comment.
/automod create says the new rule only counts infractions, but it starts enabled with hardAction: 'Warning' and a threshold of 10. Creating an Attachments rule therefore issues warnings after ten attachment messages within a minute, before the administrator configures any action. Creating a NoMentionSpam rule can ban members immediately when its default mention limit is exceeded.
Start rules disabled or with no punishment until configured, and make the reply match their behavior.
Artifacts
- Executed this isolated test against real HEAD creation, storage, message-handler, and punishment source with external effects mocked; it confirms punishment before configuration.
- Used this configuration for the single execution; inherited include patterns also selected existing repository tests.
- Ran this script to execute Vitest once and save full output plus before/after extracts with command, working directory, and exit code; the captures are traceable to the actual run.
- Sent 10 attachment messages and a message containing 21 user mentions through real handlers before creation; neither produced punishment.
- Created both rules and repeated identical inputs without edits; a Warning case and a Discord ban invocation with Ban case contradicted the count-only replies.
- Captured the actual Vitest command output, including the candidate PASS and an unrelated existing locale failure; the candidate succeeded although the overall command exited 1.
- Ran this script to capture revision, scoped diff, numbered source, test result, and worktree status; it makes the executed behavior traceable to unchanged HEAD source.
- Captured actual git and source-reading command output for the candidate path; it verifies the requested HEAD, relevant snippets, candidate PASS, and unchanged tracked files.
Ran code and verified through T-Rex
Prompt To Fix With AI
This is a comment left during a code review.
Path: projects/database/src/automod/types.ts
Line: 132-137
Comment:
**New rules punish members**
`/automod create` says the new rule only counts infractions, but it starts enabled with `hardAction: 'Warning'` and a threshold of 10. Creating an `Attachments` rule therefore issues warnings after ten attachment messages within a minute, before the administrator configures any action. Creating a `NoMentionSpam` rule can ban members immediately when its default mention limit is exceeded.
Start rules disabled or with no punishment until configured, and make the reply match their behavior.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
❓ Type of change
📚 Description
Includes the zalgo rule of #260, so merge that one first.
A server could only configure one rule per type: one word filter, one link filter, and so on, each with a single set of actions and exemptions. This brings what Dyno does: several named rules, for example a word filter that only deletes and a second one, with other words, that bans.
Rules are now rows of
GuildAutoModerationRuleinstead of settings. A server has up to 25, as many of one type as it wants, each with its own options, actions, threshold and exempt roles and channels./automod create|edit|delete|list|show|add|remove|ignoremanages them, and so doGET/POST /guilds/:guild/automod/rulesandGET/PATCH/DELETE /guilds/:guild/automod/rules/:rulefor the dashboard.Things a reviewer should know:
Mentionsrule (automodMentions*and its overrides table) had no listener, so it is dropped rather than migrated./automod ignoretoggling. Separateignore/unignoresubcommands would be clearer, but cost command size./automod-<type>commands are gone, replaced by/automod.automod<Type>*keys are gone from the settings, so fromGET/PATCH /guilds/:guild/settingstoo. The dashboard has to use the new routes.automodChannelandautomodTrackNativestay.📝 Migration
Two Prisma 8 migrations, on top of the baseline and the zalgo one from #260. The tables of the old rules are
@@control(external), so the drop is a migration of its own, not part of the first.Rules edited with the old commands between the two steps are not carried over. Then
stars commands deploy.Not safe to merge yet: concurrent edits can lose changes, migrated filters lose coverage, saved mention limits change enforcement, and newly created rules can punish members before configuration.
Reviews (2) · Last reviewed commit: "Merge remote-tracking branch 'origin/V7'..." · Reviewed by Greptile