From 0405de5d07e09cc7e3763d50165f1dea6acf300f Mon Sep 17 00:00:00 2001
From: SURYANSH-RAI
Date: Mon, 19 Oct 2026 03:07:37 +0530
Subject: [PATCH 01/33] bug fixx-org-admin-cannot-save-event-settings
R14 lets organization owners and admins configure every event in their
organization, but events.update still required an event_organizers row
in its own SQL, so an organization admin who did not create the event
got "Event not found" when saving its settings. The query now applies
the same rule as the use case. Covered by a real-Postgres test that
fails on the old query.
---
packages/db/src/repositories/events.ts | 5 ++++-
tests/integration/roster-import-ownership.test.ts | 6 ++++++
2 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts
index 17d6ed1..97b8ede 100644
--- a/packages/db/src/repositories/events.ts
+++ b/packages/db/src/repositories/events.ts
@@ -104,7 +104,10 @@ export async function update(input: {
}): Promise {
const { rows } = await query(
`${EVENT_SELECT}
- where e.id = $1 and exists (select 1 from event_organizers eo where eo.event_id = e.id and eo.attendee_id = $2)
+ where e.id = $1
+ and (exists (select 1 from event_organizers eo where eo.event_id = e.id and eo.attendee_id = $2)
+ or exists (select 1 from organization_members m
+ where m.organization_id = e.organization_id and m.attendee_id = $2 and m.role in ('owner', 'admin')))
limit 1`,
[input.eventId, input.organizerId]
);
diff --git a/tests/integration/roster-import-ownership.test.ts b/tests/integration/roster-import-ownership.test.ts
index 26d7348..e908785 100644
--- a/tests/integration/roster-import-ownership.test.ts
+++ b/tests/integration/roster-import-ownership.test.ts
@@ -64,6 +64,12 @@ describeDb("organizer roles and roster import ownership", () => {
expect(await events.isOrganizer(eventB, ids.admin)).toBe(false);
});
+ it("lets an organization admin save settings of an event they did not create", async () => {
+ const updated = await events.update({ eventId: eventA, organizerId: ids.admin, zones: ["Hall"] });
+ expect(updated?.zones).toEqual(["Hall"]);
+ expect(await events.update({ eventId: eventA2, organizerId: ids.member, zones: ["Nope"] })).toBeNull();
+ });
+
it("lists only the events a viewer may open", async () => {
const slugs = async (viewer: string) => (await events.listForOrganization(ORG_A, viewer)).map((event) => event.slug).sort();
expect(await slugs(ids.admin)).toEqual([`${ORG_A}-one`, `${ORG_A}-two`]);
From 8e00648526f60a07185af60fbe712692e479b359 Mon Sep 17 00:00:00 2001
From: SURYANSH-RAI
Date: Mon, 19 Oct 2026 03:12:08 +0530
Subject: [PATCH 02/33] Let organizers configure the participant profile form
(R15)
events.form_config existed, but the participant form was fixed.
- domain/participant/profile-form.ts: a catalog of the profile fields
matching already reads (role, domain, about, focus, build, years,
interests). Per event, organizers set each field's label, whether it
is shown and whether it is required. A required field must be shown,
and at least one descriptive field stays required so matching always
has text. Each save bumps the form version
- Organizer dashboard: "Profile form" settings (owners/admins); errors
keep the edits on screen
- The participant form renders from the config, and the server
validates against the same config with its labels
- Hidden fields keep what was saved before, and every stored field
still feeds matching, so changing the form never wipes profiles or
changes embeddings
- Migration 0008: profile_form_version per participant; someone saved
under an older form is asked for newly required answers, while their
matches keep working
---
.../[orgSlug]/events/[eventSlug]/page.tsx | 12 ++-
.../e/[eventSlug]/profile/page.tsx | 9 ++-
apps/web/app/actions/organizer.actions.ts | 20 ++++-
apps/web/app/actions/participant.actions.ts | 3 +-
.../organizer/ProfileFormSettings.tsx | 40 ++++++++++
.../components/participant/ProfileForm.tsx | 32 ++++----
.../src/application/use-cases/manage-event.ts | 13 ++++
.../use-cases/upsert-participant.ts | 15 +++-
.../domain/participant/participant.entity.ts | 27 +++++--
.../src/domain/participant/profile-form.ts | 76 ++++++++++++++++++
.../postgres/participant.repo.ts | 8 +-
.../migrations/0008_profile_form_version.sql | 8 ++
tests/unit/profile-form.test.ts | 78 +++++++++++++++++++
13 files changed, 311 insertions(+), 30 deletions(-)
create mode 100644 apps/web/components/organizer/ProfileFormSettings.tsx
create mode 100644 apps/web/src/domain/participant/profile-form.ts
create mode 100644 packages/db/migrations/0008_profile_form_version.sql
create mode 100644 tests/unit/profile-form.test.ts
diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx
index a032190..6c5e849 100644
--- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx
+++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx
@@ -1,12 +1,14 @@
import Link from "next/link";
import SignOutButton from "@/components/ui/SignOutButton";
-import { updateEventAction } from "../../../../../actions/organizer.actions";
+import { updateEventAction, updateProfileFormAction } from "../../../../../actions/organizer.actions";
+import ProfileFormSettings from "@/components/organizer/ProfileFormSettings";
+import { readProfileForm } from "@/src/domain/participant/profile-form";
import { requireOrganizerEvent } from "@/src/lib/auth";
import { EventSetupForm } from "@/components/organizer/EventForms";
export default async function EventDashboardPage({ params, searchParams }: {
params: Promise<{ orgSlug: string; eventSlug: string }>;
- searchParams: Promise<{ saved?: string }>;
+ searchParams: Promise<{ saved?: string; form?: string }>;
}) {
const { orgSlug, eventSlug } = await params;
const notice = await searchParams;
@@ -36,6 +38,12 @@ export default async function EventDashboardPage({ params, searchParams }: {
}} /> :
Registration is {event.status}. Only event owners and admins can change this event's settings.
}
+ {can("configure") && <>
+ Profile form
+ Choose which questions attendees answer, what they are called, and which are required.
+ {notice.form && Profile form saved. Attendees missing a newly required answer are asked for it next time they open their profile.
}
+
+ >}
;
}
diff --git a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx
index ee6f179..ff7ffa2 100644
--- a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx
+++ b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx
@@ -4,6 +4,7 @@ import { notFound } from "next/navigation";
import { saveParticipantProfile } from "../../../../actions/participant.actions";
import { requireParticipantEvent } from "@/src/lib/auth";
import ProfileForm from "@/components/participant/ProfileForm";
+import { missingRequiredFields, readProfileForm } from "@/src/domain/participant/profile-form";
export default async function ProfilePage({ params }: { params: Promise<{ eventSlug: string }> }) {
const { eventSlug } = await params;
@@ -12,13 +13,19 @@ export default async function ProfilePage({ params }: { params: Promise<{ eventS
if (!profile) notFound();
const intents = event.intents?.length ? event.intents : ["NETWORKING"];
const zones = event.zones ?? [];
+ const form = readProfileForm(event.form_config);
+ // Saved under an older form that now requires something they left empty.
+ const missing = profile.profileComplete && (profile.formVersion ?? 0) < form.version ? missingRequiredFields(form, profile) : [];
return
← {event.name} Connections
PARTICIPANT PROFILE
Make your next introduction count.
Confirm the profile other attendees will see, then set what you want from this event.
- 0 &&
+ The organizer now asks for: {missing.map((key) => form.fields[key].label).join(", ")}. Your matches keep working meanwhile.
+
}
+ {
+ return runFormAction(formData, async () => {
+ const session = await getSession();
+ if (!session) throw new Error("Sign in as an organizer first");
+ const container = getContainer();
+ const event = await container.events.findBySlug(organizationSlug, eventSlug);
+ if (!event) throw new Error("Event not found");
+ const fields = Object.fromEntries(PROFILE_FIELD_KEYS.map((key) => [key, {
+ label: String(formData.get(`${key}.label`) ?? ""),
+ shown: formData.get(`${key}.shown`) === "on",
+ required: formData.get(`${key}.required`) === "on",
+ }])) as Record;
+ await configureProfileForm({ eventId: event.id, organizerId: session.attendeeId, fields, currentConfig: event.form_config }, container.events);
+ redirect(`/orgs/${organizationSlug}/events/${eventSlug}?form=saved`);
+ });
+}
diff --git a/apps/web/app/actions/participant.actions.ts b/apps/web/app/actions/participant.actions.ts
index 23a2986..5db11f3 100644
--- a/apps/web/app/actions/participant.actions.ts
+++ b/apps/web/app/actions/participant.actions.ts
@@ -5,6 +5,7 @@ import { getContainer } from "../../src/composition/container";
import { assertEventAllows } from "../../src/domain/shared/event-lifecycle";
import { Intent } from "../../src/domain/participant/intent";
import { ValidationError } from "../../src/domain/shared/validation";
+import { readProfileForm } from "../../src/domain/participant/profile-form";
import { clearSession, endIdentityProviderSession, getSession } from "../../lib/session";
import { runFormAction, type FormState } from "../../lib/form-state";
import { redirect } from "next/navigation";
@@ -44,7 +45,7 @@ async function saveProfile(eventSlug: string, formData: FormData) {
selfDescription: nullable(formData.get("selfDescription")),
yearsOfExperience: parseYears(formData.get("yearsOfExperience")),
mostImpressiveBuild: nullable(formData.get("mostImpressiveBuild")),
- }, { participants: container.participants, enqueueMatching: container.enqueueEmbedding });
+ }, { participants: container.participants, enqueueMatching: container.enqueueEmbedding }, readProfileForm(event.form_config));
}
export async function signOutCurrentUser() {
diff --git a/apps/web/components/organizer/ProfileFormSettings.tsx b/apps/web/components/organizer/ProfileFormSettings.tsx
new file mode 100644
index 0000000..e505d30
--- /dev/null
+++ b/apps/web/components/organizer/ProfileFormSettings.tsx
@@ -0,0 +1,40 @@
+"use client";
+
+import { useActionState } from "react";
+import { initialFormState } from "@/lib/form-state";
+import { LABEL_LIMIT, PROFILE_FIELD_KEYS, PROFILE_FIELDS, type ProfileFormConfig } from "@/src/domain/participant/profile-form";
+import { FormAlert, SubmitButton, type FormAction } from "../ui/form";
+
+/** Organizer settings for the participant profile form: label, shown, required per field. */
+export default function ProfileFormSettings({ action, form }: { action: FormAction; form: ProfileFormConfig }) {
+ const [state, formAction] = useActionState(action, initialFormState);
+ const value = (name: string, fallback: string) => state.values[name] ?? fallback;
+ const checked = (name: string, fallback: boolean) => state.values[`${name}.submitted`] ? state.values[name] === "on" : fallback;
+ return ;
+}
+
+const input = { width: "100%", minWidth: 180, boxSizing: "border-box", padding: "9px 10px", border: "1px solid #3f3f46", borderRadius: 8, background: "#151519", color: "#f4f4f5", font: "inherit" } as const;
diff --git a/apps/web/components/participant/ProfileForm.tsx b/apps/web/components/participant/ProfileForm.tsx
index 1124adc..35b1672 100644
--- a/apps/web/components/participant/ProfileForm.tsx
+++ b/apps/web/components/participant/ProfileForm.tsx
@@ -3,6 +3,7 @@
import { useActionState } from "react";
import { initialFormState } from "@/lib/form-state";
import { LIMITS } from "@/src/domain/shared/validation";
+import type { ProfileFormConfig } from "@/src/domain/participant/profile-form";
import { FormAlert, SelectField, SubmitButton, TextField, type FormAction } from "../ui/form";
export interface ProfileFormValues {
@@ -20,28 +21,33 @@ export interface ProfileFormValues {
const label = (intent: string) => intent.replaceAll("_", " ").toLowerCase();
-export default function ProfileForm({ action, profile, intents, zones }: {
+/** The participant profile, shaped by the event's profile form (labels, hidden and required fields). */
+export default function ProfileForm({ action, profile, intents, zones, form }: {
action: FormAction;
profile: ProfileFormValues;
intents: string[];
zones: string[];
+ form: ProfileFormConfig;
}) {
const [state, formAction] = useActionState(action, initialFormState);
+ const field = form.fields;
return
{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
← Matches Connections
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 04/33] 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 05/33] 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>;
+ setMany(entries: Array<{ key: string; eventId: string; viewerId: string; candidateId: string; reason: string }>, ttlSeconds: number): Promise;
+}
diff --git a/apps/web/src/application/ports/llm-provider.ts b/apps/web/src/application/ports/llm-provider.ts
index fb5bbb1..8e38241 100644
--- a/apps/web/src/application/ports/llm-provider.ts
+++ b/apps/web/src/application/ports/llm-provider.ts
@@ -4,5 +4,7 @@ import type { ParticipantProfile } from "../../domain/participant/participant.en
export interface LlmProvider {
/** Identifies the provider and model, recorded with every reranked result. */
readonly id: string;
+ /** Bump when the prompt changes, so cached explanations are not reused across prompts. */
+ readonly promptVersion: string;
rerank(viewer: ParticipantProfile, candidates: MatchCandidate[]): Promise;
}
diff --git a/apps/web/src/composition/container.ts b/apps/web/src/composition/container.ts
index d0f73be..636323a 100644
--- a/apps/web/src/composition/container.ts
+++ b/apps/web/src/composition/container.ts
@@ -6,6 +6,7 @@ import { PostgresRateLimiter } from "../infrastructure/cache/postgres-rate-limit
import { PostgresEventRepository } from "../infrastructure/postgres/event.repo";
import { PostgresMatchQueue } from "../infrastructure/postgres/match-queue.repo";
import { PostgresCandidateCache } from "../infrastructure/cache/postgres-candidate-cache";
+import { PostgresExplanationCache } from "../infrastructure/cache/postgres-explanation-cache";
import { UpstashCandidateCache } from "../infrastructure/cache/upstash-candidate-cache";
import { RealtimeNotifier } from "../infrastructure/notifications/realtime.notifier";
import { ProviderRegistry } from "../infrastructure/providers/provider-registry";
@@ -32,7 +33,7 @@ function buildContainer() {
matchQueue: new PostgresMatchQueue(),
notifications: new RealtimeNotifier(),
limiter: new PostgresRateLimiter(),
- pipeline: new MatchingPipeline(participants, matches, embeddings, llm, candidateCache),
+ pipeline: new MatchingPipeline(participants, matches, embeddings, llm, candidateCache, new PostgresExplanationCache()),
enqueueMatching: matchingJobs.enqueue,
enqueueEmbedding: (eventId: string, participantId: string) => matchingJobs.enqueue(eventId, participantId, "embed"),
};
diff --git a/apps/web/src/domain/matching/explanation-key.ts b/apps/web/src/domain/matching/explanation-key.ts
new file mode 100644
index 0000000..5b21c1b
--- /dev/null
+++ b/apps/web/src/domain/matching/explanation-key.ts
@@ -0,0 +1,32 @@
+import { createHash } from "node:crypto";
+import type { ParticipantProfile } from "../participant/participant.entity";
+import { SCORING_CONFIG } from "./scoring-config";
+
+/** Reasons are reused for a week at most, and earlier when anything in the key changes. */
+export const EXPLANATION_TTL_SECONDS = 7 * 24 * 60 * 60;
+
+/**
+ * Identifies one directional explanation: why `candidate` suits `viewer`, at
+ * these profile revisions, from this model and prompt, under this scoring
+ * configuration, for this context ("profile" or a normalized search query).
+ */
+export function explanationKey(input: {
+ eventId: string;
+ viewer: ParticipantProfile;
+ candidate: ParticipantProfile;
+ model: string;
+ promptVersion: string;
+ context: string;
+}): string {
+ return createHash("sha256").update(JSON.stringify([
+ input.eventId,
+ input.viewer.attendeeId, input.viewer.profileRevision ?? null,
+ input.candidate.attendeeId, input.candidate.profileRevision ?? null,
+ input.model, input.promptVersion, SCORING_CONFIG.version, input.context,
+ ])).digest("hex");
+}
+
+/** The context for search explanations: the normalized query. */
+export function queryContext(query: string): string {
+ return `query:${query.trim().toLowerCase().replace(/\s+/g, " ")}`;
+}
diff --git a/apps/web/src/domain/matching/pipeline.ts b/apps/web/src/domain/matching/pipeline.ts
index 8f1e2f8..ca04f62 100644
--- a/apps/web/src/domain/matching/pipeline.ts
+++ b/apps/web/src/domain/matching/pipeline.ts
@@ -1,5 +1,7 @@
import type { EmbeddingProvider } from "../../application/ports/embedding-provider";
import type { CandidateCache } from "../../application/ports/candidate-cache";
+import type { ExplanationCache } from "../../application/ports/explanation-cache";
+import { queryContext } from "./explanation-key";
import type { LlmProvider } from "../../application/ports/llm-provider";
import type { MatchRepository } from "../../application/ports/match-repository";
import type { ParticipantRepository } from "../../application/ports/participant-repository";
@@ -60,10 +62,11 @@ export class MatchingPipeline {
matches: MatchRepository,
private readonly embeddings: EmbeddingProvider,
llm: LlmProvider | null,
- cache: CandidateCache
+ cache: CandidateCache,
+ explanations: ExplanationCache | null = null
) {
this.retrieve = new RetrieveStage(participants, cache);
- this.rerank = new LlmRerankStage(llm);
+ this.rerank = new LlmRerankStage(llm, explanations);
this.persist = new PersistStage(matches);
}
@@ -124,7 +127,7 @@ export class MatchingPipeline {
};
}).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);
+ const { candidates: ranked } = await this.rerank.execute(viewer, top, queryContext(query));
return ranked;
}
}
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 60e39c5..df0e8c2 100644
--- a/apps/web/src/domain/matching/stages/llm-rerank.stage.ts
+++ b/apps/web/src/domain/matching/stages/llm-rerank.stage.ts
@@ -1,6 +1,8 @@
import type { LlmProvider } from "../../../application/ports/llm-provider";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { MatchCandidate } from "../match-strategy";
+import type { ExplanationCache } from "../../../application/ports/explanation-cache";
+import { EXPLANATION_TTL_SECONDS, explanationKey } from "../explanation-key";
export interface RerankResult {
candidates: MatchCandidate[];
@@ -8,18 +10,59 @@ export interface RerankResult {
rankedBy: string;
}
+/**
+ * Orders the shortlist with the model and explains each match. Explanations
+ * are cached per viewer -> candidate pair: when every pair already has one,
+ * the model is not called and the scored order stands. A cached reason never
+ * decides the order of a shortlist.
+ */
export class LlmRerankStage {
- constructor(private readonly provider: LlmProvider | null) {}
+ constructor(
+ private readonly provider: LlmProvider | null,
+ private readonly cache: ExplanationCache | null = null
+ ) {}
- async execute(viewer: ParticipantProfile, candidates: MatchCandidate[]): Promise {
+ async execute(viewer: ParticipantProfile, candidates: MatchCandidate[], context = "profile"): Promise {
const scored = { candidates: candidates.map(addFallbackReason), rankedBy: "score" };
if (!this.provider || candidates.length === 0) return scored;
+ const provider = this.provider;
+ const keyFor = (candidate: MatchCandidate) => explanationKey({
+ eventId: viewer.eventId, viewer, candidate: candidate.participant,
+ model: provider.id, promptVersion: provider.promptVersion, context,
+ });
+ const keys = candidates.map(keyFor);
+ const cached = await this.readCache(keys);
+ const withCached = candidates.map((candidate, index) => ({ ...candidate, reason: cached.get(keys[index]) ?? candidate.reason }));
+ if (cached.size === candidates.length) return { candidates: withCached, rankedBy: "score" };
+
try {
- const reranked = await this.provider.rerank(viewer, candidates);
- return { candidates: reranked.map(addFallbackReason), rankedBy: `llm:${this.provider.id}` };
+ const reranked = await provider.rerank(viewer, candidates);
+ await this.writeCache(viewer, reranked.filter((candidate) => candidate.reason).map((candidate) => ({
+ key: keyFor(candidate), candidateId: candidate.participant.attendeeId, reason: candidate.reason!,
+ })));
+ return { candidates: reranked.map(addFallbackReason), rankedBy: `llm:${provider.id}` };
} catch (error) {
console.warn("[matching] LLM rerank unavailable; using scored order", error);
- return scored;
+ return { candidates: withCached.map(addFallbackReason), rankedBy: "score" };
+ }
+ }
+
+ private async readCache(keys: string[]): Promise> {
+ if (!this.cache) return new Map();
+ try {
+ return await this.cache.getMany(keys);
+ } catch (error) {
+ console.warn("[matching] explanation cache unavailable", error);
+ return new Map();
+ }
+ }
+
+ private async writeCache(viewer: ParticipantProfile, entries: Array<{ key: string; candidateId: string; reason: string }>) {
+ if (!this.cache || !entries.length) return;
+ try {
+ await this.cache.setMany(entries.map((entry) => ({ ...entry, eventId: viewer.eventId, viewerId: viewer.attendeeId })), EXPLANATION_TTL_SECONDS);
+ } catch (error) {
+ console.warn("[matching] could not cache explanations", error);
}
}
}
diff --git a/apps/web/src/domain/participant/participant.entity.ts b/apps/web/src/domain/participant/participant.entity.ts
index e9b51a7..c82b367 100644
--- a/apps/web/src/domain/participant/participant.entity.ts
+++ b/apps/web/src/domain/participant/participant.entity.ts
@@ -19,6 +19,8 @@ export interface ParticipantProfile {
venueZone: string | null;
visible: boolean;
profileComplete?: boolean;
+ /** When the profile was last saved; part of cached explanation keys. */
+ profileRevision?: string | null;
/** Version of the event's profile form this profile was saved under. */
formVersion?: number;
embedding?: number[] | null;
diff --git a/apps/web/src/infrastructure/cache/postgres-explanation-cache.ts b/apps/web/src/infrastructure/cache/postgres-explanation-cache.ts
new file mode 100644
index 0000000..575a555
--- /dev/null
+++ b/apps/web/src/infrastructure/cache/postgres-explanation-cache.ts
@@ -0,0 +1,26 @@
+import { query } from "@match-maker/db";
+import type { ExplanationCache } from "../../application/ports/explanation-cache";
+
+export class PostgresExplanationCache implements ExplanationCache {
+ async getMany(keys: string[]): Promise> {
+ if (!keys.length) return new Map();
+ const { rows } = await query<{ cache_key: string; reason: string }>(
+ `select cache_key, reason from pair_explanations where cache_key = any($1::text[]) and expires_at > now()`,
+ [keys]
+ );
+ return new Map(rows.map((row) => [row.cache_key, row.reason]));
+ }
+
+ async setMany(entries: Parameters[0], ttlSeconds: number): Promise {
+ if (!entries.length) return;
+ await query(
+ `insert into pair_explanations (cache_key, event_id, viewer_id, candidate_id, reason, expires_at)
+ select e.key, e.event_id, e.viewer_id, e.candidate_id, e.reason, now() + make_interval(secs => $2)
+ from jsonb_to_recordset($1::jsonb) as e(key text, event_id uuid, viewer_id uuid, candidate_id uuid, reason text)
+ on conflict (cache_key) do update set reason = excluded.reason, expires_at = excluded.expires_at`,
+ [JSON.stringify(entries.map((entry) => ({
+ key: entry.key, event_id: entry.eventId, viewer_id: entry.viewerId, candidate_id: entry.candidateId, reason: entry.reason,
+ }))), ttlSeconds]
+ );
+ }
+}
diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts
index 0fbcf1d..8318ef0 100644
--- a/apps/web/src/infrastructure/postgres/participant.repo.ts
+++ b/apps/web/src/infrastructure/postgres/participant.repo.ts
@@ -176,6 +176,7 @@ function mapProfile(row: ProfileRow): ParticipantProfile {
visible: row.visible,
profileComplete: Boolean(row.profile_updated_at),
formVersion: row.profile_form_version ?? 0,
+ profileRevision: row.profile_updated_at ? new Date(row.profile_updated_at).toISOString() : null,
embedding: parseEmbedding(row.embedding),
};
}
diff --git a/apps/web/src/infrastructure/providers/gemini-llm.provider.ts b/apps/web/src/infrastructure/providers/gemini-llm.provider.ts
index d3a3188..d0c9d5d 100644
--- a/apps/web/src/infrastructure/providers/gemini-llm.provider.ts
+++ b/apps/web/src/infrastructure/providers/gemini-llm.provider.ts
@@ -5,6 +5,8 @@ import type { ParticipantProfile } from "../../domain/participant/participant.en
const DEFAULT_MODEL = "gemini-3.8-flash";
export class GeminiLlmProvider implements LlmProvider {
+ readonly promptVersion = "p1";
+
get id(): string {
return `gemini:${process.env.GEMINI_LLM_MODEL || DEFAULT_MODEL}`;
}
diff --git a/packages/db/migrations/0009_pair_explanations.sql b/packages/db/migrations/0009_pair_explanations.sql
new file mode 100644
index 0000000..04b5467
--- /dev/null
+++ b/packages/db/migrations/0009_pair_explanations.sql
@@ -0,0 +1,19 @@
+-- Cached one-sentence reasons for a viewer -> candidate pair.
+--
+-- The key covers the event, both people (in that direction), both profile
+-- revisions, the model, prompt and scoring versions, and the query context,
+-- so a changed profile or query never reuses stale reasoning. Only reasons
+-- are cached here, never a shortlist order.
+
+create table if not exists pair_explanations (
+ cache_key text primary key,
+ event_id uuid not null references events(id) on delete cascade,
+ viewer_id uuid not null,
+ candidate_id uuid not null,
+ reason text not null,
+ expires_at timestamptz not null,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists idx_pair_explanations_expires on pair_explanations (expires_at);
+create index if not exists idx_pair_explanations_people on pair_explanations (event_id, candidate_id);
diff --git a/packages/db/src/repositories/housekeeping.ts b/packages/db/src/repositories/housekeeping.ts
index ec8e6fc..42226c9 100644
--- a/packages/db/src/repositories/housekeeping.ts
+++ b/packages/db/src/repositories/housekeeping.ts
@@ -13,6 +13,7 @@ export interface SweepResult {
loginChallenges: number;
rateLimitBuckets: number;
retrievalCache: number;
+ pairExplanations: number;
}
/** Deletes rows that can no longer be used. Safe to run on any schedule. */
@@ -23,5 +24,9 @@ export async function sweepExpired(): Promise {
[RETENTION.rateLimitBucketHours]
);
const cache = await query(`delete from retrieval_cache where expires_at < now()`);
- return { loginChallenges, rateLimitBuckets: buckets.rowCount ?? 0, retrievalCache: cache.rowCount ?? 0 };
+ const explanations = await query(`delete from pair_explanations where expires_at < now()`);
+ return {
+ loginChallenges, rateLimitBuckets: buckets.rowCount ?? 0, retrievalCache: cache.rowCount ?? 0,
+ pairExplanations: explanations.rowCount ?? 0,
+ };
}
diff --git a/tests/integration/explanation-cache.test.ts b/tests/integration/explanation-cache.test.ts
new file mode 100644
index 0000000..28142eb
--- /dev/null
+++ b/tests/integration/explanation-cache.test.ts
@@ -0,0 +1,52 @@
+/**
+ * The Postgres explanation cache: reads, overwrites, expiry, the housekeeping
+ * sweep and deletion with the event. Uses its own organization and event.
+ * Skipped when DATABASE_URL is unset.
+ */
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { closePool, housekeeping, query } from "@match-maker/db";
+import { migrate } from "../../packages/db/src/migrate";
+import { PostgresExplanationCache } from "../../apps/web/src/infrastructure/cache/postgres-explanation-cache";
+
+const describeDb = process.env.DATABASE_URL ? describe : describe.skip;
+const ORG = `explain-${Date.now().toString(36)}`;
+
+describeDb("Postgres explanation cache", () => {
+ const cache = new PostgresExplanationCache();
+ let eventId: string;
+ const viewerId = randomUUID();
+ const candidateId = randomUUID();
+ const entry = (key: string, reason: string) => ({ key: `${ORG}:${key}`, eventId, viewerId, candidateId, reason });
+
+ beforeAll(async () => {
+ await migrate();
+ 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) values ($1, $2, $2) returning id`, [org.id, ORG])).rows[0].id;
+ });
+
+ afterAll(async () => {
+ await query(`delete from organizations where slug = $1`, [ORG]);
+ await closePool();
+ });
+
+ it("returns stored reasons and overwrites on a second write", async () => {
+ await cache.setMany([entry("one", "First reason"), entry("two", "Second reason")], 60);
+ await cache.setMany([entry("one", "Updated reason")], 60);
+ const found = await cache.getMany([`${ORG}:one`, `${ORG}:two`, `${ORG}:missing`]);
+ expect(Object.fromEntries(found)).toEqual({ [`${ORG}:one`]: "Updated reason", [`${ORG}:two`]: "Second reason" });
+ });
+
+ it("ignores expired entries and the sweep removes them", async () => {
+ await cache.setMany([entry("old", "Old reason")], 60);
+ await query(`update pair_explanations set expires_at = now() - interval '1 minute' where cache_key = $1`, [`${ORG}:old`]);
+ expect((await cache.getMany([`${ORG}:old`])).size).toBe(0);
+ await housekeeping.sweepExpired();
+ expect((await query(`select 1 from pair_explanations where cache_key = $1`, [`${ORG}:old`])).rows).toHaveLength(0);
+ });
+
+ it("is deleted with its event", async () => {
+ await query(`delete from events where id = $1`, [eventId]);
+ expect((await cache.getMany([`${ORG}:one`, `${ORG}:two`])).size).toBe(0);
+ });
+});
diff --git a/tests/unit/explanation-cache.test.ts b/tests/unit/explanation-cache.test.ts
new file mode 100644
index 0000000..509e30a
--- /dev/null
+++ b/tests/unit/explanation-cache.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it, vi } from "vitest";
+import { LlmRerankStage } from "@/src/domain/matching/stages/llm-rerank.stage";
+import { explanationKey, queryContext } from "@/src/domain/matching/explanation-key";
+import type { ExplanationCache } from "@/src/application/ports/explanation-cache";
+import type { LlmProvider } from "@/src/application/ports/llm-provider";
+import type { MatchCandidate } from "@/src/domain/matching/match-strategy";
+import { Intent } from "@/src/domain/participant/intent";
+import type { ParticipantProfile } from "@/src/domain/participant/participant.entity";
+
+const person = (attendeeId: string, profileRevision = "r1"): ParticipantProfile => ({
+ eventId: "event", attendeeId, name: attendeeId, designation: null, domain: "AI", aboutMe: null, selfDescription: null,
+ yearsOfExperience: null, mostImpressiveBuild: null, intent: Intent.NETWORKING, interests: [], venueZone: null, visible: true,
+ profileComplete: true, embedding: null, profileRevision,
+});
+const candidate = (profile: ParticipantProfile, score: number): MatchCandidate => ({ participant: profile, score, scoreBreakdown: {}, mutualInterest: false, reason: null });
+
+function memoryCache(): ExplanationCache & { store: Map } {
+ const store = new Map();
+ return {
+ store,
+ getMany: vi.fn(async (keys: string[]) => new Map(keys.filter((key) => store.has(key)).map((key) => [key, store.get(key)!]))),
+ setMany: vi.fn(async (entries) => { for (const entry of entries) store.set(entry.key, entry.reason); }),
+ };
+}
+
+function llm(): LlmProvider & { rerank: ReturnType } {
+ return {
+ id: "test:model",
+ promptVersion: "p1",
+ // Reverses the order and writes a reason naming the candidate.
+ rerank: vi.fn(async (_viewer: ParticipantProfile, list: MatchCandidate[]) =>
+ [...list].reverse().map((item) => ({ ...item, reason: `LLM says ${item.participant.attendeeId}` }))),
+ };
+}
+
+const viewer = person("viewer");
+const shortlist = () => [candidate(person("a"), 90), candidate(person("b"), 80)];
+const order = (result: { candidates: MatchCandidate[] }) => result.candidates.map((item) => item.participant.attendeeId);
+
+describe("pair explanation cache", () => {
+ it("stores the model's reasons, then reuses them without calling the model", async () => {
+ const cache = memoryCache();
+ const provider = llm();
+ const stage = new LlmRerankStage(provider, cache);
+
+ const first = await stage.execute(viewer, shortlist());
+ expect(order(first)).toEqual(["b", "a"]);
+ expect(first.rankedBy).toBe("llm:test:model");
+ expect(cache.store.size).toBe(2);
+
+ const second = await stage.execute(viewer, shortlist());
+ expect(provider.rerank).toHaveBeenCalledTimes(1);
+ expect(second.candidates.map((item) => item.reason)).toEqual(["LLM says a", "LLM says b"]);
+ // Cached reasons never carry the model's order: the scored order stands.
+ expect(order(second)).toEqual(["a", "b"]);
+ expect(second.rankedBy).toBe("score");
+ });
+
+ it("asks the model again when a profile changes", async () => {
+ const cache = memoryCache();
+ const provider = llm();
+ const stage = new LlmRerankStage(provider, cache);
+ await stage.execute(viewer, shortlist());
+ await stage.execute(viewer, [candidate(person("a", "r2"), 90), candidate(person("b"), 80)]);
+ expect(provider.rerank).toHaveBeenCalledTimes(2);
+ });
+
+ it("never reuses one viewer's explanations for another", async () => {
+ const cache = memoryCache();
+ const provider = llm();
+ const stage = new LlmRerankStage(provider, cache);
+ await stage.execute(viewer, shortlist());
+ await stage.execute(person("someone-else"), shortlist());
+ expect(provider.rerank).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps query explanations apart from profile ones and from other queries", () => {
+ const base = { eventId: "event", viewer, candidate: person("a"), model: "m", promptVersion: "p1" };
+ const profile = explanationKey({ ...base, context: "profile" });
+ const climate = explanationKey({ ...base, context: queryContext(" Climate tools") });
+ expect(climate).toBe(explanationKey({ ...base, context: queryContext("climate tools") }));
+ expect(new Set([profile, climate, explanationKey({ ...base, context: queryContext("finance") })]).size).toBe(3);
+ expect(explanationKey({ ...base, context: "profile", promptVersion: "p2" })).not.toBe(profile);
+ });
+
+ it("falls back to cached reasons when the model fails", async () => {
+ const cache = memoryCache();
+ const provider = llm();
+ const stage = new LlmRerankStage(provider, cache);
+ await stage.execute(viewer, [candidate(person("a"), 90)]);
+ provider.rerank.mockRejectedValueOnce(new Error("timeout"));
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = await stage.execute(viewer, shortlist());
+ expect(result.candidates.map((item) => item.reason)).toEqual(["LLM says a", expect.stringMatching(/perspective|fit/)]);
+ });
+
+ it("keeps working when the cache itself fails", async () => {
+ const provider = llm();
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const broken: ExplanationCache = { getMany: vi.fn().mockRejectedValue(new Error("down")), setMany: vi.fn().mockRejectedValue(new Error("down")) };
+ const result = await new LlmRerankStage(provider, broken).execute(viewer, shortlist());
+ expect(result.rankedBy).toBe("llm:test:model");
+ });
+});
From bec5ce7d906a53b8345dbd587ca98cdfaae82bce Mon Sep 17 00:00:00 2001
From: SURYANSH-RAI
Date: Mon, 19 Oct 2026 03:31:20 +0530
Subject: [PATCH 06/33] Add connection abuse controls and profile visibility
(R19 part 1)
- A declined request is final for the event: re-requesting used to
reset it to pending, letting someone keep asking
- If the other person already asked, the requester is pointed to their
request instead of creating a second one; accepted pairs are refused
- At most 20 intro requests an hour and 25 waiting for an answer per
person and event; self-requests are refused in the use case too
- An attendee removed from the event disappears from other people's
connections and their contact is no longer shown; restoring access
brings both back. Accepting a request from a removed person fails
- Participants can hide their profile from matches and search; hidden,
they keep browsing and their accepted connections (consent already
given), and nobody new can request them
- Tests: request rules, abuse limits, and real-Postgres checks of
decline finality and removal
---
.../e/[eventSlug]/profile/page.tsx | 2 +-
apps/web/app/actions/participant.actions.ts | 1 +
.../components/participant/ProfileForm.tsx | 9 +++
.../src/application/ports/intro-repository.ts | 4 ++
.../application/use-cases/request-intro.ts | 13 +++-
.../application/use-cases/respond-to-intro.ts | 3 +
.../src/domain/connection/connection.rules.ts | 23 +++++++
.../domain/participant/participant.entity.ts | 2 +-
.../src/infrastructure/postgres/intro.repo.ts | 31 ++++++++--
.../postgres/participant.repo.ts | 5 +-
tests/integration/connection-privacy.test.ts | 62 +++++++++++++++++++
tests/unit/candidate-eligibility.test.ts | 4 +-
tests/unit/intro-rules.test.ts | 59 ++++++++++++++++++
13 files changed, 206 insertions(+), 12 deletions(-)
create mode 100644 tests/integration/connection-privacy.test.ts
create mode 100644 tests/unit/intro-rules.test.ts
diff --git a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx
index ff7ffa2..277c435 100644
--- a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx
+++ b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx
@@ -28,7 +28,7 @@ export default async function ProfilePage({ params }: { params: Promise<{ eventS
;
}
diff --git a/apps/web/app/actions/participant.actions.ts b/apps/web/app/actions/participant.actions.ts
index 5db11f3..e0f0aa0 100644
--- a/apps/web/app/actions/participant.actions.ts
+++ b/apps/web/app/actions/participant.actions.ts
@@ -45,6 +45,7 @@ async function saveProfile(eventSlug: string, formData: FormData) {
selfDescription: nullable(formData.get("selfDescription")),
yearsOfExperience: parseYears(formData.get("yearsOfExperience")),
mostImpressiveBuild: nullable(formData.get("mostImpressiveBuild")),
+ visible: formData.get("visible") === "on",
}, { participants: container.participants, enqueueMatching: container.enqueueEmbedding }, readProfileForm(event.form_config));
}
diff --git a/apps/web/components/participant/ProfileForm.tsx b/apps/web/components/participant/ProfileForm.tsx
index 35b1672..e05f743 100644
--- a/apps/web/components/participant/ProfileForm.tsx
+++ b/apps/web/components/participant/ProfileForm.tsx
@@ -17,6 +17,7 @@ export interface ProfileFormValues {
interests: string[];
intent: string;
venueZone: string | null;
+ visible: boolean;
}
const label = (intent: string) => intent.replaceAll("_", " ").toLowerCase();
@@ -52,6 +53,14 @@ export default function ProfileForm({ action, profile, intents, zones, form }: {
options={intents.map((intent) => ({ value: intent, label: label(intent) }))} />
{zones.length > 0 && ({ value: zone, label: zone }))} />}
+
+
+
+
+ Show my profile in other attendees' matches and search
+
+ Hidden, you can still browse and keep your accepted connections; nobody new can find you or request an introduction.
+
Save profile and find matches
;
}
diff --git a/apps/web/src/application/ports/intro-repository.ts b/apps/web/src/application/ports/intro-repository.ts
index 2b1167c..bc9e54b 100644
--- a/apps/web/src/application/ports/intro-repository.ts
+++ b/apps/web/src/application/ports/intro-repository.ts
@@ -4,6 +4,10 @@ export interface IntroRepository {
create(input: { eventId: string; requesterId: string; recipientId: string; message?: string | null }): Promise;
findById(eventId: string, introId: string): Promise;
respond(eventId: string, introId: string, actorId: string, status: Extract): Promise;
+ /** Requests in either direction between two people. */
+ findBetween(eventId: string, a: string, b: string): Promise;
+ countPendingOutgoing(eventId: string, requesterId: string): Promise;
+ /** The participant's requests, excluding those with someone removed from the event. */
listForParticipant(eventId: string, participantId: string): Promise;
getRevealedContacts(eventId: string, participantId: string): Promise>;
}
diff --git a/apps/web/src/application/use-cases/request-intro.ts b/apps/web/src/application/use-cases/request-intro.ts
index 1dc00b1..ed31eee 100644
--- a/apps/web/src/application/use-cases/request-intro.ts
+++ b/apps/web/src/application/use-cases/request-intro.ts
@@ -2,11 +2,14 @@ import type { IntroRepository } from "../ports/intro-repository";
import type { ParticipantRepository } from "../ports/participant-repository";
import type { NotificationPort } from "../ports/notification";
import { boundedText, LIMITS } from "../../domain/shared/validation";
+import { INTRO_LIMITS, introRequestRefusal } from "../../domain/connection/connection.rules";
+import type { RateLimiter } from "../ports/rate-limiter";
export async function requestIntro(
input: { eventId: string; requesterId: string; recipientId: string; message?: string | null; eventName?: string },
- dependencies: { participants: ParticipantRepository; intros: IntroRepository; notifications?: NotificationPort }
+ dependencies: { participants: ParticipantRepository; intros: IntroRepository; notifications?: NotificationPort; limiter?: RateLimiter }
) {
+ if (input.requesterId === input.recipientId) throw new Error("You cannot request an intro to yourself");
if (!(await dependencies.participants.hasEventAccess(input.eventId, input.requesterId))) throw new Error("You are not registered for this event");
if (!(await dependencies.participants.hasEventAccess(input.eventId, input.recipientId))) throw new Error("This participant is not in the event");
const [requester, recipient] = await Promise.all([
@@ -15,6 +18,14 @@ export async function requestIntro(
]);
if (!requester || !recipient || !recipient.visible || !recipient.profileComplete) throw new Error("This participant is unavailable");
const message = boundedText(input.message, "message", "Message", LIMITS.introMessage);
+ const refusal = introRequestRefusal(input.requesterId, await dependencies.intros.findBetween(input.eventId, input.requesterId, input.recipientId));
+ if (refusal) throw new Error(refusal);
+ if (await dependencies.intros.countPendingOutgoing(input.eventId, input.requesterId) >= INTRO_LIMITS.pendingOutgoing) {
+ throw new Error(`You have ${INTRO_LIMITS.pendingOutgoing} requests waiting for an answer. Wait for replies before asking more people.`);
+ }
+ if (dependencies.limiter && !(await dependencies.limiter.consume(`intro:${input.eventId}:${input.requesterId}`, INTRO_LIMITS.perHour, 3600))) {
+ throw new Error("You have sent many introduction requests this hour. Please try again later.");
+ }
const intro = await dependencies.intros.create({ ...input, message });
if (recipient.email && dependencies.notifications) {
await dependencies.notifications.introRequested({
diff --git a/apps/web/src/application/use-cases/respond-to-intro.ts b/apps/web/src/application/use-cases/respond-to-intro.ts
index c7f880c..3ee9ba2 100644
--- a/apps/web/src/application/use-cases/respond-to-intro.ts
+++ b/apps/web/src/application/use-cases/respond-to-intro.ts
@@ -8,6 +8,9 @@ export async function respondToIntro(
) {
const existing = await dependencies.intros.findById(input.eventId, input.introId);
if (!existing) throw new Error("Intro request not found");
+ if (input.accept && !(await dependencies.participants.hasEventAccess(input.eventId, existing.requesterId))) {
+ throw new Error("This person is no longer part of the event");
+ }
const updated = await dependencies.intros.respond(input.eventId, input.introId, input.actorId, input.accept ? "accepted" : "declined");
if (updated.status === "accepted" && dependencies.notifications) {
const requester = await dependencies.participants.findProfile(input.eventId, updated.requesterId);
diff --git a/apps/web/src/domain/connection/connection.rules.ts b/apps/web/src/domain/connection/connection.rules.ts
index e18d7f7..684899d 100644
--- a/apps/web/src/domain/connection/connection.rules.ts
+++ b/apps/web/src/domain/connection/connection.rules.ts
@@ -4,3 +4,26 @@ import type { IntroRequest } from "./intro-request.entity";
export function mayRevealContact(request: IntroRequest): boolean {
return request.status === "accepted";
}
+
+/** Limits on introduction requests, per requester and event. */
+export const INTRO_LIMITS = {
+ perHour: 20,
+ pendingOutgoing: 25,
+} as const;
+
+/**
+ * Whether a new request from `requesterId` may be created, given the requests
+ * already existing between the two people (either direction). A decline is
+ * final for the event, and a pending request the other way should be
+ * answered rather than duplicated.
+ */
+export function introRequestRefusal(requesterId: string, existing: IntroRequest[]): string | null {
+ for (const intro of existing) {
+ const mine = intro.requesterId === requesterId;
+ if (intro.status === "accepted") return "You are already connected";
+ if (mine && intro.status === "pending") return "You already asked to meet them";
+ if (mine && intro.status === "declined") return "They declined an earlier request, so you cannot ask again at this event";
+ if (!mine && intro.status === "pending") return "They already asked to meet you. Accept their request on your Connections page";
+ }
+ return null;
+}
diff --git a/apps/web/src/domain/participant/participant.entity.ts b/apps/web/src/domain/participant/participant.entity.ts
index c82b367..53fe075 100644
--- a/apps/web/src/domain/participant/participant.entity.ts
+++ b/apps/web/src/domain/participant/participant.entity.ts
@@ -40,7 +40,7 @@ export type ParticipantProfileInput = Pick<
| "interests"
| "venueZone"
| "formVersion"
->;
+> & { visible?: boolean };
export function profileText(profile: ParticipantProfile): string {
return [
diff --git a/apps/web/src/infrastructure/postgres/intro.repo.ts b/apps/web/src/infrastructure/postgres/intro.repo.ts
index 4f58db0..88595fe 100644
--- a/apps/web/src/infrastructure/postgres/intro.repo.ts
+++ b/apps/web/src/infrastructure/postgres/intro.repo.ts
@@ -23,9 +23,7 @@ export class PostgresIntroRepository implements IntroRepository {
const { rows } = await query(
`insert into intro_requests (event_id, requester_id, recipient_id, message)
values ($1, $2, $3, $4)
- on conflict (event_id, requester_id, recipient_id) do update
- set status = 'pending', message = excluded.message, created_at = now(), responded_at = null
- where intro_requests.status = 'declined'
+ on conflict (event_id, requester_id, recipient_id) do nothing
returning ${INTRO_COLUMNS}`,
[input.eventId, input.requesterId, input.recipientId, message]
);
@@ -52,11 +50,30 @@ export class PostgresIntroRepository implements IntroRepository {
return mapIntro(rows[0]);
}
- async listForParticipant(eventId: string, participantId: string): Promise {
+ async findBetween(eventId: string, a: string, b: string): Promise {
const { rows } = await query(
`select ${INTRO_COLUMNS} from intro_requests
- where event_id = $1 and (requester_id = $2 or recipient_id = $2)
- order by created_at desc`,
+ where event_id = $1 and ((requester_id = $2 and recipient_id = $3) or (requester_id = $3 and recipient_id = $2))`,
+ [eventId, a, b]
+ );
+ return rows.map(mapIntro);
+ }
+
+ async countPendingOutgoing(eventId: string, requesterId: string): Promise {
+ const { rows } = await query<{ count: number }>(
+ `select count(*)::int as count from intro_requests where event_id = $1 and requester_id = $2 and status = 'pending'`,
+ [eventId, requesterId]
+ );
+ return rows[0]?.count ?? 0;
+ }
+
+ async listForParticipant(eventId: string, participantId: string): Promise {
+ const { rows } = await query(
+ `select ${INTRO_COLUMNS_R} from intro_requests r
+ join event_participants other on other.event_id = r.event_id
+ and other.attendee_id = case when r.requester_id = $2 then r.recipient_id else r.requester_id end
+ where r.event_id = $1 and (r.requester_id = $2 or r.recipient_id = $2) and other.revoked_at is null
+ order by r.created_at desc`,
[eventId, participantId]
);
return rows.map(mapIntro);
@@ -71,6 +88,8 @@ export class PostgresIntroRepository implements IntroRepository {
left join event_participants cp on cp.event_id = r.event_id and cp.attendee_id = c.id
where r.event_id = $1 and r.status = 'accepted'
and (r.requester_id = $2 or r.recipient_id = $2)
+ -- Someone removed from the event no longer has their contact shown.
+ and cp.revoked_at is null
order by r.responded_at desc`,
[eventId, participantId]
);
diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts
index 8318ef0..c6bddb0 100644
--- a/apps/web/src/infrastructure/postgres/participant.repo.ts
+++ b/apps/web/src/infrastructure/postgres/participant.repo.ts
@@ -63,11 +63,12 @@ export class PostgresParticipantRepository implements ParticipantRepository {
intent = $3, interests = $4, venue_zone = $5,
about_me = $6, designation = $7, domain = $8,
self_description = $9, years_of_experience = $10,
- most_impressive_build = $11, profile_form_version = $12, embedding = null, profile_updated_at = now(), updated_at = now()
+ most_impressive_build = $11, profile_form_version = $12, visible = coalesce($13, visible),
+ embedding = null, profile_updated_at = now(), updated_at = now()
where event_id = $1 and attendee_id = $2`,
[input.eventId, input.attendeeId, input.intent, input.interests, input.venueZone,
input.aboutMe, input.designation, input.domain, input.selfDescription,
- input.yearsOfExperience, input.mostImpressiveBuild, input.formVersion ?? 0]
+ input.yearsOfExperience, input.mostImpressiveBuild, input.formVersion ?? 0, input.visible ?? null]
);
if (!rowCount) throw new Error("This attendee is not on the event roster");
const saved = await this.findProfile(input.eventId, input.attendeeId);
diff --git a/tests/integration/connection-privacy.test.ts b/tests/integration/connection-privacy.test.ts
new file mode 100644
index 0000000..ddd16b9
--- /dev/null
+++ b/tests/integration/connection-privacy.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Connection privacy against a real Postgres: a declined request stays
+ * declined, and an attendee removed from the event disappears from other
+ * people's connections and contacts. 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 { PostgresIntroRepository } from "../../apps/web/src/infrastructure/postgres/intro.repo";
+
+const describeDb = process.env.DATABASE_URL ? describe : describe.skip;
+const RUN = Date.now().toString(36);
+const ORG = `privacy-${RUN}`;
+const email = (key: string) => `privacy-${key}-${RUN}@example.com`;
+
+describeDb("connection privacy", () => {
+ const intros = new PostgresIntroRepository();
+ const ids: Record = {};
+ let eventId: string;
+
+ beforeAll(async () => {
+ await migrate();
+ await attendees.upsertMany(["ann", "bo", "cy"].map((key) => ({ name: key, email: email(key), phone: null })));
+ for (const key of ["ann", "bo", "cy"]) 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));
+ });
+
+ afterAll(async () => {
+ await query(`delete from organizations where slug = $1`, [ORG]);
+ await query(`delete from registered_attendees where email like $1`, [`privacy-%-${RUN}@example.com`]);
+ await closePool();
+ });
+
+ it("keeps a declined request declined", async () => {
+ const declined = await intros.create({ eventId, requesterId: ids.ann, recipientId: ids.bo });
+ await intros.respond(eventId, declined.id, ids.bo, "declined");
+ await expect(intros.create({ eventId, requesterId: ids.ann, recipientId: ids.bo })).rejects.toThrow(/already exists/);
+ expect((await intros.findById(eventId, declined.id))?.status).toBe("declined");
+ expect(await intros.findBetween(eventId, ids.bo, ids.ann)).toHaveLength(1);
+ });
+
+ it("counts pending outgoing requests", async () => {
+ await intros.create({ eventId, requesterId: ids.cy, recipientId: ids.bo });
+ expect(await intros.countPendingOutgoing(eventId, ids.cy)).toBe(1);
+ });
+
+ it("hides a removed attendee from connections and contacts", async () => {
+ const accepted = await intros.create({ eventId, requesterId: ids.ann, recipientId: ids.cy });
+ await intros.respond(eventId, accepted.id, ids.cy, "accepted");
+ expect((await intros.getRevealedContacts(eventId, ids.ann)).map((row) => row.contact.id)).toEqual([ids.cy]);
+
+ await events.setRevoked(eventId, ids.cy, true);
+ expect((await intros.listForParticipant(eventId, ids.ann)).some((intro) => intro.id === accepted.id)).toBe(false);
+ expect(await intros.getRevealedContacts(eventId, ids.ann)).toEqual([]);
+
+ await events.setRevoked(eventId, ids.cy, false);
+ expect((await intros.getRevealedContacts(eventId, ids.ann)).map((row) => row.contact.id)).toEqual([ids.cy]);
+ });
+});
diff --git a/tests/unit/candidate-eligibility.test.ts b/tests/unit/candidate-eligibility.test.ts
index 5ac19bc..eab1454 100644
--- a/tests/unit/candidate-eligibility.test.ts
+++ b/tests/unit/candidate-eligibility.test.ts
@@ -64,7 +64,9 @@ describe("intro request recipient", () => {
hasEventAccess: vi.fn(async () => true),
findProfile: vi.fn(async (_eventId: string, id: string) => (id === "requester" ? profile("requester") : recipient)),
} as unknown as ParticipantRepository;
- const intros = { create: vi.fn(async () => ({ id: "intro" })) } as unknown as IntroRepository;
+ const intros = {
+ create: vi.fn(async () => ({ id: "intro" })), findBetween: vi.fn(async () => []), countPendingOutgoing: vi.fn(async () => 0),
+ } as unknown as IntroRepository;
return { participants, intros };
}
const send = (dependencies: ReturnType, recipientId: string) =>
diff --git a/tests/unit/intro-rules.test.ts b/tests/unit/intro-rules.test.ts
new file mode 100644
index 0000000..e6ffc3e
--- /dev/null
+++ b/tests/unit/intro-rules.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from "vitest";
+import { INTRO_LIMITS, introRequestRefusal } from "@/src/domain/connection/connection.rules";
+import { requestIntro } from "@/src/application/use-cases/request-intro";
+import type { IntroRequest } from "@/src/domain/connection/intro-request.entity";
+
+const intro = (requesterId: string, recipientId: string, status: IntroRequest["status"]): IntroRequest => ({
+ id: `${requesterId}-${recipientId}`, eventId: "event", requesterId, recipientId, status, message: null, createdAt: new Date(), respondedAt: null,
+});
+
+describe("intro request rules", () => {
+ it.each([
+ [[], null],
+ [[intro("a", "b", "pending")], /already asked to meet them/],
+ [[intro("a", "b", "declined")], /declined an earlier request/],
+ [[intro("b", "a", "pending")], /already asked to meet you/],
+ [[intro("b", "a", "accepted")], /already connected/],
+ [[intro("b", "a", "declined")], null],
+ ] as const)("refuses or allows a request from a given %o", (existing, expected) => {
+ const refusal = introRequestRefusal("a", [...existing]);
+ if (expected === null) expect(refusal).toBeNull();
+ else expect(refusal).toMatch(expected);
+ });
+});
+
+function deps(overrides: { existing?: IntroRequest[]; pending?: number; allowed?: boolean } = {}) {
+ const profile = (id: string) => ({ attendeeId: id, name: id, visible: true, profileComplete: true, email: `${id}@example.com` });
+ return {
+ participants: { hasEventAccess: vi.fn(async () => true), findProfile: vi.fn(async (_e: string, id: string) => profile(id)) },
+ intros: {
+ findBetween: vi.fn(async () => overrides.existing ?? []),
+ countPendingOutgoing: vi.fn(async () => overrides.pending ?? 0),
+ create: vi.fn(async () => intro("a", "b", "pending")),
+ },
+ limiter: { consume: vi.fn(async () => overrides.allowed ?? true) },
+ };
+}
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const ask = (dependencies: ReturnType) => requestIntro({ eventId: "event", requesterId: "a", recipientId: "b" }, dependencies as any);
+
+describe("requestIntro abuse controls", () => {
+ it("creates a request when nothing blocks it", async () => {
+ const d = deps();
+ await ask(d);
+ expect(d.intros.create).toHaveBeenCalled();
+ expect(d.limiter.consume).toHaveBeenCalledWith("intro:event:a", INTRO_LIMITS.perHour, 3600);
+ });
+
+ it("refuses a request to yourself", async () => {
+ const d = deps();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await expect(requestIntro({ eventId: "event", requesterId: "a", recipientId: "a" }, d as any)).rejects.toThrow(/yourself/);
+ });
+
+ it("refuses after a decline, with too many pending, or over the hourly limit", async () => {
+ await expect(ask(deps({ existing: [intro("a", "b", "declined")] }))).rejects.toThrow(/declined/);
+ await expect(ask(deps({ pending: INTRO_LIMITS.pendingOutgoing }))).rejects.toThrow(/waiting for an answer/);
+ await expect(ask(deps({ allowed: false }))).rejects.toThrow(/this hour/);
+ });
+});
From b81b1e5d22112a3f8fd3a251553d2dcae0ce2788 Mon Sep 17 00:00:00 2001
From: SURYANSH-RAI
Date: Mon, 19 Oct 2026 03:35:15 +0530
Subject: [PATCH 07/33] Record sensitive actions and enforce data retention
(R19 part 2)
- Migration 0010: audit_events (event, actor, action, subject, details
with counts and field names only). Recorded: roster imports,
invitations, access removed/restored, settings and profile-form
changes, introductions accepted (contacts shared), and account
disable/enable/revoke/erase. Recording failures are logged and never
block the action. Organizers see "Recent activity" on the analytics
page. Records are kept for a year by the hourly sweep and survive
their event's deletion
- Removing someone from an event deletes cached explanations written
about or for them; hiding a profile deletes explanations of it
- npm run account:erase -- --yes for deletion requests:
deletes the Keycloak user first (so a failure leaves data to retry),
then the attendee and everything cascading from it, cached
explanations and login challenges; refuses without --yes
- Tests: real Postgres for records, sweep, retention on removal and
hiding, and erasure against the local Keycloak realm
---
ReadMe.md | 1 +
.../events/[eventSlug]/analytics/page.tsx | 25 ++++-
apps/web/app/actions/organizer.actions.ts | 8 +-
apps/web/src/application/ports/audit-log.ts | 14 +++
.../src/application/use-cases/manage-event.ts | 15 ++-
.../use-cases/manage-invitations.ts | 12 ++-
.../application/use-cases/respond-to-intro.ts | 6 +-
apps/web/src/composition/container.ts | 2 +
.../src/infrastructure/postgres/audit.repo.ts | 19 ++++
.../postgres/participant.repo.ts | 4 +
package.json | 3 +-
packages/auth/src/index.ts | 1 +
packages/auth/src/keycloak.ts | 7 ++
packages/db/migrations/0010_audit_events.sql | 17 ++++
packages/db/src/index.ts | 1 +
packages/db/src/repositories/attendees.ts | 17 ++++
packages/db/src/repositories/audit.ts | 43 ++++++++
packages/db/src/repositories/events.ts | 4 +
packages/db/src/repositories/housekeeping.ts | 5 +-
tests/integration/audit-retention.test.ts | 97 +++++++++++++++++++
tests/unit/invitations.test.ts | 11 +++
tools/manage-account.ts | 37 +++++--
22 files changed, 329 insertions(+), 20 deletions(-)
create mode 100644 apps/web/src/application/ports/audit-log.ts
create mode 100644 apps/web/src/infrastructure/postgres/audit.repo.ts
create mode 100644 packages/db/migrations/0010_audit_events.sql
create mode 100644 packages/db/src/repositories/audit.ts
create mode 100644 tests/integration/audit-retention.test.ts
diff --git a/ReadMe.md b/ReadMe.md
index a5d93b0..818de3f 100644
--- a/ReadMe.md
+++ b/ReadMe.md
@@ -110,6 +110,7 @@ The first command imports the global attendee directory so the organizer account
| `npm run keycloak:sync` | Bring an existing realm up to date: client secret, Google credentials, the account-linking flow (Google joins an account an e-mail code created), and the site login theme. Run after the first Keycloak start and after upgrades |
| `npm run account:disable -- ` | Block sign-in and end every session (database and Keycloak); `account:enable` undoes it |
| `npm run account:revoke-sessions -- ` | Sign the person out everywhere without disabling the account |
+| `npm run account:erase -- --yes` | Deletion request: delete the person, their event profiles, matches, introductions, cached explanations and Keycloak user (recorded in the audit log) |
| `npm run docker:up` | Build images and start the local Compose stack |
`DATABASE_URL` should point at `localhost` for commands run on the host. Compose sets the service hostname `postgres` inside containers.
diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx
index a7a028c..f246a3f 100644
--- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx
+++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx
@@ -5,7 +5,7 @@ import { requireOrganizerEvent } from "@/src/lib/auth";
export default async function AnalyticsPage({ params }: { params: Promise<{ orgSlug: string; eventSlug: string }> }) {
const { orgSlug, eventSlug } = await params;
const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug);
- const analytics = await container.events.analytics(event.id);
+ const [analytics, activity] = await Promise.all([container.events.analytics(event.id), container.audit.recent(event.id)]);
const completion = analytics.roster ? Math.round(analytics.profiles / analytics.roster * 100) : 0;
return
← Dashboard Roster Matching
@@ -20,9 +20,32 @@ export default async function AnalyticsPage({ params }: { params: Promise<{ orgS
+ Recent activity
+ {!activity.length ? No recorded activity yet.
:
+ {activity.map((item) =>
+ {ACTIVITY_LABELS[item.action] ?? item.action}
+ {item.subjectName && <> · {item.subjectName}>}
+ {item.actorName ?? "System"} · {item.createdAt.toLocaleString("en-IN", { dateStyle: "medium", timeStyle: "short" })}{summary(item.details)}
+ )}
+ }
;
}
+const ACTIVITY_LABELS: Record = {
+ "roster.imported": "Roster imported",
+ "invitations.sent": "Invitations sent",
+ "access.removed": "Access removed",
+ "access.restored": "Access restored",
+ "event.updated": "Settings changed",
+ "profile_form.updated": "Profile form changed",
+ "contacts.revealed": "Introduction accepted, contacts shared",
+};
+
+function summary(details: Record): string {
+ const parts = ["attached", "sent", "failed", "version"].filter((key) => typeof details[key] === "number").map((key) => `${key} ${details[key]}`);
+ return parts.length ? ` · ${parts.join(", ")}` : "";
+}
+
function Card({ label, value, note }: { label: string; value: number | string; note?: string }) {
return {label} {value} {note && {note} } ;
}
diff --git a/apps/web/app/actions/organizer.actions.ts b/apps/web/app/actions/organizer.actions.ts
index a1d756a..fa5c761 100644
--- a/apps/web/app/actions/organizer.actions.ts
+++ b/apps/web/app/actions/organizer.actions.ts
@@ -43,7 +43,7 @@ async function importRoster(organizationSlug: string, eventSlug: string, formDat
const event = await container.events.findBySlug(organizationSlug, eventSlug);
if (!event) throw new Error("Event not found");
const { records, skipped } = parseRosterWorkbook(await file.arrayBuffer());
- const result = await importEventRoster({ eventId: event.id, organizerId: session.attendeeId, records }, container.events);
+ const result = await importEventRoster({ eventId: event.id, organizerId: session.attendeeId, records }, container.events, container.audit);
const report = new URLSearchParams({
imported: String(result.attached), skipped: String(skipped), already: String(result.alreadyOnRoster),
kept: String(result.keptExisting), phones: String(result.phoneConflicts),
@@ -73,7 +73,7 @@ async function saveEvent(organizationSlug: string, eventSlug: string, formData:
status: status as "draft" | "open" | "closed",
intents,
zones,
- }, container.events);
+ }, container.events, container.audit);
redirect(`/orgs/${organizationSlug}/events/${eventSlug}?saved=1`);
}
@@ -88,7 +88,7 @@ async function queueMatches(organizationSlug: string, eventSlug: string) {
const event = await container.events.findBySlug(organizationSlug, eventSlug);
if (!event) throw new Error("Event not found");
assertEventAllows(event.status, "computeMatches");
- if (event.status === "draft") await updateEvent({ eventId: event.id, organizerId: session.attendeeId, status: "open" }, container.events);
+ if (event.status === "draft") await updateEvent({ eventId: event.id, organizerId: session.attendeeId, status: "open" }, container.events, container.audit);
const queued = await queueEventMatches({ eventId: event.id, organizerId: session.attendeeId }, container.events, container.enqueueEmbedding);
redirect(`/orgs/${organizationSlug}/events/${eventSlug}/matching?queued=${queued}`);
}
@@ -138,7 +138,7 @@ export async function updateProfileFormAction(organizationSlug: string, eventSlu
shown: formData.get(`${key}.shown`) === "on",
required: formData.get(`${key}.required`) === "on",
}])) as Record;
- await configureProfileForm({ eventId: event.id, organizerId: session.attendeeId, fields, currentConfig: event.form_config }, container.events);
+ await configureProfileForm({ eventId: event.id, organizerId: session.attendeeId, fields, currentConfig: event.form_config }, container.events, container.audit);
redirect(`/orgs/${organizationSlug}/events/${eventSlug}?form=saved`);
});
}
diff --git a/apps/web/src/application/ports/audit-log.ts b/apps/web/src/application/ports/audit-log.ts
new file mode 100644
index 0000000..228950f
--- /dev/null
+++ b/apps/web/src/application/ports/audit-log.ts
@@ -0,0 +1,14 @@
+/** Records sensitive actions. Recording must never block or fail the action itself. */
+export interface AuditLog {
+ record(entry: {
+ eventId?: string | null;
+ actorId?: string | null;
+ action: string;
+ subjectId?: string | null;
+ details?: Record;
+ }): Promise;
+ /** The event's most recent records, newest first, with people's names. */
+ recent(eventId: string, limit?: number): Promise; createdAt: Date;
+ }>>;
+}
diff --git a/apps/web/src/application/use-cases/manage-event.ts b/apps/web/src/application/use-cases/manage-event.ts
index fcbd9f2..d800e8f 100644
--- a/apps/web/src/application/use-cases/manage-event.ts
+++ b/apps/web/src/application/use-cases/manage-event.ts
@@ -1,4 +1,5 @@
import type { EventRepository, RosterAttendeeInput } from "../ports/event-repository";
+import type { AuditLog } from "../ports/audit-log";
import { slugify } from "../../domain/shared/value-objects";
import { Intent } from "../../domain/participant/intent";
import { boundedItems, boundedText, LIMITS, ValidationError } from "../../domain/shared/validation";
@@ -29,7 +30,7 @@ export async function updateEvent(input: {
status?: "draft" | "open" | "closed";
intents?: string[];
zones?: string[];
-}, events: EventRepository) {
+}, events: EventRepository, audit?: AuditLog) {
await authorizeOrganizer(events, input.eventId, input.organizerId, "configure");
const updated = await events.update({
...input,
@@ -41,13 +42,17 @@ export async function updateEvent(input: {
: boundedItems(input.zones, "zones", "venue zones", { count: LIMITS.zoneCount, length: LIMITS.zoneLength }),
});
if (!updated) throw new Error("Event not found");
+ const fields = Object.keys(input).filter((key) => !["eventId", "organizerId"].includes(key) && input[key as keyof typeof input] !== undefined);
+ await audit?.record({ eventId: input.eventId, actorId: input.organizerId, action: "event.updated", details: { fields, status: updated.status } });
return updated;
}
-export async function importEventRoster(input: { eventId: string; organizerId: string; records: RosterAttendeeInput[] }, events: EventRepository) {
+export async function importEventRoster(input: { eventId: string; organizerId: string; records: RosterAttendeeInput[] }, events: EventRepository, audit?: AuditLog) {
await authorizeOrganizer(events, input.eventId, input.organizerId, "importRoster");
if (!input.records.length) return { created: 0, attached: 0, alreadyOnRoster: 0, keptExisting: 0, phoneConflicts: 0 };
- return events.importRoster(input.eventId, input.records);
+ const result = await events.importRoster(input.eventId, input.records);
+ await audit?.record({ eventId: input.eventId, actorId: input.organizerId, action: "roster.imported", details: { rows: input.records.length, ...result } });
+ return result;
}
export async function queueEventMatches(input: { eventId: string; organizerId: string }, events: EventRepository, enqueue: (eventId: string, participantId: string) => Promise) {
@@ -73,11 +78,13 @@ function eventIntents(values: string[]) {
/** Saves the organizer's profile form settings as a new form version. */
export async function configureProfileForm(
input: { eventId: string; organizerId: string; fields: Record; currentConfig: unknown },
- events: EventRepository
+ events: EventRepository,
+ audit?: AuditLog
) {
await authorizeOrganizer(events, input.eventId, input.organizerId, "configure");
const form = buildProfileForm(input.fields, readProfileForm(input.currentConfig));
const updated = await events.update({ eventId: input.eventId, organizerId: input.organizerId, formConfig: { ...form } });
if (!updated) throw new Error("Event not found");
+ await audit?.record({ eventId: input.eventId, actorId: input.organizerId, action: "profile_form.updated", details: { version: form.version } });
return form;
}
diff --git a/apps/web/src/application/use-cases/manage-invitations.ts b/apps/web/src/application/use-cases/manage-invitations.ts
index 869c987..f6bb05d 100644
--- a/apps/web/src/application/use-cases/manage-invitations.ts
+++ b/apps/web/src/application/use-cases/manage-invitations.ts
@@ -2,6 +2,7 @@ import { RESEND_AFTER_MINUTES } from "../../domain/participant/invitation";
import type { EventRepository } from "../ports/event-repository";
import type { NotificationPort } from "../ports/notification";
import { authorizeOrganizer } from "./manage-event";
+import type { AuditLog } from "../ports/audit-log";
export interface InvitationResult {
sent: number;
@@ -15,7 +16,7 @@ export interface InvitationResult {
*/
export async function sendInvitations(
input: { eventId: string; organizerId: string; eventName: string; organizationName: string; eventUrl: string; attendeeId?: string },
- dependencies: { events: EventRepository; notifications: NotificationPort }
+ dependencies: { events: EventRepository; notifications: NotificationPort; audit?: AuditLog }
): Promise {
await authorizeOrganizer(dependencies.events, input.eventId, input.organizerId, "invite");
const targets = await dependencies.events.invitationTargets(input.eventId, input.attendeeId ?? null, RESEND_AFTER_MINUTES);
@@ -40,6 +41,10 @@ export async function sendInvitations(
result.failed += 1;
}
}
+ await dependencies.audit?.record({
+ eventId: input.eventId, actorId: input.organizerId, action: "invitations.sent",
+ subjectId: input.attendeeId ?? null, details: { ...result, resend: Boolean(input.attendeeId) },
+ });
return result;
}
@@ -50,10 +55,13 @@ export async function sendInvitations(
*/
export async function setAttendeeAccess(
input: { eventId: string; organizerId: string; attendeeId: string; revoked: boolean },
- dependencies: { events: EventRepository }
+ dependencies: { events: EventRepository; audit?: AuditLog }
): Promise {
await authorizeOrganizer(dependencies.events, input.eventId, input.organizerId, "manageAccess");
if (!(await dependencies.events.setRevoked(input.eventId, input.attendeeId, input.revoked))) {
throw new Error("This attendee is not on the event roster");
}
+ await dependencies.audit?.record({
+ eventId: input.eventId, actorId: input.organizerId, action: input.revoked ? "access.removed" : "access.restored", subjectId: input.attendeeId,
+ });
}
diff --git a/apps/web/src/application/use-cases/respond-to-intro.ts b/apps/web/src/application/use-cases/respond-to-intro.ts
index 3ee9ba2..fe9492d 100644
--- a/apps/web/src/application/use-cases/respond-to-intro.ts
+++ b/apps/web/src/application/use-cases/respond-to-intro.ts
@@ -1,10 +1,11 @@
import type { IntroRepository } from "../ports/intro-repository";
import type { NotificationPort } from "../ports/notification";
import type { ParticipantRepository } from "../ports/participant-repository";
+import type { AuditLog } from "../ports/audit-log";
export async function respondToIntro(
input: { eventId: string; introId: string; actorId: string; accept: boolean; eventName?: string },
- dependencies: { intros: IntroRepository; participants: ParticipantRepository; notifications?: NotificationPort }
+ dependencies: { intros: IntroRepository; participants: ParticipantRepository; notifications?: NotificationPort; audit?: AuditLog }
) {
const existing = await dependencies.intros.findById(input.eventId, input.introId);
if (!existing) throw new Error("Intro request not found");
@@ -12,6 +13,9 @@ export async function respondToIntro(
throw new Error("This person is no longer part of the event");
}
const updated = await dependencies.intros.respond(input.eventId, input.introId, input.actorId, input.accept ? "accepted" : "declined");
+ if (updated.status === "accepted") {
+ await dependencies.audit?.record({ eventId: input.eventId, actorId: input.actorId, action: "contacts.revealed", subjectId: updated.requesterId });
+ }
if (updated.status === "accepted" && dependencies.notifications) {
const requester = await dependencies.participants.findProfile(input.eventId, updated.requesterId);
const recipient = await dependencies.participants.findProfile(input.eventId, updated.recipientId);
diff --git a/apps/web/src/composition/container.ts b/apps/web/src/composition/container.ts
index 636323a..05b44b7 100644
--- a/apps/web/src/composition/container.ts
+++ b/apps/web/src/composition/container.ts
@@ -4,6 +4,7 @@ import { PostgresMatchRepository } from "../infrastructure/postgres/match.repo";
import { PostgresParticipantRepository } from "../infrastructure/postgres/participant.repo";
import { PostgresRateLimiter } from "../infrastructure/cache/postgres-rate-limiter";
import { PostgresEventRepository } from "../infrastructure/postgres/event.repo";
+import { PostgresAuditLog } from "../infrastructure/postgres/audit.repo";
import { PostgresMatchQueue } from "../infrastructure/postgres/match-queue.repo";
import { PostgresCandidateCache } from "../infrastructure/cache/postgres-candidate-cache";
import { PostgresExplanationCache } from "../infrastructure/cache/postgres-explanation-cache";
@@ -31,6 +32,7 @@ function buildContainer() {
llm,
candidateCache,
matchQueue: new PostgresMatchQueue(),
+ audit: new PostgresAuditLog(),
notifications: new RealtimeNotifier(),
limiter: new PostgresRateLimiter(),
pipeline: new MatchingPipeline(participants, matches, embeddings, llm, candidateCache, new PostgresExplanationCache()),
diff --git a/apps/web/src/infrastructure/postgres/audit.repo.ts b/apps/web/src/infrastructure/postgres/audit.repo.ts
new file mode 100644
index 0000000..69603c3
--- /dev/null
+++ b/apps/web/src/infrastructure/postgres/audit.repo.ts
@@ -0,0 +1,19 @@
+import { audit } from "@match-maker/db";
+import type { AuditLog } from "../../application/ports/audit-log";
+
+export class PostgresAuditLog implements AuditLog {
+ async record(entry: Parameters[0]): Promise {
+ try {
+ await audit.record(entry);
+ } catch (error) {
+ // An unavailable audit table must not undo or block the action it records.
+ console.error("[audit] could not record", entry.action, error);
+ }
+ }
+
+ async recent(eventId: string, limit = 20) {
+ return (await audit.listForEvent(eventId, limit)).map((row) => ({
+ id: row.id, action: row.action, actorName: row.actor_name, subjectName: row.subject_name, details: row.details, createdAt: row.created_at,
+ }));
+ }
+}
diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts
index c6bddb0..6063788 100644
--- a/apps/web/src/infrastructure/postgres/participant.repo.ts
+++ b/apps/web/src/infrastructure/postgres/participant.repo.ts
@@ -71,6 +71,10 @@ export class PostgresParticipantRepository implements ParticipantRepository {
input.yearsOfExperience, input.mostImpressiveBuild, input.formVersion ?? 0, input.visible ?? null]
);
if (!rowCount) throw new Error("This attendee is not on the event roster");
+ if (input.visible === false) {
+ // Hidden profiles are not explained to others any more.
+ await query(`delete from pair_explanations where event_id = $1 and candidate_id = $2`, [input.eventId, input.attendeeId]);
+ }
const saved = await this.findProfile(input.eventId, input.attendeeId);
if (!saved) throw new Error("Could not load the saved profile");
return saved;
diff --git a/package.json b/package.json
index 4e6833c..3001b6e 100644
--- a/package.json
+++ b/package.json
@@ -31,7 +31,8 @@
"keycloak:sync": "tsx tools/sync-keycloak.ts",
"account:disable": "tsx tools/manage-account.ts disable",
"account:enable": "tsx tools/manage-account.ts enable",
- "account:revoke-sessions": "tsx tools/manage-account.ts revoke-sessions"
+ "account:revoke-sessions": "tsx tools/manage-account.ts revoke-sessions",
+ "account:erase": "tsx tools/manage-account.ts erase"
},
"devDependencies": {
"@types/node": "^22.10.2",
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 2a7239b..6c82d83 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -33,6 +33,7 @@ export {
isUserEnabled,
setUserEnabled,
logoutUser,
+ deleteUser,
resetCaches,
type Pkce,
type TokenSet,
diff --git a/packages/auth/src/keycloak.ts b/packages/auth/src/keycloak.ts
index da23cae..aca8fe5 100644
--- a/packages/auth/src/keycloak.ts
+++ b/packages/auth/src/keycloak.ts
@@ -387,6 +387,13 @@ export async function setUserEnabled(sub: string, enabled: boolean): Promise {
+ const res = await adminFetch(`/users/${encodeURIComponent(sub)}`, { method: "DELETE" });
+ if (!res.ok && res.status !== 404) throw new Error(`Keycloak user deletion failed (${res.status})`);
+ userStatus.delete(sub);
+}
+
/** Ends the user's Keycloak (SSO) sessions, so Google sign-in asks again. */
export async function logoutUser(sub: string): Promise {
const res = await adminFetch(`/users/${encodeURIComponent(sub)}/logout`, { method: "POST" });
diff --git a/packages/db/migrations/0010_audit_events.sql b/packages/db/migrations/0010_audit_events.sql
new file mode 100644
index 0000000..d9c0983
--- /dev/null
+++ b/packages/db/migrations/0010_audit_events.sql
@@ -0,0 +1,17 @@
+-- Security audit records: who did what to whom, for sensitive actions
+-- (roster imports, invitations, access changes, settings, contact reveals,
+-- account administration). Details hold counts and field names, never
+-- contact data. Kept for a year by the housekeeping sweep.
+
+create table if not exists audit_events (
+ id bigserial primary key,
+ event_id uuid references events(id) on delete set null,
+ actor_id uuid,
+ action text not null,
+ subject_id uuid,
+ details jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists idx_audit_events_event on audit_events (event_id, created_at desc);
+create index if not exists idx_audit_events_created on audit_events (created_at);
diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts
index 8d37dd8..596eb49 100644
--- a/packages/db/src/index.ts
+++ b/packages/db/src/index.ts
@@ -12,3 +12,4 @@ export * as matches from "./repositories/matches";
export * as events from "./repositories/events";
export * as matchingJobs from "./repositories/matching-jobs";
export * as housekeeping from "./repositories/housekeeping";
+export * as audit from "./repositories/audit";
diff --git a/packages/db/src/repositories/attendees.ts b/packages/db/src/repositories/attendees.ts
index 32866ad..d41a6ee 100644
--- a/packages/db/src/repositories/attendees.ts
+++ b/packages/db/src/repositories/attendees.ts
@@ -93,6 +93,23 @@ export async function revokeSessions(email: string): Promise {
return (rowCount ?? 0) > 0;
}
+/**
+ * Erases a person for a deletion request: their attendee row and everything
+ * that cascades from it (event participation, matches, introductions, login
+ * challenges), plus cached explanations and login challenges by e-mail.
+ * Returns the erased id, or null when the e-mail is unknown.
+ */
+export async function erase(email: string): Promise {
+ const normalized = normalizeEmail(email);
+ const { rows } = await query<{ id: string }>(`select id from registered_attendees where email = $1`, [normalized]);
+ const id = rows[0]?.id;
+ if (!id) return null;
+ await query(`delete from pair_explanations where viewer_id = $1 or candidate_id = $1`, [id]);
+ await query(`delete from login_challenges where email = $1`, [normalized]);
+ await query(`delete from registered_attendees where id = $1`, [id]);
+ return id;
+}
+
/** True when the e-mail is on the attendee roster — the gate for every login. */
export async function isRegisteredEmail(email: string): Promise {
const { rows } = await query<{ exists: boolean }>(
diff --git a/packages/db/src/repositories/audit.ts b/packages/db/src/repositories/audit.ts
new file mode 100644
index 0000000..e433f61
--- /dev/null
+++ b/packages/db/src/repositories/audit.ts
@@ -0,0 +1,43 @@
+import { query } from "../client";
+
+export interface AuditEntry {
+ eventId?: string | null;
+ actorId?: string | null;
+ action: string;
+ subjectId?: string | null;
+ /** Counts and field names only, never contact data. */
+ details?: Record;
+}
+
+export interface AuditRecord {
+ id: string;
+ action: string;
+ actor_name: string | null;
+ subject_name: string | null;
+ details: Record;
+ created_at: Date;
+}
+
+/** Audit records are kept this long, then swept. */
+export const AUDIT_RETENTION_DAYS = 365;
+
+export async function record(entry: AuditEntry): Promise {
+ await query(
+ `insert into audit_events (event_id, actor_id, action, subject_id, details) values ($1, $2, $3, $4, $5::jsonb)`,
+ [entry.eventId ?? null, entry.actorId ?? null, entry.action, entry.subjectId ?? null, JSON.stringify(entry.details ?? {})]
+ );
+}
+
+export async function listForEvent(eventId: string, limit = 20): Promise {
+ const { rows } = await query(
+ `select e.id::text as id, e.action, actor.name as actor_name, subject.name as subject_name, e.details, e.created_at
+ from audit_events e
+ left join registered_attendees actor on actor.id = e.actor_id
+ left join registered_attendees subject on subject.id = e.subject_id
+ where e.event_id = $1
+ order by e.created_at desc, e.id desc
+ limit $2`,
+ [eventId, limit]
+ );
+ return rows;
+}
diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts
index 97b8ede..979dc01 100644
--- a/packages/db/src/repositories/events.ts
+++ b/packages/db/src/repositories/events.ts
@@ -246,6 +246,10 @@ export async function setRevoked(eventId: string, attendeeId: string, revoked: b
where event_id = $1 and attendee_id = $2`,
[eventId, attendeeId, revoked]
);
+ // Explanations written about or for a removed attendee are not kept.
+ if (revoked && rowCount) {
+ await query(`delete from pair_explanations where event_id = $1 and (viewer_id = $2 or candidate_id = $2)`, [eventId, attendeeId]);
+ }
return (rowCount ?? 0) > 0;
}
diff --git a/packages/db/src/repositories/housekeeping.ts b/packages/db/src/repositories/housekeeping.ts
index 42226c9..36f995e 100644
--- a/packages/db/src/repositories/housekeeping.ts
+++ b/packages/db/src/repositories/housekeeping.ts
@@ -1,5 +1,6 @@
import { query } from "../client";
import { deleteExpired as deleteExpiredChallenges } from "./login-challenges";
+import { AUDIT_RETENTION_DAYS } from "./audit";
/** How long a dead row is kept before the sweep removes it. */
export const RETENTION = {
@@ -14,6 +15,7 @@ export interface SweepResult {
rateLimitBuckets: number;
retrievalCache: number;
pairExplanations: number;
+ auditEvents: number;
}
/** Deletes rows that can no longer be used. Safe to run on any schedule. */
@@ -25,8 +27,9 @@ export async function sweepExpired(): Promise {
);
const cache = await query(`delete from retrieval_cache where expires_at < now()`);
const explanations = await query(`delete from pair_explanations where expires_at < now()`);
+ const audits = await query(`delete from audit_events where created_at < now() - make_interval(days => $1)`, [AUDIT_RETENTION_DAYS]);
return {
loginChallenges, rateLimitBuckets: buckets.rowCount ?? 0, retrievalCache: cache.rowCount ?? 0,
- pairExplanations: explanations.rowCount ?? 0,
+ pairExplanations: explanations.rowCount ?? 0, auditEvents: audits.rowCount ?? 0,
};
}
diff --git a/tests/integration/audit-retention.test.ts b/tests/integration/audit-retention.test.ts
new file mode 100644
index 0000000..d9b8b61
--- /dev/null
+++ b/tests/integration/audit-retention.test.ts
@@ -0,0 +1,97 @@
+/**
+ * Audit records and data retention against a real Postgres (and the local
+ * Keycloak realm for erasure). Uses its own organization, event and people.
+ * Skipped when DATABASE_URL is unset; the erase case also needs Keycloak.
+ */
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { attendees, audit, closePool, events, housekeeping, query } from "@match-maker/db";
+import { ensureUser, findUserByEmail } from "@match-maker/auth";
+import { migrate } from "../../packages/db/src/migrate";
+import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo";
+import { manageAccount } from "../../tools/manage-account";
+import { Intent } from "../../apps/web/src/domain/participant/intent";
+
+const describeDb = process.env.DATABASE_URL ? describe : describe.skip;
+const issuer = (process.env.KEYCLOAK_INTERNAL_ISSUER || process.env.KEYCLOAK_ISSUER || "").replace(/\/$/, "");
+const keycloakUp = await fetch(`${issuer}/.well-known/openid-configuration`, { signal: AbortSignal.timeout(3000) }).then((res) => res.ok).catch(() => false);
+const RUN = Date.now().toString(36);
+const ORG = `audit-${RUN}`;
+const email = (key: string) => `audit-${key}-${RUN}@example.com`;
+
+describeDb("audit records and retention", () => {
+ const participants = new PostgresParticipantRepository();
+ const ids: Record = {};
+ let eventId: string;
+
+ const explain = (viewer: string, candidate: string) => query(
+ `insert into pair_explanations (cache_key, event_id, viewer_id, candidate_id, reason, expires_at)
+ values ($1, $2, $3, $4, 'reason', now() + interval '1 day')`, [randomUUID(), eventId, viewer, candidate]);
+ const explanationsAbout = async (id: string) =>
+ (await query(`select 1 from pair_explanations where viewer_id = $1 or candidate_id = $1`, [id])).rows.length;
+
+ beforeAll(async () => {
+ await migrate();
+ await attendees.upsertMany(["org", "kim", "lou", "max"].map((key) => ({ name: `Audit ${key}`, email: email(key) })));
+ for (const key of ["org", "kim", "lou", "max"]) 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, [ids.kim, ids.lou, ids.max]);
+ });
+
+ afterAll(async () => {
+ await query(`delete from audit_events where subject_id = any($1::uuid[]) or actor_id = any($1::uuid[])`, [Object.values(ids)]);
+ await query(`delete from organizations where slug = $1`, [ORG]);
+ await query(`delete from registered_attendees where email like $1`, [`audit-%-${RUN}@example.com`]);
+ await closePool();
+ });
+
+ it("records actions with the people involved, newest first", async () => {
+ await audit.record({ eventId, actorId: ids.org, action: "roster.imported", details: { attached: 3 } });
+ await audit.record({ eventId, actorId: ids.org, action: "access.removed", subjectId: ids.kim });
+ const recent = await audit.listForEvent(eventId);
+ expect(recent.map((row) => row.action)).toEqual(["access.removed", "roster.imported"]);
+ expect(recent[0]).toMatchObject({ actor_name: "Audit org", subject_name: "Audit kim" });
+ expect(recent[1].details).toEqual({ attached: 3 });
+ });
+
+ it("sweeps records older than the retention period", async () => {
+ await audit.record({ eventId, action: "old.action", subjectId: ids.lou });
+ await query(`update audit_events set created_at = now() - interval '400 days' where action = 'old.action' and subject_id = $1`, [ids.lou]);
+ await housekeeping.sweepExpired();
+ expect((await query(`select 1 from audit_events where action = 'old.action' and subject_id = $1`, [ids.lou])).rows).toHaveLength(0);
+ });
+
+ it("drops cached explanations about someone removed from the event", async () => {
+ await explain(ids.kim, ids.lou);
+ await explain(ids.lou, ids.kim);
+ await events.setRevoked(eventId, ids.kim, true);
+ expect(await explanationsAbout(ids.kim)).toBe(0);
+ });
+
+ it("drops explanations of a profile that is hidden", async () => {
+ await explain(ids.max, ids.lou);
+ await participants.saveProfile({
+ eventId, attendeeId: ids.lou, designation: "Engineer", domain: "AI", aboutMe: "x", selfDescription: null,
+ yearsOfExperience: null, mostImpressiveBuild: null, intent: Intent.NETWORKING, interests: [], venueZone: null, visible: false,
+ });
+ expect(await explanationsAbout(ids.lou)).toBe(0);
+ });
+
+ (keycloakUp && process.env.KEYCLOAK_ADMIN_PASSWORD ? it : it.skip)("erases a person, their event data and their Keycloak user", async () => {
+ await ensureUser(email("max"), "Audit max");
+ await explain(ids.lou, ids.max);
+ const report = await manageAccount("erase", email("max"));
+ expect(report.join("\n")).toMatch(/keycloak: user deleted/);
+ expect(await attendees.findByEmail(email("max"))).toBeNull();
+ expect((await query(`select 1 from event_participants where attendee_id = $1`, [ids.max])).rows).toHaveLength(0);
+ expect(await explanationsAbout(ids.max)).toBe(0);
+ expect(await findUserByEmail(email("max"))).toBeNull();
+ expect((await query(`select 1 from audit_events where action = 'account.erased' and subject_id = $1`, [ids.max])).rows).toHaveLength(1);
+ });
+
+ it("keeps records when their event is deleted", async () => {
+ await query(`delete from events where id = $1`, [eventId]);
+ expect((await query(`select event_id from audit_events where action = 'roster.imported' and actor_id = $1`, [ids.org])).rows[0].event_id).toBeNull();
+ });
+});
diff --git a/tests/unit/invitations.test.ts b/tests/unit/invitations.test.ts
index 35c176b..595497e 100644
--- a/tests/unit/invitations.test.ts
+++ b/tests/unit/invitations.test.ts
@@ -84,6 +84,17 @@ describe("setAttendeeAccess", () => {
});
});
+describe("audit records", () => {
+ it("records invitations sent and access changes", async () => {
+ const { events, notifications } = ports([{ attendee_id: "a", email: "a@example.com", name: "A" }]);
+ const audit = { record: vi.fn(async () => {}), recent: vi.fn() };
+ await sendInvitations(event, { events, notifications, audit });
+ await setAttendeeAccess({ eventId: "event", organizerId: "organizer", attendeeId: "a", revoked: true }, { events, audit });
+ expect(audit.record).toHaveBeenCalledWith(expect.objectContaining({ action: "invitations.sent", actorId: "organizer", details: expect.objectContaining({ sent: 1 }) }));
+ expect(audit.record).toHaveBeenCalledWith(expect.objectContaining({ action: "access.removed", subjectId: "a" }));
+ });
+});
+
describe("renderInvitationEmail", () => {
it("links to the event and escapes names in the HTML", () => {
const mail = renderInvitationEmail({ name: "