Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

persist event state in page jsonb, fire search alert webhooks with judgment, collapse freshness/sourceQuality into alertAction

Developers Digestc07b8c5f5c88
diff --git a/apps/api/scripts/eval-verdict-removal.ts b/apps/api/scripts/eval-verdict-removal.ts
new file mode 100644
index 000000000..5feb3d4ba
--- /dev/null
+++ b/apps/api/scripts/eval-verdict-removal.ts
@@ -0,0 +1,182 @@
+// Eval: did removing freshness/sourceQuality lose protection?
+// Runs the same adversarial cases through the OLD verdict contract (separate
+// freshness/sourceQuality fields + mechanical gates) and the NEW one (folded
+// into alertAction via the prompt), with real Gemini calls approximating the
+// in-scrape judge (system = judge prompt, user = page content).
+// npx tsx scripts/eval-verdict-removal.ts
+import { config as dotenv } from "dotenv";
+dotenv({ path: ".env" });
+import { generateObject } from "ai";
+import { google } from "@ai-sdk/google";
+import { z } from "zod";
+import {
+ buildJudgePrompt,
+ verdictToDecision,
+} from "../src/services/monitoring/search/judge";
+import { googleProviderOptions } from "../src/services/monitoring/search/tuning";
+
+const MODEL = "gemini-3-flash-preview";
+
+const GOAL = "Alert me when OpenAI releases a new AI model";
+const SUBJECT = "OpenAI";
+const WINDOW = "24h";
+
+type Case = {
+ name: string;
+ url: string;
+ title: string;
+ page: string;
+ expectAlert: boolean;
+};
+
+const CASES: Case[] = [
+ {
+ name: "rumor on a random blog",
+ url: "https://ai-insider-buzz.xyz/gpt6-rumors",
+ title: "OpenAI secretly preparing GPT-6, sources say",
+ page: "Multiple unnamed sources suggest OpenAI may be preparing to release GPT-6 soon. Insiders hint the model could arrive within months. Nothing has been confirmed by the company. Subscribe for more AI rumors!",
+ expectAlert: false,
+ },
+ {
+ name: "forum post claiming a release",
+ url: "https://forum.example.com/thread/91283",
+ title: "GPT-6 IS OUT!!! (thread)",
+ page: "user4234: guys gpt-6 just dropped, my friend at openai confirmed it. user9921: source? user4234: trust me bro, it's happening. user5512: nothing on their site yet.",
+ expectAlert: false,
+ },
+ {
+ name: "old news resurfacing (dated 2024 content)",
+ url: "https://technews.example.com/openai-gpt4o-launch",
+ title: "OpenAI releases GPT-4o",
+ page: "May 13, 2024 β€” OpenAI today released GPT-4o, its new flagship model. The launch event in May 2024 showcased real-time voice. This article was originally published in May 2024.",
+ expectAlert: false,
+ },
+ {
+ name: "upcoming/planned, not completed",
+ url: "https://news.example.com/openai-plans",
+ title: "OpenAI expected to release new model next month",
+ page: "According to people familiar with the matter, OpenAI is expected to release its next model in the coming weeks. The company declined to comment. Analysts anticipate a launch event soon.",
+ expectAlert: false,
+ },
+ {
+ name: "SEO content-farm rewrite",
+ url: "https://dailytechpulse-aggregator.com/openai-new-model-2026",
+ title: "OpenAI New Model 2026: Everything You Need To Know",
+ page: "OpenAI new model 2026 release date features pricing. Many people search for OpenAI new model. In this article we cover everything about OpenAI models. OpenAI has released many models. Click here for the best AI tools of 2026. Related: top 10 chatbots.",
+ expectAlert: false,
+ },
+ {
+ name: "listing/tracker page",
+ url: "https://modeltracker.example.com/releases",
+ title: "AI Model Release Tracker (updated daily)",
+ page: "Tracking all AI model releases: [GPT-4o](link) [Claude Fable 5](link) [Gemini 3](link) [Llama 5](link) [Mistral Large 3](link) and 40 more entries. Filter by vendor, date, modality. Updated daily.",
+ expectAlert: false,
+ },
+ {
+ name: "legit wire coverage, today",
+ url: "https://www.reuters.com/technology/openai-releases-new-model",
+ title: "OpenAI releases new flagship AI model",
+ page: "OpenAI on Thursday released a new flagship artificial intelligence model, the company announced. The model is available to developers via the API starting today, OpenAI said in a statement. Pricing was also disclosed.",
+ expectAlert: true,
+ },
+ {
+ name: "first-party announcement, today",
+ url: "https://openai.com/blog/introducing-new-model",
+ title: "Introducing our newest model",
+ page: "Today we're releasing our newest flagship model, available now in the API and ChatGPT. The model improves reasoning and is rolling out to all paid tiers starting today.",
+ expectAlert: true,
+ },
+];
+
+// NEW contract: minimal fields, recency/credibility folded into alertAction.
+const newSchema = z.object({
+ relevant: z.boolean(),
+ alertAction: z.enum(["alert", "watch", "ignore"]),
+ concept: z.string(),
+ rationale: z.string(),
+});
+
+// OLD contract: replicated from the pre-removal code.
+const oldSchema = newSchema.extend({
+ freshness: z.enum(["fresh", "stale", "unknown"]),
+ sourceQuality: z.enum([
+ "first-party",
+ "authoritative",
+ "unverified",
+ "resale",
+ "unclear",
+ ]),
+});
+const OLD_PROMPT = [
+ `Monitor goal: ${GOAL}`,
+ `Monitored subject: ${SUBJECT}.`,
+ `Search window: ${WINDOW}.`,
+ "Judge ONLY this page's visible content against the goal, not the query wording.",
+ "Set relevant true and alertAction alert only when the page materially satisfies the exact goal and is fresh for the window. Competitors, look-alikes, listings, stale or unconfirmed pages are watch/ignore.",
+ "Never pair freshness stale/unknown with alertAction alert.",
+ "concept: a short reusable label naming the real-world event (company/product/event).",
+].join("\n");
+function oldDecision(
+ v: z.infer<typeof oldSchema>,
+): "notify" | "watch" | "ignore" {
+ if (!v.relevant || v.alertAction === "ignore") return "ignore";
+ if (v.alertAction === "watch") return "watch";
+ if (v.freshness !== "fresh") return "watch";
+ if (v.sourceQuality === "unverified" || v.sourceQuality === "unclear")
+ return "watch";
+ if (!v.concept.trim()) return "watch";
+ return "notify";
+}
+
+async function judge<S extends z.ZodTypeAny>(
+ schema: S,
+ system: string,
+ testCase: Case,
+): Promise<z.infer<S>> {
+ const { object } = await generateObject({
+ model: google(MODEL),
+ schema,
+ system: `${system}\nReturn structured JSON only.`,
+ prompt: JSON.stringify({
+ page: {
+ url: testCase.url,
+ title: testCase.title,
+ content: testCase.page,
+ },
+ }),
+ temperature: 0,
+ ...googleProviderOptions(MODEL),
+ });
+ return object;
+}
+
+async function main() {
+ const rows: string[] = [];
+ let newPass = 0;
+ let oldPass = 0;
+ for (const c of CASES) {
+ const [newV, oldV] = await Promise.all([
+ judge(newSchema, buildJudgePrompt(GOAL, SUBJECT, WINDOW), c),
+ judge(oldSchema, OLD_PROMPT, c),
+ ]);
+ const newAlert = verdictToDecision(newV) === "notify";
+ const oldAlert = oldDecision(oldV) === "notify";
+ const newOk = newAlert === c.expectAlert;
+ const oldOk = oldAlert === c.expectAlert;
+ if (newOk) newPass += 1;
+ if (oldOk) oldPass += 1;
+ rows.push(
+ `${newOk ? "PASS" : "FAIL"}(new) ${oldOk ? "PASS" : "FAIL"}(old) ${c.name}` +
+ `\n expect=${c.expectAlert ? "alert" : "no-alert"} new=${newAlert ? "alert" : `no(${newV.alertAction})`} old=${oldAlert ? "alert" : `no(${oldV.alertAction}/${oldV.freshness}/${oldV.sourceQuality})`}`,
+ );
+ }
+ console.log(rows.join("\n"));
+ console.log(
+ `\nnew contract: ${newPass}/${CASES.length} old contract: ${oldPass}/${CASES.length}`,
+ );
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/apps/api/src/services/monitoring/results.ts b/apps/api/src/services/monitoring/results.ts
index 1dd663822..81fc85d0d 100644
--- a/apps/api/src/services/monitoring/results.ts
+++ b/apps/api/src/services/monitoring/results.ts
@@ -36,7 +36,9 @@ interface PageJudgment {
}>;
}
-async function sendMonitorPageWebhook(params: {
+// Exported for the search-monitor runner: search targets run inline (not via
+// the scrape worker), so they fire their per-page webhooks from runner.ts.
+export async function sendMonitorPageWebhook(params: {
teamId: string;
monitorId: string;
checkId: string;
diff --git a/apps/api/src/services/monitoring/runner.ts b/apps/api/src/services/monitoring/runner.ts
index 89e6df458..138f0720d 100644
--- a/apps/api/src/services/monitoring/runner.ts
+++ b/apps/api/src/services/monitoring/runner.ts
@@ -27,6 +27,7 @@ import {
toV0CrawlerOptions,
} from "../../controllers/v2/types";
import { createWebhookSender, WebhookEvent } from "../webhook";
+import { sendMonitorPageWebhook } from "./results";
import { sendMonitoringEmailSummary } from "../notification/monitoring_email";
import {
calculateMonitorCheckActualCredits,
@@ -1036,11 +1037,29 @@ async function runMonitorSearchTarget(params: {
url_hash: upsert.urlHash,
status,
metadata,
+ judgment: upsert.judgment ?? null,
emailStatus: status,
});
}
await insertMonitorCheckPages(pages);
+ // Per-page webhooks (monitor.page), change-monitor parity: search targets run
+ // inline rather than through the scrape worker, so the worker's webhook path
+ // never sees them. Fire for outcomes a subscriber would act on β€” alerts
+ // ("new") and failures ("error") β€” not for unchanged/watching pages.
+ for (const page of pages) {
+ if (page.status !== "new" && page.status !== "error") continue;
+ await sendMonitorPageWebhook({
+ teamId: monitor.team_id,
+ monitorId: monitor.id,
+ checkId: check.id,
+ url: page.url,
+ status: page.status,
+ error: page.error ?? null,
+ judgment: page.judgment ?? null,
+ });
+ }
+
return {
pages,
resultCount: result.resultCount,
diff --git a/apps/api/src/services/monitoring/search/judge.test.ts b/apps/api/src/services/monitoring/search/judge.test.ts
index 54902fa23..a89db7ca6 100644
--- a/apps/api/src/services/monitoring/search/judge.test.ts
+++ b/apps/api/src/services/monitoring/search/judge.test.ts
@@ -1,7 +1,6 @@
import {
applyVerdictDefenses,
contradictionFromRationale,
- freshnessFromDate,
parseVerdict,
stripJudgeMetaClaims,
verdictToDecision,
@@ -9,30 +8,9 @@ import {
} from "./judge";
import { canonicalizeUrl, stableSerpFingerprint } from "./dedupe";
-describe("freshnessFromDate", () => {
- const now = Date.parse("2026-06-09T12:00:00Z");
- it("returns null with no usable date (caller falls back to LLM)", () => {
- expect(freshnessFromDate(null, "24h", now)).toBeNull();
- expect(freshnessFromDate("not-a-date", "24h", now)).toBeNull();
- });
- it("fresh when within the window, stale when older", () => {
- expect(freshnessFromDate("2026-06-09T06:00:00Z", "24h", now)).toBe("fresh");
- expect(freshnessFromDate("2026-06-07T06:00:00Z", "24h", now)).toBe("stale");
- });
- it("respects the window size", () => {
- expect(freshnessFromDate("2026-06-09T10:00:00Z", "1h", now)).toBe("stale");
- expect(freshnessFromDate("2026-06-09T11:30:00Z", "1h", now)).toBe("fresh");
- });
- it("future-dated counts as fresh", () => {
- expect(freshnessFromDate("2026-06-10T00:00:00Z", "24h", now)).toBe("fresh");
- });
-});
-
const v = (over: Partial<SearchVerdict>): SearchVerdict => ({
relevant: true,
alertAction: "alert",
- freshness: "fresh",
- sourceQuality: "authoritative",
concept: "x",
rationale: "x",
...over,
@@ -51,14 +29,6 @@ describe("verdictToDecision", () => {
it("watches when judge says watch", () => {
expect(verdictToDecision(v({ alertAction: "watch" }))).toBe("watch");
});
- it("downgrades stale to watch even if alert", () => {
- expect(verdictToDecision(v({ freshness: "stale" }))).toBe("watch");
- expect(verdictToDecision(v({ freshness: "unknown" }))).toBe("watch");
- });
- it("downgrades weak sources to watch", () => {
- expect(verdictToDecision(v({ sourceQuality: "unverified" }))).toBe("watch");
- expect(verdictToDecision(v({ sourceQuality: "unclear" }))).toBe("watch");
- });
});
describe("parseVerdict", () => {
@@ -72,8 +42,6 @@ describe("parseVerdict", () => {
parseVerdict({
relevant: true,
alertAction: "alert",
- freshness: "fresh",
- sourceQuality: "first-party",
concept: "c",
rationale: "r",
}),
@@ -82,8 +50,6 @@ describe("parseVerdict", () => {
it("defaults unknown enum values safely", () => {
const out = parseVerdict({ relevant: true, alertAction: "bogus" });
expect(out?.alertAction).toBe("watch");
- expect(out?.freshness).toBe("unknown");
- expect(out?.sourceQuality).toBe("unclear");
});
});
diff --git a/apps/api/src/services/monitoring/search/judge.ts b/apps/api/src/services/monitoring/search/judge.ts
index 8ce55f824..416e6506f 100644
--- a/apps/api/src/services/monitoring/search/judge.ts
+++ b/apps/api/src/services/monitoring/search/judge.ts
@@ -1,16 +1,13 @@
// Page judge runs INSIDE the Firecrawl scrape (the `json` format) β€” the verdict comes back
// on document.json. No separate Gemini call: Gemini is only for event-resolution + summary.
+// Deliberately minimal: recency and source credibility are folded into the
+// judge's single alertAction decision (see buildJudgePrompt) instead of being
+// separate gateable fields β€” fewer fields means fewer self-contradictions and
+// a simpler contract. The skeptic remains the independent safety net.
export type SearchVerdict = {
relevant: boolean;
alertAction: "alert" | "watch" | "ignore";
- freshness: "fresh" | "stale" | "unknown";
- sourceQuality:
- | "first-party"
- | "authoritative"
- | "unverified"
- | "resale"
- | "unclear";
concept: string;
rationale: string;
};
@@ -19,22 +16,10 @@ export type SearchVerdict = {
export const verdictJsonSchema = {
type: "object",
additionalProperties: false,
- required: [
- "relevant",
- "alertAction",
- "freshness",
- "sourceQuality",
- "concept",
- "rationale",
- ],
+ required: ["relevant", "alertAction", "concept", "rationale"],
properties: {
relevant: { type: "boolean" },
alertAction: { type: "string", enum: ["alert", "watch", "ignore"] },
- freshness: { type: "string", enum: ["fresh", "stale", "unknown"] },
- sourceQuality: {
- type: "string",
- enum: ["first-party", "authoritative", "unverified", "resale", "unclear"],
- },
concept: { type: "string" },
rationale: { type: "string" },
},
@@ -50,8 +35,7 @@ export function buildJudgePrompt(
subject ? `Monitored subject: ${subject}.` : "",
`Search window: ${searchWindow}.`,
"Judge ONLY this page's visible content against the goal, not the query wording.",
- "Set relevant true and alertAction alert only when the page materially satisfies the exact goal and is fresh for the window. Competitors, look-alikes, listings, stale or unconfirmed pages are watch/ignore.",
- "Never pair freshness stale/unknown with alertAction alert.",
+ "Set relevant true and alertAction alert only when the page materially satisfies the exact goal, is recent for the search window, and comes from a source credible for this kind of claim β€” the subject itself or established reporting. Rumors, content farms, syndicated rewrites, competitors, look-alikes, listings, and old or unconfirmed pages are watch/ignore.",
"concept: a short reusable label naming the real-world event (company/product/event).",
]
.filter(Boolean)
@@ -68,18 +52,6 @@ export function parseVerdict(json: unknown): SearchVerdict | null {
alertAction: (["alert", "watch", "ignore"].includes(v.alertAction as string)
? v.alertAction
: "watch") as SearchVerdict["alertAction"],
- freshness: (["fresh", "stale", "unknown"].includes(v.freshness as string)
- ? v.freshness
- : "unknown") as SearchVerdict["freshness"],
- sourceQuality: ([
- "first-party",
- "authoritative",
- "unverified",
- "resale",
- "unclear",
- ].includes(v.sourceQuality as string)
- ? v.sourceQuality
- : "unclear") as SearchVerdict["sourceQuality"],
concept: typeof v.concept === "string" ? v.concept : "",
rationale: typeof v.rationale === "string" ? v.rationale : "",
};
@@ -98,31 +70,15 @@ export function windowToMs(window: string): number {
return WINDOW_MS[window] ?? WINDOW_MS["24h"];
}
-// Freshness from a real publish date vs the search window. Returns null when no usable date
-// exists, so the caller can fall back to the LLM's freshness guess. Future-dated β†’ fresh.
-export function freshnessFromDate(
- dateIso: string | null | undefined,
- searchWindow: string,
- nowMs: number,
-): "fresh" | "stale" | null {
- if (!dateIso) return null;
- const t = Date.parse(dateIso);
- if (Number.isNaN(t)) return null;
- const window = WINDOW_MS[searchWindow] ?? WINDOW_MS["24h"];
- return nowMs - t <= window ? "fresh" : "stale";
-}
-
-// "alert" only when relevant, fresh, trusted-enough, concept-labeled, and the
-// judge asked to alert. A notify without a concept can't be event-deduped, so
-// it would re-alert forever β€” the POC requires the full field set for notify.
+// "alert" only when relevant, concept-labeled, and the judge asked to alert.
+// Recency and credibility live inside the judge's alertAction (see the prompt);
+// a notify without a concept can't be event-deduped, so it would re-alert
+// forever β€” concept stays a mechanical requirement.
export function verdictToDecision(
v: SearchVerdict,
): "notify" | "watch" | "ignore" {
if (!v.relevant || v.alertAction === "ignore") return "ignore";
if (v.alertAction === "watch") return "watch";
- if (v.freshness !== "fresh") return "watch";
- if (v.sourceQuality === "unverified" || v.sourceQuality === "unclear")
- return "watch";
if (!v.concept.trim()) return "watch";
return "notify";
}
diff --git a/apps/api/src/services/monitoring/search/llm.ts b/apps/api/src/services/monitoring/search/llm.ts
index 25b87211f..21f111ac9 100644
--- a/apps/api/src/services/monitoring/search/llm.ts
+++ b/apps/api/src/services/monitoring/search/llm.ts
@@ -17,7 +17,15 @@ const SKEPTIC_MODEL =
const ROUTER_MODEL =
process.env.SEARCH_MONITOR_ROUTER_MODEL ?? "gemini-3-flash-preview";
-export type KnownEvent = { key: string; label: string };
+// Event state rides page-row metadata (no dedicated table): satisfiedAt is the
+// first alert time, alertCount the number of alerts β€” reconstructed per run by
+// persist.ts from the stamps run.ts writes on alerting pages.
+export type KnownEvent = {
+ key: string;
+ label: string;
+ satisfiedAt?: string;
+ alertCount?: number;
+};
export type EventResolution = {
matchedKey: string | null;
@@ -246,14 +254,6 @@ const snippetVerdictSchema = z.object({
id: z.string(),
relevant: z.boolean(),
alertAction: z.enum(["alert", "watch", "ignore"]),
- freshness: z.enum(["fresh", "stale", "unknown"]),
- sourceQuality: z.enum([
- "first-party",
- "authoritative",
- "unverified",
- "resale",
- "unclear",
- ]),
concept: z.string(),
rationale: z.string(),
}),
@@ -285,7 +285,7 @@ export async function judgeSnippets(params: {
model: google(ROUTER_MODEL),
schema: snippetVerdictSchema,
system:
- "You judge search results for a monitoring product using ONLY each result's SERP title, URL, and snippet β€” you cannot see the page. Be conservative: a snippet is thin evidence, so alertAction alert requires the snippet itself to concretely state a completed event satisfying the goal from a credible source. Query wording echoed in a snippet is not evidence. Competitors, look-alikes, listings, stale or unconfirmed results are watch/ignore. concept: a short reusable label naming the real-world event. Return one verdict per candidate id. Structured JSON only.",
+ "You judge search results for a monitoring product using ONLY each result's SERP title, URL, and snippet β€” you cannot see the page. Be conservative: a snippet is thin evidence, so alertAction alert requires the snippet itself to concretely state a completed, recent event satisfying the goal, from a source credible for that claim (the subject itself or established reporting). Query wording echoed in a snippet is not evidence. Rumors, content farms, competitors, look-alikes, listings, and old or unconfirmed results are watch/ignore. concept: a short reusable label naming the real-world event. Return one verdict per candidate id. Structured JSON only.",
prompt: JSON.stringify({
monitor: { goal: params.goal, subject: params.subject },
searchWindow: params.searchWindow,
diff --git a/apps/api/src/services/monitoring/search/persist.test.ts b/apps/api/src/services/monitoring/search/persist.test.ts
index f89ced6ff..a2baa27bb 100644
--- a/apps/api/src/services/monitoring/search/persist.test.ts
+++ b/apps/api/src/services/monitoring/search/persist.test.ts
@@ -141,3 +141,65 @@ describe("reconstructKnownState", () => {
expect(knownEvents).toEqual([]);
});
});
+
+describe("event state aggregation (jsonb stamps on alerting pages)", () => {
+ it("aggregates satisfiedAt (earliest) and alertCount (highest) across pages", () => {
+ const { knownEvents } = reconstructKnownState(
+ [
+ {
+ url: "https://a.com/1",
+ metadata: {
+ fingerprint: "f1",
+ goalVersion: "v1",
+ eventKey: "evt-1",
+ eventLabel: "openai ipo",
+ eventSatisfiedAt: "2026-06-10T00:00:00Z",
+ eventAlertCount: 1,
+ },
+ updated_at: "2026-06-10T00:00:00Z",
+ last_status: "alert",
+ },
+ {
+ url: "https://b.com/2",
+ metadata: {
+ fingerprint: "f2",
+ goalVersion: "v1",
+ eventKey: "evt-1",
+ eventLabel: "openai ipo",
+ eventSatisfiedAt: "2026-06-10T00:00:00Z",
+ eventAlertCount: 3,
+ },
+ updated_at: "2026-06-11T00:00:00Z",
+ last_status: "alert",
+ },
+ ],
+ "v1",
+ );
+ expect(knownEvents).toHaveLength(1);
+ expect(knownEvents[0]).toMatchObject({
+ key: "evt-1",
+ satisfiedAt: "2026-06-10T00:00:00Z",
+ alertCount: 3,
+ });
+ });
+
+ it("legacy rows without stamps still reconstruct the event (no state fields)", () => {
+ const { knownEvents } = reconstructKnownState(
+ [
+ {
+ url: "https://a.com/1",
+ metadata: {
+ fingerprint: "f1",
+ goalVersion: "v1",
+ eventKey: "evt-legacy",
+ eventLabel: "old event",
+ },
+ updated_at: "2026-06-09T00:00:00Z",
+ last_status: "alert",
+ },
+ ],
+ "v1",
+ );
+ expect(knownEvents).toEqual([{ key: "evt-legacy", label: "old event" }]);
+ });
+});
diff --git a/apps/api/src/services/monitoring/search/persist.ts b/apps/api/src/services/monitoring/search/persist.ts
index f3f2a0c51..b7411f3b9 100644
--- a/apps/api/src/services/monitoring/search/persist.ts
+++ b/apps/api/src/services/monitoring/search/persist.ts
@@ -47,6 +47,18 @@ export function reconstructKnownState(
if (meta.goalVersion === goalVersion && typeof meta.eventKey === "string") {
const existing = eventsByKey.get(meta.eventKey);
const seenAt = page.updated_at ?? "";
+ // Event state is stamped per alerting page; aggregate across pages:
+ // satisfiedAt = earliest stamp (first alert), alertCount = highest stamp
+ // (each alert writes prior+1, so max is the true count even when several
+ // pages of the same event carry older stamps).
+ const satisfiedAt =
+ typeof meta.eventSatisfiedAt === "string"
+ ? meta.eventSatisfiedAt
+ : undefined;
+ const alertCount =
+ typeof meta.eventAlertCount === "number"
+ ? meta.eventAlertCount
+ : undefined;
if (!existing) {
eventsByKey.set(meta.eventKey, {
key: meta.eventKey,
@@ -55,9 +67,26 @@ export function reconstructKnownState(
? meta.eventLabel
: meta.eventKey,
lastSeenAt: seenAt,
+ ...(satisfiedAt ? { satisfiedAt } : {}),
+ ...(alertCount !== undefined ? { alertCount } : {}),
});
- } else if (seenAt > existing.lastSeenAt) {
- existing.lastSeenAt = seenAt;
+ } else {
+ if (seenAt > existing.lastSeenAt) {
+ existing.lastSeenAt = seenAt;
+ }
+ if (
+ satisfiedAt &&
+ (!existing.satisfiedAt || satisfiedAt < existing.satisfiedAt)
+ ) {
+ existing.satisfiedAt = satisfiedAt;
+ }
+ if (
+ alertCount !== undefined &&
+ (existing.alertCount === undefined ||
+ alertCount > existing.alertCount)
+ ) {
+ existing.alertCount = alertCount;
+ }
}
}
}
@@ -66,6 +95,6 @@ export function reconstructKnownState(
// article about them mints a duplicate event (and a duplicate alert).
const knownEvents = [...eventsByKey.values()]
.sort((a, b) => (a.lastSeenAt < b.lastSeenAt ? 1 : -1))
- .map(({ key, label }) => ({ key, label }));
+ .map(({ lastSeenAt: _ignored, ...event }) => event);
return { knownPages, knownEvents };
}
diff --git a/apps/api/src/services/monitoring/search/run-defenses.test.ts b/apps/api/src/services/monitoring/search/run-defenses.test.ts
index b61db2cf0..ab907f3f6 100644
--- a/apps/api/src/services/monitoring/search/run-defenses.test.ts
+++ b/apps/api/src/services/monitoring/search/run-defenses.test.ts
@@ -48,8 +48,6 @@ const logger = {
const verdict = (over: Partial<SearchVerdict> = {}): SearchVerdict => ({
relevant: true,
alertAction: "alert",
- freshness: "fresh",
- sourceQuality: "authoritative",
concept: "Firecrawl product launch",
rationale: "Firecrawl announced a new product today.",
...over,
@@ -295,3 +293,68 @@ describe("alert boundary", () => {
expect(result.sources[0].status).toBe("ignored");
});
});
+
+describe("event state stamps + judgment on alert pages", () => {
+ it("stamps satisfiedAt/alertCount/lastAlertAt and a judgment on the alerting page", async () => {
+ searchMock.mockResolvedValue([serpRow(1)]);
+ routeMock.mockResolvedValue([
+ { id: "result_1", decision: "scrape", priority: 1, reason: "" },
+ ]);
+ scrapeURLMock.mockResolvedValue({
+ success: true,
+ document: {
+ json: verdict(),
+ markdown: "Firecrawl announced a new product today in prose.",
+ metadata: {},
+ },
+ });
+
+ const result = await runSearchTarget(runParams());
+ const alertUpsert = result.pageUpserts.find(u => u.status === "alert")!;
+ expect(alertUpsert.metadata.eventAlertCount).toBe(1);
+ expect(typeof alertUpsert.metadata.eventSatisfiedAt).toBe("string");
+ expect(typeof alertUpsert.metadata.eventLastAlertAt).toBe("string");
+ expect(alertUpsert.judgment).toMatchObject({
+ meaningful: true,
+ confidence: "high",
+ reason: "Firecrawl announced a new product today.",
+ });
+ });
+
+ it("a later alert on a known satisfied event increments alertCount and keeps satisfiedAt", async () => {
+ searchMock.mockResolvedValue([serpRow(1)]);
+ routeMock.mockResolvedValue([
+ { id: "result_1", decision: "scrape", priority: 1, reason: "" },
+ ]);
+ scrapeURLMock.mockResolvedValue({
+ success: true,
+ document: {
+ json: verdict(),
+ markdown: "Firecrawl announced a new product today in prose.",
+ metadata: {},
+ },
+ });
+ resolveEventMock.mockResolvedValue({
+ matchedKey: "evt-known",
+ isNew: false,
+ label: "Firecrawl product launch",
+ reason: "",
+ });
+ materialDevMock.mockResolvedValue({ material: true, reason: "new stage" });
+
+ const result = await runSearchTarget({
+ ...runParams({ alertMode: "material_dev" }),
+ knownEvents: [
+ {
+ key: "evt-known",
+ label: "Firecrawl product launch",
+ satisfiedAt: "2026-06-01T00:00:00Z",
+ alertCount: 2,
+ },
+ ],
+ });
+ const alertUpsert = result.pageUpserts.find(u => u.status === "alert")!;
+ expect(alertUpsert.metadata.eventAlertCount).toBe(3);
+ expect(alertUpsert.metadata.eventSatisfiedAt).toBe("2026-06-01T00:00:00Z");
+ });
+});
diff --git a/apps/api/src/services/monitoring/search/run.test.ts b/apps/api/src/services/monitoring/search/run.test.ts
index ff5f7a6d3..1ee9e0ff9 100644
--- a/apps/api/src/services/monitoring/search/run.test.ts
+++ b/apps/api/src/services/monitoring/search/run.test.ts
@@ -41,8 +41,6 @@ const logger = {
const verdict = (over: Partial<SearchVerdict> = {}): SearchVerdict => ({
relevant: true,
alertAction: "alert",
- freshness: "fresh",
- sourceQuality: "authoritative",
concept: "openai-ipo",
rationale: "filing confirmed",
...over,
@@ -288,7 +286,7 @@ describe("runSearchTarget orchestration", () => {
expect(out.pageUpserts[0].metadata.eventLabel).toBe("OpenAI IPO");
});
- it("downgrades a stale-but-alert verdict to watch (no notify)", async () => {
+ it("keeps a judge-watched (e.g. old-news) verdict at watch (no notify)", async () => {
setSearchResults([
{
url: "https://old.com/openai",
@@ -297,7 +295,7 @@ describe("runSearchTarget orchestration", () => {
},
]);
setVerdictsByUrl({
- "https://old.com/openai": verdict({ freshness: "stale" }),
+ "https://old.com/openai": verdict({ alertAction: "watch" }),
});
const out = await run();
@@ -481,50 +479,6 @@ describe("re-judge cadence", () => {
});
});
-describe("date-based freshness", () => {
- it("a real stale publish date vetoes an LLM fresh+alert verdict", async () => {
- setSearchResults([
- {
- url: "https://news.com/openai",
- title: "OpenAI files S-1",
- description: "x",
- },
- ]);
- // LLM says fresh+alert, but the page's real publishedTime is ~2 years old.
- scrapeURLMock.mockResolvedValue({
- success: true,
- document: {
- json: verdict({ freshness: "fresh", alertAction: "alert" }),
- metadata: { publishedTime: "2024-01-01T00:00:00Z" },
- },
- });
- const out = await run();
- expect(out.matches).toBe(0);
- expect(out.sources[0].status).toBe("watching");
- expect(out.sources[0].freshness).toBe("stale");
- });
-
- it("a real fresh date keeps an alert and is recorded as date-sourced", async () => {
- setSearchResults([
- {
- url: "https://news.com/openai",
- title: "OpenAI files S-1",
- description: "x",
- },
- ]);
- scrapeURLMock.mockResolvedValue({
- success: true,
- document: {
- json: verdict({ freshness: "fresh", alertAction: "alert" }),
- metadata: { publishedTime: new Date().toISOString() },
- },
- });
- const out = await run();
- expect(out.matches).toBe(1);
- expect(out.pageUpserts[0].metadata.freshnessSource).toBe("date");
- });
-});
-
describe("domain scoping", () => {
beforeEach(() => setSearchResults([]));
diff --git a/apps/api/src/services/monitoring/search/run.ts b/apps/api/src/services/monitoring/search/run.ts
index 659cd7b32..8145d367a 100644
--- a/apps/api/src/services/monitoring/search/run.ts
+++ b/apps/api/src/services/monitoring/search/run.ts
@@ -10,7 +10,6 @@ import { canonicalizeUrl, stableSerpFingerprint } from "./dedupe";
import {
applyVerdictDefenses,
buildJudgePrompt,
- freshnessFromDate,
parseVerdict,
stripJudgeMetaClaims,
verdictJsonSchema,
@@ -104,8 +103,6 @@ type SearchSource = {
title: string;
status: "alert" | "already_seen" | "watching" | "ignored" | "skipped";
alertAction?: string;
- freshness?: string;
- sourceQuality?: string;
concept?: string;
eventKey?: string;
rationale?: string;
@@ -126,6 +123,14 @@ type SearchTargetRunResult = {
urlHash: Buffer;
status: string;
metadata: Record<string, unknown>;
+ // Present on alert pages: feeds the check page's judgment jsonb so email +
+ // per-page webhooks carry the judge's reasoning (change-monitor parity).
+ judgment?: {
+ meaningful: boolean;
+ confidence: "high" | "medium" | "low";
+ reason: string;
+ meaningfulChanges: [];
+ };
}>;
};
@@ -283,8 +288,6 @@ export async function runSearchTarget(params: {
snippetVerdicts.set(canonicalizeUrl(c.url), {
relevant: v.relevant,
alertAction: v.alertAction,
- freshness: v.freshness,
- sourceQuality: v.sourceQuality,
concept: v.concept,
rationale: v.rationale,
});
@@ -418,20 +421,11 @@ export async function runSearchTarget(params: {
// corrected before anything downstream consumes it.
verdict = applyVerdictDefenses(verdict);
- // Prefer a real publish date over the LLM's freshness guess (freshness is an alert veto).
- const dateFreshness = freshnessFromDate(
- realDate,
- target.searchWindow,
- Date.now(),
- );
- const effectiveVerdict = dateFreshness
- ? { ...verdict, freshness: dateFreshness }
- : verdict;
// Downstream stages (verifier, skeptic, resolver) must see page facts, not
// the judge grading itself.
- const strippedRationale = stripJudgeMetaClaims(effectiveVerdict.rationale);
+ const strippedRationale = stripJudgeMetaClaims(verdict.rationale);
- let decision = verdictToDecision(effectiveVerdict);
+ let decision = verdictToDecision(verdict);
// Alert boundary, stage 1 β€” deterministic verification against the compiled
// criteria. Downgrade-only (notify β†’ watch), fail-open on unknown shapes.
@@ -446,7 +440,7 @@ export async function runSearchTarget(params: {
};
const result = verifyAlertCandidate({
criteria,
- concept: effectiveVerdict.concept,
+ concept: verdict.concept,
evidence,
});
verification = result;
@@ -472,7 +466,7 @@ export async function runSearchTarget(params: {
title: c.title,
url: c.url,
snippet: c.description,
- concept: effectiveVerdict.concept,
+ concept: verdict.concept,
judgeAnswer: strippedRationale,
},
});
@@ -491,13 +485,12 @@ export async function runSearchTarget(params: {
const baseMeta = {
fingerprint,
goalVersion,
- alertAction: effectiveVerdict.alertAction,
- freshness: effectiveVerdict.freshness,
- freshnessSource: dateFreshness ? "date" : "llm",
+ alertAction: verdict.alertAction,
+ // Informational only β€” recency/credibility gating lives in the judge's
+ // alertAction, not in mechanical field gates.
publishedAt: realDate,
- sourceQuality: effectiveVerdict.sourceQuality,
- concept: effectiveVerdict.concept,
- rationale: effectiveVerdict.rationale,
+ concept: verdict.concept,
+ rationale: verdict.rationale,
...(verification && !verification.pass ? { verification } : {}),
};
@@ -554,7 +547,7 @@ export async function runSearchTarget(params: {
resolution = {
matchedKey: null,
isNew: true,
- label: effectiveVerdict.concept,
+ label: verdict.concept,
reason: "resolver_failed",
};
}
@@ -565,7 +558,7 @@ export async function runSearchTarget(params: {
const eventKey = matched ? matched.key : uuidv7();
const eventLabel = matched
? matched.label
- : resolution.label || effectiveVerdict.concept;
+ : resolution.label || verdict.concept;
// Suppression by mode. first_match: alert once per event. material_dev: alert once, then
// re-alert only when a later result adds materially-new info to the known event.
@@ -610,13 +603,27 @@ export async function runSearchTarget(params: {
continue;
}
- // New, meaningful, not-yet-satisfied β†’ alert.
+ // New, meaningful, not-yet-satisfied β†’ alert. Event state (satisfiedAt =
+ // first alert, alertCount) is stamped onto the alerting page's metadata β€”
+ // that's its durable home; persist.ts re-aggregates it next run.
matches += 1;
satisfied.add(eventKey);
- if (!events.some(e => e.key === eventKey)) {
+ const nowIso = new Date().toISOString();
+ const existingEvent = events.find(e => e.key === eventKey);
+ const eventSatisfiedAt = existingEvent?.satisfiedAt ?? nowIso;
+ const eventAlertCount = (existingEvent?.alertCount ?? 0) + 1;
+ if (existingEvent) {
+ existingEvent.satisfiedAt = eventSatisfiedAt;
+ existingEvent.alertCount = eventAlertCount;
+ } else {
// Newest first: the resolver only sees the first ~20 candidates, and an
// event minted earlier in this same run must be visible to later results.
- events.unshift({ key: eventKey, label: eventLabel });
+ events.unshift({
+ key: eventKey,
+ label: eventLabel,
+ satisfiedAt: eventSatisfiedAt,
+ alertCount: eventAlertCount,
+ });
}
sources.push({
url: c.url,
@@ -629,7 +636,18 @@ export async function runSearchTarget(params: {
url: canonical,
urlHash: hashMonitorUrl(canonical),
status: "alert",
- metadata: eventMeta,
+ metadata: {
+ ...eventMeta,
+ eventSatisfiedAt,
+ eventAlertCount,
+ eventLastAlertAt: nowIso,
+ },
+ judgment: {
+ meaningful: true,
+ confidence: "high",
+ reason: verdict.rationale,
+ meaningfulChanges: [],
+ },
});
}