Comments - Design Document
Status: Partially released -- Core commenting is live. See Comments feature documentation for the user-facing guide.
Overview
Comments let users share feedback, reactions, and discussion on published entities (characters, modes, lorebooks, packages). The system is creator-controlled -- entity owners decide whether comments are enabled, who can participate, and how the comment section is moderated. The goal is to give creators a lightweight community space directly on their content, without requiring external platforms.
Emoji reactions exist on comments only -- there are no standalone reactions on entities themselves. If a user wants to express quick appreciation for an entity, favorites and bookmarks serve that purpose.
Problem
Today
There is no way for users to give public feedback on entities they use. Creators have no visibility into what resonates, what's confusing, or what users want improved. Users who want to discuss a character or recommend it to others have to go off-platform.
What this enables
- Direct feedback loop: Users tell creators what works, what's broken, what they want more of.
- Social proof: A character with enthusiastic comments signals quality to browsers.
- Community around content: Threads let users discuss strategies, share setups, or coordinate around shared experiences (especially relevant for packages).
- Creator curation: Highlighted comments surface the best feedback. Hidden comments keep the space clean without deleting content.
Core Model
Comment Entity
Comment
├── Id UUID
├── EntityType 'character' | 'mode' | 'lorebook' | 'package'
├── EntityId FK to the entity
├── UserId FK to the commenter
├── ParentCommentId FK to parent (null for top-level comments)
├── Content Text (markdown: bold, italic, inline code, spoilers)
├── Status 'visible' | 'hidden' | 'pending'
├── IsHighlighted bool (creator-pinned)
├── IsEdited bool
├── CreatedAt timestamp
├── UpdatedAt timestamp
└── DeletedAt timestamp (soft delete)
Status values:
| Status | Meaning |
|---|---|
visible |
Normal, publicly displayed comment |
hidden |
Hidden by the entity creator. Still visible to the creator (in moderation view) and to the comment author (marked as hidden). |
pending |
Awaiting review. Used when a keyword filter flags a comment for manual review instead of outright rejection, or when the future AI content check holds a comment. Not publicly visible until a creator or admin approves it. |
Reported is not a status. Whether a comment has been reported is derived from the existing reports table (with entity_type = Comment). A comment can be visible and reported, or hidden and reported -- these are independent. This avoids status conflicts where a creator hides a comment and a report would overwrite the status or vice versa.
Comment Reports — Reusing the Existing Report System
Comment reports use the existing reports table (database/v1/12_tables_moderation.sql) with a new Comment entity type added to the EntityType enum. No separate comment_reports table is needed.
Why reuse instead of a new table:
The existing report system already provides claim/resolve workflow, admin queue integration (vw_moderation_queue_items), bulk actions, resolution notifications, and duplicate prevention. A separate table would duplicate ~80% of this infrastructure for one added concept: creator-report priority.
How it maps:
Existing reports column |
Comment report usage |
|---|---|
entity_type |
New value: Comment (5) |
entity_id |
The comment ID |
report_type |
Reuses existing categories: Harmful, Spam, Other, etc. |
status |
Same lifecycle: NeedsReview → UnderReview → Resolved |
resolution / resolution_text |
Same moderator workflow |
| UNIQUE per user per entity | Prevents duplicate reports on same comment |
Creator-report priority is computed, not stored. When a creator reports a comment on their own entity, the moderation queue view computes this via join rather than storing a denormalized flag:
reports → comments (entity_id) → entity (entity_type, entity_id) → owner_user_id
If reports.user_id = entity.owner_user_id, the report is a creator report and gets priority boost in the queue. This is a query-time join — report volume is low, moderators aren't querying thousands per second, and it avoids storing derived data that can go stale.
Queue priority boost: The vw_moderation_queue_items view (or a comments-specific filtered version) adds a priority tier for reports where the reporter is the entity owner. Combined with existing report-volume priority, creator reports surface first.
Reports are rate-limited per user (10 reports/hour via IUserRateLimiter with reports.comment.per_hour limit key) to prevent abuse of the reporting system.
Comment Edit History
Every edit creates a snapshot of the previous content. Edit history is not publicly visible -- only platform admins can view it to track abusive edit patterns (e.g., posting inflammatory content, collecting reactions, then editing to something innocuous).
CommentEditHistory
├── Id UUID
├── CommentId FK
├── PreviousContent text
├── EditedAt timestamp
└── EditedByUserId FK (always the comment author, tracked for audit)
Reactions
CommentReaction
├── CommentId FK
├── UserId FK
├── Emoji text (from allowed emoji set)
├── CreatedAt timestamp
└── UNIQUE(CommentId, UserId, Emoji)
Reactions use a curated emoji set rather than arbitrary Unicode. This keeps the UI consistent and prevents abuse. The initial set should cover the common cases -- heart, thumbs up, laugh, fire, thinking, star -- and can be extended later. One user can add multiple different reactions to the same comment, but only one of each type.
Reactions are subject to the same restriction checks as commenting (blacklist, timeout, audience). If a user can't comment, they can't react either.
Entity Comment Settings
Comment behavior is configured per entity by the creator.
EntityCommentSettings
├── EntityType 'character' | 'mode' | 'lorebook' | 'package'
├── EntityId FK
├── CommentsEnabled bool (default: false)
├── AllowedAudience 'everyone' | 'followers' | 'users'
├── MinAccountAgeDays int (default: 0 — no restriction)
└── UpdatedAt timestamp
| Audience | Who can comment | Applicable entities |
|---|---|---|
everyone |
Any logged-in user | All entity types |
followers |
Only users who follow the creator | All entity types |
users |
Only users who have used the entity | Characters (started a conversation), modes (used in a conversation), packages (started a conversation). Not available for lorebooks -- lorebooks have no direct "use" action that maps cleanly to a user relationship. |
Default: comments disabled. Creators opt in by enabling comments on each entity. This avoids surprising creators with a comment section they didn't ask for and ensures only creators who want engagement get it.
Markdown in Comments
Comments support a subset of markdown:
| Syntax | Renders as |
|---|---|
**bold** |
bold |
*italic* |
italic |
`inline code` |
inline code |
\|\|spoiler text\|\| |
Spoiler (hidden until clicked, Discord-style) |
No images, no links (spam prevention), no headings or block-level elements. Spoiler tags are essential for narrative-heavy entities like packages and characters where users may discuss plot points.
Who Can Comment
Subscription Tier
Commenting is available to all users, but with tier-based guardrails:
| Tier | Requirements | Rate Limits |
|---|---|---|
| Free | Verified email (or authenticated via Discord/Google OAuth) | ~5 comments/hour, ~20/day per entity |
| Pro | No additional requirements | ~20 comments/hour, ~100/day per entity |
The verified-email requirement for free users serves as a basic anti-spam gate. Users who signed up with Discord or Google and kept the address that account already confirmed are verified from the start; a linked account alone doesn't count.
Creators do not need Pro to enable comments on their entities -- this is a free feature for all creators.
Rate limit numbers are initial estimates and should be tuned based on actual usage patterns. The limits are per-entity to prevent a single user from flooding one comment section while still allowing normal activity across multiple entities.
Minimum Account Age
Creators can set a minimum account age (in days) for commenters on their entities. Default is 0 (no restriction). This lets creators of popular entities filter out throwaway accounts without requiring platform-wide policy.
Restriction Checks
A user cannot comment or react if any of the following apply:
- They are on the creator's blacklist
- They are under an active platform comment timeout (see Platform Moderation)
- Their account does not meet the entity's minimum account age
- They are not in the allowed audience group
- (Free tier) Their email is not verified and they did not use OAuth
When a user is prevented from commenting for any reason, the UI shows the same generic message:
"Oops, looks like you can't leave a comment on this right now."
This message is intentionally vague. It does not distinguish between blacklisting, audience restrictions, account age, or timeouts. This prevents users from deducing exactly why they're blocked (which would help them circumvent the restriction) while still being honest that something is preventing their comment.
Reporting is not blocked by restrictions. A blacklisted or timed-out user can still report comments -- the ability to flag abuse should not be gated by moderation status. Reports from restricted users are rate-limited (same as all users) to prevent abuse of the report system.
Creator Blacklist
Creators can blacklist specific users from commenting on their entities. A blacklisted user:
- Cannot post new comments or replies on any entity owned by that creator
- Cannot add reactions on any entity owned by that creator
- Existing comments remain visible (not retroactively hidden) unless the creator also hides them
- Sees the same generic "can't comment" message as any other restricted user
The blacklist is per-creator, not per-entity -- blocking a user blocks them across all of that creator's content. This prevents whack-a-mole moderation.
Identity and Anonymity
All comments are attributed to the user's public display name and avatar. There is no anonymous commenting and no option to comment under an alternate identity.
This is a deliberate design choice: anonymous comments dramatically lower the barrier for bad-faith content -- harassment, trolling, and drive-by negativity. When users know their identity is attached to their words, they self-moderate. Creators also need to know who is commenting to make meaningful moderation decisions (blacklisting an anonymous user accomplishes nothing).
Users who are uncomfortable commenting under their display name can choose not to comment. The platform's privacy stance is that public actions (comments, reactions) are public.
Threads and Replies
Comments support one level of nesting. A top-level comment can have replies, but replies cannot have their own replies. This keeps threads readable and avoids deeply nested UI.
Top-level comment (ParentCommentId = null)
├── Reply 1 (ParentCommentId = top-level)
├── Reply 2 (ParentCommentId = top-level)
└── Reply 3 (ParentCommentId = top-level)
Replies can @mention other users in the thread to direct conversation without introducing structural nesting. If a user replies to Reply 2, it still attaches to the top-level comment but the UI can show "replying to @username" context.
Thread Ordering
- Top-level comments: Newest first by default, with options for oldest-first and most-reacted.
- Replies within a thread: Always chronological (oldest first).
Creator Moderation
Creators have full moderation control over comments on their entities. These actions are available from a context menu on each comment.
Actions
| Action | Effect | Reversible |
|---|---|---|
| Hide | Sets comment status to hidden. Still visible to the creator in moderation view and to the commenter (marked as hidden). |
Yes -- creator can set back to visible |
| Highlight | Pins comment to the top of the comment section with visual emphasis. One entity can have multiple highlighted comments. | Yes -- creator can remove highlight |
| Report | Creates a CommentReport entry flagged as creator-reported for priority platform review. Does not change comment status -- creator should also hide if they want it removed from public view. |
No -- once reported, platform moderators handle it |
| Blacklist user | Adds the commenter to the creator's blacklist. Can be done from any comment by that user. | Yes -- creator can remove from blacklist |
| Approve | Sets a pending comment to visible. Only relevant when keyword filters or future AI checks hold a comment for review. |
N/A |
Moderation Dashboard
Creators can access a lightweight comment management view from their entity's edit page or from a dedicated section in the Creator's Forge. This view shows:
- All comments across the creator's entities, filterable by entity
- Filter by status: all, visible, hidden, pending, reported (join)
- Bulk actions: hide multiple comments, blacklist user from comment context
- Comment count and reaction summary per entity
- Keyword filter management (see Auto-Moderation)
- Pending comments queue (when keyword/AI filters hold comments)
Auto-Moderation
Manual moderation doesn't scale for popular creators. The system provides layered auto-moderation:
Keyword Filters
Two tiers of keyword filtering run on every comment before it's posted. This uses the same matching pattern as the existing platform moderation keyword checks -- whole-word, case-insensitive matching to avoid false positives on substrings (e.g., "ass" does not match "class" or "assistant").
| Level | Managed by | Scope |
|---|---|---|
| Global | Platform admins | Applies to all comments everywhere. Catches slurs, hate speech, platform-policy violations. |
| Creator | Entity creator | Additive -- creator adds terms specific to their content. E.g., a creator might block competitor names, off-topic terms, or spoiler keywords. |
When a comment triggers a keyword filter:
- The comment is not posted
- The user sees: "Your comment couldn't be posted. Please review and try again."
- No indication of which word triggered the filter (prevents probing)
- The attempt is logged for admin audit
Creator keyword filters are managed from the moderation dashboard and apply across all of that creator's entities.
AI Content Review (Future-Ready)
The auto-moderation pipeline is designed with a hook point for AI-based content review. The architecture should support:
Comment submitted
→ Keyword filter (global)
→ Keyword filter (creator)
→ [Future: AI content check]
→ Post comment
The AI check slot is a no-op initially but the pipeline stage exists in the code. When implemented, it would catch nuanced policy violations that keyword filters miss (context-dependent toxicity, coded language, etc.). The check should be async -- comments can post with pending status if the AI check is slow, and be auto-hidden if flagged.
This is design only -- no AI integration is built in v1. But the pipeline should not require restructuring to add it.
Notifications
All comment-related notifications are delivered through the existing notification system. Each notification has an event type that determines routing, display, and user preferences.
Event Types
| Event Type | Recipient | Description |
|---|---|---|
comment.new |
Entity creator | Someone posted a top-level comment on their entity |
comment.reply |
Parent comment author | Someone replied to their comment |
comment.reaction |
Comment author | Someone reacted to their comment |
comment.mention |
Mentioned user | Someone @mentioned them in a comment or reply |
comment.highlighted |
Comment author | Creator highlighted their comment |
Each event type is independently configurable in notification settings (see below). The event type is the key used for routing, filtering, and preference lookups -- there is no separate "creator vs commenter" split in the notification pipeline.
Notification Settings
Users configure comment notification preferences in their account settings. Every event type maps to a toggle:
| Setting | Default | Controls event type |
|---|---|---|
| New comments on my entities | On | comment.new |
| Replies to my comments | On | comment.reply |
| Reactions to my comments | On | comment.reaction |
| Mentions | On | comment.mention |
| Comment highlighted | On | comment.highlighted |
Additionally:
| Setting | Scope | Effect |
|---|---|---|
| Mute entity | Per entity (creator only) | Suppresses comment.new for a specific entity. Useful for popular entities that generate too much noise. |
| Mute thread | Per thread (any participant) | Suppresses comment.reply, comment.reaction, and comment.mention for a specific thread. Accessible from the thread context menu. |
Muting is additive -- muting a thread does not affect global settings, and unmuting restores notifications for that thread.
User Reporting
Any logged-in user can report a comment, regardless of whether they are otherwise restricted (blacklisted, timed out, etc.). The ability to flag abuse should not be gated by moderation status.
How It Works
- Report action is available in the context menu on every comment (same menu as reply, react)
- User selects a reason category from the existing
report_typeenum (Harmful, Spam, Misleading, Other) and optionally adds a text note - One report per user per comment (existing UNIQUE constraint on
reportsprevents duplicates) - After reporting, the user sees a confirmation: "Thanks for reporting. We'll review this."
- The comment remains visible unless a creator hides it or a moderator force-removes it
- Reports enter the existing moderation queue with the same NeedsReview → UnderReview → Resolved lifecycle
- On resolution, the reporter receives the same notification as other report types (
ReportResolved)
Report Priority
Reports are queued for platform moderator review via the existing vw_moderation_queue_items view. Priority is influenced by:
- Creator reports — computed via join:
reports.user_id = entity_owner_user_id(reporter owns the entity the comment belongs to). These get a priority boost in the queue view. No stored flag needed. - Report volume -- a comment with multiple reports surfaces faster
- Reporter history -- users with a history of accurate reports may have their reports weighted higher (future consideration)
Rate Limiting
Reports are rate-limited per user (10 reports/hour via IUserRateLimiter with reports.comment.per_hour limit key) to prevent weaponized mass-reporting. Same limit for all tiers.
Entity Lifecycle and Comments
When an Entity Is Unpublished
If a creator sets an entity to private or unlisted, its comments are no longer publicly accessible. The comments are not deleted -- they remain in the database tied to the entity. If the creator republishes the entity, comments reappear.
When an Entity Is Deleted
Entity deletion is soft-delete for most entity types. Comments on soft-deleted entities are no longer accessible through any public or creator-facing UI. They remain in the database and can be cleaned up by DB maintenance jobs later. No special cascade logic is needed at delete time.
Shared Entities
Comments are visible on shared entities according to the same view rights that govern the entity itself. If a user can see the entity via share token, they can see its comments. Whether they can post comments still depends on the audience rules and authentication requirements -- share-link viewers who are not logged in can read comments but not post.
Comment Counts and Public Profile
Browse / Hub Cards
Entity cards on browse and hub pages display a comment count icon alongside the existing favorite count. This serves as social proof and signals active community discussion.
♥ 142 💬 38
Comment count is sourced from a materialized view (same pattern as mv_user_stats for entity stats). Only visible comments are counted -- hidden and pending comments are excluded. The view is refreshed periodically, not on every write -- slight staleness is acceptable for social proof counts.
User Profile
Users can toggle a profile setting to show their comment activity publicly:
| Setting | Default | Effect |
|---|---|---|
| Show comment activity | Off | When enabled, the user's profile displays entities they've commented on and total comment count |
This is opt-in because some users may not want their comment history visible. When enabled, the profile shows a "Comments" section with recent comment activity.
API Design
Public Endpoints
GET /api/entities/{entityType}/{entityId}/comments # List comments (paginated)
POST /api/entities/{entityType}/{entityId}/comments # Post a comment
PATCH /api/comments/{commentId} # Edit own comment
DELETE /api/comments/{commentId} # Soft-delete own comment
POST /api/comments/{commentId}/reactions # Add reaction
DELETE /api/comments/{commentId}/reactions/{emoji} # Remove reaction
POST /api/reports # Report a comment (existing endpoint, entity_type=Comment)
Note: Comment reporting uses the existing /api/reports endpoint (ReportsEndpoints.cs) with entity_type = Comment. No separate report endpoint is needed.
Creator Endpoints
PATCH /api/comments/{commentId}/moderate # Hide/unhide/highlight/approve
GET /api/creator/comments # All comments on own entities (filterable)
GET /api/entities/{entityType}/{entityId}/comment-settings # Get comment settings
PUT /api/entities/{entityType}/{entityId}/comment-settings # Update comment settings
GET /api/creator/comment-settings # Unified settings load (blacklist, keyword filters, etc.)
POST /api/creator/comment-settings/blacklist/{slug} # Add to creator blacklist (by user slug)
DELETE /api/creator/comment-settings/blacklist/{slug} # Remove from creator blacklist (by user slug)
GET /api/creator/keyword-filters # List creator keyword filters
PUT /api/creator/keyword-filters # Update creator keyword filters
Admin Endpoints
GET /api/admin/comments/{commentId}/edit-history # View edit history
DELETE /api/admin/comments/{commentId} # Force-remove comment
GET /api/admin/keyword-filters # List global keyword filters
PUT /api/admin/keyword-filters # Update global keyword filters
POST /api/admin/comment-timeouts # Issue a comment timeout
GET /api/admin/comment-timeouts # List active timeouts
DELETE /api/admin/comment-timeouts/{timeoutId} # Lift a timeout early
Note: Reported comments appear in the existing admin moderation queue (/api/moderation/queue) filtered by entity_type = Comment. The queue view computes creator-report priority via join. No separate reported-comments endpoint is needed.
Pagination
Comment listing uses cursor-based pagination. The response includes:
- Top-level comments (paginated)
- First N replies per thread (collapsed beyond that, loadable on demand)
- Reaction summary per comment (emoji + count, whether current user reacted)
- Commenter display name and avatar
- Whether the current user has reported the comment
UI
Entity Detail Page
When comments are enabled on an entity, a "Comments" section appears below the entity description on the public detail page (hub / browse). The section shows:
- Comment count
- Comment input (if user is allowed to comment per audience/restriction rules)
- Generic restriction message if the user cannot comment
- Top-level comments with inline reply threads
- Highlighted comments pinned to the top
- Reaction bar below each comment
- Spoiler text rendered as blurred/hidden blocks (click to reveal)
- Report action in comment context menu (available to all logged-in users)
- "Load more" pagination for both top-level comments and long threads
When comments are disabled or the entity is private, the section is not rendered.
Comment box
- Markdown support: bold, italic, inline code, spoiler tags (
||spoiler||). - No images, no links (spam prevention).
- Character limit (to be determined, likely 2000 characters).
- @mention autocomplete for users in the thread.
- Edit window: comments can be edited within a time window after posting (e.g., 15 minutes). After that, they're locked. Edited comments show an "(edited)" indicator.
Creator Settings UI
On the entity edit page, a "Comments" settings section includes:
- Toggle: enable/disable comments
- Audience selector: everyone / followers / users (lorebooks only show everyone and followers)
- Minimum account age input (days, default 0)
- Link to comment moderation view
- Link to manage blacklist
- Link to manage keyword filters
Permissions and Access Control
| Action | Who can do it |
|---|---|
| View comments | Anyone who can view the entity (including share-link viewers) |
| Post comment | Logged-in users passing all restriction checks (audience, blacklist, timeout, account age, email verification) |
| React to comment | Same restriction checks as posting |
| Edit own comment | Comment author (within edit window), while they can still see the entity |
| Delete own comment | Comment author (soft delete) — even after the entity went private |
| Report comment | Any logged-in user (including restricted users), rate-limited |
| Hide/unhide comments | Entity creator |
| Highlight comments | Entity creator |
| Approve pending comments | Entity creator |
| Manage comment settings | Entity creator |
| Manage blacklist | Entity creator |
| Manage creator keyword filters | Entity creator |
| View comment edit history | Platform admins only |
| Force-remove comments | Platform moderators / admins |
| Issue comment timeouts | Platform moderators / admins |
| Manage global keyword filters | Platform admins |
Platform Moderation
Beyond creator-level moderation, platform moderators can:
- Review reported comments across all entities, prioritized by creator reports and report volume
- Force-remove comments that violate platform content guidelines
- View comment edit history to track abusive edit patterns
- Manage global keyword filters
- View moderation audit log (who reported, who acted, when)
Comment Timeout
Platform moderators can issue a comment timeout on a user's account:
| Field | Description |
|---|---|
| User | The target user |
| Duration | Time period (e.g., 1 hour, 24 hours, 7 days, 30 days, permanent) |
| Reason | Internal note (visible to admins, not to the user) |
| Scope | comments_only -- cannot post comments or reactions; public_presence -- additionally hidden from public-facing features (comment history, profile activity) |
| Issued by | Admin user ID |
| Expires at | Computed timestamp (null for permanent) |
A timed-out user:
- Cannot post comments or reactions on any entity
- Sees the same generic "can't leave a comment" message (indistinguishable from other restrictions)
- Can still report comments (reporting is never blocked)
- (
public_presencescope) Is hidden from comment activity on profiles, comment counts don't include their hidden comments - Existing comments remain visible unless individually hidden by creators or force-removed by admins
- Is automatically restored when the timeout expires
Timeouts integrate with the existing moderation system (moderation_reports admin area). The admin UI shows active timeouts with expiry countdowns and the ability to lift them early.
Implementation Considerations
Database
commentstable with the fields from the model above, indexed on(entity_type, entity_id, created_at)for listing and(parent_comment_id)for thread loading.- No
comment_reportstable — comment reports use the existingreportstable withentity_type = Comment(5). Creator-report priority is computed via join at query time, not stored. comment_edit_historytable for admin audit trail.comment_reactionstable with unique constraint on(comment_id, user_id, emoji).entity_comment_settingstable keyed on(entity_type, entity_id).creator_blackliststable keyed on(creator_user_id, blocked_user_id).comment_keyword_filterstable withscope('global' | 'creator'),creator_user_id(null for global), andkeywordtext. Uses same whole-word case-insensitive matching as existing moderation keyword checks.comment_timeoutstable withuser_id,scope,reason,issued_by,expires_at,created_at.- Materialized view for comment counts per entity (same approach as
mv_user_stats). Only countsvisiblecomments. Refreshed periodically — slight staleness is acceptable for browse/hub card counts. - Add
Comment = 5to theEntityTypeenum inEntityRegistry.csand the corresponding DB entity type value.
Rate Limiting
Comments use the generic per-user rate limiting system (Core/RateLimiting/). This system is in-memory with tier-aware limits resolved from fn_get_user_subscription_limit.
How it works:
- The
IUserRateLimiterservice is injected into the comments endpoint. - On comment/reaction submission, the endpoint calls
CheckAndIncrementAsyncwith the action and scope. - Limits are resolved from subscription tier limit keys (see below). Missing keys = no restriction.
- The in-memory store tracks counters per user/action/scope/time-window. Counters expire automatically.
- If the limit is exceeded, the endpoint returns HTTP 429 with
retryAfterset to the window reset time.
Subscription tier limit keys (added to 20a_seed_subscription_tiers.sql):
| Limit Key | Free | Pro | Description |
|---|---|---|---|
comments.post.per_hour |
5 | 20 | Comments per hour per entity |
comments.post.per_day |
20 | 100 | Comments per day per entity |
comments.react.per_hour |
30 | 100 | Reactions per hour (global) |
reports.comment.per_hour |
10 | 10 | Comment reports per hour (same for all tiers) |
Endpoint usage pattern:
// Hourly per-entity rate limit
var hourly = await rateLimiter.CheckAndIncrementAsync(
userId, "comments.post",
scope: $"entity_{entityType}_{entityId}",
RateLimitWindow.Hour);
if (!hourly.Allowed)
return Results.Json(new { error = "Rate limit exceeded", retryAfter = hourly.ResetsAt }, statusCode: 429);
// Daily per-entity rate limit (separate window)
var daily = await rateLimiter.CheckAndIncrementAsync(
userId, "comments.post",
scope: $"entity_{entityType}_{entityId}",
RateLimitWindow.Day);
if (!daily.Allowed)
return Results.Json(new { error = "Rate limit exceeded", retryAfter = daily.ResetsAt }, statusCode: 429);
Key design points:
- Scope isolation: Limits are per-entity — flooding one comment section doesn't block commenting elsewhere.
- Reactions use the same system with
"comments.react"action and global scope (no per-entity isolation needed for reactions). - Reports are rate-limited equally across tiers to prevent weaponized mass-reporting.
- In-memory storage: Counters don't survive restarts. This is intentional — rate limiting is a soft guardrail, not a billing meter. The
IRateLimitStoreinterface supports future DB-backed storage if multi-instance sync is needed. - Tier limit caching: The
SubscriptionLimitProvidercaches tier lookups for 5 minutes to avoid hitting the DB on every rate-limited request.
Auto-Moderation Pipeline
Comment submitted
→ Rate limit check (IUserRateLimiter — hourly + daily, per entity)
→ Account restrictions check (timeout, blacklist, audience, account age, email verification)
→ Keyword filter: global (whole-word, case-insensitive)
→ Keyword filter: creator (whole-word, case-insensitive)
→ [Future: AI content review hook — no-op in v1]
→ Post comment (status: visible)
→ Dispatch notifications
→ (Comment counts update on next materialized view refresh)
Performance
- Comment listings are read-heavy. Cache aggressively at the entity level, invalidate on new comment/reaction/moderation action.
- Reaction counts should be stored as a summary (JSONB or separate counter table) rather than computed on every read.
- Thread expansion (loading all replies) is a separate query, not part of the initial page load.
- Comment counts on browse/hub cards come from the materialized view, not live COUNT queries.
- Rate limit checks are in-memory with cached tier lookups — negligible latency impact on comment submission.
Content Safety
- Comments go through the auto-moderation pipeline before posting.
- Rate limiting enforced via
IUserRateLimiterwith tier-based thresholds (hourly + daily, per entity). - No images or links in comments to minimize abuse surface.
- Hidden comments are soft-hidden, not deleted -- preserves audit trail and allows unhiding.
- Edit history preserved for admin review to catch edit-based abuse.
- Report rate limiting prevents weaponized mass-reporting (same limit for all tiers).
Implementation Phases
The comments feature is sliced into independent phases that can be built, tested, and merged separately. Each phase delivers working infrastructure that sits inert until the final phase wires everything together.
Phase 0: Foundation (already done)
- Generic per-user rate limiting (
Core/RateLimiting/) — in-memory, tier-aware, scoped. Committed and registered in ServerAPI.
Phase 1: Creator Blacklist (done)
-
creator_blackliststable with UNIQUE constraint, CHECK(no self-block),fn_is_blacklistedhelper function -
ICreatorBlacklistRepository(Core) +CreatorBlacklistRepository(Database) +CreatorBlacklistService(Core, self-block validation) - Unified comment settings endpoint:
GET /api/creator/comment-settingsloads blacklist + keyword filters (+ stub for comment settings). Mutations:POST /DELETE /api/creator/comment-settings/blacklist/{slug}(slug-based, no integer IDs exposed) - User search endpoint:
GET /api/users/search?q=(ILIKE with wildcard escaping, excludes banned users) - Comments tab in Settings page (
/settings#comments) — Blocked Users (active), Keyword Filters (active), Comment Settings (coming soon) - Service unit tests (9) + repository integration tests (12)
What it unblocks: Comments restriction checks, future community board restrictions.
Phase 2: Creator Keyword Filters (done)
-
creator_keyword_filterstable:(creator_user_id, keyword, created_at)with UNIQUE constraint per creator -
fn_check_creator_keywords(creator_user_id, text)function — returns matched keywords using whole-word, case-insensitive matching with regex metacharacter escaping (unlike the globalfn_run_keyword_check, creator keywords are treated as literals) -
ICreatorKeywordFilterRepository(Core) +CreatorKeywordFilterRepository(Database, transactional bulk replace) +CreatorKeywordFilterService(Core, validation: trim, dedup case-insensitive, max 100 chars/keyword, max 200 keywords) - 2 endpoints in ServerAPI:
GET /api/creator/comment-settings/keyword-filters,PUT /api/creator/comment-settings/keyword-filters(bulk replace, returns cleaned list) - Unified
GET /api/creator/comment-settingsnow returns real keyword data (was stub[]) - Creator Settings UI: "Keyword Filters" section in Comments tab — textarea (one keyword per line), save button, active count
- Service unit tests (11) + repository integration tests (13)
What it unblocks: Auto-moderation pipeline's creator keyword filter stage.
Phase 3: Comment Timeouts (done)
-
comment_timeoutstable:(user_id, scope, reason, issued_by_user_id, expires_at, created_at)with scope enumcomments_only|public_presence -
IAdminCommentTimeoutRepository(Database) with admin CRUD (issue, lift, list with pagination/filtering/search, counts) + user check (CheckActiveTimeoutAsync) -
fn_has_active_comment_timeout(user_id)helper function — returns(has_timeout, scope, expires_at)or(FALSE, NULL, NULL) - 3 endpoints in AdminAPI:
POST /api/admin/comment-timeouts,GET /api/admin/comment-timeouts,DELETE /api/admin/comment-timeouts/{id} - Admin UI: timeout management in moderation section (list, issue, lift)
- Validation unit tests + repository integration tests
What it unblocks: Comments restriction checks, admin moderation workflow.
Phase 4: Notification Extensions (done)
-
NotificationTypeenum extended:CommentNew(10),CommentReply(11),CommentReaction(12),CommentMention(13),CommentHighlighted(14) — in both Core and Database enum definitions - Fixed
fn_create_notificationtype ID mappings (were incorrectly at 7/8, now at 10-14) - New settings keys:
CommentReaction,CommentMention,CommentHighlightedinSettingsKeys.cs,SettingsDefaults.cs, andclientConsole/settingKeys.ts -
notification_mutestable:(user_id, mute_type, target_type, target_id, created_at)with UNIQUE constraint, entity and thread mute types -
fn_create_notificationupdated to checknotification_mutesbefore inserting — suppresses types 10-13, preserves 14-15 (creator moderation actions always reach the user) -
INotificationMuteRepository(Database) +NotificationMuteRepository(Database, idempotent upsert/delete) -
NotificationMuteValidator(Core) — static validation for mute type and target type usingEntityRegistry - 3 endpoints in AuthService:
GET/POST/DELETE /api/notifications/muteswith string entity type names resolved to ints - Validation unit tests (13) + repository integration tests (10) + database function tests (9)
What it unblocks: All comment notification dispatch.
Phase 5: Entity Type + Comment Settings (done)
-
Comment = 12added toEntityTypeenum inEntityRegistry.cswith fullEntityDefinition -
entity_comment_settingstable:(entity_type, entity_id, comments_enabled, allowed_audience, min_account_age_days, updated_at)with UNIQUE on(entity_type, entity_id), CHECK constraints on audience and min age -
fn_get_comment_settings(entity_type, entity_id)— returns settings with safe defaults (disabled, everyone, 0) when no row exists -
IEntityCommentSettingsRepository(Core) +EntityCommentSettingsRepository(Database, upsert via ON CONFLICT) -
IEntityCommentSettingsService(Core) +EntityCommentSettingsService— validates 6 commentable entity types (Character, Mode, Lorebook, Creator, Package, Project), audience rules ("users" not available for Lorebook/Creator), min age 0–365 - 4 endpoints in ServerAPI: UUID-based GET/PUT
/api/entities/{entityType}/{entityId:guid}/comment-settingsfor characters, modes, lorebooks, packages, projects + slug-based GET/PUT/api/entities/creators/{slug}/comment-settingsfor creator profiles - Ownership enforcement: UUID entities via
ResolveOwnerIdAsync, creator profiles via self-check - Frontend:
CommentSettingsSectioncomponent (collapsible, collapsed by default) with toggle, audience select, min account age input, dirty tracking, save with toast feedback - Integrated into CharacterEditForm, ModeEditForm, LorebookEditForm (gated on
entityId && isPublic) - Service unit tests (20) + repository integration tests (10)
What it unblocks: The "can this user comment on this entity?" check.
Phase 6: Subscription Tier Limit Keys (done)
- Rate limit keys added to subscription tier seed data in
20_tables_subscriptions.sql:comments.post.per_hour: Free=5, Pro=20comments.post.per_day: Free=50, Pro=200comments.react.per_hour: Free=30, Pro=100reports.comment.per_hour: Free=10, Pro=10
- Database integration tests updated: count assertions and comment-specific spot-checks
What it unblocks: Rate limiting enforcement in comment endpoints.
Phase 7: Core Comments System (done)
- Database:
comments,comment_edit_history,comment_reactionstables,mv_entity_comment_countsmaterialized view,fn_can_user_comment,fn_get_entity_owner_id,fn_refresh_comment_counts - Repository:
ICommentRepository+CommentRepository— full CRUD, paginated listing with cursor support, batch replies, reactions, moderation actions, edit history, admin force-delete - Auto-moderation pipeline: Rate limits (Phase 0) → restriction checks (timeout/blacklist/audience/account age/email) → global keyword filter → creator keyword filter → post → notification dispatch
- API (ServerAPI): 10 endpoints — list comments, post, edit (15-min window), delete, add/remove reactions, moderate (hide/unhide/highlight/approve/delete), creator dashboard, entity summaries, load replies
- API (AdminAPI): Edit history retrieval, force-delete
- Notifications: Dispatch
comment.new,comment.reply,comment.reaction,comment.highlightedvia existing system (Phase 4), mute table checks, follow fan-out to entity/thread followers, auto-follow on reply - UI:
CommentsSection,CommentComposer(markdown hints, 2000 char limit),CommentItem(status badges, context menu, inline edit/reply),ReactionBar(6 emojis),RepliesList,CreatorCommentsList(moderation dashboard). Integrated into entity detail pages and share views. - Tests:
CommentServiceTests(688 lines),CommentRepositoryTests(260 lines),EntityCommentSettingsServiceTests(373 lines),CommentTimeoutValidationTests(138 lines),AdminCommentTimeoutRepositoryTests(325 lines)
Design decisions resolved: @mentions implemented in Phase 8 (global scope, slug-based format). Edit window: 15 minutes hardcoded (moderators exempt). Reaction emoji set: heart, thumbs_up, laugh, fire, thinking, star (hardcoded constant).
Phase 8: @Mentions ✅
- Mention format:
@[displayName](slug)stored in comment text — uses public-facing slugs (no numeric IDs), parseable by regex - Backend parser:
MentionParser.ParseMentions()with deduplication, 10-mention cap per comment - Slug resolution: Batch
GetUserIdsBySlugAsync()for efficient mention→userId lookup - Notification dispatch:
comment.mention(type 13) inDispatchCommentNotificationAsync, deduplicated with existing reply/follow/owner notifications vianotifiedHashSet - Autocomplete: Global user search via existing
GET /api/users/search?q=&limit=endpoint (not thread-scoped — any platform user can be mentioned, like Discord) - UI — CommentComposer:
@trigger detection, debounced search (300ms),MentionDropdownwith keyboard navigation (arrows, Enter, Tab, Escape), inserts@[displayName](slug)format - UI — MarkdownContent:
preprocessMentions()converts@[name](slug)to styled<span class="mention">elements, clickable via react-router navigation to/creator/{slug} - Tests:
MentionParserTests(11 tests),CommentServiceTestsmention notification suite (7 tests covering dispatch, deduplication, self-mention, unknown slugs, cap at 10)
Future Considerations
- Notification batching/digest -- Popular entities can generate hundreds of notifications. A digest mode ("3 new comments on your character since yesterday") would reduce noise without losing signal. This is important and should be designed as part of a broader notification system overhaul, not comments-specific.
- AI content review -- Hook point exists in the pipeline. When implemented, would catch nuanced violations that keyword filters miss. Comments would post as
pendingand auto-resolve or auto-hide. - Reporter reputation weighting -- Users with a history of accurate reports could have their reports weighted higher in the moderation queue.
- Verified user badges on comments from users who have extensive experience with the entity
- Creator responses -- visually distinct replies from the entity creator
- Comment voting (upvote/downvote) as an alternative or complement to emoji reactions
- Comment search within an entity's comment section
- Pinned creator announcement -- a special top comment slot for creator updates distinct from highlighted comments
- Cross-entity comment view on creator profiles -- "latest comments on my content" as a profile section (ties into Profile Customization)
Open follow-ups (knowledge review, 2026-09-29)
pendinghas no writer, so creator Approve is unreachable. Both planned writers went another way: keyword filters reject outright (see Keyword Filters), and AI review shipped holding comments asflaggedfor the platform-admin queue — deliberately notpending, which is creator-reviewed (internal design doc:COMMENT_AI_MODERATION.md, "Why admin-level, not creator-level"). No code path sets a comment topending, yet it is still carried end to end: thecomments.statusCHECK and the owner-only visibility branch (database/v1/functions/11g_comment_functions.sql:480),CommentServiceapprove(server/EchoOfDreams.ServerAPI/Services/CommentService.cs:451), the admin approve path (AdminCommentsEndpoints.cs:228) and the creator menu's Approve item (clientConsole/src/components/comments/CreatorCommentsList.tsx:231). Decide: build a writer (a creator "hold new comments for my approval" comment setting — the natural home is Entity Comment Settings), or retirependingacross the stack.-
pendingeither has a real writer reachable from the creator's comment settings, or is removed from the CHECK, the visibility function, both approve paths and the creator menu.
-
Acceptance Criteria
Scoped to thread visibility — the rules in Entity Lifecycle and Comments and the "View comments" row of Permissions and Access Control. Until 2026-09-24 the comment routes resolved the entity and never asked whether the caller could see it, so anyone holding a private entity's id could read and post its thread. The gate is fn_comment_target_visibility (the per-kind rule, mirroring each detail page) plus CommentTargetGate (share links, applied through EntityAccessAuthorizer).
User use cases — satisfiable + accessible:
- As a signed-in reader who opened a private character through a share link, I can read and post in its comment thread from that page, the same way the page itself opens for me.
- As the owner of a private character, I can read and post in its thread and change its comment settings.
- As a collaborator with a direct grant (view, or use-only) or project membership, I can read and post in the thread of the private entity I was given.
Behavior:
- Every thread route asks the gate first: list, post, replies, add reaction, edit, and the comment-settings read and write.
- A share link opens only the thread of the entity it was minted for; a link for another entity changes nothing.
- The anonymous-reachable reads (list, replies) judge a guest token as anonymous, never as its shadow user.
Invariants that must stay true:
- Public (effectively public: approved and past any scheduled release) threads stay readable to every signed-in reader.
- Signed-out and guest readers get exactly what the entity's page gives them: a published blog post's thread (and an anonymously-viewable project's or creator profile's); a character / mode / lorebook thread only through that entity's own share link; a package or conversation thread not at all. "Public" here is the signed-in catalog, not the guest zone.
- Only the thread's audience hears about it: reply, follow, mention, reaction and highlight notifications go only to recipients who can still see the thread on their own account, so a follow that outlived its access stops delivering the thread's comment ids.
- A private entity's thread answers a stranger with the same 404 body as an entity that does not exist — on list and post alike; a comment on it answers the same 404 as a comment that does not exist.
- Security lorebooks, system lorebooks, soft-deleted entities, and static pages are never a thread — not even for their author, and not through a share link.
- Withdrawing your own words keeps working after a thread goes private: deleting your comment and removing your reaction are not gated.
- Those ungated routes (delete, remove reaction, moderate) still don't leak: their "not yours" 403 — or an un-react that removed nothing — goes only to a caller who can see the thread; anyone else gets the missing-comment 404.
- A reply naming a parent comment on another entity is refused exactly like a missing parent.
- A comment can be followed or muted, and is named on the notification settings page, only by someone who can see its thread; its author always sees their own comment named. A follow made before access was lost stays listed (and removable) but unnamed.
- Thread follows and thread mutes are keyed by the thread's root comment, so the settings page names a thread by its opening, and muting a thread silences replies, reactions and mentions in it (and nothing else on the entity).
- The settings write keeps its 403 for a caller who can see the entity but does not own it; a caller who cannot see it gets the 404.
Edges:
- A package, conversation or blog post that is not public is visible only to its owner (no share link exists for those kinds); a conversation must also be approved before strangers see its thread.
- A private project follows the project profile's own gate (owner, accepted member, catalog-listed or anonymously viewable), plus its share link.