Files
loki/scripts/test/event-candidate.ts
CatoandClaude Opus 5 1cc39fb361 feat(events): a weekly scout for what is worth going to (#787)
The operator asked to hear about events worth attending instead of finding them
by accident after they had happened. Finding events is the easy half; sending a
message that is still worth opening in week six is the hard one.

So the shape is borrowed from what already works in this repo rather than
invented:

  ONE MESSAGE, NOT ONE PER EVENT. The 2026-08-05 disk-alert storm (40 pings in
  three hours) is the standing lesson about per-item notification.

  EVERY LINE IS ACTIONABLE. Each suggestion is a real draft in the approval
  queue with its own one-tap Approve link, so "that looks good" is a tap and it
  is in the calendar — not a link to a listings page and a note to self. The
  queue, the signed links and the booking drain all already existed and are
  already proven; the scout's whole delivery story is "write a draft".

  A CLASH IS NAMED. Each suggestion is checked against the calendar mirror, so
  a Thursday gig that collides with an existing meeting says so before it is
  accepted rather than after.

FOUR DECISIONS WORTH THE REVIEW:

1. SEARCH COMES FROM ai-kit/web. fleet/SHARED.md owns this and says plainly: do
   not hand-roll fetch-and-summarise. That package already has the backend chain
   (self-hosted searxng → brave → tavily), an SSRF-safe reader for urls the
   MODEL chose, and a three-valued answer. `could_not_look` is not `nothing`:
   a dead backend must never be reported as "there are no events in Zurich this
   week". Writing a second client here would have reinvented that bug — and
   memory already records the specific shape (a stock searxng answers JSON with
   403, which reads as "no results").

2. ONE MODEL CALL PER RUN, NOT ONE PER RESULT. Extraction has to be a model —
   snippets carry dates as prose, in two languages — but the AI budget is
   rationed and shared across ten apps, so per-result extraction would spend a
   day's allowance on one digest. Every snippet goes into a single batched call.

3. THE MODEL IS NOT TRUSTED ABOUT TIME. It is told today's date and told that
   omitting is always correct; whatever comes back is screened AGAIN in pure
   code, which drops undated, past and out-of-horizon entries regardless of what
   it claimed. This is not hypothetical: the first search run while building
   this returned a Zurich meetup dated September 2025 as its top hit.

4. THE CAP IS THE PRODUCT. The operator selected all four purposes, so ranking
   cannot lean on exclusion — six per week is what stops a curated handful
   becoming a feed. Better to miss a good event than to send the message that
   teaches him to swipe past the next one.

Rejections are the memory: a suggestion turned down is never proposed again,
however it is spelled, so the operator says no once rather than every week.

Tests: 21 cases on what reaches the digest, written from the side that hurts —
the guessed date, the duplicate, the rejected thing returning — with the real
2025 listing as a fixture. The cron installer gains a weekly OnCalendar form
(existing daily/hourly entries expand exactly as before) and the scout is added
to the one list that both writes AND enables timers, because listing a job twice
is how one gets a timer and never runs.

Deliberately NOT built: a separate same-day reminder. Approved events go into
Google Calendar, which already reminds; a second notifier would be the second
one of something that works.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 06:47:45 -07:00

150 lines
6.0 KiB
TypeScript

// Pins what reaches the operator's weekly event digest.
//
// WHY IT EARNS A TEST
// Every suggestion is an interruption with a button on it. The failure that
// matters is not missing a good event — it is sending a message the operator
// learns to swipe past, because after that the good ones are missed too, and
// silently.
//
// The specific ways that happens, each pinned below:
//
// A GUESSED DATE. The very first search run while building this returned a
// Zurich meetup dated September 2025 as its top hit. Listings pages say
// "upcoming" about anything. A candidate whose date cannot be read must be
// DROPPED, never defaulted to "soon" — a suggestion for an event that already
// happened teaches the operator the whole feed is junk.
//
// A DUPLICATE. Listings spell one evening a dozen ways. Comparing raw titles
// dedupes almost nothing, and the same meetup three times reads as spam.
//
// A REJECTED THING RETURNING. The operator says no once; the queue is the
// memory. Re-proposing is how a learning loop proves it isn't one.
import {
resolveCandidateTimes,
dedupeKey,
screenCandidates,
type EventCandidate,
} from "@/lib/events/candidate";
const NOW = new Date("2026-09-17T10:00:00Z");
const base = (over: Partial<EventCandidate> = {}): EventCandidate => ({
title: "Zurich AI Meetup",
startsAt: "2026-09-24T18:00:00+02:00",
category: "meetup",
rationale: "small rooms",
...over,
});
const screen = (candidates: EventCandidate[], seen: string[] = [], max = 6) =>
screenCandidates({ candidates, now: NOW, horizonDays: 21, seenKeys: new Set(seen), max });
let pass = 0;
const cases: Array<[string, boolean]> = [];
const check = (name: string, cond: boolean) => {
cases.push([name, cond]);
if (cond) pass++;
};
// ── Time resolution: unknown is a drop, never a guess ───────────────────────
check("a timed event resolves", resolveCandidateTimes(base())?.allDay === false);
check(
"start with no end gets 2h (under-stating length lets clashes through)",
resolveCandidateTimes({ ...base(), endsAt: undefined })?.end.toISOString() ===
"2026-09-24T18:00:00.000Z",
);
check(
"a bare day is all-day with an exclusive end",
(() => {
const t = resolveCandidateTimes(base({ startsAt: "2026-09-26", endsAt: undefined }));
return t?.allDay === true && t.end.toISOString() === "2026-09-27T00:00:00.000Z";
})(),
);
check("no date at all ⇒ null", resolveCandidateTimes(base({ startsAt: undefined })) === null);
check(
"unparseable date ⇒ null",
resolveCandidateTimes(base({ startsAt: "next Thursday" })) === null,
);
check("empty date ⇒ null", resolveCandidateTimes(base({ startsAt: " " })) === null);
// ── Screening ───────────────────────────────────────────────────────────────
check("a good candidate survives", screen([base()]).length === 1);
check(
"an undated candidate is dropped, not guessed",
screen([base({ startsAt: undefined })]).length === 0,
);
check(
"THE 2025 CASE: a listing from last year is dropped",
screen([base({ startsAt: "2025-09-20T21:30:00+02:00" })]).length === 0,
);
check(
"something past the horizon is dropped",
screen([base({ startsAt: "2026-12-01T18:00:00Z" })]).length === 0,
);
check(
"an event running RIGHT NOW still counts as live",
screen([base({ startsAt: "2026-09-17T09:00:00Z", endsAt: "2026-09-17T23:00:00Z" })]).length === 1,
);
check(
"an event that ended an hour ago is dropped",
screen([base({ startsAt: "2026-09-17T07:00:00Z", endsAt: "2026-09-17T08:00:00Z" })]).length === 0,
);
check("a titleless candidate is dropped", screen([base({ title: " " })]).length === 0);
// ── Dedupe ──────────────────────────────────────────────────────────────────
check(
"issue numbers and the city don't make it a different event",
dedupeKey({ title: "ZURICH AI Meetup #14" }) === dedupeKey({ title: "Zurich AI Meetup" }),
);
check(
"tracking params don't make it a different event",
dedupeKey({ title: "X", url: "https://www.meetup.com/a?utm=1" }) ===
dedupeKey({ title: "X", url: "https://meetup.com/a/b?ref=2" }),
);
check(
"genuinely different events keep different keys",
dedupeKey({ title: "Rust Meetup" }) !== dedupeKey({ title: "Rust Conference" }),
);
check(
"the same evening spelled two ways appears once",
screen([base(), base({ title: "ZURICH AI MEETUP #14" })]).length === 1,
);
// ── Learning: a no is remembered ────────────────────────────────────────────
check(
"something already proposed is not proposed again",
screen([base()], [dedupeKey({ title: "Zurich AI Meetup" })]).length === 0,
);
check(
"a rejected event stays rejected even when spelled differently",
screen([base({ title: "Zurich AI Meetup #15" })], [dedupeKey({ title: "Zurich AI Meetup" })])
.length === 0,
);
// ── Order and cap ───────────────────────────────────────────────────────────
check(
"soonest first — the decision you owe first comes first",
(() => {
const out = screen([
base({ title: "Later", startsAt: "2026-10-01T18:00:00Z" }),
base({ title: "Sooner", startsAt: "2026-09-19T18:00:00Z" }),
]);
return out[0]?.title === "Sooner";
})(),
);
check(
"the cap holds — the digest is a handful, not a feed",
screen(
Array.from({ length: 30 }, (_, i) =>
base({
title: `Thing ${i}`,
startsAt: `2026-09-${String(18 + (i % 5)).padStart(2, "0")}T18:00:00Z`,
}),
),
[],
6,
).length === 6,
);
for (const [name, ok] of cases) console.log(`${ok ? "✓" : "✗"} ${name}`);
console.log(`\n${pass}/${cases.length} passed`);
if (pass !== cases.length) process.exit(1);