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 && {[person.designation, person.domain].filter(Boolean).join(" · ")}
{person.aboutMe && {person.aboutMe}
}
{person.reason}
- {person.mutualInterest && Your event goals align}
+ {person.mutualInterest && Likely a strong fit for each other}
)}
diff --git a/apps/web/src/domain/matching/pipeline.ts b/apps/web/src/domain/matching/pipeline.ts
index 89ea3b6..8f1e2f8 100644
--- a/apps/web/src/domain/matching/pipeline.ts
+++ b/apps/web/src/domain/matching/pipeline.ts
@@ -8,7 +8,8 @@ import { NO_FILTERS, queryRelevance, queryTerms, searchScore, type SearchFilters
import { ComplementarityScorer } from "./scorers/complementarity.scorer";
import { DomainScorer } from "./scorers/domain.scorer";
import { IntentScorer } from "./scorers/intent.scorer";
-import { JaccardScorer } from "./scorers/jaccard.scorer";
+import { InterestCoverageScorer } from "./scorers/jaccard.scorer";
+import { SCORING_CONFIG } from "./scoring-config";
import { SemanticScorer } from "./scorers/semantic.scorer";
import { SeniorityScorer } from "./scorers/seniority.scorer";
import { IntentFilterStage } from "./stages/intent-filter.stage";
@@ -31,20 +32,25 @@ export interface MatchingInput {
* Bump when scorers, weights, or stage behavior change, so persisted matches
* from an older computation can be recognised and recomputed.
*/
-export const MATCHING_PIPELINE_VERSION = "v1";
+export const MATCHING_PIPELINE_VERSION = `v2.${SCORING_CONFIG.version}`;
-/** Same retrieve/filter/score/top-K/rerank pipeline for both entry points. */
-export class MatchingPipeline {
- private readonly retrieve: RetrieveStage;
- private readonly filter = new IntentFilterStage();
- private readonly score = new ScoreStage([
+/** The scorers the pipeline combines, weighted by SCORING_CONFIG. */
+export function defaultScorers() {
+ return [
new SemanticScorer(),
new IntentScorer(),
new DomainScorer(),
- new JaccardScorer(),
+ new InterestCoverageScorer(),
new ComplementarityScorer(),
new SeniorityScorer(),
- ]);
+ ];
+}
+
+/** Same retrieve/filter/score/top-K/rerank pipeline for both entry points. */
+export class MatchingPipeline {
+ private readonly retrieve: RetrieveStage;
+ private readonly filter = new IntentFilterStage();
+ private readonly score = new ScoreStage(defaultScorers());
private readonly topK = new TopKStage();
private readonly rerank: LlmRerankStage;
private readonly persist: PersistStage;
diff --git a/apps/web/src/domain/matching/scorers/complementarity.scorer.ts b/apps/web/src/domain/matching/scorers/complementarity.scorer.ts
index 229606b..0cf04cc 100644
--- a/apps/web/src/domain/matching/scorers/complementarity.scorer.ts
+++ b/apps/web/src/domain/matching/scorers/complementarity.scorer.ts
@@ -1,10 +1,11 @@
import { areIntentsMutuallyCompatible } from "../../participant/intent";
+import { SCORING_CONFIG } from "../scoring-config";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { Scorer } from "./scorer";
export class ComplementarityScorer implements Scorer {
readonly name = "complementarity";
- readonly weight = 0.05;
+ readonly weight = SCORING_CONFIG.weights.complementarity;
score(viewer: ParticipantProfile, candidate: ParticipantProfile): number {
if (areIntentsMutuallyCompatible(viewer.intent, candidate.intent)) return 1;
return viewer.domain && candidate.domain && viewer.domain !== candidate.domain ? 0.7 : 0.45;
diff --git a/apps/web/src/domain/matching/scorers/domain.scorer.ts b/apps/web/src/domain/matching/scorers/domain.scorer.ts
index 4ae9113..6492874 100644
--- a/apps/web/src/domain/matching/scorers/domain.scorer.ts
+++ b/apps/web/src/domain/matching/scorers/domain.scorer.ts
@@ -1,9 +1,10 @@
+import { SCORING_CONFIG } from "../scoring-config";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { Scorer } from "./scorer";
export class DomainScorer implements Scorer {
readonly name = "domain";
- readonly weight = 0.15;
+ readonly weight = SCORING_CONFIG.weights.domain;
score(viewer: ParticipantProfile, candidate: ParticipantProfile): number {
const a = viewer.domain?.trim().toLowerCase();
const b = candidate.domain?.trim().toLowerCase();
diff --git a/apps/web/src/domain/matching/scorers/intent.scorer.ts b/apps/web/src/domain/matching/scorers/intent.scorer.ts
index b6fcdbf..60c8105 100644
--- a/apps/web/src/domain/matching/scorers/intent.scorer.ts
+++ b/apps/web/src/domain/matching/scorers/intent.scorer.ts
@@ -1,10 +1,11 @@
import { isIntentCompatible } from "../../participant/intent";
+import { SCORING_CONFIG } from "../scoring-config";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { Scorer } from "./scorer";
export class IntentScorer implements Scorer {
readonly name = "intent";
- readonly weight = 0.25;
+ readonly weight = SCORING_CONFIG.weights.intent;
score(viewer: ParticipantProfile, candidate: ParticipantProfile): number {
return isIntentCompatible(viewer.intent, candidate.intent) ? 1 : 0;
}
diff --git a/apps/web/src/domain/matching/scorers/jaccard.scorer.ts b/apps/web/src/domain/matching/scorers/jaccard.scorer.ts
index b690d0b..1970bda 100644
--- a/apps/web/src/domain/matching/scorers/jaccard.scorer.ts
+++ b/apps/web/src/domain/matching/scorers/jaccard.scorer.ts
@@ -1,14 +1,20 @@
import type { ParticipantProfile } from "../../participant/participant.entity";
+import { SCORING_CONFIG } from "../scoring-config";
import { tokenize, type Scorer } from "./scorer";
-export class JaccardScorer implements Scorer {
+/**
+ * Directional interest fit: how much of what the viewer cares about (their
+ * interests and domain) the candidate shares. Unlike a symmetric overlap, a
+ * narrow profile can fit a broad one well while the reverse fits poorly,
+ * which is what lets score(A→B) and score(B→A) differ.
+ */
+export class InterestCoverageScorer implements Scorer {
readonly name = "interests";
- readonly weight = 0.2;
+ readonly weight = SCORING_CONFIG.weights.interests;
score(viewer: ParticipantProfile, candidate: ParticipantProfile): number {
- const left = new Set([...viewer.interests, viewer.domain ?? ""].flatMap((v) => [...tokenize(v)]));
- const right = new Set([...candidate.interests, candidate.domain ?? ""].flatMap((v) => [...tokenize(v)]));
- if (!left.size || !right.size) return 0.4;
- const intersection = [...left].filter((word) => right.has(word)).length;
- return intersection / new Set([...left, ...right]).size;
+ const wanted = new Set([...viewer.interests, viewer.domain ?? ""].flatMap((v) => [...tokenize(v)]));
+ const offered = new Set([...candidate.interests, candidate.domain ?? ""].flatMap((v) => [...tokenize(v)]));
+ if (!wanted.size || !offered.size) return 0.4;
+ return [...wanted].filter((word) => offered.has(word)).length / wanted.size;
}
}
diff --git a/apps/web/src/domain/matching/scorers/semantic.scorer.ts b/apps/web/src/domain/matching/scorers/semantic.scorer.ts
index 7f092b3..a89f0b7 100644
--- a/apps/web/src/domain/matching/scorers/semantic.scorer.ts
+++ b/apps/web/src/domain/matching/scorers/semantic.scorer.ts
@@ -1,9 +1,10 @@
+import { SCORING_CONFIG } from "../scoring-config";
import type { ParticipantProfile } from "../../participant/participant.entity";
import { cosineSimilarity, tokenize, type Scorer } from "./scorer";
export class SemanticScorer implements Scorer {
readonly name = "semantic";
- readonly weight = 0.3;
+ readonly weight = SCORING_CONFIG.weights.semantic;
score(viewer: ParticipantProfile, candidate: ParticipantProfile): number {
const vectorScore = cosineSimilarity(viewer.embedding, candidate.embedding);
diff --git a/apps/web/src/domain/matching/scorers/seniority.scorer.ts b/apps/web/src/domain/matching/scorers/seniority.scorer.ts
index 55f6a15..8b3750a 100644
--- a/apps/web/src/domain/matching/scorers/seniority.scorer.ts
+++ b/apps/web/src/domain/matching/scorers/seniority.scorer.ts
@@ -1,9 +1,10 @@
+import { SCORING_CONFIG } from "../scoring-config";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { Scorer } from "./scorer";
export class SeniorityScorer implements Scorer {
readonly name = "seniority";
- readonly weight = 0.05;
+ readonly weight = SCORING_CONFIG.weights.seniority;
score(viewer: ParticipantProfile, candidate: ParticipantProfile): number {
if (viewer.yearsOfExperience == null || candidate.yearsOfExperience == null) return 0.5;
return Math.max(0.25, 1 - Math.abs(viewer.yearsOfExperience - candidate.yearsOfExperience) / 20);
diff --git a/apps/web/src/domain/matching/scoring-config.ts b/apps/web/src/domain/matching/scoring-config.ts
new file mode 100644
index 0000000..02ea30a
--- /dev/null
+++ b/apps/web/src/domain/matching/scoring-config.ts
@@ -0,0 +1,33 @@
+/**
+ * The scoring configuration: scorer weights and the mutual-interest rule.
+ * Bump `version` whenever a weight, scorer or the threshold changes; it is
+ * part of the persisted computation version, so matches computed under an
+ * older configuration can be found and recomputed.
+ */
+export const SCORING_CONFIG = {
+ version: "s2",
+ weights: {
+ semantic: 0.3,
+ intent: 0.25,
+ interests: 0.2,
+ domain: 0.15,
+ complementarity: 0.05,
+ seniority: 0.05,
+ },
+ /**
+ * Mutual interest means each person is a strong fit for the other: both
+ * directional scores, score(A→B) and score(B→A), reach this value (0–1).
+ * Calibrated on the examples in tests/unit/mutual-interest.test.ts. With
+ * these weights, compatible goals plus a shared domain already reach about
+ * 0.55, so 0.65 requires real interest overlap: a pair sharing domain and
+ * interests scores about 0.75 both ways, a one-way fit about 0.75 and 0.63,
+ * and compatible goals alone about 0.48.
+ */
+ mutualInterestThreshold: 0.65,
+} as const;
+
+export type ScorerName = keyof typeof SCORING_CONFIG.weights;
+
+export function isMutualInterest(forward: number, reverse: number, threshold: number = SCORING_CONFIG.mutualInterestThreshold): boolean {
+ return forward >= threshold && reverse >= threshold;
+}
diff --git a/apps/web/src/domain/matching/stages/llm-rerank.stage.ts b/apps/web/src/domain/matching/stages/llm-rerank.stage.ts
index 6002c0a..60e39c5 100644
--- a/apps/web/src/domain/matching/stages/llm-rerank.stage.ts
+++ b/apps/web/src/domain/matching/stages/llm-rerank.stage.ts
@@ -27,7 +27,9 @@ export class LlmRerankStage {
function addFallbackReason(candidate: MatchCandidate): MatchCandidate {
if (candidate.reason) return candidate;
const person = candidate.participant;
- const sharedIntent = candidate.mutualInterest ? "Your networking goals align" : "Their background adds a complementary perspective";
+ const sharedIntent = candidate.mutualInterest
+ ? "You look like a strong fit for each other"
+ : "Their background adds a complementary perspective";
const detail = person.domain ? ` in ${person.domain}` : "";
return { ...candidate, reason: `${sharedIntent}${detail}.` };
}
diff --git a/apps/web/src/domain/matching/stages/score.stage.ts b/apps/web/src/domain/matching/stages/score.stage.ts
index 3c4abff..29bbc35 100644
--- a/apps/web/src/domain/matching/stages/score.stage.ts
+++ b/apps/web/src/domain/matching/stages/score.stage.ts
@@ -1,31 +1,36 @@
-import { areIntentsMutuallyCompatible } from "../../participant/intent";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { MatchCandidate } from "../match-strategy";
+import { isMutualInterest } from "../scoring-config";
import type { Scorer } from "../scorers/scorer";
+/**
+ * Scores each candidate for the viewer, and the viewer for each candidate.
+ * The forward score ranks; both directions decide mutual interest.
+ */
export class ScoreStage {
constructor(private readonly scorers: Scorer[]) {}
execute(viewer: ParticipantProfile, candidates: ParticipantProfile[]): MatchCandidate[] {
return candidates.map((participant) => {
- const scoreBreakdown = Object.fromEntries(
- this.scorers.map((scorer) => [scorer.name, clamp(scorer.score(viewer, participant))])
- );
- const totalWeight = this.scorers.reduce((sum, scorer) => sum + scorer.weight, 0) || 1;
- const score = this.scorers.reduce(
- (sum, scorer) => sum + scoreBreakdown[scorer.name] * scorer.weight,
- 0
- ) / totalWeight;
-
+ const { total: forward, breakdown } = this.pairScore(viewer, participant);
+ const { total: reverse } = this.pairScore(participant, viewer);
return {
participant,
- score: Math.round(score * 100),
- scoreBreakdown,
- mutualInterest: areIntentsMutuallyCompatible(viewer.intent, participant.intent),
+ score: Math.round(forward * 100),
+ scoreBreakdown: { ...breakdown, reverse },
+ mutualInterest: isMutualInterest(forward, reverse),
reason: null,
};
}).sort((a, b) => b.score - a.score);
}
+
+ /** How well `candidate` fits `viewer`, 0–1, with each scorer's part. */
+ pairScore(viewer: ParticipantProfile, candidate: ParticipantProfile): { total: number; breakdown: Record } {
+ const breakdown = Object.fromEntries(this.scorers.map((scorer) => [scorer.name, clamp(scorer.score(viewer, candidate))]));
+ const totalWeight = this.scorers.reduce((sum, scorer) => sum + scorer.weight, 0) || 1;
+ const total = this.scorers.reduce((sum, scorer) => sum + breakdown[scorer.name] * scorer.weight, 0) / totalWeight;
+ return { total, breakdown };
+ }
}
function clamp(value: number): number {
diff --git a/tests/unit/mutual-interest.test.ts b/tests/unit/mutual-interest.test.ts
new file mode 100644
index 0000000..8c216b6
--- /dev/null
+++ b/tests/unit/mutual-interest.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import { defaultScorers, MATCHING_PIPELINE_VERSION } from "@/src/domain/matching/pipeline";
+import { isMutualInterest, SCORING_CONFIG } from "@/src/domain/matching/scoring-config";
+import { ScoreStage } from "@/src/domain/matching/stages/score.stage";
+import { Intent } from "@/src/domain/participant/intent";
+import type { ParticipantProfile } from "@/src/domain/participant/participant.entity";
+
+const person = (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 stage = new ScoreStage(defaultScorers());
+const both = (a: ParticipantProfile, b: ParticipantProfile) => ({ forward: stage.pairScore(a, b).total, reverse: stage.pairScore(b, a).total });
+const flag = (a: ParticipantProfile, b: ParticipantProfile) => stage.execute(a, [b])[0];
+
+// Calibration examples behind SCORING_CONFIG.mutualInterestThreshold.
+describe("mutual interest", () => {
+ it("flags a pair that fits strongly in both directions", () => {
+ const a = person("a", { domain: "AI", interests: ["rag", "agents"], aboutMe: "Builds retrieval agents" });
+ const b = person("b", { domain: "AI", interests: ["rag", "agents"], aboutMe: "Researches retrieval agents" });
+ const scores = both(a, b);
+ expect(scores.forward).toBeGreaterThanOrEqual(SCORING_CONFIG.mutualInterestThreshold);
+ expect(scores.reverse).toBeGreaterThanOrEqual(SCORING_CONFIG.mutualInterestThreshold);
+ expect(flag(a, b).mutualInterest).toBe(true);
+ });
+
+ it("does not flag compatible goals alone", () => {
+ const a = person("a", { intent: Intent.HIRING, domain: "Finance", interests: ["payments"] });
+ const b = person("b", { intent: Intent.LOOKING_FOR_WORK, domain: "Biology", interests: ["genomics"] });
+ expect(flag(a, b).mutualInterest).toBe(false);
+ });
+
+ it("does not flag a fit that holds only one way", () => {
+ const narrow = person("narrow", { domain: "AI", interests: ["rag"] });
+ const broad = person("broad", { domain: "AI", interests: ["rag", "solar", "policy", "finance"] });
+ const scores = both(narrow, broad);
+ expect(scores.forward).toBeGreaterThanOrEqual(SCORING_CONFIG.mutualInterestThreshold);
+ expect(scores.reverse).toBeLessThan(SCORING_CONFIG.mutualInterestThreshold);
+ expect(flag(narrow, broad).mutualInterest).toBe(false);
+ expect(flag(broad, narrow).mutualInterest).toBe(false);
+ });
+
+ it("still decides without embeddings, and uses them when present", () => {
+ const a = person("a", { domain: "AI", interests: ["rag"] });
+ const b = person("b", { domain: "AI", interests: ["rag"] });
+ const withoutVectors = flag(a, b);
+ const withVectors = flag({ ...a, embedding: [1, 0] }, { ...b, embedding: [1, 0] });
+ expect(withVectors.scoreBreakdown.semantic).toBe(1);
+ expect(withVectors.score).toBeGreaterThan(withoutVectors.score);
+ expect(withVectors.mutualInterest).toBe(true);
+ });
+
+ it("records the reverse score next to the forward breakdown", () => {
+ const result = flag(person("a", { domain: "AI" }), person("b", { domain: "AI" }));
+ expect(result.scoreBreakdown.reverse).toBeGreaterThan(0);
+ });
+
+ it("applies the threshold to both directions", () => {
+ expect(isMutualInterest(0.9, 0.59, 0.6)).toBe(false);
+ expect(isMutualInterest(0.6, 0.6, 0.6)).toBe(true);
+ });
+
+ it("puts the scoring version in the persisted computation version", () => {
+ expect(MATCHING_PIPELINE_VERSION).toContain(SCORING_CONFIG.version);
+ });
+});
From 67f6c8aff64851ad94b91f587545947d22b343ae Mon Sep 17 00:00:00 2001
From: SURYANSH-RAI
Date: Mon, 19 Oct 2026 03:26:54 +0530
Subject: [PATCH 03/31] Cache match explanations per viewer and candidate pair
(R18)
Every rerank asked the model to explain the whole shortlist again,
even when nothing about the pairs had changed.
- Migration 0009: pair_explanations (cache key, event, viewer,
candidate, reason, expiry), deleted with the event
- domain/matching/explanation-key.ts: the key covers event, the
viewer -> candidate direction, both profile revisions (last saved),
model, prompt version, scoring version, and the context: "profile"
or the normalized search query
- LlmRerankStage reads cached reasons first. When every shortlisted
pair has one, the model is not called and the scored order stands: a
cached reason never decides a shortlist's order. Otherwise the model
ranks as before and its new reasons are cached for a week. If the
model fails, cached reasons are used where they exist; a cache outage
never blocks matching
- ExplanationCache port with a Postgres adapter; LlmProvider exposes a
prompt version; the hourly sweep removes expired explanations
---
.../application/ports/explanation-cache.ts | 5 +
.../web/src/application/ports/llm-provider.ts | 2 +
apps/web/src/composition/container.ts | 3 +-
.../src/domain/matching/explanation-key.ts | 32 ++++++
apps/web/src/domain/matching/pipeline.ts | 9 +-
.../matching/stages/llm-rerank.stage.ts | 53 ++++++++-
.../domain/participant/participant.entity.ts | 2 +
.../cache/postgres-explanation-cache.ts | 26 +++++
.../postgres/participant.repo.ts | 1 +
.../providers/gemini-llm.provider.ts | 2 +
.../db/migrations/0009_pair_explanations.sql | 19 ++++
packages/db/src/repositories/housekeeping.ts | 7 +-
tests/integration/explanation-cache.test.ts | 52 +++++++++
tests/unit/explanation-cache.test.ts | 104 ++++++++++++++++++
14 files changed, 307 insertions(+), 10 deletions(-)
create mode 100644 apps/web/src/application/ports/explanation-cache.ts
create mode 100644 apps/web/src/domain/matching/explanation-key.ts
create mode 100644 apps/web/src/infrastructure/cache/postgres-explanation-cache.ts
create mode 100644 packages/db/migrations/0009_pair_explanations.sql
create mode 100644 tests/integration/explanation-cache.test.ts
create mode 100644 tests/unit/explanation-cache.test.ts
diff --git a/apps/web/src/application/ports/explanation-cache.ts b/apps/web/src/application/ports/explanation-cache.ts
new file mode 100644
index 0000000..55a1204
--- /dev/null
+++ b/apps/web/src/application/ports/explanation-cache.ts
@@ -0,0 +1,5 @@
+/** Cached match reasons for single viewer -> candidate pairs (never a ranking). */
+export interface ExplanationCache {
+ getMany(keys: string[]): Promise