From 34b6cc18945ba8b29a2dcdb33cd7299001092c6f Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:19:09 +0530 Subject: [PATCH 01/31] Make search query-aware with intent and domain filters (R16) Search replaced the searcher's profile embedding with the query's, so query relevance and personal compatibility were blurred together, and without embeddings (no API key) retrieval was alphabetical, so every query returned the same people. There were no filters. - domain/matching/search-query.ts: query words, query relevance (semantic when both vectors exist, else word-prefix matches), and a final score of 60% query relevance and 40% personal compatibility; both appear in the score breakdown - The pipeline's search path keeps the searcher's own profile for compatibility and uses the query only for retrieval and relevance, so the same query ranks differently for different people - Without a query embedding, retrieval uses Postgres full-text search (any word, prefix match) ranked by ts_rank - Intent and domain filters, validated against the event's intents and the domains present among eligible participants; applied in SQL and again on shared-cache hits, and part of the cache key with the normalized query and retrieval kind - Search page: filter selects with their own labels --- .../e/[eventSlug]/search/SearchForm.tsx | 26 +++- .../e/[eventSlug]/search/page.tsx | 5 +- apps/web/app/actions/match.actions.ts | 8 +- .../ports/participant-repository.ts | 6 + .../use-cases/search-participants.ts | 12 +- apps/web/src/domain/matching/pipeline.ts | 50 +++++-- apps/web/src/domain/matching/search-query.ts | 79 +++++++++++ .../domain/matching/stages/retrieve.stage.ts | 17 ++- .../postgres/participant.repo.ts | 30 ++++- tests/integration/search-retrieval.test.ts | 74 +++++++++++ tests/unit/search.test.ts | 124 ++++++++++++++++++ 11 files changed, 404 insertions(+), 27 deletions(-) create mode 100644 apps/web/src/domain/matching/search-query.ts create mode 100644 tests/integration/search-retrieval.test.ts create mode 100644 tests/unit/search.test.ts diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx index e124e5d..cb0b6aa 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx @@ -18,8 +18,12 @@ interface SearchResult { mutualInterest: boolean; } -export default function SearchForm({ eventSlug }: { eventSlug: string }) { +const intentLabel = (intent: string) => intent.replaceAll("_", " ").toLowerCase(); + +export default function SearchForm({ eventSlug, intents, domains }: { eventSlug: string; intents: string[]; domains: string[] }) { const [query, setQuery] = useState(""); + const [intent, setIntent] = useState(""); + const [domain, setDomain] = useState(""); const [results, setResults] = useState([]); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); @@ -30,7 +34,7 @@ export default function SearchForm({ eventSlug }: { eventSlug: string }) { setBusy(true); setError(""); try { - const response = await searchEventParticipants(eventSlug, query); + const response = await searchEventParticipants(eventSlug, query, { intent: intent || null, domain: domain || null }); setResults(response.results); setError(response.error ?? ""); setSearched(response.error ? "" : query.trim()); @@ -47,6 +51,22 @@ export default function SearchForm({ eventSlug }: { eventSlug: string }) { setQuery(event.target.value)} required maxLength={LIMITS.searchQuery} placeholder="e.g. a product designer interested in climate AI" style={input} /> +
+
+ + +
+ {domains.length > 0 &&
+ + +
} +
{error &&

{error}

}

{busy ? "Searching" : searched ? `${results.length} results for ${searched}` : ""}

