From 4d2c241edd89615a57fc068cfb97316819598b4a Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:32 -0500 Subject: [PATCH 01/12] docs: update knowledge base for guild aliases --- KNOWLEDGE_BASE.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index c86097248..c6650e490 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -594,8 +594,8 @@ A signed request sees what the web shows you, such as your own pending commits a - follow or unfollow people and organizations, mute or unmute, and block or unblock, and list who you muted and blocked; - read who to follow, also as it is suggested beside a profile or a commit, and mark a suggestion not interested; - read the hot topics, and each one's commits from the past week with its recap; -- list guilds as the Guilds page does, 24 a page, searched by name, handle or description, with whether you joined or muted each one and whether it is paused, while guilds are available to you; -- read a guild's board as its page does, 30 threads a page with reply previews, with the guild, its pinned commit and whether you moderate it, while guilds are available to you. The pinned commit also keeps its place in the list, so an app that shows it apart skips it there by its id; +- list guilds as the Guilds page does, 24 a page, searched by name, handle, alias or description, with each guild's aliases, whether you joined or muted each one and whether it is paused, while guilds are available to you; +- read a guild's board as its page does, by its handle or one of its aliases, 30 threads a page with reply previews, with the guild, its pinned commit and whether you moderate it, while guilds are available to you. The pinned commit also keeps its place in the list, so an app that shows it apart skips it there by its id; - star or unstar, and list who starred your own commit, newest first, 20 a page; - create polls on commits that are neither replies nor quotes, and vote on polls; - change Remotes settings, read and send messages with images, link cards, and voice notes in conversations and orgs, mark them pulled, react to messages and list your reactions, pin and unpin org messages as a maintainer, find people, and start orgs; @@ -652,7 +652,7 @@ Sources: [issue command UI](resources/js/components/issue-command.tsx), [issue v Guilds are public groups around hashtags and are not generally available yet. In the preview, matching hashtags become small clickable guild labels; ordinary hashtags still open search. Create a guild from the Guilds overview or a hashtag's search page. From the overview, its display name determines the hashtag: “Laravel 4ever” becomes `#laravel4ever`. Display names and handles each allow up to 60 characters. When claiming a hashtag, the display name must match its letters, numbers and underscores, ignoring case; spaces, punctuation and decorative symbols are ignored, so `/dev/null` is valid for `#devnull`. Accents and underscores remain significant. Its creator joins automatically and maintains its display name, icon and description; a new display name must still match the hashtag, so `#adhd` can become “ADHD” but never another hashtag. Each person can create up to 100 guilds. A guild's name, description and icon pass the same automated moderation as commits before the guild is published or edited. When the moderation flags a new guild or an edit, it waits for an admin to review it instead: nothing of it is public until it is approved, the guild keeps its current details meanwhile, and a rejected submission is discarded. Submitting again for the same hashtag replaces the one still waiting, and new guilds waiting for review count toward the creation limit. -The Guilds page lists groups by member count, with 24 guilds per page. Search matches keywords in guild names, handles, and descriptions, ignoring case; a leading `#` is optional. This directory search is keyword-based, not semantic. Click a guild's member count to browse its members: the moderator appears first, labeled “(moderator)”, followed by newest joins, with 50 people per page and Load more for the next page. Joining adds matching commits to Following without following every author and clears any existing mute. When a commit appears only because of a joined guild, it says “because you joined” beside the guild label. Leave a guild to reveal its Mute control. Muting hides matching commits from logs and search, including commits by followed authors. You can still open the guild or a commit directly. +The Guilds page lists groups by member count, with 24 guilds per page. Search matches keywords in guild names, handles, aliases, and descriptions, ignoring case; a leading `#` is optional. This directory search is keyword-based, not semantic. Click a guild's member count to browse its members: the moderator appears first, labeled “(moderator)”, followed by newest joins, with 50 people per page and Load more for the next page. Joining adds matching commits to Following without following every author and clears any existing mute. When a commit appears only because of a joined guild, it says “because you joined” beside the guild label. Leave a guild to reveal its Mute control. Muting hides matching commits from logs and search, including commits by followed authors. You can still open the guild or a commit directly. The guilds you joined are listed in the left navigation, with the guilds that have the most commits you missed first. Guilds with the same number of missed commits are ordered by how much you have committed in them, counting your recent approved commits. The count of missed commits starts from your last visit to the guild's board, or from when you joined, and leaves out your own commits, commits you cannot see, and commits by people you muted. Counts above 99 show as 99+, and a muted guild is not listed. Opening a board clears its count, and a line marks where the commits that are new since your last visit end. @@ -660,6 +660,8 @@ While guilds are available to you, profiles show a guild count beside following Each guild's bulletin board shows commits posted directly to it and regular commits containing its exact hashtag—not semantic search. Matching replies bring their thread onto the board, even when the root has no hashtag. Threads show reply previews and expand like a regular commit log, ordered by root date, newest first. Each page contains 30 distinct root commits; replies do not use up that limit, and Load more adds the next page. Posts from the board's composer stay attached to that guild without an automatic hashtag, including scheduled posts. They count toward the author's commit count but do not appear in their profile log or general feeds. Outside the board, such as when one is opened by its link, a board post names the guild it was posted in and notes that it is not shown in general logs. They appear in Following when you join the guild, and in semantic search suggestions and results under a divider with the guild's name and icon. Regular hashtag commits keep appearing on profiles and in feeds as usual. Typing a hashtag offers matching guilds in the autocomplete menu; select one with the keyboard or pointer to insert its handle. +A guild's moderator can add aliases from its page: other hashtags that lead to the same guild. With `#golang` as an alias of `#go`, both hashtags show the guild's label, commits containing either appear on its board and count for joining, muting and missed commits, and `/guilds/golang` opens the same guild. An alias follows the rules of a handle: it starts with a letter, contains only letters, numbers and underscores, and allows up to 60 characters. It must be a free hashtag: one that is already a guild, including a paused guild, or already an alias of any guild cannot be used, and nobody can create a guild for a hashtag that is an alias. Each guild can have up to 10 aliases, and each passes the same automated moderation as commits; one that is flagged is refused. Aliases are listed beside the hashtag on the guild's page, the hashtag autocomplete finds a guild by an alias and inserts its handle, and the directory search matches them. The moderator can remove an alias at any time, which takes commits that only carry that hashtag off the board. Aliases stay with a paused guild. + The guild's moderator can pin one commit from its board, including a thread brought in by a matching reply. It appears first with a “Pinned to board” label, without appearing twice or changing profile pins or other guilds. The pin is separate from the 30 chronological threads per page, so pinning never changes what Load more brings in. Pinning another replaces it; unpinning restores its natural position if already loaded, or removes its promotion until you load that older page. A pin never overrides visibility, blocks or author mutes, and disappears from the board if the thread no longer matches the guild. Permanently deleting the pinned commit clears the pin. Guild descriptions can be reported privately. When a guild has no moderator, including after its moderator deletes their account, it is paused, not deleted. Its page, posts, icon, description, memberships and mute preferences stay connected. New board posts wait until it has a moderator; scheduled board posts stay pending and keep their guild, and committing one now says the guild is paused. Ordinary hashtag commits still appear. A different person can claim the hashtag to resume the same guild, but a removed moderator cannot reclaim it. @@ -672,7 +674,7 @@ Choose **Download JSON** in Settings → Profile to export your account data. Th - the days you used /dev/null (dates, not times), oldest first, with which of its apps you used on each (days before apps were tracked say web, whatever you used, and a phone approved before the mobile app started identifying itself says other), and the last of them; - your commits and replies (including pending, rejected, and deleted entries still stored), their cached translations, polls, and your votes; - stars, followers and people you follow, mutes, blocks, and dismissed **Not interested** suggestions; -- guilds you moderate, guilds and guild edits you submitted that are waiting for review, your guild memberships and mutes, reports you submitted, and guild moderator-removal records relating to your account; +- guilds you moderate with their aliases, guilds and guild edits you submitted that are waiting for review, your guild memberships and mutes, reports you submitted, and guild moderator-removal records relating to your account; - messages you sent, including links to your voice notes, and notifications; - SSH key fingerprints, approved devices, timeout history, and ban history; - active-session metadata: IP address, browser information, and last activity. From a508a553d4e0c5da10fe6ee366b35b2c9e04b26d Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:28 -0500 Subject: [PATCH 02/12] test: add frontend tests for guild aliases --- tests/Unit/GuildControls.test.tsx | 29 +++++++++++++++++++ tests/Unit/Guilds.test.ts | 21 ++++++++++++++ tests/Unit/LinkifiedText.test.tsx | 16 +++++++++-- tests/Unit/OrgMentionSuggestions.test.tsx | 35 ++++++++++++++++++++++- 4 files changed, 97 insertions(+), 4 deletions(-) create mode 100644 tests/Unit/Guilds.test.ts diff --git a/tests/Unit/GuildControls.test.tsx b/tests/Unit/GuildControls.test.tsx index 31d29ee29..6cbcef199 100644 --- a/tests/Unit/GuildControls.test.tsx +++ b/tests/Unit/GuildControls.test.tsx @@ -18,6 +18,7 @@ vi.doMock('@inertiajs/react', async () => ({ { id: 'guild-id', handle: 'rust', + aliases: [], name: 'Rust', is_joined: true, }, @@ -60,6 +61,8 @@ const { default: GuildBoard } = await import('../../resources/js/pages/guild/show'); const { CommitCard } = await import('../../resources/js/components/commit-card'); +const { GuildAliasesButton } = + await import('../../resources/js/components/guild-aliases'); const { GuildDialog } = await import('../../resources/js/components/guild-dialog'); const { GuildPreferences } = @@ -181,6 +184,32 @@ test('clears the missed commits of a joined guild when its board opens', () => { assert.deepEqual(put.mock.calls[0][2].only, ['joinedGuilds']); }); +test('removes an alias optimistically from its own guild only', () => { + const remove = vi.fn(); + const optimistic = vi + .spyOn(router, 'optimistic') + .mockReturnValue({ delete: remove } as unknown as typeof router); + const guild = { + id: 'guild-id', + handle: 'go', + aliases: ['golang', 'gopher'], + } as Guild; + const other = { id: 'other', handle: 'rust', aliases: ['golang'] } as Guild; + + const button = elements(GuildAliasesButton({ guild })).find( + (element) => element.props['aria-label'] === 'Remove #golang', + )!; + (button.props.onClick as () => void)(); + + const update = optimistic.mock.calls[0][0] as (props: { + guilds: Guild[]; + }) => unknown; + assert.deepEqual(update({ guilds: [guild, other] }), { + guilds: [{ id: 'guild-id', handle: 'go', aliases: ['gopher'] }, other], + }); + assert.equal(remove.mock.calls[0][0], '/guilds/go/aliases/golang'); +}); + test('changes only the pin optimistically and prevents pin and load-more requests from overlapping', () => { const commit = { id: 'target' } as Commit; const view = () => { diff --git a/tests/Unit/Guilds.test.ts b/tests/Unit/Guilds.test.ts new file mode 100644 index 000000000..fa76b229b --- /dev/null +++ b/tests/Unit/Guilds.test.ts @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { guildFor } from '../../resources/js/lib/guilds.ts'; + +const guilds = [ + { handle: 'go', aliases: ['golang', 'gopher'] }, + { handle: 'rust', aliases: [] }, +]; + +await test('finds a guild by its handle or by one of its aliases', () => { + assert.equal(guildFor(guilds, 'go'), guilds[0]); + assert.equal(guildFor(guilds, 'golang'), guilds[0]); + assert.equal(guildFor(guilds, 'gopher'), guilds[0]); + assert.equal(guildFor(guilds, 'rust'), guilds[1]); +}); + +await test('finds no guild for a hashtag nobody claimed, or without the guilds', () => { + assert.equal(guildFor(guilds, 'golanguage'), undefined); + assert.equal(guildFor(null, 'go'), undefined); + assert.equal(guildFor(undefined, 'go'), undefined); +}); diff --git a/tests/Unit/LinkifiedText.test.tsx b/tests/Unit/LinkifiedText.test.tsx index e8b14424a..80d5cf26d 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -108,7 +108,7 @@ test('renders only matching prose hashtags as guilds when the preview is availab const content = ( @@ -119,6 +119,7 @@ test('renders only matching prose hashtags as guilds when the preview is availab guilds: [ { handle: 'jobs', + aliases: ['work'], name: 'Job Board', description: 'Hiring', emoji: '💼', @@ -127,8 +128,9 @@ test('renders only matching prose hashtags as guilds when the preview is availab ], }); - assert.equal((markup.match(/href="\/guilds\/jobs"/g) ?? []).length, 1); + assert.equal((markup.match(/href="\/guilds\/jobs"/g) ?? []).length, 2); assert.match(markup, /aria-label="Job Board, #JoBs guild"/); + assert.match(markup, /aria-label="Job Board, #Work guild"/); assert.match(markup, /href="\/search\?q=%23rust"/); assert.match(markup, /]*>#jobs<\/code>/); assert.match(markup, /href="https:\/\/example.com\/#jobs"/); @@ -787,7 +789,15 @@ test('gives a bare hex-shaped hashtag its guild or search link and renders an ex const auth = { user: { id: 'viewer' }, pasteis: null }; const html = renderPage(content, { auth, - guilds: [{ handle: 'dead', name: 'Dead', emoji: '💻', icon_url: null }], + guilds: [ + { + handle: 'dead', + aliases: [], + name: 'Dead', + emoji: '💻', + icon_url: null, + }, + ], }); assert.equal((html.match(/href="\/guilds\/dead"/g) ?? []).length, 1); diff --git a/tests/Unit/OrgMentionSuggestions.test.tsx b/tests/Unit/OrgMentionSuggestions.test.tsx index 65102d241..8a82e9f3b 100644 --- a/tests/Unit/OrgMentionSuggestions.test.tsx +++ b/tests/Unit/OrgMentionSuggestions.test.tsx @@ -108,6 +108,7 @@ test('suggests loaded guilds and inserts a hex-shaped hashtag without fetching', ({ id: handle, handle, + aliases: [] as string[], name: handle, emoji: '💻', icon_url: null, @@ -142,6 +143,31 @@ test('suggests loaded guilds and inserts a hex-shaped hashtag without fetching', assert.equal(fetchMock.mock.calls.length, 0); }); +test('suggests a guild by one of its aliases', () => { + guilds = [ + { + id: 'laravel', + handle: 'laravel', + aliases: ['artisan'], + name: 'Laravel', + emoji: '💻', + icon_url: null, + } as Guild, + ]; + state[0] = { kind: 'guild', start: 6, query: 'ART' }; + cursor = 0; + effects = []; + const fields = elements( + MentionTextarea({ value: 'Hello #ART', onValueChange: () => {} }), + ); + assert.deepEqual( + fields + .filter((element) => element.props.role === 'option') + .map((option) => option.props.id), + ['mentions-guild-laravel'], + ); +}); + test('does not suggest guilds inside code, URLs, partial handles or when preview data is absent', () => { for (const value of [ '`#rust', @@ -152,7 +178,14 @@ test('does not suggest guilds inside code, URLs, partial handles or when preview '##rust', 'color(#dead', ]) { - guilds = [{ id: 'rust', handle: 'rust', name: 'Rust' } as Guild]; + guilds = [ + { + id: 'rust', + handle: 'rust', + aliases: [] as string[], + name: 'Rust', + } as Guild, + ]; cursor = 0; state[0] = null; const fields = elements( From bcf7ec73207622d03c38924362d57eb5a4515fe1 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:25 -0500 Subject: [PATCH 03/12] feat: integrate guild aliases into frontend components --- resources/js/components/guild-aliases.tsx | 134 +++++++++++++++++++ resources/js/components/linkified-text.tsx | 6 +- resources/js/components/mention-textarea.tsx | 3 + resources/js/pages/guild/show.tsx | 13 ++ resources/js/pages/search/index.tsx | 5 +- 5 files changed, 155 insertions(+), 6 deletions(-) create mode 100644 resources/js/components/guild-aliases.tsx diff --git a/resources/js/components/guild-aliases.tsx b/resources/js/components/guild-aliases.tsx new file mode 100644 index 000000000..1fea0e459 --- /dev/null +++ b/resources/js/components/guild-aliases.tsx @@ -0,0 +1,134 @@ +import { Form, router } from '@inertiajs/react'; +import { Plus, X } from 'lucide-react'; +import { + destroy, + store, +} from '@/actions/App/Http/Controllers/GuildAliasController'; +import InputError from '@/components/input-error'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { Label } from '@/components/ui/label'; +import type { Guild } from '@/types/guild'; + +export function GuildAliasesButton({ guild }: { guild: Guild }) { + function remove(alias: string) { + router + .optimistic<{ guilds: Guild[] | null }>((props) => ({ + guilds: props.guilds?.map((item) => + item.id === guild.id + ? { + ...item, + aliases: item.aliases.filter( + (other) => other !== alias, + ), + } + : item, + ), + })) + .delete(destroy.url({ guild: guild.handle, alias }), { + preserveScroll: true, + onSuccess: () => router.flushAll(), + }); + } + + return ( + + + + + + + Aliases of #{guild.handle} + + An alias is another hashtag that leads here: commits + with it appear on this board, and it links to this + guild. A hashtag that already has a guild cannot be an + alias. + + +
    + {guild.aliases.map((alias) => ( +
  • + + #{alias} + + +
  • + ))} + {guild.aliases.length === 0 && ( +
  • + No aliases yet. +
  • + )} +
+
router.flushAll()} + resetOnSuccess + > + {({ errors, processing }) => ( + <> + +
+ + +
+
+ +
+ + )} +
+
+
+ ); +} diff --git a/resources/js/components/linkified-text.tsx b/resources/js/components/linkified-text.tsx index 38fe900d7..24e86b4a5 100644 --- a/resources/js/components/linkified-text.tsx +++ b/resources/js/components/linkified-text.tsx @@ -16,6 +16,7 @@ import { UserPreview } from '@/components/user-preview'; import { typedProse, withoutCode } from '@/lib/code'; import type { Color } from '@/lib/colors'; import { colorsIn } from '@/lib/colors'; +import { guildFor } from '@/lib/guilds'; import { hashtagPattern } from '@/lib/hashtags'; import { mentionPattern } from '@/lib/mentions'; import { pasteisParts } from '@/lib/pasteis'; @@ -635,10 +636,7 @@ export function Hashtag({ }) { const { auth, guilds } = usePage().props; const guild = - postedGuild ?? - guilds?.find( - (guild) => guild.handle === hashtag.slice(1).toLowerCase(), - ); + postedGuild ?? guildFor(guilds, hashtag.slice(1).toLowerCase()); if (guild) { const canOpenGuild = !!auth.user && !!guilds; diff --git a/resources/js/components/mention-textarea.tsx b/resources/js/components/mention-textarea.tsx index aa6a06bfe..d3a9b0932 100644 --- a/resources/js/components/mention-textarea.tsx +++ b/resources/js/components/mention-textarea.tsx @@ -516,6 +516,9 @@ export function MentionTextarea({ .filter( (guild) => guild.handle.includes(guildQuery) || + guild.aliases.some((alias) => + alias.includes(guildQuery), + ) || guild.name.toLowerCase().includes(guildQuery), ) .toSorted( diff --git a/resources/js/pages/guild/show.tsx b/resources/js/pages/guild/show.tsx index cbadaf590..9339f6dfc 100644 --- a/resources/js/pages/guild/show.tsx +++ b/resources/js/pages/guild/show.tsx @@ -10,6 +10,7 @@ import { CommitComposer } from '@/components/commit-composer'; import { EmptyFeed } from '@/components/commit-feed'; import { GraphCanvas } from '@/components/graph-canvas'; import { RailSegment } from '@/components/graph-rail'; +import { GuildAliasesButton } from '@/components/guild-aliases'; import { GuildDialog } from '@/components/guild-dialog'; import { GuildIcon } from '@/components/guild-icon'; import { @@ -175,6 +176,8 @@ export default function Show({ ); } + const aliases = guild.aliases.map((alias) => `#${alias}`).join(' '); + return ( <> @@ -213,6 +216,15 @@ export default function Show({ #{handle} + {aliases && ( + + also {aliases} + + )} · {guild.is_paused @@ -227,6 +239,7 @@ export default function Show({

{!canModerate && } + {canModerate && } {auth.isAdmin && !guild.is_paused && ( )} diff --git a/resources/js/pages/search/index.tsx b/resources/js/pages/search/index.tsx index d1782d8b1..9198154df 100644 --- a/resources/js/pages/search/index.tsx +++ b/resources/js/pages/search/index.tsx @@ -14,6 +14,7 @@ import { rememberSearch, useRecentSearches } from '@/hooks/use-recent-searches'; import AppLayout from '@/layouts/app-layout'; import { searchCommits } from '@/lib/commit-search'; import { CommitSearchResults } from '@/lib/commit-search-results'; +import { guildFor } from '@/lib/guilds'; const skeletonDelay = 300; @@ -159,7 +160,7 @@ function HashtagGuild({ term }: { term: string }) { return null; } - const guild = guilds.find((guild) => guild.handle === handle); + const guild = guildFor(guilds, handle); return (
@@ -175,7 +176,7 @@ function HashtagGuild({ term }: { term: string }) {
From eada1e5fb6fd028aee3bb372408e4457f70e34d7 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:22 -0500 Subject: [PATCH 04/12] feat: update frontend types and utility for guild aliases --- resources/js/lib/guilds.ts | 13 +++++++++++++ resources/js/types/guild.ts | 1 + 2 files changed, 14 insertions(+) create mode 100644 resources/js/lib/guilds.ts diff --git a/resources/js/lib/guilds.ts b/resources/js/lib/guilds.ts new file mode 100644 index 000000000..180142b24 --- /dev/null +++ b/resources/js/lib/guilds.ts @@ -0,0 +1,13 @@ +import type { Guild } from '@/types/guild'; + +/** + * The guild a hashtag leads to: the one with that handle, or with it as an alias. + */ +export function guildFor>( + guilds: T[] | null | undefined, + handle: string, +): T | undefined { + return guilds?.find( + (guild) => guild.handle === handle || guild.aliases.includes(handle), + ); +} diff --git a/resources/js/types/guild.ts b/resources/js/types/guild.ts index a91f59c26..141da73f1 100644 --- a/resources/js/types/guild.ts +++ b/resources/js/types/guild.ts @@ -1,6 +1,7 @@ export type Guild = { id: string; handle: string; + aliases: string[]; name: string; description: string; emoji: string; From 3b409cbe296470e455bd9c6336bfd6ac35456316 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:19 -0500 Subject: [PATCH 05/12] test: add backend tests for guild aliases --- .../Controllers/Api/GuildControllerTest.php | 27 +- .../Controllers/ExportControllerTest.php | 7 +- .../Controllers/GuildAliasControllerTest.php | 235 ++++++++++++++++++ tests/Unit/Queries/GuildCommitsQueryTest.php | 17 ++ tests/Unit/Queries/JoinedGuildsQueryTest.php | 13 + 5 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 tests/Feature/Controllers/GuildAliasControllerTest.php diff --git a/tests/Feature/Controllers/Api/GuildControllerTest.php b/tests/Feature/Controllers/Api/GuildControllerTest.php index e8e8a88ef..58af4af4b 100644 --- a/tests/Feature/Controllers/Api/GuildControllerTest.php +++ b/tests/Feature/Controllers/Api/GuildControllerTest.php @@ -7,6 +7,7 @@ use App\Enums\Feature; use App\Models\Commit; use App\Models\Guild; +use App\Models\GuildAlias; use App\Models\User; use App\Queries\GuildsQuery; use App\Services\Features; @@ -20,6 +21,8 @@ it('lists guilds by member count then handle, with whether the user joined or muted each one', function (): void { $rust = Guild::factory()->create(['handle' => 'rust', 'name' => 'Rust', 'description' => 'Fearless concurrency', 'emoji' => '🦀', 'icon_path' => 'guild-icons/rust.webp']); + GuildAlias::factory()->for($rust)->create(['handle' => 'rustlang']); + GuildAlias::factory()->for($rust)->create(['handle' => 'rs']); Guild::factory()->create(['handle' => 'go', 'user_id' => null]); $php = Guild::factory()->create(['handle' => 'php']); resolve(UpdateGuildMembership::class)->handle($this->user, $rust, true); @@ -32,6 +35,7 @@ ->assertJsonPath('data.*.handle', ['rust', 'php', 'go']) ->assertJsonPath('data.0', [ 'handle' => 'rust', + 'aliases' => ['rs', 'rustlang'], 'name' => 'Rust', 'description' => 'Fearless concurrency', 'emoji' => '🦀', @@ -43,6 +47,7 @@ 'html_url' => route('guild.show', 'rust'), ]) ->assertJsonStructure(['data' => ['*' => ['icon_url']]]) + ->assertJsonPath('data.1.aliases', []) ->assertJsonPath('data.1.icon_url', null) ->assertJsonPath('data.1.is_joined', false) ->assertJsonPath('data.1.is_muted', true) @@ -50,15 +55,17 @@ ->assertJsonPath('data.2.is_paused', true); }); -it('finds guilds by handle, name or description, ignoring case and a leading hashtag', function (string $query): void { - Guild::factory()->create(['handle' => 'laravel', 'name' => 'Artisans', 'description' => 'Elegant web apps']); - Guild::factory()->create(['handle' => 'symfony', 'name' => 'Symfony', 'description' => 'Components']); +it('finds guilds by handle, alias, name or description, ignoring case and a leading hashtag', function (string $query): void { + $laravel = Guild::factory()->create(['handle' => 'laravel', 'name' => 'Artisans', 'description' => 'Elegant web apps']); + GuildAlias::factory()->for($laravel)->create(['handle' => 'eloquent']); + GuildAlias::factory()->for(Guild::factory()->create(['handle' => 'symfony', 'name' => 'Symfony', 'description' => 'Components']))->create(['handle' => 'twig']); signedApiRequest($this->keyPair, 'GET', route('api-guild.index', ['q' => $query])) ->assertOk() ->assertJsonPath('data.*.handle', ['laravel']); })->with([ 'handle' => '#LARAVEL', + 'alias' => '#Eloquent', 'name' => 'artisans', 'description' => 'elegant', ]); @@ -129,6 +136,20 @@ ->assertJsonPath('can_moderate', false); }); +it('shows a guild by its alias, with the commits tagging the alias on its board', function (): void { + $go = Guild::factory()->create(['handle' => 'go']); + GuildAlias::factory()->for($go)->create(['handle' => 'golang']); + $aliased = Commit::factory()->create(['body' => 'Learning #GoLang']); + Commit::factory()->create(['body' => 'Learning #golanguage']); + + signedApiRequest($this->keyPair, 'GET', route('api-guild.show', 'golang')) + ->assertOk() + ->assertJsonPath('data.*.id', [$aliased->id]) + ->assertJsonPath('guild.handle', 'go') + ->assertJsonPath('guild.aliases', ['golang']) + ->assertJsonPath('guild.html_url', route('guild.show', 'go')); +}); + it('pages the board 30 roots at a time', function (): void { $rust = Guild::factory()->create(['handle' => 'rust']); $oldest = Commit::factory()->for($rust)->create(['created_at' => now()->subYear()]); diff --git a/tests/Feature/Controllers/ExportControllerTest.php b/tests/Feature/Controllers/ExportControllerTest.php index ebd7b84f5..a2e616baa 100644 --- a/tests/Feature/Controllers/ExportControllerTest.php +++ b/tests/Feature/Controllers/ExportControllerTest.php @@ -20,6 +20,7 @@ use App\Models\CommitReport; use App\Models\Device; use App\Models\Guild; +use App\Models\GuildAlias; use App\Models\GuildSubmission; use App\Models\Message; use App\Models\MessageVoice; @@ -745,7 +746,9 @@ it('exports only the users guilds without internal paths or identifiers', function (): void { $user = User::factory()->create(); $pin = Commit::factory()->create(['body' => '#jobs']); - Guild::factory()->create(['user_id' => $user->id, 'handle' => 'jobs', 'name' => 'Job Board', 'description' => 'Hiring.', 'emoji' => '💼', 'icon_path' => 'guild-icons/private-path.webp', 'pinned_commit_id' => $pin->id]); + $jobs = Guild::factory()->create(['user_id' => $user->id, 'handle' => 'jobs', 'name' => 'Job Board', 'description' => 'Hiring.', 'emoji' => '💼', 'icon_path' => 'guild-icons/private-path.webp', 'pinned_commit_id' => $pin->id]); + GuildAlias::factory()->for($jobs)->create(['handle' => 'work']); + GuildAlias::factory()->for($jobs)->create(['handle' => 'hiring']); Guild::factory()->create(['user_id' => $user->id, 'handle' => 'rust']); Guild::factory()->create(['name' => 'Someone else']); GuildSubmission::factory()->for($user)->create(['handle' => 'adhd', 'name' => 'ADHD', 'description' => 'Waiting for review.', 'icon_path' => 'guild-icons/pending-path.webp']); @@ -757,11 +760,13 @@ expect($data['guilds'])->toHaveCount(2) ->and($data['guilds'][0])->toBe([ 'handle' => 'jobs', 'name' => 'Job Board', 'description' => 'Hiring.', 'emoji' => '💼', + 'aliases' => ['hiring', 'work'], 'icon' => route('guild-icon.show', 'jobs'), 'pinned_commit_id' => $pin->id, 'created_at' => now()->toIso8601String(), 'updated_at' => now()->toIso8601String(), ]) ->and($data['guilds'][1]['icon'])->toBeNull() + ->and($data['guilds'][1]['aliases'])->toBe([]) ->and($data['guild_submissions'])->toBe([[ 'handle' => 'adhd', 'name' => 'ADHD', 'description' => 'Waiting for review.', 'emoji' => '💻', 'has_icon' => true, 'created_at' => now()->toIso8601String(), diff --git a/tests/Feature/Controllers/GuildAliasControllerTest.php b/tests/Feature/Controllers/GuildAliasControllerTest.php new file mode 100644 index 000000000..862532d13 --- /dev/null +++ b/tests/Feature/Controllers/GuildAliasControllerTest.php @@ -0,0 +1,235 @@ +update(Feature::Guilds, true, adminOnly: false); +}); + +it('lets the moderator add an alias and tells the people who see the guild', function (): void { + $moderator = User::factory()->create(); + $member = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + $guild->members()->attach($member, ['joined_at' => now()]); + Event::fake([UsersUpdated::class]); + + $this->actingAs($moderator)->post(route('guild-alias.store', 'go'), ['handle' => ' #GoLang ']) + ->assertSessionHasNoErrors()->assertRedirectToRoute('guild.show', 'go'); + + $this->assertDatabaseHas('guild_aliases', ['guild_id' => $guild->id, 'handle' => 'golang']); + Event::assertDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Guilds + && in_array($member->id, $event->userIds, true) && in_array($moderator->id, $event->userIds, true)); + + $this->get(route('guild.show', 'go'))->assertOk()->assertInertia(fn ($page) => $page + ->where('guilds.0.handle', 'go')->where('guilds.0.aliases', ['golang'])); +}); + +it('brings the commits of an alias to the guild and opens the guild by its alias', function (): void { + $moderator = User::factory()->create(); + $reader = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + $tagged = Commit::factory()->create(['body' => 'Learning #go', 'created_at' => now()->subMinutes(2)]); + $aliased = Commit::factory()->create(['body' => 'Learning #GoLang', 'created_at' => now()->subMinute()]); + $other = Commit::factory()->create(['body' => 'Learning #golanguage']); + + $this->actingAs($reader)->get(route('guild.show', 'go'))->assertInertia(fn ($page) => $page + ->has('commits', 1)->where('commits.0.id', $tagged->id)); + $this->get(route('guild.show', 'golang'))->assertNotFound(); + + $this->actingAs($moderator)->post(route('guild-alias.store', 'go'), ['handle' => 'golang'])->assertSessionHasNoErrors(); + + $this->actingAs($reader)->get(route('guild.show', 'go'))->assertInertia(fn ($page) => $page + ->has('commits', 2)->where('commits.0.id', $aliased->id)->where('commits.1.id', $tagged->id)); + $this->get(route('guild.show', 'golang'))->assertOk()->assertInertia(fn ($page) => $page + ->where('handle', 'go')->has('commits', 2)); + + $this->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page->has('commits.data', 0)); + $this->put(route('guild-membership.update', $guild), ['joined' => true])->assertRedirect(); + $this->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page + ->has('commits.data', 2)->where('commits.data.0.id', $aliased->id)->where('commits.data.0.joined_guild', 'go')); + + $this->put(route('guild-mute.update', $guild), ['muted' => true])->assertRedirect(); + $this->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page->has('commits.data', 0)); + $this->get(route('log.show', 'latest'))->assertInertia(fn ($page) => $page + ->has('commits.data', 1)->where('commits.data.0.id', $other->id)); +}); + +it('refuses an alias that is not a free hashtag', function (string $handle, string $message): void { + $moderator = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + GuildAlias::factory()->for($guild)->create(['handle' => 'gopher']); + Guild::factory()->create(['handle' => 'rust']); + Guild::factory()->create(['handle' => 'paused', 'user_id' => null]); + GuildAlias::factory()->create(['handle' => 'rustlang']); + + $this->actingAs($moderator)->postJson(route('guild-alias.store', 'go'), ['handle' => $handle]) + ->assertUnprocessable()->assertJsonValidationErrors(['handle' => $message]); + + $this->assertDatabaseCount('guild_aliases', 2); +})->with([ + 'its own handle' => ['go', 'A guild already uses this hashtag.'], + 'another guild' => ['#Rust', 'A guild already uses this hashtag.'], + 'a paused guild' => ['paused', 'A guild already uses this hashtag.'], + 'an alias it already has' => ['gopher', 'A guild already uses this hashtag.'], + 'an alias of another guild' => ['rustlang', 'A guild already uses this hashtag.'], + 'not starting with a letter' => ['1337', 'Use a hashtag that starts with a letter and contains only letters, numbers and underscores.'], + 'punctuation' => ['go-lang', 'Use a hashtag that starts with a letter and contains only letters, numbers and underscores.'], + 'too long' => [str_repeat('g', 61), 'The handle field must not be greater than 60 characters.'], + 'empty' => ['#', 'The handle field is required.'], +]); + +it('refuses an alias that is not text', function (): void { + $moderator = User::factory()->create(); + Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + + $this->actingAs($moderator)->postJson(route('guild-alias.store', 'go'), ['handle' => ['golang']]) + ->assertUnprocessable()->assertJsonValidationErrors('handle'); + + $this->assertDatabaseCount('guild_aliases', 0); +}); + +it('caps the aliases of a guild at ten', function (): void { + $moderator = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + GuildAlias::factory()->for($guild)->count(9)->create(); + + $this->actingAs($moderator)->post(route('guild-alias.store', 'go'), ['handle' => 'golang'])->assertSessionHasNoErrors(); + $this->postJson(route('guild-alias.store', 'go'), ['handle' => 'gopher']) + ->assertUnprocessable()->assertJsonValidationErrors(['handle' => 'A guild can have up to 10 aliases.']); + + $this->assertDatabaseCount('guild_aliases', 10); +}); + +it('refuses an alias the moderation flags', function (array $scores, bool $harmful): void { + $moderation = $this->mock(ModerationProvider::class); + $moderation->shouldReceive('moderate')->once()->with('#mess', [])->andReturn($scores); + $moderation->shouldReceive('isHarmful')->with('#mess')->andReturn($harmful); + $moderator = User::factory()->create(); + Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + + $this->actingAs($moderator)->postJson(route('guild-alias.store', 'go'), ['handle' => 'mess']) + ->assertUnprocessable()->assertJsonValidationErrors(['handle' => 'This hashtag cannot be used as an alias.']); + + $this->assertDatabaseCount('guild_aliases', 0); +})->with([ + 'flagged' => [['harassment' => 0.9], false], + 'harmful' => [[], true], +]); + +it('hides the aliases endpoints from everyone but the moderator', function (): void { + $moderator = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + GuildAlias::factory()->for($guild)->create(['handle' => 'golang']); + + $this->actingAs(User::factory()->create())->post(route('guild-alias.store', 'go'), ['handle' => 'gopher'])->assertNotFound(); + $this->delete(route('guild-alias.destroy', ['go', 'golang']))->assertNotFound(); + + resolve(Features::class)->update(Feature::Guilds, false); + $this->actingAs($moderator)->post(route('guild-alias.store', 'go'), ['handle' => 'gopher'])->assertNotFound(); + $this->delete(route('guild-alias.destroy', ['go', 'golang']))->assertNotFound(); + + expect(GuildAlias::query()->pluck('handle')->all())->toBe(['golang']); +}); + +it('leaves the alias out when it stops being allowed after validation', function (string $change): void { + $moderator = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + Event::fake([UsersUpdated::class]); + $changed = false; + $this->app->beforeResolving(CreateGuildAlias::class, function () use (&$changed, $change, $guild): void { + if (! $changed) { + $changed = true; + match ($change) { + 'guild' => Guild::factory()->create(['handle' => 'golang']), + 'alias' => GuildAlias::factory()->create(['handle' => 'golang']), + 'moderator' => Guild::query()->whereKey($guild->id)->update(['user_id' => null]), + }; + } + }); + + $this->actingAs($moderator)->post(route('guild-alias.store', 'go'), ['handle' => 'golang'])->assertRedirectToRoute('guild.show', 'go'); + + expect($changed)->toBeTrue()->and($guild->aliases()->exists())->toBeFalse(); + Event::assertNotDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Guilds); +})->with(['guild', 'alias', 'moderator']); + +it('lets the moderator remove an alias, which takes its commits off the board', function (): void { + $moderator = User::factory()->create(); + $member = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + $guild->members()->attach($member, ['joined_at' => now()]); + GuildAlias::factory()->for($guild)->create(['handle' => 'golang']); + GuildAlias::factory()->for($guild)->create(['handle' => 'gopher']); + Commit::factory()->create(['body' => 'Learning #golang']); + Event::fake([UsersUpdated::class]); + + $this->actingAs($moderator)->get(route('guild.show', 'go'))->assertInertia(fn ($page) => $page->has('commits', 1)); + $this->delete(route('guild-alias.destroy', ['go', 'golang']))->assertRedirectToRoute('guild.show', 'go'); + + expect($guild->aliases()->pluck('handle')->all())->toBe(['gopher']); + Event::assertDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Guilds + && in_array($member->id, $event->userIds, true) && in_array($moderator->id, $event->userIds, true)); + $this->get(route('guild.show', 'go'))->assertInertia(fn ($page) => $page->has('commits', 0)->where('guilds.0.aliases', ['gopher'])); + $this->get(route('guild.show', 'golang'))->assertNotFound(); +}); + +it('does not remove the alias of another guild', function (): void { + $moderator = User::factory()->create(); + Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'go']); + GuildAlias::factory()->create(['handle' => 'rustlang']); + + $this->actingAs($moderator)->delete(route('guild-alias.destroy', ['go', 'rustlang']))->assertNotFound(); + + $this->assertDatabaseCount('guild_aliases', 1); +}); + +it('refuses a new guild whose hashtag is an alias', function (): void { + GuildAlias::factory()->create(['handle' => 'golang']); + + $this->actingAs(User::factory()->create())->postJson(route('guild.store'), ['name' => 'Go Lang', 'description' => 'Gophers.', 'emoji' => '💻']) + ->assertUnprocessable()->assertJsonValidationErrors(['handle' => 'A guild already uses this hashtag. Choose a different display name.']); + + $this->assertDatabaseMissing('guilds', ['handle' => 'golang']); +}); + +it('refuses a new guild whose hashtag becomes an alias after validation', function (): void { + $changed = false; + $this->app->beforeResolving(CreateGuild::class, function () use (&$changed): void { + if (! $changed) { + $changed = true; + GuildAlias::factory()->create(['handle' => 'golang']); + } + }); + + $this->actingAs(User::factory()->create())->from(route('guild.index')) + ->post(route('guild.store'), ['name' => 'Go Lang', 'description' => 'Gophers.', 'emoji' => '💻']) + ->assertRedirectToRoute('guild.index') + ->assertSessionHasErrors(['handle' => 'A guild already uses this hashtag. Choose a different display name.']); + + $this->assertDatabaseMissing('guilds', ['handle' => 'golang']); +}); + +it('discards an approved submission whose hashtag became an alias', function (): void { + $submission = GuildSubmission::factory()->create(['handle' => 'golang']); + GuildAlias::factory()->create(['handle' => 'golang']); + + resolve(CreateGuildSubmissionApproval::class)->handle($submission); + + $this->assertDatabaseCount('guild_submissions', 0); + $this->assertDatabaseMissing('guilds', ['handle' => 'golang']); +}); diff --git a/tests/Unit/Queries/GuildCommitsQueryTest.php b/tests/Unit/Queries/GuildCommitsQueryTest.php index efdae453f..53a827954 100644 --- a/tests/Unit/Queries/GuildCommitsQueryTest.php +++ b/tests/Unit/Queries/GuildCommitsQueryTest.php @@ -5,6 +5,7 @@ use App\Enums\Feature; use App\Models\Commit; use App\Models\Guild; +use App\Models\GuildAlias; use App\Models\User; use App\Queries\GuildCommitsQuery; use App\Services\Features; @@ -33,6 +34,22 @@ function muteGuildFor(User $user, Guild $guild): void expect($kept->modelKeys())->toBe([$postedInOther->id, $inCode->id, $plain->id]); }); +it('rejects the commits tagging an alias of a muted guild', function (): void { + resolve(Features::class)->update(Feature::Guilds, true, adminOnly: false); + $viewer = User::factory()->create(); + $muted = Guild::factory()->create(['handle' => 'go']); + GuildAlias::factory()->for($muted)->create(['handle' => 'golang']); + GuildAlias::factory()->for($muted)->create(['handle' => 'gopher']); + muteGuildFor($viewer, $muted); + $aliased = Commit::factory()->create(['body' => 'Learning #GoLang today']); + $postedInMuted = Commit::factory()->create(['guild_id' => $muted->id, 'body' => 'Board post']); + $other = Commit::factory()->create(['body' => 'Learning #golanguage today']); + + $kept = resolve(GuildCommitsQuery::class)->rejectMuted(new Collection([$aliased, $postedInMuted, $other]), $viewer); + + expect($kept->modelKeys())->toBe([$other->id]); +}); + it('keeps every commit for a viewer who muted no guild', function (): void { resolve(Features::class)->update(Feature::Guilds, true, adminOnly: false); $commit = Commit::factory()->create(['body' => 'Learning #rust today']); diff --git a/tests/Unit/Queries/JoinedGuildsQueryTest.php b/tests/Unit/Queries/JoinedGuildsQueryTest.php index 2da82016d..28b5dbd36 100644 --- a/tests/Unit/Queries/JoinedGuildsQueryTest.php +++ b/tests/Unit/Queries/JoinedGuildsQueryTest.php @@ -6,6 +6,7 @@ use App\Enums\Feature; use App\Models\Commit; use App\Models\Guild; +use App\Models\GuildAlias; use App\Models\User; use App\Queries\JoinedGuildsQuery; use App\Services\Features; @@ -105,6 +106,18 @@ expect(array_column(resolve(JoinedGuildsQuery::class)->get($reader), 'handle'))->toBe(['alpha', 'beta']); }); +it('counts a commit tagging an alias of a joined guild as missed', function (): void { + resolve(Features::class)->update(Feature::Guilds, true, adminOnly: false); + $reader = User::factory()->create(); + $guild = Guild::factory()->create(['handle' => 'go']); + GuildAlias::factory()->for($guild)->create(['handle' => 'golang']); + DB::table('guild_preferences')->insert(['guild_id' => $guild->id, 'user_id' => $reader->id, 'joined_at' => now()->subDay()]); + Commit::factory()->create(['body' => 'Learning #GoLang']); + Commit::factory()->create(['body' => 'Learning #golanguage']); + + expect(array_column(resolve(JoinedGuildsQuery::class)->get($reader), 'missed_commits', 'handle'))->toBe(['go' => 1]); +}); + it('reads the order with the same number of queries for more commits of the reader', function (): void { resolve(Features::class)->update(Feature::Guilds, true, adminOnly: false); $reader = User::factory()->create(); From f4fdf44799e5ea53c397a5fb8434c4ee7d1e7f68 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:16 -0500 Subject: [PATCH 06/12] feat: include guild aliases in data export --- app/Actions/CreateExport.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Actions/CreateExport.php b/app/Actions/CreateExport.php index 26ff673e4..da3d08caf 100644 --- a/app/Actions/CreateExport.php +++ b/app/Actions/CreateExport.php @@ -140,8 +140,9 @@ public function handle(User $user): array 'dismissed_suggestions' => $this->handles($user->dismissedSuggestions()), 'organizations' => $this->organizations($user), 'followed_organizations' => $this->followedOrganizations($user), - 'guilds' => Guild::query()->where('user_id', $user->id)->orderBy('handle')->get()->map(fn (Guild $guild): array => [ + 'guilds' => Guild::query()->with('aliases')->where('user_id', $user->id)->orderBy('handle')->get()->map(fn (Guild $guild): array => [ ...$guild->toArray(), + 'aliases' => $guild->aliases->pluck('handle')->all(), 'icon' => $guild->icon_path === null ? null : route('guild-icon.show', $guild->handle), 'pinned_commit_id' => $guild->pinned_commit_id, 'created_at' => $guild->created_at->toIso8601String(), From 0ba0deb338b82f7f55bc3deaa6917deca9493e8b Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:12 -0500 Subject: [PATCH 07/12] refactor: update guild queries to support aliases --- app/Queries/GuildCommitsQuery.php | 56 ++++++++++++++++++++++--------- app/Queries/GuildsQuery.php | 6 ++-- app/Queries/JoinedGuildsQuery.php | 4 +-- 3 files changed, 47 insertions(+), 19 deletions(-) diff --git a/app/Queries/GuildCommitsQuery.php b/app/Queries/GuildCommitsQuery.php index 09249f63e..6eec79ae8 100644 --- a/app/Queries/GuildCommitsQuery.php +++ b/app/Queries/GuildCommitsQuery.php @@ -15,6 +15,7 @@ use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\JoinClause; use Illuminate\Pagination\Paginator; +use Illuminate\Support\Collection as SupportCollection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Fluent; use Illuminate\Support\LazyCollection; @@ -66,13 +67,11 @@ public function pinned(Guild $guild, User $viewer): ?Commit public function forPreference(User $user, bool $muted): Builder { - /** @var list $handles */ - $handles = resolve(Features::class)->available(Feature::Guilds, $user) - ? DB::table('guild_preferences')->join('guilds', 'guilds.id', '=', 'guild_preferences.guild_id') - ->where('guild_preferences.user_id', $user->id)->whereNotNull($muted ? 'muted_at' : 'joined_at')->pluck('handle')->all() + $hashtags = resolve(Features::class)->available(Feature::Guilds, $user) + ? $this->hashtagsOf($this->preferencesOf($user)->whereNotNull($muted ? 'muted_at' : 'joined_at')->get()) : []; - return DB::query()->selectRaw('jsonb_array_elements_text(?)::uuid', [$this->ids($user, $handles)->values()->toJson()]); + return DB::query()->selectRaw('jsonb_array_elements_text(?)::uuid', [$this->ids($user, array_keys($hashtags))->values()->toJson()]); } /** @@ -85,13 +84,12 @@ public function rejectMuted(Collection $commits, ?User $user): Collection return $commits; } - /** @var array $muted */ - $muted = DB::table('guild_preferences')->join('guilds', 'guilds.id', '=', 'guild_preferences.guild_id') - ->where('guild_preferences.user_id', $user->id)->whereNotNull('muted_at')->pluck('handle', 'guilds.id')->all(); + $muted = $this->preferencesOf($user)->whereNotNull('muted_at')->get(); + $hashtags = array_keys($this->hashtagsOf($muted)); - return $muted === [] ? $commits : $commits->reject(fn (Commit $commit): bool => $commit->guild_id !== null - ? array_key_exists($commit->guild_id, $muted) - : array_intersect($muted, $this->hashtags->handles($commit->body)) !== [])->values(); + return $muted->isEmpty() ? $commits : $commits->reject(fn (Commit $commit): bool => $commit->guild_id !== null + ? $muted->contains('id', $commit->guild_id) + : array_intersect($hashtags, $this->hashtags->handles($commit->body)) !== [])->values(); } /** @@ -104,21 +102,22 @@ public function joinedFor(iterable $commits, User $user): array return []; } - $handles = DB::table('guild_preferences')->join('guilds', 'guilds.id', '=', 'guild_preferences.guild_id') - ->where('guild_preferences.user_id', $user->id)->whereNotNull('joined_at')->whereNull('muted_at')->orderBy('handle')->pluck('handle')->all(); + $hashtags = $this->hashtagsOf($this->preferencesOf($user)->whereNotNull('joined_at')->whereNull('muted_at')->get()); $following = $user->following(); $organizations = $user->followedOrganizations(); $authors = $following->newPivotQuery()->pluck($following->getRelatedPivotKeyName()) ->merge($organizations->newPivotQuery()->pluck($organizations->getRelatedPivotKeyName()))->push($user->id); return collect($commits)->reject(fn (Commit $commit): bool => $commit->guild_id === null && $authors->contains($commit->author_id)) - ->mapWithKeys(fn (Commit $commit): array => [$commit->id => $commit->guild->handle ?? collect($this->hashtags->handles($commit->body))->first(fn (string $handle): bool => in_array($handle, $handles, true))]) + ->mapWithKeys(fn (Commit $commit): array => [$commit->id => $commit->guild->handle ?? collect($this->hashtags->handles($commit->body))->map(fn (string $hashtag): ?string => $hashtags[$hashtag] ?? null)->filter()->first()]) ->filter()->all(); } /** @return LazyCollection */ public function rootIds(Guild $guild, User $viewer, ?string $forRoot = null): LazyCollection { + $hashtags = $guild->hashtags(); + $tags = array_map(fn (string $hashtag): string => '#'.str_replace('ς', 'σ', $hashtag), $hashtags); $roots = Commit::query()->topLevel()->visibleTo($viewer)->withoutMutedAuthorsFor($viewer) ->when($forRoot !== null, fn (CommitBuilder $query): CommitBuilder => $query->whereKey($forRoot)) ->select(['id', 'created_at']); @@ -131,7 +130,7 @@ public function rootIds(Guild $guild, User $viewer, ?string $forRoot = null): La ->select(['roots.id', 'commits.body', 'commits.guild_id'])->toBase()->cursor() ->map(fn (stdClass $commit): Fluent => new Fluent(get_object_vars($commit))) ->filter(fn (Fluent $commit): bool => $commit->get('guild_id') !== null - || (str_contains(str_replace('ς', 'σ', mb_strtolower($commit->string('body')->value())), '#'.str_replace('ς', 'σ', $guild->handle)) && in_array($guild->handle, $this->hashtags->handles($commit->string('body')->value()), true))) + || ($commit->string('body')->lower()->replace('ς', 'σ')->contains($tags) && array_intersect($hashtags, $this->hashtags->handles($commit->string('body')->value())) !== [])) ->map(fn (Fluent $commit): string => $commit->string('id')->value()) ->unique()->values(); } @@ -148,6 +147,33 @@ private function page(Guild $guild, User $viewer, int $page): Paginator return new Paginator($commits, 30, $page, ['path' => Paginator::resolveCurrentPath()]); } + /** + * The guilds the user has preferences for, with a row for each alias, so one read brings every hashtag of them. + */ + private function preferencesOf(User $user): Builder + { + return DB::table('guild_preferences')->join('guilds', 'guilds.id', '=', 'guild_preferences.guild_id') + ->leftJoin('guild_aliases', 'guild_aliases.guild_id', '=', 'guilds.id') + ->where('guild_preferences.user_id', $user->id) + ->select(['guilds.id', 'guilds.handle', 'guild_aliases.handle as alias']); + } + + /** + * The handle of the guild each hashtag leads to, by hashtag: the handles themselves, and the aliases. + * + * @param SupportCollection $guilds + * @return array + */ + private function hashtagsOf(SupportCollection $guilds): array + { + /** @var array $handles */ + $handles = $guilds->pluck('handle', 'handle')->all(); + /** @var array $aliases */ + $aliases = $guilds->whereNotNull('alias')->pluck('handle', 'alias')->all(); + + return [...$handles, ...$aliases]; + } + /** * @param list $handles * @return LazyCollection diff --git a/app/Queries/GuildsQuery.php b/app/Queries/GuildsQuery.php index ab829625e..8f0c4bff3 100644 --- a/app/Queries/GuildsQuery.php +++ b/app/Queries/GuildsQuery.php @@ -39,7 +39,9 @@ public function paginate(string $term, int $page, User $user): LengthAwarePagina ->when($term !== '', fn (Builder $query): Builder => $query->where(fn (Builder $query): Builder => $query ->whereRaw('TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]) ->orWhereRaw('TRANSLATE(LOWER(name COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]) - ->orWhereRaw('TRANSLATE(LOWER(description COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]))) + ->orWhereRaw('TRANSLATE(LOWER(description COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]) + ->orWhereHas('aliases', fn (Builder $query): Builder => $query + ->whereRaw('TRANSLATE(LOWER(guild_aliases.handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"])))) ->orderByDesc('members_count')->orderBy('handle') ->paginate(24, page: $page); } @@ -51,7 +53,7 @@ public function paginate(string $term, int $page, User $user): LengthAwarePagina */ private function withPreferencesOf(User $user): Builder { - return Guild::query()->withCount('members')->withExists([ + return Guild::query()->with('aliases')->withCount('members')->withExists([ 'members as is_joined' => fn (Builder $query): Builder => $query->whereKey($user->id), 'muters as is_muted' => fn (Builder $query): Builder => $query->whereKey($user->id), ]); diff --git a/app/Queries/JoinedGuildsQuery.php b/app/Queries/JoinedGuildsQuery.php index fda59ae0d..bff61646d 100644 --- a/app/Queries/JoinedGuildsQuery.php +++ b/app/Queries/JoinedGuildsQuery.php @@ -46,7 +46,7 @@ public function get(User $user): array $commits = $this->commitsSince($user, array_keys($readFrom), min($readFrom)); $ownCommits = $this->ownCommits($user, array_keys($readFrom)); - $guilds = Guild::query()->whereKey(array_keys($readFrom))->get(); + $guilds = Guild::query()->with('aliases')->whereKey(array_keys($readFrom))->get(); $ownCommitCounts = $guilds->mapWithKeys(fn (Guild $guild): array => [ $guild->handle => $ownCommits->filter(fn (array $commit): bool => $this->isPostedIn($guild, $commit))->count(), ]); @@ -133,6 +133,6 @@ private function ownCommits(User $user, array $guildIds): Collection private function isPostedIn(Guild $guild, array $commit): bool { return $commit['guild_id'] === $guild->id - || ($commit['guild_id'] === null && in_array($guild->handle, $commit['handles'], true)); + || ($commit['guild_id'] === null && array_intersect($guild->hashtags(), $commit['handles']) !== []); } } From 7bf2599b6e692fd2d8e028df543b757d67c15272 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:09 -0500 Subject: [PATCH 08/12] feat: add guild alias API and web routes --- app/Http/Controllers/GuildAliasController.php | 32 +++++++++++++++++++ app/Http/Controllers/GuildController.php | 3 ++ app/Http/Resources/GuildResource.php | 3 +- routes/web.php | 3 ++ 4 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 app/Http/Controllers/GuildAliasController.php diff --git a/app/Http/Controllers/GuildAliasController.php b/app/Http/Controllers/GuildAliasController.php new file mode 100644 index 000000000..3ef4e5dbd --- /dev/null +++ b/app/Http/Controllers/GuildAliasController.php @@ -0,0 +1,32 @@ +handle($guild, $user, $request->string('handle')->value()); + + return to_route('guild.show', $guild->handle); + } + + public function destroy(DeleteGuildAliasRequest $request, Guild $guild, GuildAlias $alias, DeleteGuildAlias $action): RedirectResponse + { + $action->handle($guild, $alias); + + return to_route('guild.show', $guild->handle); + } +} diff --git a/app/Http/Controllers/GuildController.php b/app/Http/Controllers/GuildController.php index de80fc205..13a4e9d83 100644 --- a/app/Http/Controllers/GuildController.php +++ b/app/Http/Controllers/GuildController.php @@ -6,6 +6,7 @@ use App\Actions\CreateGuild; use App\Actions\UpdateGuild; +use App\Exceptions\GuildHandleTaken; use App\Exceptions\GuildModeratorRemoved; use App\Http\Requests\CreateGuildRequest; use App\Http\Requests\ListGuildsRequest; @@ -44,6 +45,8 @@ public function store(CreateGuildRequest $request, #[CurrentUser] User $user, Cr $guild = $action->handle($user, $request->string('handle')->value(), $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->isFlagged()); } catch (GuildModeratorRemoved) { return back()->withErrors(['handle' => 'You cannot reclaim a guild you were removed from.']); + } catch (GuildHandleTaken) { + return back()->withErrors(['handle' => 'A guild already uses this hashtag. Choose a different display name.']); } if ($guild instanceof GuildSubmission) { diff --git a/app/Http/Resources/GuildResource.php b/app/Http/Resources/GuildResource.php index d5d37f240..9e239de17 100644 --- a/app/Http/Resources/GuildResource.php +++ b/app/Http/Resources/GuildResource.php @@ -10,7 +10,7 @@ /** * A guild as the web's Guilds page shows it, with whether the user joined or muted it. A guild without a moderator is - * paused. + * paused. Its aliases are the other hashtags that lead to it. * * On API routes, icon_url is signed for the user, as the app has no web session, and stays the same all day so the app * can cache it. @@ -26,6 +26,7 @@ public function toArray(Request $request): array { return [ 'handle' => $this->handle, + 'aliases' => $this->aliases->pluck('handle')->all(), 'name' => $this->name, 'description' => $this->description, 'emoji' => $this->emoji, diff --git a/routes/web.php b/routes/web.php index 3338fbb40..d6c7a9483 100644 --- a/routes/web.php +++ b/routes/web.php @@ -60,6 +60,7 @@ use App\Http\Controllers\FailedJobsController; use App\Http\Controllers\FeatureController; use App\Http\Controllers\ForecastController; +use App\Http\Controllers\GuildAliasController; use App\Http\Controllers\GuildCommitPinController; use App\Http\Controllers\GuildController; use App\Http\Controllers\GuildIconController; @@ -379,6 +380,8 @@ Route::get('guilds/{guild:handle}/icon', [GuildIconController::class, 'show'])->name('guild-icon.show'); Route::post('guilds', [GuildController::class, 'store'])->middleware([PreventPostingInTimeout::class, 'throttle:10,1'])->name('guild.store'); Route::put('guilds/{guild:handle}', [GuildController::class, 'update'])->middleware([PreventPostingInTimeout::class, 'throttle:10,1'])->name('guild.update'); + Route::post('guilds/{guild:handle}/aliases', [GuildAliasController::class, 'store'])->middleware([PreventPostingInTimeout::class, 'throttle:10,1'])->name('guild-alias.store'); + Route::delete('guilds/{guild:handle}/aliases/{alias:handle}', [GuildAliasController::class, 'destroy'])->middleware('throttle:10,1')->name('guild-alias.destroy'); Route::put('guilds/{guild:handle}/commits/{commit}/pin', [GuildCommitPinController::class, 'update']) ->whereUuid('commit')->withTrashed()->middleware('throttle:pins')->name('guild-commit-pin.update'); Route::put('guild-memberships/{guild}', [GuildMembershipController::class, 'update'])->whereUuid('guild')->middleware('throttle:follows')->name('guild-membership.update'); From cb611ad2472d05371f6346e982a49616311922da Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:06 -0500 Subject: [PATCH 09/12] feat: add guild alias request validation --- app/Http/Requests/CreateGuildAliasRequest.php | 77 +++++++++++++++++++ app/Http/Requests/CreateGuildRequest.php | 2 +- app/Http/Requests/DeleteGuildAliasRequest.php | 29 +++++++ 3 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 app/Http/Requests/CreateGuildAliasRequest.php create mode 100644 app/Http/Requests/DeleteGuildAliasRequest.php diff --git a/app/Http/Requests/CreateGuildAliasRequest.php b/app/Http/Requests/CreateGuildAliasRequest.php new file mode 100644 index 000000000..92cd72cdb --- /dev/null +++ b/app/Http/Requests/CreateGuildAliasRequest.php @@ -0,0 +1,77 @@ +route('guild'); + assert($guild instanceof Guild); + + return $features->available(Feature::Guilds, $this->user()) && $guild->user_id === $this->user()?->id + ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array> */ + public function rules(): array + { + return [ + 'handle' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD', Rule::unique('guilds', 'handle'), Rule::unique('guild_aliases', 'handle')], + ]; + } + + /** @return list */ + public function after(FlaggedGuild $flagged): array + { + return [function (Validator $validator) use ($flagged): void { + if ($validator->errors()->isNotEmpty()) { + return; + } + + $guild = $this->route('guild'); + assert($guild instanceof Guild); + + if ($guild->aliases()->count() >= self::MAX_PER_GUILD) { + $validator->errors()->add('handle', 'A guild can have up to '.self::MAX_PER_GUILD.' aliases.'); + + return; + } + + if ($flagged->validate($validator, '#'.$this->string('handle')->value(), null)) { + $validator->errors()->add('handle', 'This hashtag cannot be used as an alias.'); + } + }]; + } + + /** @return array */ + public function messages(): array + { + return [ + 'handle.unique' => 'A guild already uses this hashtag.', + 'handle.regex' => 'Use a hashtag that starts with a letter and contains only letters, numbers and underscores.', + ]; + } + + public function prepareForValidation(): void + { + if (is_string($this->input('handle'))) { + $this->merge(['handle' => $this->string('handle')->trim()->ltrim('#')->lower()->value()]); + } + } +} diff --git a/app/Http/Requests/CreateGuildRequest.php b/app/Http/Requests/CreateGuildRequest.php index 30f8539b1..9169ebc79 100644 --- a/app/Http/Requests/CreateGuildRequest.php +++ b/app/Http/Requests/CreateGuildRequest.php @@ -35,7 +35,7 @@ public function authorize(Features $features): Response public function rules(EmojiShortcodes $emoji): array { return [ - 'handle' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD', Rule::unique('guilds', 'handle')->whereNotNull('user_id')], + 'handle' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD', Rule::unique('guilds', 'handle')->whereNotNull('user_id'), Rule::unique('guild_aliases', 'handle')], 'name' => ['required', 'string', 'max:60'], 'description' => ['required', 'string', 'max:500'], 'emoji' => ['required', 'string', Rule::in($emoji->emoji())], diff --git a/app/Http/Requests/DeleteGuildAliasRequest.php b/app/Http/Requests/DeleteGuildAliasRequest.php new file mode 100644 index 000000000..261199874 --- /dev/null +++ b/app/Http/Requests/DeleteGuildAliasRequest.php @@ -0,0 +1,29 @@ +route('guild'); + assert($guild instanceof Guild); + + return $features->available(Feature::Guilds, $this->user()) && $guild->user_id === $this->user()?->id + ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array{} */ + public function rules(): array + { + return []; + } +} From ffada21665d019b45ed1a08999d5ad705164b553 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sat, 21 Nov 2026 14:52:03 -0500 Subject: [PATCH 10/12] feat: introduce GuildHandleTaken exception and alias actions --- app/Actions/CreateGuild.php | 11 ++++- app/Actions/CreateGuildAlias.php | 40 +++++++++++++++++++ app/Actions/CreateGuildSubmissionApproval.php | 5 ++- app/Actions/DeleteGuildAlias.php | 21 ++++++++++ app/Exceptions/GuildHandleTaken.php | 9 +++++ 5 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 app/Actions/CreateGuildAlias.php create mode 100644 app/Actions/DeleteGuildAlias.php create mode 100644 app/Exceptions/GuildHandleTaken.php diff --git a/app/Actions/CreateGuild.php b/app/Actions/CreateGuild.php index c5fe66fbd..f8c8e21ba 100644 --- a/app/Actions/CreateGuild.php +++ b/app/Actions/CreateGuild.php @@ -4,8 +4,10 @@ namespace App\Actions; +use App\Exceptions\GuildHandleTaken; use App\Exceptions\GuildModeratorRemoved; use App\Models\Guild; +use App\Models\GuildAlias; use App\Models\GuildSubmission; use App\Models\User; use Illuminate\Http\UploadedFile; @@ -19,7 +21,8 @@ public function __construct(private CreateImageFiles $images, private UpdateGuil } /** - * The icon is an upload, or the path of one already stored, such as a reviewed submission's. + * The icon is an upload, or the path of one already stored, such as a reviewed submission's. A hashtag that became + * another guild's alias meanwhile is taken. */ public function handle(User $user, string $handle, string $name, string $description, string $emoji, UploadedFile|string|null $icon, bool $flagged = false): Guild|GuildSubmission { @@ -30,6 +33,12 @@ public function handle(User $user, string $handle, string $name, string $descrip throw new GuildModeratorRemoved; } + DB::select('select pg_advisory_xact_lock(hashtextextended(?, 0))', [CreateGuildAlias::HANDLE_LOCK.mb_strtolower($handle)]); + + if (GuildAlias::query()->where('handle', mb_strtolower($handle))->exists()) { + throw new GuildHandleTaken; + } + if ($flagged) { assert($icon instanceof UploadedFile || $icon === null); diff --git a/app/Actions/CreateGuildAlias.php b/app/Actions/CreateGuildAlias.php new file mode 100644 index 000000000..575eda581 --- /dev/null +++ b/app/Actions/CreateGuildAlias.php @@ -0,0 +1,40 @@ +whereKey($guild->id)->lockForUpdate()->firstOrFail(); + + if ($guild->user_id !== $user->id || Guild::query()->where('handle', $handle)->exists() || GuildAlias::query()->where('handle', $handle)->exists()) { + return; + } + + $guild->aliases()->create(['handle' => $handle]); + + event(new UsersUpdated(DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($guild->user_id), UserUpdate::Guilds)); + }); + } +} diff --git a/app/Actions/CreateGuildSubmissionApproval.php b/app/Actions/CreateGuildSubmissionApproval.php index f104739bb..25c287397 100644 --- a/app/Actions/CreateGuildSubmissionApproval.php +++ b/app/Actions/CreateGuildSubmissionApproval.php @@ -4,6 +4,7 @@ namespace App\Actions; +use App\Exceptions\GuildHandleTaken; use App\Exceptions\GuildModeratorRemoved; use App\Models\Guild; use App\Models\GuildSubmission; @@ -20,7 +21,7 @@ public function __construct(private CreateGuild $createGuild, private UpdateGuil /** * Publishes the submission as if it had passed the moderation: an edit when its author still moderates the guild, * otherwise a new guild, which claims a paused one and leaves one someone else moderates alone. An author removed - * from the guild meanwhile gets nothing. + * from the guild meanwhile gets nothing, and neither does a hashtag that became another guild's alias. */ public function handle(?GuildSubmission $submission): void { @@ -43,7 +44,7 @@ public function handle(?GuildSubmission $submission): void } else { $this->createGuild->handle($submission->user, $submission->handle, $submission->name, $submission->description, $submission->emoji, $submission->icon_path); } - } catch (GuildModeratorRemoved) { + } catch (GuildHandleTaken|GuildModeratorRemoved) { // } diff --git a/app/Actions/DeleteGuildAlias.php b/app/Actions/DeleteGuildAlias.php new file mode 100644 index 000000000..60b6101d0 --- /dev/null +++ b/app/Actions/DeleteGuildAlias.php @@ -0,0 +1,21 @@ +delete(); + + event(new UsersUpdated(DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($guild->user_id), UserUpdate::Guilds)); + } +} diff --git a/app/Exceptions/GuildHandleTaken.php b/app/Exceptions/GuildHandleTaken.php new file mode 100644 index 000000000..7f9853d68 --- /dev/null +++ b/app/Exceptions/GuildHandleTaken.php @@ -0,0 +1,9 @@ + Date: Sat, 21 Nov 2026 14:52:00 -0500 Subject: [PATCH 11/12] feat: add guild alias model and migration --- app/Models/Guild.php | 36 +++++++++++++++++++ app/Models/GuildAlias.php | 30 ++++++++++++++++ database/factories/GuildAliasFactory.php | 26 ++++++++++++++ ...1_21_101500_create_guild_aliases_table.php | 20 +++++++++++ 4 files changed, 112 insertions(+) create mode 100644 app/Models/GuildAlias.php create mode 100644 database/factories/GuildAliasFactory.php create mode 100644 database/migrations/2026_11_21_101500_create_guild_aliases_table.php diff --git a/app/Models/Guild.php b/app/Models/Guild.php index fe4d6ab8e..4b3ff1051 100644 --- a/app/Models/Guild.php +++ b/app/Models/Guild.php @@ -6,13 +6,17 @@ use Carbon\CarbonInterface; use Database\Factories\GuildFactory; +use Illuminate\Contracts\Database\Eloquent\Builder as BuilderContract; use Illuminate\Database\Eloquent\Attributes\Visible; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Facades\URL; +use Override; /** * @property-read string $id @@ -43,6 +47,38 @@ public function commits(): HasMany return $this->hasMany(Commit::class); } + /** @return HasMany */ + public function aliases(): HasMany + { + return $this->hasMany(GuildAlias::class)->orderBy('handle'); + } + + /** + * The hashtags that bring a commit to the guild: its handle, then its aliases. + * + * @return list + */ + public function hashtags(): array + { + return [$this->handle, ...$this->aliases->map(fn (GuildAlias $alias): string => $alias->handle)->all()]; + } + + /** + * Resolves "guilds/{handle}" URLs by the guild's handle or by one of its aliases. + * + * @param Model|BuilderContract|Relation $query + * @param mixed $value + * @param string|null $field + */ + #[Override] + public function resolveRouteBindingQuery($query, $value, $field = null): BuilderContract + { + return $field === 'handle' + ? parent::resolveRouteBindingQuery($query, self::query()->select('id')->where('handle', $value) + ->orWhereHas('aliases', fn (Builder $aliases): Builder => $aliases->where('guild_aliases.handle', $value))->limit(1), 'id') + : parent::resolveRouteBindingQuery($query, $value, $field); + } + /** @return BelongsToMany */ public function members(): BelongsToMany { diff --git a/app/Models/GuildAlias.php b/app/Models/GuildAlias.php new file mode 100644 index 000000000..e8ae988fd --- /dev/null +++ b/app/Models/GuildAlias.php @@ -0,0 +1,30 @@ + */ + use HasFactory; + + use HasUuids; + + public $timestamps = false; +} diff --git a/database/factories/GuildAliasFactory.php b/database/factories/GuildAliasFactory.php new file mode 100644 index 000000000..b79ba3669 --- /dev/null +++ b/database/factories/GuildAliasFactory.php @@ -0,0 +1,26 @@ + + */ +final class GuildAliasFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'guild_id' => Guild::factory(), + 'handle' => fake()->unique()->lexify('alias????????'), + ]; + } +} diff --git a/database/migrations/2026_11_21_101500_create_guild_aliases_table.php b/database/migrations/2026_11_21_101500_create_guild_aliases_table.php new file mode 100644 index 000000000..a4dd8f1a4 --- /dev/null +++ b/database/migrations/2026_11_21_101500_create_guild_aliases_table.php @@ -0,0 +1,20 @@ +uuid('id')->primary(); + $table->foreignUuid('guild_id')->constrained()->cascadeOnDelete(); + $table->string('handle', 60)->unique(); + $table->index('guild_id'); + }); + } +}; From d229302ee9c401391b785e3cee529232dbe78c96 Mon Sep 17 00:00:00 2001 From: Ris Adams Date: Sun, 22 Nov 2026 06:28:04 -0500 Subject: [PATCH 12/12] feat: enforce maximum alias limit per guild The maximum number of aliases a guild can have is now defined as `MAX_PER_GUILD` on the `GuildAlias` model. This limit is enforced both during request validation and again within the `CreateGuildAlias` action, under a guild-specific lock, to prevent race conditions and ensure the cap is respected even with concurrent alias creation attempts. --- app/Actions/CreateGuildAlias.php | 7 +++++++ app/Http/Requests/CreateGuildAliasRequest.php | 7 +++---- app/Models/GuildAlias.php | 13 +++++++++++++ .../Controllers/GuildAliasControllerTest.php | 5 +++-- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/app/Actions/CreateGuildAlias.php b/app/Actions/CreateGuildAlias.php index 575eda581..96cd0b84f 100644 --- a/app/Actions/CreateGuildAlias.php +++ b/app/Actions/CreateGuildAlias.php @@ -21,6 +21,9 @@ /** * The alias is checked again under the lock, and left out when its hashtag was taken meanwhile or the user no * longer moderates the guild. + * + * The request checks the cap before this runs, but aliases added at the same moment each see the others missing. + * So the cap is counted again here, under the guild's lock: an alias past it is left out. */ public function handle(Guild $guild, User $user, string $handle): void { @@ -32,6 +35,10 @@ public function handle(Guild $guild, User $user, string $handle): void return; } + if ($guild->aliases()->count() >= GuildAlias::MAX_PER_GUILD) { + return; + } + $guild->aliases()->create(['handle' => $handle]); event(new UsersUpdated(DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($guild->user_id), UserUpdate::Guilds)); diff --git a/app/Http/Requests/CreateGuildAliasRequest.php b/app/Http/Requests/CreateGuildAliasRequest.php index 92cd72cdb..e358e872c 100644 --- a/app/Http/Requests/CreateGuildAliasRequest.php +++ b/app/Http/Requests/CreateGuildAliasRequest.php @@ -6,6 +6,7 @@ use App\Enums\Feature; use App\Models\Guild; +use App\Models\GuildAlias; use App\Rules\FlaggedGuild; use App\Services\Features; use Closure; @@ -17,8 +18,6 @@ final class CreateGuildAliasRequest extends FormRequest { - private const int MAX_PER_GUILD = 10; - public function authorize(Features $features): Response { $guild = $this->route('guild'); @@ -47,8 +46,8 @@ public function after(FlaggedGuild $flagged): array $guild = $this->route('guild'); assert($guild instanceof Guild); - if ($guild->aliases()->count() >= self::MAX_PER_GUILD) { - $validator->errors()->add('handle', 'A guild can have up to '.self::MAX_PER_GUILD.' aliases.'); + if ($guild->aliases()->count() >= GuildAlias::MAX_PER_GUILD) { + $validator->errors()->add('handle', 'A guild can have up to '.GuildAlias::MAX_PER_GUILD.' aliases.'); return; } diff --git a/app/Models/GuildAlias.php b/app/Models/GuildAlias.php index e8ae988fd..a7a8a6af8 100644 --- a/app/Models/GuildAlias.php +++ b/app/Models/GuildAlias.php @@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Another hashtag that leads to a guild, beside its handle. No guild has it as its handle, and no other guild as an @@ -17,6 +18,7 @@ * @property-read string $id * @property-read string $guild_id * @property-read string $handle + * @property-read Guild $guild */ #[Visible(['handle'])] final class GuildAlias extends Model @@ -26,5 +28,16 @@ final class GuildAlias extends Model use HasUuids; + /** + * How many aliases one guild can have. + */ + public const int MAX_PER_GUILD = 10; + public $timestamps = false; + + /** @return BelongsTo */ + public function guild(): BelongsTo + { + return $this->belongsTo(Guild::class); + } } diff --git a/tests/Feature/Controllers/GuildAliasControllerTest.php b/tests/Feature/Controllers/GuildAliasControllerTest.php index 862532d13..06d41e546 100644 --- a/tests/Feature/Controllers/GuildAliasControllerTest.php +++ b/tests/Feature/Controllers/GuildAliasControllerTest.php @@ -158,15 +158,16 @@ 'guild' => Guild::factory()->create(['handle' => 'golang']), 'alias' => GuildAlias::factory()->create(['handle' => 'golang']), 'moderator' => Guild::query()->whereKey($guild->id)->update(['user_id' => null]), + 'limit' => GuildAlias::factory()->for($guild)->count(GuildAlias::MAX_PER_GUILD)->create(), }; } }); $this->actingAs($moderator)->post(route('guild-alias.store', 'go'), ['handle' => 'golang'])->assertRedirectToRoute('guild.show', 'go'); - expect($changed)->toBeTrue()->and($guild->aliases()->exists())->toBeFalse(); + expect($changed)->toBeTrue()->and($guild->aliases()->where('handle', 'golang')->exists())->toBeFalse(); Event::assertNotDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Guilds); -})->with(['guild', 'alias', 'moderator']); +})->with(['guild', 'alias', 'moderator', 'limit']); it('lets the moderator remove an alias, which takes its commits off the board', function (): void { $moderator = User::factory()->create();