@@ -69,3 +89,5 @@ export default function SearchForm({ eventSlug }: { eventSlug: string }) { const input = { flex: "1 1 240px", minWidth: 0, padding: 13, borderRadius: 8, border: "1px solid #3f3f46", background: "#151519", color: "#f4f4f5" } as const; const card = { display: "flex", gap: 18, flexWrap: "wrap", alignItems: "center", padding: 20, borderRadius: 12, background: "#151519", border: "1px solid #333" } as const; const muted = { color: "#a1a1aa" } as const; +const filterLabel = { display: "grid", gap: 4, fontSize: 14, color: "#a1a1aa" } as const; +const select = { padding: 10, borderRadius: 8, border: "1px solid #3f3f46", background: "#151519", color: "#f4f4f5", font: "inherit" } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx index cd0fcbc..a46c084 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx @@ -5,11 +5,12 @@ import SearchForm from "./SearchForm"; export default async function SearchPage({ params }: { params: Promise<{ eventSlug: string }> }) { const { eventSlug } = await params; - await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`, "search"); + const { event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`, "search"); + const domains = await container.participants.listDomains(event.id); return

Search your event

Describe the people, skills, or collaboration you are looking for.

- +
; } diff --git a/apps/web/app/actions/match.actions.ts b/apps/web/app/actions/match.actions.ts index 23099e1..2de5008 100644 --- a/apps/web/app/actions/match.actions.ts +++ b/apps/web/app/actions/match.actions.ts @@ -8,22 +8,22 @@ import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { getSession } from "../../lib/session"; import { runFormAction, userMessage, type FormState } from "../../lib/form-state"; -export async function searchEventParticipants(eventSlug: string, searchText: string) { +export async function searchEventParticipants(eventSlug: string, searchText: string, filters: { intent?: string | null; domain?: string | null } = {}) { try { - return { results: await searchEvent(eventSlug, searchText), error: null }; + return { results: await searchEvent(eventSlug, searchText, filters), error: null }; } catch (error) { return { results: [], error: userMessage(error, "Search failed. Please try again.") }; } } -async function searchEvent(eventSlug: string, searchText: string) { +async function searchEvent(eventSlug: string, searchText: string, filters: { intent?: string | null; domain?: string | null }) { const session = await getSession(); if (!session) throw new Error("Sign in to search this event"); const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); assertEventAllows(event.status, "search"); - const results = await searchParticipants({ eventId: event.id, participantId: session.attendeeId, query: searchText }, container); + const results = await searchParticipants({ eventId: event.id, participantId: session.attendeeId, query: searchText, eventIntents: event.intents, filters }, container); return results.map((match) => ({ id: match.participant.attendeeId, name: match.participant.name, diff --git a/apps/web/src/application/ports/participant-repository.ts b/apps/web/src/application/ports/participant-repository.ts index b54e77b..0bab47e 100644 --- a/apps/web/src/application/ports/participant-repository.ts +++ b/apps/web/src/application/ports/participant-repository.ts @@ -1,4 +1,5 @@ import type { ParticipantProfile, ParticipantProfileInput } from "../../domain/participant/participant.entity"; +import type { SearchFilters } from "../../domain/matching/search-query"; export interface ParticipantRepository { findProfile(eventId: string, attendeeId: string): Promise; @@ -7,8 +8,13 @@ export interface ParticipantRepository { eventId: string; excludeAttendeeId: string | null; embedding?: number[] | null; + /** Without an embedding, only candidates matching one of these words, best first. */ + terms?: string[]; + filters?: SearchFilters; limit?: number; }): Promise; + /** Domains present among eligible participants, for the search filter. */ + listDomains(eventId: string): Promise; findCandidatesByIds(eventId: string, ids: string[]): Promise; setEmbedding(eventId: string, attendeeId: string, embedding: number[]): Promise; shareVenueZone(eventId: string, attendeeId: string, zone: string): Promise; diff --git a/apps/web/src/application/use-cases/search-participants.ts b/apps/web/src/application/use-cases/search-participants.ts index bb6f1e2..3e66fde 100644 --- a/apps/web/src/application/use-cases/search-participants.ts +++ b/apps/web/src/application/use-cases/search-participants.ts @@ -1,14 +1,20 @@ import { MatchingPipeline } from "../../domain/matching/pipeline"; +import { normalizeFilters } from "../../domain/matching/search-query"; +import type { ParticipantRepository } from "../ports/participant-repository"; import type { RateLimiter } from "../ports/rate-limiter"; import { boundedText, LIMITS } from "../../domain/shared/validation"; export async function searchParticipants( - input: { eventId: string; participantId: string; query: string; limit?: number }, - dependencies: { pipeline: MatchingPipeline; limiter?: RateLimiter } + input: { eventId: string; participantId: string; query: string; eventIntents: string[]; filters?: { intent?: string | null; domain?: string | null }; limit?: number }, + dependencies: { pipeline: MatchingPipeline; participants: ParticipantRepository; limiter?: RateLimiter } ) { if (dependencies.limiter && !(await dependencies.limiter.consume(`search:${input.participantId}`, 30, 60))) { throw new Error("Too many searches. Wait a moment and try again."); } const query = boundedText(input.query, "query", "Search", LIMITS.searchQuery, { required: true })!; - return dependencies.pipeline.run({ ...input, query, mode: "search" }); + const filters = normalizeFilters(input.filters ?? {}, { + intents: input.eventIntents, + domains: input.filters?.domain ? await dependencies.participants.listDomains(input.eventId) : [], + }); + return dependencies.pipeline.run({ eventId: input.eventId, participantId: input.participantId, query, filters, limit: input.limit, mode: "search" }); } diff --git a/apps/web/src/domain/matching/pipeline.ts b/apps/web/src/domain/matching/pipeline.ts index 0a4351a..89ea3b6 100644 --- a/apps/web/src/domain/matching/pipeline.ts +++ b/apps/web/src/domain/matching/pipeline.ts @@ -3,7 +3,8 @@ import type { CandidateCache } from "../../application/ports/candidate-cache"; import type { LlmProvider } from "../../application/ports/llm-provider"; import type { MatchRepository } from "../../application/ports/match-repository"; import type { ParticipantRepository } from "../../application/ports/participant-repository"; -import { profileText } from "../participant/participant.entity"; +import { profileText, type ParticipantProfile } from "../participant/participant.entity"; +import { NO_FILTERS, queryRelevance, queryTerms, searchScore, type SearchFilters } from "./search-query"; import { ComplementarityScorer } from "./scorers/complementarity.scorer"; import { DomainScorer } from "./scorers/domain.scorer"; import { IntentScorer } from "./scorers/intent.scorer"; @@ -22,6 +23,7 @@ export interface MatchingInput { participantId: string; mode: "profile" | "search"; query?: string; + filters?: SearchFilters; limit?: number; } @@ -65,11 +67,10 @@ export class MatchingPipeline { // Hidden viewers may still browse; only a saved profile is required. if (!storedProfile?.profileComplete) throw new Error("Complete your event profile before continuing"); - const embeddingText = input.mode === "search" ? input.query!.trim() : profileText(storedProfile); - const embedding = input.mode === "profile" && storedProfile.embedding - ? storedProfile.embedding - : await this.embeddings.embed(embeddingText, input.mode === "search" ? "query" : "profile"); - if (input.mode === "profile" && embedding) { + if (input.mode === "search") return this.search(input, storedProfile); + + const embedding = storedProfile.embedding ?? await this.embeddings.embed(profileText(storedProfile), "profile"); + if (embedding && !storedProfile.embedding) { await this.participants.setEmbedding(input.eventId, input.participantId, embedding); } const viewer = { ...storedProfile, embedding: embedding ?? storedProfile.embedding }; @@ -78,7 +79,6 @@ export class MatchingPipeline { eventId: input.eventId, viewerId: input.participantId, embedding, - query: input.mode === "search" ? input.query : undefined, limit: 50, }); const compatible = this.filter.execute(viewer, retrieved); @@ -86,9 +86,39 @@ export class MatchingPipeline { const top = this.topK.execute(scored, input.limit ?? 12); const { candidates: ranked, rankedBy } = await this.rerank.execute(viewer, top); - if (input.mode === "profile") { - await this.persist.execute(input.eventId, input.participantId, ranked, `${MATCHING_PIPELINE_VERSION}+${rankedBy}`); - } + await this.persist.execute(input.eventId, input.participantId, ranked, `${MATCHING_PIPELINE_VERSION}+${rankedBy}`); + return ranked; + } + + /** + * Search: the query embedding (or its words, without embeddings) retrieves + * and measures relevance; the searcher's own profile measures compatibility. + * Both feed the score, so the same query ranks differently per person. + */ + private async search(input: MatchingInput, viewer: ParticipantProfile) { + const query = input.query!.trim(); + const terms = queryTerms(query); + const queryEmbedding = await this.embeddings.embed(query, "query"); + const retrieved = await this.retrieve.execute({ + eventId: input.eventId, + viewerId: input.participantId, + embedding: queryEmbedding, + query, + terms, + filters: input.filters ?? NO_FILTERS, + limit: 50, + }); + const compatible = this.filter.execute(viewer, retrieved); + const scored = this.score.execute(viewer, compatible).map((candidate) => { + const relevance = queryRelevance(terms, queryEmbedding, candidate.participant); + return { + ...candidate, + score: searchScore(relevance, candidate.score), + scoreBreakdown: { ...candidate.scoreBreakdown, query: relevance, profile: candidate.score / 100 }, + }; + }).sort((a, b) => b.score - a.score); + const top = this.topK.execute(scored, input.limit ?? 12); + const { candidates: ranked } = await this.rerank.execute(viewer, top); return ranked; } } diff --git a/apps/web/src/domain/matching/search-query.ts b/apps/web/src/domain/matching/search-query.ts new file mode 100644 index 0000000..31ee5aa --- /dev/null +++ b/apps/web/src/domain/matching/search-query.ts @@ -0,0 +1,79 @@ +import { Intent } from "../participant/intent"; +import { profileText, type ParticipantProfile } from "../participant/participant.entity"; +import { ValidationError } from "../shared/validation"; +import { cosineSimilarity } from "./scorers/scorer"; + +/** + * What a search means. The query decides who is relevant; the searcher's own + * profile decides who is compatible. The two are scored separately and then + * combined, so the same query ranks differently for different people. + */ +export interface SearchFilters { + intent: Intent | null; + /** One of the domains present among the event's participants. */ + domain: string | null; +} + +export const NO_FILTERS: SearchFilters = { intent: null, domain: null }; + +/** Share of the final search score that comes from the query; the rest is personal compatibility. */ +export const QUERY_WEIGHT = 0.6; + +const MAX_TERMS = 12; +const STOPWORDS = new Set([ + "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "from", "has", "have", "i", "in", "into", "is", "it", + "looking", "me", "my", "of", "on", "or", "people", "person", "someone", "somebody", "the", "their", "they", "to", + "want", "who", "with", "working", "works", "someone's", "interested", "like", "find", "need", "about", +]); + +/** Meaningful lowercase words from a query, used for lexical retrieval and relevance. */ +export function queryTerms(query: string): string[] { + const words = query.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; + return [...new Set(words.filter((word) => word.length > 1 && !STOPWORDS.has(word)))].slice(0, MAX_TERMS); +} + +/** Validates filters against what the event offers; unknown values are rejected, not ignored. */ +export function normalizeFilters( + raw: { intent?: string | null; domain?: string | null }, + allowed: { intents: string[]; domains: string[] } +): SearchFilters { + const intent = raw.intent?.trim() || null; + if (intent && (!allowed.intents.includes(intent) || !Object.values(Intent).includes(intent as Intent))) { + throw new ValidationError("intent", "Choose an intent offered by this event"); + } + const wanted = raw.domain?.trim().toLowerCase() || null; + const domain = wanted ? allowed.domains.find((value) => value.toLowerCase() === wanted) ?? null : null; + if (wanted && !domain) throw new ValidationError("domain", "Choose a domain from the list"); + return { intent: intent as Intent | null, domain }; +} + +export function matchesFilters(profile: ParticipantProfile, filters: SearchFilters): boolean { + if (filters.intent && profile.intent !== filters.intent) return false; + if (filters.domain && profile.domain?.toLowerCase() !== filters.domain.toLowerCase()) return false; + return true; +} + +/** Fraction of query terms that start a word of the candidate's profile (0–1). */ +export function lexicalRelevance(terms: string[], profile: ParticipantProfile): number { + if (!terms.length) return 0; + const words = profileText(profile).toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; + const found = terms.filter((term) => words.some((word) => word.startsWith(term))); + return found.length / terms.length; +} + +/** How well a candidate answers the query: semantic when both vectors exist, otherwise lexical. */ +export function queryRelevance(terms: string[], queryEmbedding: number[] | null, profile: ParticipantProfile): number { + const semantic = cosineSimilarity(queryEmbedding, profile.embedding); + return semantic > 0 ? semantic : lexicalRelevance(terms, profile); +} + +/** Final search score (0–100) from query relevance (0–1) and personal compatibility (0–100). */ +export function searchScore(relevance: number, personal: number): number { + return Math.round(QUERY_WEIGHT * relevance * 100 + (1 - QUERY_WEIGHT) * personal); +} + +/** Postgres to_tsquery text matching any term as a prefix; terms are already letters and digits only. */ +export function lexicalTsQuery(terms: string[]): string | null { + const safe = terms.map((term) => term.replace(/[^\p{L}\p{N}]/gu, "")).filter(Boolean); + return safe.length ? safe.map((term) => `${term}:*`).join(" | ") : null; +} diff --git a/apps/web/src/domain/matching/stages/retrieve.stage.ts b/apps/web/src/domain/matching/stages/retrieve.stage.ts index 9bc9b66..f544a85 100644 --- a/apps/web/src/domain/matching/stages/retrieve.stage.ts +++ b/apps/web/src/domain/matching/stages/retrieve.stage.ts @@ -3,6 +3,7 @@ import type { ParticipantRepository } from "../../../application/ports/participa import type { MatchRepository } from "../../../application/ports/match-repository"; import type { CandidateCache } from "../../../application/ports/candidate-cache"; import type { ParticipantProfile } from "../../participant/participant.entity"; +import { matchesFilters, NO_FILTERS, type SearchFilters } from "../search-query"; export class RetrieveStage { constructor( @@ -15,29 +16,37 @@ export class RetrieveStage { viewerId: string; embedding: number[] | null; query?: string; + terms?: string[]; + filters?: SearchFilters; limit?: number; }): Promise { const limit = input.limit ?? 50; - const normalizedQuery = input.query?.trim().toLowerCase(); + const filters = input.filters ?? NO_FILTERS; + const normalizedQuery = input.query?.trim().toLowerCase().replace(/\s+/g, " "); if (normalizedQuery) { + // Shared across viewers for the same event, query, filters and retrieval + // kind; the ranking that follows is still personal. const key = createHash("sha256") - .update(`${input.eventId}:${normalizedQuery}`) + .update(JSON.stringify([input.eventId, normalizedQuery, filters.intent, filters.domain?.toLowerCase() ?? null, input.embedding ? "semantic" : "lexical"])) .digest("hex"); const cachedIds = await this.cache.get(key); if (cachedIds) { const cached = await this.participants.findCandidatesByIds(input.eventId, cachedIds); const byId = new Map(cached.map((profile) => [profile.attendeeId, profile])); - return cachedIds.map((id) => byId.get(id)).filter((row): row is ParticipantProfile => row !== undefined && row.attendeeId !== input.viewerId); + return cachedIds.map((id) => byId.get(id)) + .filter((row): row is ParticipantProfile => row !== undefined && row.attendeeId !== input.viewerId && matchesFilters(row, filters)); } const candidates = await this.participants.listCandidates({ eventId: input.eventId, excludeAttendeeId: null, embedding: input.embedding, + terms: input.terms, + filters, limit, }); await this.cache.set(key, candidates.map((c) => c.attendeeId), 300); - return candidates.filter((candidate) => candidate.attendeeId !== input.viewerId); + return candidates.filter((candidate) => candidate.attendeeId !== input.viewerId && matchesFilters(candidate, filters)); } return this.participants.listCandidates({ diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index 2787c84..0fbcf1d 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -1,4 +1,5 @@ import { query } from "@match-maker/db"; +import { lexicalTsQuery, type SearchFilters } from "../../domain/matching/search-query"; import type { ParticipantRepository } from "../../application/ports/participant-repository"; import { Intent } from "../../domain/participant/intent"; import type { ParticipantProfile, ParticipantProfileInput } from "../../domain/participant/participant.entity"; @@ -40,6 +41,10 @@ const PROFILE_FROM = `from event_participants p * join), visible, named, and with a saved event profile. Every results path — * fresh retrieval, cached ids, saved matches — applies this same rule. */ +/** Profile text searched when no embeddings are available. */ +const SEARCH_DOCUMENT = `to_tsvector('simple', concat_ws(' ', a.name, p.designation, p.domain, p.about_me, + p.self_description, p.most_impressive_build, array_to_string(p.interests, ' ')))`; + export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null and p.revoked_at is null`; export class PostgresParticipantRepository implements ParticipantRepository { @@ -74,20 +79,41 @@ export class PostgresParticipantRepository implements ParticipantRepository { eventId: string; excludeAttendeeId: string | null; embedding?: number[] | null; + terms?: string[]; + filters?: SearchFilters; limit?: number; }): Promise { const vector = toVector(input.embedding ?? null); + // Lexical retrieval only when there is no query vector to rank by. + const tsQuery = vector ? null : lexicalTsQuery(input.terms ?? []); const { rows } = await query( `select ${PROFILE_COLUMNS} ${PROFILE_FROM} where p.event_id = $1 and ($2::uuid is null or a.id <> $2::uuid) and ${ELIGIBLE_CANDIDATE} + and ($5::text is null or p.intent = $5) + and ($6::text is null or lower(p.domain) = lower($6)) + and ($7::text is null or ${SEARCH_DOCUMENT} @@ to_tsquery('simple', $7)) order by case when $3::vector is not null and p.embedding is not null then 0 else 1 end, - p.embedding <=> $3::vector nulls last, a.name asc + p.embedding <=> $3::vector nulls last, + case when $7::text is null then 0 else ts_rank(${SEARCH_DOCUMENT}, to_tsquery('simple', $7)) end desc, + a.name asc limit $4`, - [input.eventId, input.excludeAttendeeId, vector, Math.max(1, Math.min(100, input.limit ?? 50))] + [input.eventId, input.excludeAttendeeId, vector, Math.max(1, Math.min(100, input.limit ?? 50)), + input.filters?.intent ?? null, input.filters?.domain ?? null, tsQuery] ); return rows.map(mapProfile); } + async listDomains(eventId: string): Promise { + const { rows } = await query<{ domain: string }>( + // One entry per domain ignoring case, preferring a capitalised spelling. + `select (array_agg(trim(p.domain) order by trim(p.domain) = lower(trim(p.domain)), trim(p.domain)))[1] as domain ${PROFILE_FROM} + where p.event_id = $1 and ${ELIGIBLE_CANDIDATE} and coalesce(trim(p.domain), '') <> '' + group by lower(trim(p.domain)) order by 1`, + [eventId] + ); + return rows.map((row) => row.domain.trim()); + } + async findCandidatesByIds(eventId: string, ids: string[]): Promise { if (!ids.length) return []; const { rows } = await query( diff --git a/tests/integration/search-retrieval.test.ts b/tests/integration/search-retrieval.test.ts new file mode 100644 index 0000000..b404d42 --- /dev/null +++ b/tests/integration/search-retrieval.test.ts @@ -0,0 +1,74 @@ +/** + * Query-sensitive retrieval without embeddings, and search filters, against a + * real Postgres. Uses its own organization, event and attendees. + * Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { attendees, closePool, events, query } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo"; +import { Intent } from "../../apps/web/src/domain/participant/intent"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const RUN = Date.now().toString(36); +const ORG = `search-${RUN}`; +const email = (key: string) => `search-${key}-${RUN}@example.com`; + +// Neutral names: names are part of the searchable text. +const NAMES: Record = { designer: "Ana Rao", engineer: "Ben Iyer", founder: "Cy Das" }; +const PEOPLE = { + designer: { designation: "Product Designer", domain: "Design", about_me: "Designing climate tools", intent: "NETWORKING", interests: ["climate"] }, + engineer: { designation: "ML Engineer", domain: "AI", about_me: "Builds retrieval and search systems", intent: "NETWORKING", interests: ["rag"] }, + founder: { designation: "Founder", domain: "ai", about_me: "Hiring engineers for search", intent: "HIRING", interests: ["search"] }, +} as const; + +describeDb("search retrieval", () => { + const repo = new PostgresParticipantRepository(); + let eventId: string; + const ids: Record = {}; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(Object.keys(PEOPLE).map((key) => ({ name: NAMES[key], email: email(key) }))); + for (const key of Object.keys(PEOPLE)) ids[key] = (await attendees.findByEmail(email(key)))!.id; + const { rows: [org] } = await query<{ id: string }>(`insert into organizations (name, slug) values ($1, $1) returning id`, [ORG]); + eventId = (await query<{ id: string }>(`insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') returning id`, [org.id, ORG])).rows[0].id; + await events.attachRoster(eventId, Object.values(ids)); + for (const [key, person] of Object.entries(PEOPLE)) { + await query( + `update event_participants set designation = $3, domain = $4, about_me = $5, intent = $6, interests = $7, profile_updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, ids[key], person.designation, person.domain, person.about_me, person.intent, person.interests] + ); + } + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email like $1`, [`search-%-${RUN}@example.com`]); + await closePool(); + }); + + const names = async (input: Parameters[0]) => + (await repo.listCandidates(input)).map((profile) => profile.name); + + it("returns only people matching the query words, best match first", async () => { + expect(await names({ eventId, excludeAttendeeId: null, terms: ["climate"] })).toEqual(["Ana Rao"]); + const searchers = await names({ eventId, excludeAttendeeId: null, terms: ["search", "engineer"] }); + expect(searchers.sort()).toEqual(["Ben Iyer", "Cy Das"]); + expect(await names({ eventId, excludeAttendeeId: null, terms: ["quantum"] })).toEqual([]); + }); + + it("matches word prefixes", async () => { + expect(await names({ eventId, excludeAttendeeId: null, terms: ["design"] })).toEqual(["Ana Rao"]); + }); + + it("applies intent and domain filters, ignoring domain case", async () => { + expect(await names({ eventId, excludeAttendeeId: null, terms: ["search"], filters: { intent: Intent.HIRING, domain: null } })).toEqual(["Cy Das"]); + expect((await names({ eventId, excludeAttendeeId: null, filters: { intent: null, domain: "AI" } })).sort()).toEqual(["Ben Iyer", "Cy Das"]); + }); + + it("lists each domain present once", async () => { + expect(await repo.listDomains(eventId)).toEqual(["AI", "Design"]); + }); +}); diff --git a/tests/unit/search.test.ts b/tests/unit/search.test.ts new file mode 100644 index 0000000..0de3900 --- /dev/null +++ b/tests/unit/search.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it, vi } from "vitest"; +import { MatchingPipeline } from "@/src/domain/matching/pipeline"; +import { + lexicalRelevance, lexicalTsQuery, matchesFilters, normalizeFilters, queryRelevance, queryTerms, searchScore, +} from "@/src/domain/matching/search-query"; +import type { ParticipantRepository } from "@/src/application/ports/participant-repository"; +import { Intent } from "@/src/domain/participant/intent"; +import type { ParticipantProfile } from "@/src/domain/participant/participant.entity"; +import { ValidationError } from "@/src/domain/shared/validation"; + +const profile = (attendeeId: string, overrides: Partial = {}): ParticipantProfile => ({ + eventId: "event", attendeeId, name: attendeeId, designation: null, domain: null, aboutMe: null, + selfDescription: null, yearsOfExperience: null, mostImpressiveBuild: null, + intent: Intent.NETWORKING, interests: [], venueZone: null, visible: true, profileComplete: true, embedding: null, ...overrides, +}); + +const designer = profile("designer", { designation: "Product Designer", domain: "Design", aboutMe: "Designing climate tools", interests: ["climate"] }); +const engineer = profile("engineer", { designation: "ML Engineer", domain: "AI", aboutMe: "Builds retrieval systems", interests: ["rag", "search"] }); +const founder = profile("founder", { designation: "Founder", domain: "AI", aboutMe: "Hiring engineers", intent: Intent.HIRING, interests: ["search"] }); + +describe("query terms and relevance", () => { + it("keeps meaningful words only", () => { + expect(queryTerms("Someone working on Climate design, with RAG!")).toEqual(["climate", "design", "rag"]); + }); + + it("matches words by prefix against the profile", () => { + expect(lexicalRelevance(["climat", "design"], designer)).toBe(1); + expect(lexicalRelevance(["climate", "rag"], engineer)).toBe(0.5); + expect(lexicalRelevance([], engineer)).toBe(0); + }); + + it("prefers semantic relevance when both vectors exist", () => { + const withVector = { ...engineer, embedding: [1, 0] }; + expect(queryRelevance(["nothing"], [1, 0], withVector)).toBeCloseTo(1); + expect(queryRelevance(["rag"], null, withVector)).toBe(1); + }); + + it("weights query relevance over personal compatibility", () => { + expect(searchScore(1, 0)).toBe(60); + expect(searchScore(0, 100)).toBe(40); + }); + + it("builds a prefix OR query from safe words", () => { + expect(lexicalTsQuery(["climate", "ml"])).toBe("climate:* | ml:*"); + expect(lexicalTsQuery([])).toBeNull(); + }); +}); + +describe("search filters", () => { + const allowed = { intents: ["NETWORKING", "HIRING"], domains: ["AI", "Design"] }; + + it("accepts the event's intents and present domains, matching case", () => { + expect(normalizeFilters({ intent: "HIRING", domain: "ai" }, allowed)).toEqual({ intent: "HIRING", domain: "AI" }); + expect(normalizeFilters({}, allowed)).toEqual({ intent: null, domain: null }); + }); + + it("rejects values outside the catalog", () => { + expect(() => normalizeFilters({ intent: "INVESTING" }, allowed)).toThrow(ValidationError); + expect(() => normalizeFilters({ domain: "Biotech" }, allowed)).toThrow(/Choose a domain/); + }); + + it("checks a profile against the filters", () => { + expect(matchesFilters(founder, { intent: Intent.HIRING, domain: "ai" })).toBe(true); + expect(matchesFilters(engineer, { intent: Intent.HIRING, domain: null })).toBe(false); + }); +}); + +function searchPipeline(candidates: ParticipantProfile[], viewer: ParticipantProfile, cached: string[] | null = null) { + const participants = { + findProfile: vi.fn(async () => viewer), + listCandidates: vi.fn(async () => candidates), + findCandidatesByIds: vi.fn(async (_event: string, ids: string[]) => candidates.filter((c) => ids.includes(c.attendeeId))), + setEmbedding: vi.fn(), + } as unknown as ParticipantRepository; + const cache = { get: vi.fn(async () => cached), set: vi.fn() }; + const matches = { save: vi.fn(), listForParticipant: vi.fn() }; + const pipeline = new MatchingPipeline(participants, matches, { embed: vi.fn(async () => null) }, null, cache); + return { pipeline, participants, cache, matches }; +} + +const search = (pipeline: MatchingPipeline, query: string, filters = { intent: null, domain: null }) => + pipeline.run({ eventId: "event", participantId: "viewer", mode: "search", query, filters }).then((ranked) => ranked.map((c) => c.participant.attendeeId)); + +describe("search pipeline", () => { + const viewer = profile("viewer", { domain: "AI", interests: ["search"] }); + + it("ranks by the query: different queries, different order", async () => { + const { pipeline } = searchPipeline([designer, engineer, founder], viewer); + expect((await search(pipeline, "climate designer"))[0]).toBe("designer"); + expect((await search(pipeline, "retrieval engineer"))[0]).toBe("engineer"); + }); + + it("still ranks personally: the same query orders differently for different people", async () => { + const twins = [profile("ai-person", { domain: "AI", interests: ["search"], aboutMe: "Builds products" }), + profile("design-person", { domain: "Design", interests: ["climate"], aboutMe: "Builds products" })]; + const aiViewer = await search(searchPipeline(twins, profile("viewer", { domain: "AI", interests: ["search"] })).pipeline, "products"); + const designViewer = await search(searchPipeline(twins, profile("viewer", { domain: "Design", interests: ["climate"] })).pipeline, "products"); + expect(aiViewer[0]).toBe("ai-person"); + expect(designViewer[0]).toBe("design-person"); + }); + + it("passes words and filters to retrieval, and keeps the searcher's profile for compatibility", async () => { + const { pipeline, participants, matches } = searchPipeline([engineer], viewer); + await search(pipeline, "RAG engineers", { intent: null, domain: "AI" }); + expect(participants.listCandidates).toHaveBeenCalledWith(expect.objectContaining({ terms: ["rag", "engineers"], filters: { intent: null, domain: "AI" } })); + expect(matches.save).not.toHaveBeenCalled(); + }); + + it("applies filters to cache hits too", async () => { + const { pipeline, participants } = searchPipeline([designer, engineer, founder], viewer, ["designer", "engineer", "founder"]); + expect(await search(pipeline, "search", { intent: Intent.HIRING, domain: null })).toEqual(["founder"]); + expect(participants.listCandidates).not.toHaveBeenCalled(); + }); + + it("keys the shared cache by query and filters", async () => { + const { pipeline, cache } = searchPipeline([engineer], viewer); + await search(pipeline, "search"); + await search(pipeline, " SEARCH "); + await search(pipeline, "search", { intent: null, domain: "AI" }); + const keys = cache.set.mock.calls.map((call) => call[0]); + expect(keys[0]).toBe(keys[1]); + expect(keys[2]).not.toBe(keys[0]); + }); +}); From 111331463163310ac256a308c3dc53fb1fcc74b6 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:23:25 +0530 Subject: [PATCH 02/31] Score mutual interest in both directions with a versioned config (R17) mutualInterest was set from intent compatibility alone, so any two people with compatible goals were shown "Your event goals align" however poorly they fit. Every scorer was also symmetric, so a two-direction rule would have meant nothing. - domain/matching/scoring-config.ts: scorer weights, the mutual interest threshold and a version in one place; the version is part of the persisted computation version (v2.s2), so older results can be found and recomputed - Interests are now directional (how much of what the viewer cares about the candidate shares), so score(A->B) and score(B->A) can differ - ScoreStage computes both directions; the flag needs both to reach the threshold (0.65, calibrated on documented examples). The reverse score is stored in the breakdown - Wording: "Likely a strong fit for each other"; the fallback reason no longer presents intent compatibility as a prediction - Calibration tests: both high flags; compatible goals alone, or a one-way fit, do not; works with and without embeddings --- .../e/[eventSlug]/matches/page.tsx | 2 +- .../e/[eventSlug]/search/SearchForm.tsx | 2 +- apps/web/src/domain/matching/pipeline.ts | 24 ++++--- .../scorers/complementarity.scorer.ts | 3 +- .../domain/matching/scorers/domain.scorer.ts | 3 +- .../domain/matching/scorers/intent.scorer.ts | 3 +- .../domain/matching/scorers/jaccard.scorer.ts | 20 ++++-- .../matching/scorers/semantic.scorer.ts | 3 +- .../matching/scorers/seniority.scorer.ts | 3 +- .../web/src/domain/matching/scoring-config.ts | 33 +++++++++ .../matching/stages/llm-rerank.stage.ts | 4 +- .../src/domain/matching/stages/score.stage.ts | 31 +++++---- tests/unit/mutual-interest.test.ts | 68 +++++++++++++++++++ 13 files changed, 162 insertions(+), 37 deletions(-) create mode 100644 apps/web/src/domain/matching/scoring-config.ts create mode 100644 tests/unit/mutual-interest.test.ts diff --git a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx index 1526903..8e5bd80 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx @@ -43,7 +43,7 @@ export default async function MatchesPage({ params, searchParams }: { {match.participant.aboutMe &&

{match.participant.aboutMe}

} {match.participant.mostImpressiveBuild &&

Built: {match.participant.mostImpressiveBuild}

}

{match.reason || "A promising person to meet at this event."}

-

{match.mutualInterest ? "Your event goals align" : "Suggested for your profile"}

+

{match.mutualInterest ? "Likely a strong fit for each other" : "Suggested for your profile"}

{Math.round(match.score)}%
{canRequestIntro &&