Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

wire search monitor target into runner with goal-versioned dedup and fee-path billing

Developers Digest0a31d65d4f5e
diff --git a/apps/api/src/services/monitoring/runner.ts b/apps/api/src/services/monitoring/runner.ts
index d4ba63523..06a574cab 100644
--- a/apps/api/src/services/monitoring/runner.ts
+++ b/apps/api/src/services/monitoring/runner.ts
@@ -59,6 +59,13 @@ import {
MONITOR_CHECK_STALE_TIMEOUT_MS,
} from "./stale";
import { trackMonitorCheckStartedInterest } from "./interest";
+import { runSearchTarget } from "./search/run";
+import { computeGoalVersion } from "./search/dedupe";
+import {
+ reconstructKnownState,
+ searchStatusToPageStatus,
+ searchPageWasScraped,
+} from "./search/persist";
const logger = _logger.child({ module: "monitoring-runner" });
const poll = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
@@ -101,6 +108,15 @@ type MonitorTargetRun =
targetId: string;
type: "crawl";
crawlId: string;
+ }
+ | {
+ // Search runs inline during dispatch (self-contained: search + scrape + judge),
+ // so its run descriptor needs no async handle. Summary/counts are filled in after it runs.
+ targetId: string;
+ type: "search";
+ resultCount?: number;
+ matches?: number;
+ summary?: string;
};
function createMonitorTargetRun(target: MonitorTarget): MonitorTargetRun {
@@ -112,6 +128,13 @@ function createMonitorTargetRun(target: MonitorTarget): MonitorTargetRun {
};
}
+ if (target.type === "search") {
+ return {
+ targetId: target.id,
+ type: "search",
+ };
+ }
+
return {
targetId: target.id,
type: "crawl",
@@ -923,6 +946,107 @@ async function enqueueMonitorCrawlTarget(params: {
return params.targetRun;
}
+// Reuse the canonical credit logic (no new constants): a search result that was scraped ran a
+// json verdict extraction (5 credits); already-seen results skip the scrape (0); failures bill base.
+const SEARCH_JSON_DOC = { json: {} } as const;
+const SEARCH_JSON_OPTS = { formats: [{ type: "json" }] } as const;
+function searchPageCredits(status: string): number {
+ if (status === "already_seen") return 0;
+ if (searchPageWasScraped(status)) {
+ return estimateActualCredits(SEARCH_JSON_DOC, SEARCH_JSON_OPTS);
+ }
+ return estimateActualCredits({}, SEARCH_JSON_OPTS); // skipped/other → base scrape credit
+}
+
+// Search targets run inline (they own their search + scrape + judge). We reconstruct the dedup
+// memory from prior monitor_pages, run the target, then persist results onto the same
+// monitor_pages / monitor_check_pages tables the reconciler tallies — no new storage.
+async function runMonitorSearchTarget(params: {
+ monitor: MonitorRow;
+ check: MonitorCheckRow;
+ target: MonitorTarget;
+}): Promise<{
+ pages: PageResult[];
+ resultCount: number;
+ matches: number;
+ summary: string;
+}> {
+ if (params.target.type !== "search") {
+ return { pages: [], resultCount: 0, matches: 0, summary: "" };
+ }
+ const { monitor, check, target } = params;
+ const goalVersion = computeGoalVersion(monitor.goal, target.queries);
+
+ // Rebuild per-URL dedup memory + the event index from prior pages of this target.
+ const priorPages = await listActiveMonitorPages({
+ monitorId: monitor.id,
+ targetId: target.id,
+ });
+ const { knownPages, knownEvents } = reconstructKnownState(
+ priorPages,
+ goalVersion,
+ );
+
+ const result = await runSearchTarget({
+ monitor: {
+ id: monitor.id,
+ teamId: monitor.team_id,
+ goal: monitor.goal,
+ subject: monitor.name,
+ },
+ target: {
+ id: target.id,
+ queries: target.queries,
+ searchWindow: target.searchWindow,
+ alertMode: target.alertMode,
+ includeDomains: target.includeDomains,
+ maxResults: target.maxResults,
+ },
+ goalVersion,
+ knownPages,
+ knownEvents,
+ zeroDataRetention: false,
+ logger,
+ });
+
+ const pages: PageResult[] = [];
+ for (const upsert of result.pageUpserts) {
+ const status = searchStatusToPageStatus(upsert.status);
+ const creditsUsed = searchPageCredits(upsert.status);
+ const metadata = { ...upsert.metadata, creditsUsed };
+ await upsertMonitorPage({
+ monitorId: monitor.id,
+ teamId: monitor.team_id,
+ targetId: target.id,
+ url: upsert.url,
+ source: "discovered",
+ checkId: check.id,
+ scrapeId: null,
+ status,
+ metadata,
+ });
+ pages.push({
+ check_id: check.id,
+ monitor_id: monitor.id,
+ team_id: monitor.team_id,
+ target_id: target.id,
+ url: upsert.url,
+ url_hash: upsert.urlHash,
+ status,
+ metadata,
+ emailStatus: status,
+ });
+ }
+ await insertMonitorCheckPages(pages);
+
+ return {
+ pages,
+ resultCount: result.resultCount,
+ matches: result.matches,
+ summary: result.summary,
+ };
+}
+
export async function processMonitorCheckJob(
job: MonitorCheckJobData,
): Promise<void> {
@@ -1014,8 +1138,23 @@ export async function processMonitorCheckJob(
await enqueueMonitorScrapeTarget({ monitor, check, target, targetRun });
} else if (target.type === "crawl" && targetRun.type === "crawl") {
await enqueueMonitorCrawlTarget({ monitor, check, target, targetRun });
+ } else if (target.type === "search" && targetRun.type === "search") {
+ // Search is synchronous: run it now and fold its outcome back into target_results
+ // so the reconciler (which treats search runs as already-complete) finalizes the check.
+ const searchResult = await runMonitorSearchTarget({
+ monitor,
+ check,
+ target,
+ });
+ targetRun.resultCount = searchResult.resultCount;
+ targetRun.matches = searchResult.matches;
+ targetRun.summary = searchResult.summary;
}
}
+
+ await updateMonitorCheck(check.id, {
+ target_results: targetResults,
+ });
} catch (error) {
if (lockId) {
await autumnService.finalizeCreditsLock({
diff --git a/apps/api/src/services/monitoring/search/dedupe.ts b/apps/api/src/services/monitoring/search/dedupe.ts
index 71037fc83..58ed86c56 100644
Binary files a/apps/api/src/services/monitoring/search/dedupe.ts and b/apps/api/src/services/monitoring/search/dedupe.ts differ
diff --git a/apps/api/src/services/monitoring/search/judge.test.ts b/apps/api/src/services/monitoring/search/judge.test.ts
new file mode 100644
index 000000000..c5bdd9eb9
--- /dev/null
+++ b/apps/api/src/services/monitoring/search/judge.test.ts
@@ -0,0 +1,95 @@
+import { parseVerdict, verdictToDecision, type SearchVerdict } from "./judge";
+import { canonicalizeUrl, stableSerpFingerprint } from "./dedupe";
+
+const v = (over: Partial<SearchVerdict>): SearchVerdict => ({
+ relevant: true,
+ alertAction: "alert",
+ freshness: "fresh",
+ sourceQuality: "authoritative",
+ concept: "x",
+ rationale: "x",
+ ...over,
+});
+
+describe("verdictToDecision", () => {
+ it("notifies on relevant + fresh + trusted + alert", () => {
+ expect(verdictToDecision(v({}))).toBe("notify");
+ });
+ it("ignores when not relevant", () => {
+ expect(verdictToDecision(v({ relevant: false }))).toBe("ignore");
+ });
+ it("ignores when judge says ignore", () => {
+ expect(verdictToDecision(v({ alertAction: "ignore" }))).toBe("ignore");
+ });
+ 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", () => {
+ it("returns null for non-objects / missing relevant", () => {
+ expect(parseVerdict(null)).toBeNull();
+ expect(parseVerdict("x")).toBeNull();
+ expect(parseVerdict({})).toBeNull();
+ });
+ it("coerces a valid verdict", () => {
+ expect(
+ parseVerdict({
+ relevant: true,
+ alertAction: "alert",
+ freshness: "fresh",
+ sourceQuality: "first-party",
+ concept: "c",
+ rationale: "r",
+ }),
+ ).toMatchObject({ relevant: true, alertAction: "alert", concept: "c" });
+ });
+ 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");
+ });
+});
+
+describe("dedupe", () => {
+ it("canonicalizes (host/www/trailing slash/case)", () => {
+ expect(canonicalizeUrl("https://www.Example.com/Path/")).toBe(
+ canonicalizeUrl("https://example.com/path"),
+ );
+ });
+ it("same title+snippet → same fingerprint (URL-independent)", () => {
+ const a = stableSerpFingerprint({
+ url: "https://a.com",
+ title: "T",
+ snippet: "S",
+ });
+ const b = stableSerpFingerprint({
+ url: "https://b.com",
+ title: "T",
+ snippet: "S",
+ });
+ expect(a).toBe(b);
+ });
+ it("different snippet → different fingerprint", () => {
+ const a = stableSerpFingerprint({
+ url: "https://a.com",
+ title: "T",
+ snippet: "S1",
+ });
+ const b = stableSerpFingerprint({
+ url: "https://a.com",
+ title: "T",
+ snippet: "S2",
+ });
+ expect(a).not.toBe(b);
+ });
+});
diff --git a/apps/api/src/services/monitoring/search/persist.test.ts b/apps/api/src/services/monitoring/search/persist.test.ts
new file mode 100644
index 000000000..3e511e809
--- /dev/null
+++ b/apps/api/src/services/monitoring/search/persist.test.ts
@@ -0,0 +1,120 @@
+import {
+ reconstructKnownState,
+ searchStatusToPageStatus,
+ searchPageWasScraped,
+} from "./persist";
+import { canonicalizeUrl } from "./dedupe";
+
+describe("searchStatusToPageStatus", () => {
+ it("maps alert→new, skipped→error, rest→same", () => {
+ expect(searchStatusToPageStatus("alert")).toBe("new");
+ expect(searchStatusToPageStatus("skipped")).toBe("error");
+ expect(searchStatusToPageStatus("already_seen")).toBe("same");
+ expect(searchStatusToPageStatus("watching")).toBe("same");
+ expect(searchStatusToPageStatus("ignored")).toBe("same");
+ });
+});
+
+describe("searchPageWasScraped", () => {
+ it("true only for statuses produced by a successful scrape+judge", () => {
+ expect(searchPageWasScraped("alert")).toBe(true);
+ expect(searchPageWasScraped("watching")).toBe(true);
+ expect(searchPageWasScraped("ignored")).toBe(true);
+ expect(searchPageWasScraped("already_seen")).toBe(false);
+ expect(searchPageWasScraped("skipped")).toBe(false);
+ });
+});
+
+describe("reconstructKnownState", () => {
+ it("rebuilds the dedup map keyed by canonical URL", () => {
+ const { knownPages } = reconstructKnownState(
+ [
+ {
+ url: "https://www.Example.com/A/",
+ metadata: { fingerprint: "fp1", goalVersion: "gv1" },
+ },
+ ],
+ "gv1",
+ );
+ expect(knownPages.get(canonicalizeUrl("https://example.com/a"))).toEqual({
+ fingerprint: "fp1",
+ goalVersion: "gv1",
+ });
+ });
+
+ it("loads fingerprints from any goalVersion (the runner gate decides freshness)", () => {
+ const { knownPages } = reconstructKnownState(
+ [
+ {
+ url: "https://a.com",
+ metadata: { fingerprint: "old", goalVersion: "gvOLD" },
+ },
+ ],
+ "gvNEW",
+ );
+ expect(knownPages.get(canonicalizeUrl("https://a.com"))?.goalVersion).toBe(
+ "gvOLD",
+ );
+ });
+
+ it("only includes events from the current goalVersion (goal change starts clean)", () => {
+ const { knownEvents } = reconstructKnownState(
+ [
+ {
+ url: "https://a.com",
+ metadata: {
+ fingerprint: "f1",
+ goalVersion: "gv1",
+ eventKey: "e1",
+ eventLabel: "Event One",
+ },
+ },
+ {
+ url: "https://b.com",
+ metadata: {
+ fingerprint: "f2",
+ goalVersion: "gvOLD",
+ eventKey: "eOld",
+ eventLabel: "Stale",
+ },
+ },
+ ],
+ "gv1",
+ );
+ expect(knownEvents).toEqual([{ key: "e1", label: "Event One" }]);
+ });
+
+ it("dedups repeated event keys and falls back label→key", () => {
+ const { knownEvents } = reconstructKnownState(
+ [
+ {
+ url: "https://a.com",
+ metadata: { fingerprint: "f1", goalVersion: "gv1", eventKey: "e1" },
+ },
+ {
+ url: "https://b.com",
+ metadata: {
+ fingerprint: "f2",
+ goalVersion: "gv1",
+ eventKey: "e1",
+ eventLabel: "Later",
+ },
+ },
+ ],
+ "gv1",
+ );
+ expect(knownEvents).toEqual([{ key: "e1", label: "e1" }]);
+ });
+
+ it("ignores pages with no usable metadata", () => {
+ const { knownPages, knownEvents } = reconstructKnownState(
+ [
+ { url: "https://a.com", metadata: null },
+ { url: "https://b.com", metadata: {} },
+ ],
+ "gv1",
+ );
+ expect(knownPages.size).toBe(0);
+ expect(knownEvents).toEqual([]);
+ });
+});
diff --git a/apps/api/src/services/monitoring/search/persist.ts b/apps/api/src/services/monitoring/search/persist.ts
new file mode 100644
index 000000000..582cb5ff6
--- /dev/null
+++ b/apps/api/src/services/monitoring/search/persist.ts
@@ -0,0 +1,57 @@
+import { canonicalizeUrl } from "./dedupe";
+import type { KnownPage } from "./run";
+import type { KnownEvent } from "./llm";
+
+// Search verdict status → the monitor page-status enum the reconciler counts.
+// alert = a genuinely-new meaningful match (new); seen/watching/ignored = no new alert (same);
+// a failed scrape = error. This keeps search runs visible in the same new/same/error tallies.
+export function searchStatusToPageStatus(
+ status: string,
+): "same" | "new" | "changed" | "removed" | "error" {
+ if (status === "alert") return "new";
+ if (status === "skipped") return "error";
+ return "same";
+}
+
+// A scraped search result ran a json verdict extraction; already-seen results skip the scrape.
+// The runner maps these flags onto the canonical credit estimator (no new constants here).
+export function searchPageWasScraped(status: string): boolean {
+ return status === "alert" || status === "watching" || status === "ignored";
+}
+
+type PriorPage = { url: string; metadata: unknown | null };
+
+// Rebuild the per-URL dedup memory and the event index from prior monitor_pages of this target.
+// Stale-goal fingerprints are still loaded (the runner's goalVersion gate decides freshness),
+// but the event index only carries events from the CURRENT goalVersion so a goal change starts clean.
+export function reconstructKnownState(
+ priorPages: PriorPage[],
+ goalVersion: string,
+): { knownPages: Map<string, KnownPage>; knownEvents: KnownEvent[] } {
+ const knownPages = new Map<string, KnownPage>();
+ const eventsByKey = new Map<string, KnownEvent>();
+ for (const page of priorPages) {
+ const meta = (page.metadata ?? {}) as Record<string, unknown>;
+ if (
+ typeof meta.fingerprint === "string" &&
+ typeof meta.goalVersion === "string"
+ ) {
+ knownPages.set(canonicalizeUrl(page.url), {
+ fingerprint: meta.fingerprint,
+ goalVersion: meta.goalVersion,
+ });
+ }
+ if (
+ meta.goalVersion === goalVersion &&
+ typeof meta.eventKey === "string" &&
+ !eventsByKey.has(meta.eventKey)
+ ) {
+ eventsByKey.set(meta.eventKey, {
+ key: meta.eventKey,
+ label:
+ typeof meta.eventLabel === "string" ? meta.eventLabel : meta.eventKey,
+ });
+ }
+ }
+ return { knownPages, knownEvents: [...eventsByKey.values()] };
+}
diff --git a/apps/api/src/services/monitoring/search/run.test.ts b/apps/api/src/services/monitoring/search/run.test.ts
new file mode 100644
index 000000000..f1bb2dfaa
--- /dev/null
+++ b/apps/api/src/services/monitoring/search/run.test.ts
@@ -0,0 +1,282 @@
+import type { Logger } from "winston";
+import type { SearchVerdict } from "./judge";
+import type { EventResolution } from "./llm";
+import { canonicalizeUrl, stableSerpFingerprint } from "./dedupe";
+
+// --- Mock the external boundaries; the orchestration logic in run.ts runs for real. ---
+const searchMock = jest.fn();
+const scrapeURLMock = jest.fn();
+const resolveEventMock = jest.fn();
+const summarizeRunMock = jest.fn();
+
+jest.mock("uuid", () => ({ v7: () => "00000000-0000-7000-8000-000000000000" }));
+jest.mock("../../../search", () => ({
+ search: (...a: unknown[]) => searchMock(...a),
+}));
+jest.mock("../../../scraper/scrapeURL", () => ({
+ scrapeURL: (...a: unknown[]) => scrapeURLMock(...a),
+}));
+jest.mock("./llm", () => ({
+ resolveEvent: (...a: unknown[]) => resolveEventMock(...a),
+ summarizeRun: (...a: unknown[]) => summarizeRunMock(...a),
+}));
+
+import { runSearchTarget, type KnownPage } from "./run";
+
+const logger = {
+ warn: jest.fn(),
+ info: jest.fn(),
+ error: jest.fn(),
+} as unknown as Logger;
+
+const verdict = (over: Partial<SearchVerdict> = {}): SearchVerdict => ({
+ relevant: true,
+ alertAction: "alert",
+ freshness: "fresh",
+ sourceQuality: "authoritative",
+ concept: "openai-ipo",
+ rationale: "filing confirmed",
+ ...over,
+});
+
+const okScrape = (v: SearchVerdict) => ({
+ success: true,
+ document: { json: v },
+});
+
+function setSearchResults(
+ results: Array<{ url: string; title: string; description: string }>,
+) {
+ searchMock.mockResolvedValue(results);
+}
+
+// scrapeURL returns a verdict chosen by URL.
+function setVerdictsByUrl(map: Record<string, SearchVerdict>) {
+ scrapeURLMock.mockImplementation((_id: string, url: string) => {
+ const v = map[url];
+ if (!v) return Promise.resolve({ success: false });
+ return Promise.resolve(okScrape(v));
+ });
+}
+
+const baseTarget = {
+ id: "t1",
+ queries: ["openai ipo"],
+ searchWindow: "24h",
+ alertMode: "first_match" as const,
+ maxResults: 10,
+};
+
+const baseMonitor = {
+ id: "m1",
+ teamId: "team1",
+ goal: "Alert when OpenAI files for IPO",
+ subject: "OpenAI",
+};
+
+function run(
+ over: {
+ target?: Partial<typeof baseTarget>;
+ knownPages?: Map<string, KnownPage>;
+ knownEvents?: EventResolution[] extends never
+ ? never
+ : { key: string; label: string }[];
+ goalVersion?: string;
+ alertMode?: "first_match" | "every_new_result";
+ } = {},
+) {
+ return runSearchTarget({
+ monitor: baseMonitor,
+ target: {
+ ...baseTarget,
+ ...over.target,
+ alertMode: over.alertMode ?? baseTarget.alertMode,
+ },
+ goalVersion: over.goalVersion ?? "gv1",
+ knownPages: over.knownPages ?? new Map(),
+ knownEvents: over.knownEvents ?? [],
+ zeroDataRetention: false,
+ logger,
+ });
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ resolveEventMock.mockResolvedValue({
+ matchedKey: null,
+ isNew: true,
+ label: "OpenAI IPO",
+ reason: "",
+ });
+ summarizeRunMock.mockResolvedValue({
+ label: "meaningful",
+ summary: "OpenAI filed for IPO.",
+ });
+});
+
+describe("runSearchTarget orchestration", () => {
+ it("alerts on a new, relevant, fresh result", async () => {
+ setSearchResults([
+ {
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ description: "filing",
+ },
+ ]);
+ setVerdictsByUrl({ "https://sec.gov/openai": verdict() });
+
+ const out = await run();
+
+ expect(out.matches).toBe(1);
+ expect(out.sources[0].status).toBe("alert");
+ expect(out.sources[0].eventKey).toBeTruthy();
+ expect(out.pageUpserts[0].status).toBe("alert");
+ expect(out.summary).toBe("OpenAI filed for IPO.");
+ expect(scrapeURLMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("skips scrape/judge for an already-seen unchanged page (same goalVersion)", async () => {
+ setSearchResults([
+ {
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ description: "filing",
+ },
+ ]);
+ // Precompute the fingerprint the same way run.ts does, via the real dedupe module.
+ const canonical = canonicalizeUrl("https://sec.gov/openai");
+ const fingerprint = stableSerpFingerprint({
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ snippet: "filing",
+ });
+ const knownPages = new Map<string, KnownPage>([
+ [canonical, { fingerprint, goalVersion: "gv1" }],
+ ]);
+
+ const out = await run({ knownPages });
+
+ expect(out.sources[0].status).toBe("already_seen");
+ expect(scrapeURLMock).not.toHaveBeenCalled();
+ expect(out.matches).toBe(0);
+ });
+
+ it("re-evaluates a known page when the goalVersion changed (stale memory)", async () => {
+ setSearchResults([
+ {
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ description: "filing",
+ },
+ ]);
+ setVerdictsByUrl({ "https://sec.gov/openai": verdict() });
+ const canonical = canonicalizeUrl("https://sec.gov/openai");
+ const fingerprint = stableSerpFingerprint({
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ snippet: "filing",
+ });
+ // Known under the OLD goal version → must be treated as new under gv2.
+ const knownPages = new Map<string, KnownPage>([
+ [canonical, { fingerprint, goalVersion: "gv1" }],
+ ]);
+
+ const out = await run({ knownPages, goalVersion: "gv2" });
+
+ expect(scrapeURLMock).toHaveBeenCalledTimes(1);
+ expect(out.sources[0].status).toBe("alert");
+ });
+
+ it("first_match: suppresses a second result resolving to the same event", async () => {
+ setSearchResults([
+ {
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ description: "filing",
+ },
+ {
+ url: "https://nytimes.com/openai-ipo",
+ title: "OpenAI to IPO",
+ description: "report",
+ },
+ ]);
+ setVerdictsByUrl({
+ "https://sec.gov/openai": verdict(),
+ "https://nytimes.com/openai-ipo": verdict({ concept: "openai-ipo" }),
+ });
+ // First result creates the event; second resolves to the same key.
+ resolveEventMock
+ .mockResolvedValueOnce({
+ matchedKey: null,
+ isNew: true,
+ label: "OpenAI IPO",
+ reason: "",
+ })
+ .mockResolvedValueOnce({
+ matchedKey: undefined,
+ isNew: false,
+ label: "OpenAI IPO",
+ reason: "same",
+ });
+
+ const out = await run({ alertMode: "first_match" });
+
+ const statuses = out.sources.map(s => s.status);
+ expect(statuses).toContain("alert");
+ expect(statuses).toContain("already_seen");
+ expect(out.matches).toBe(1);
+ });
+
+ it("downgrades a stale-but-alert verdict to watch (no notify)", async () => {
+ setSearchResults([
+ {
+ url: "https://old.com/openai",
+ title: "OpenAI old news",
+ description: "2019",
+ },
+ ]);
+ setVerdictsByUrl({
+ "https://old.com/openai": verdict({ freshness: "stale" }),
+ });
+
+ const out = await run();
+
+ expect(out.sources[0].status).toBe("watching");
+ expect(out.matches).toBe(0);
+ expect(resolveEventMock).not.toHaveBeenCalled();
+ });
+
+ it("marks a result skipped when the scrape fails", async () => {
+ setSearchResults([
+ { url: "https://dead.com/x", title: "x", description: "y" },
+ ]);
+ scrapeURLMock.mockResolvedValue({ success: false });
+
+ const out = await run();
+
+ expect(out.sources[0].status).toBe("skipped");
+ expect(out.skipped).toBe(1);
+ expect(out.matches).toBe(0);
+ });
+
+ it("dedups the same canonical URL returned by two queries", async () => {
+ setSearchResults([
+ {
+ url: "https://sec.gov/openai",
+ title: "OpenAI S-1",
+ description: "filing",
+ },
+ {
+ url: "https://www.SEC.gov/openai/",
+ title: "OpenAI S-1",
+ description: "filing",
+ },
+ ]);
+ setVerdictsByUrl({ "https://sec.gov/openai": verdict() });
+
+ const out = await run();
+
+ expect(out.resultCount).toBe(1);
+ expect(scrapeURLMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/api/src/services/monitoring/search/run.ts b/apps/api/src/services/monitoring/search/run.ts
index bdf1d1d8b..94f031300 100644
--- a/apps/api/src/services/monitoring/search/run.ts
+++ b/apps/api/src/services/monitoring/search/run.ts
@@ -31,7 +31,7 @@ function slugifyEvent(label: string): string {
);
}
-export type SearchTargetInput = {
+type SearchTargetInput = {
id: string;
queries: string[];
searchWindow: string;
@@ -47,7 +47,7 @@ export type KnownPage = {
goalVersion: string;
};
-export type SearchSource = {
+type SearchSource = {
url: string;
title: string;
status: "alert" | "already_seen" | "watching" | "ignored" | "skipped";
@@ -59,7 +59,7 @@ export type SearchSource = {
rationale?: string;
};
-export type SearchTargetRunResult = {
+type SearchTargetRunResult = {
targetId: string;
type: "search";
resultCount: number;
@@ -126,7 +126,11 @@ export async function runSearchTarget(params: {
const canonical = canonicalizeUrl(r.url);
if (seenThisRun.has(canonical)) continue;
seenThisRun.add(canonical);
- candidates.push({ url: r.url, title: r.title, description: r.description });
+ candidates.push({
+ url: r.url,
+ title: r.title,
+ description: r.description,
+ });
}
}
resultCount = candidates.length;
@@ -141,7 +145,8 @@ export async function runSearchTarget(params: {
});
const known = knownPages.get(canonical);
// P0(#1): a page judged under a different goal is stale — treat it as new.
- const knownCurrent = known && known.goalVersion === goalVersion ? known : undefined;
+ const knownCurrent =
+ known && known.goalVersion === goalVersion ? known : undefined;
const isNewOrChanged =
!knownCurrent || knownCurrent.fingerprint !== fingerprint;
@@ -212,13 +217,33 @@ export async function runSearchTarget(params: {
};
if (decision === "ignore") {
- sources.push({ url: c.url, title: c.title, status: "ignored", ...baseMeta });
- pageUpserts.push({ url: canonical, urlHash: hashMonitorUrl(canonical), status: "ignored", metadata: baseMeta });
+ sources.push({
+ url: c.url,
+ title: c.title,
+ status: "ignored",
+ ...baseMeta,
+ });
+ pageUpserts.push({
+ url: canonical,
+ urlHash: hashMonitorUrl(canonical),
+ status: "ignored",
+ metadata: baseMeta,
+ });
continue;
}
if (decision === "watch") {
- sources.push({ url: c.url, title: c.title, status: "watching", ...baseMeta });
- pageUpserts.push({ url: canonical, urlHash: hashMonitorUrl(canonical), status: "watching", metadata: baseMeta });
+ sources.push({
+ url: c.url,
+ title: c.title,
+ status: "watching",
+ ...baseMeta,
+ });
+ pageUpserts.push({
+ url: canonical,
+ urlHash: hashMonitorUrl(canonical),
+ status: "watching",
+ metadata: baseMeta,
+ });
continue;
}
@@ -231,7 +256,9 @@ export async function runSearchTarget(params: {
});
const eventKey =
resolution.matchedKey ??
- (resolution.label ? slugifyEvent(resolution.label) : slugifyEvent(verdict.concept));
+ (resolution.label
+ ? slugifyEvent(resolution.label)
+ : slugifyEvent(verdict.concept));
const eventLabel =
events.find(e => e.key === eventKey)?.label ||
resolution.label ||
@@ -242,8 +269,19 @@ export async function runSearchTarget(params: {
const eventMeta = { ...baseMeta, eventKey, eventLabel };
if (alreadySatisfied) {
- sources.push({ url: c.url, title: c.title, status: "already_seen", eventKey, ...baseMeta });
- pageUpserts.push({ url: canonical, urlHash: hashMonitorUrl(canonical), status: "already_seen", metadata: eventMeta });
+ sources.push({
+ url: c.url,
+ title: c.title,
+ status: "already_seen",
+ eventKey,
+ ...baseMeta,
+ });
+ pageUpserts.push({
+ url: canonical,
+ urlHash: hashMonitorUrl(canonical),
+ status: "already_seen",
+ metadata: eventMeta,
+ });
continue;
}
@@ -253,8 +291,19 @@ export async function runSearchTarget(params: {
if (!events.some(e => e.key === eventKey)) {
events.push({ key: eventKey, label: eventLabel });
}
- sources.push({ url: c.url, title: c.title, status: "alert", eventKey, ...baseMeta });
- pageUpserts.push({ url: canonical, urlHash: hashMonitorUrl(canonical), status: "alert", metadata: eventMeta });
+ sources.push({
+ url: c.url,
+ title: c.title,
+ status: "alert",
+ eventKey,
+ ...baseMeta,
+ });
+ pageUpserts.push({
+ url: canonical,
+ urlHash: hashMonitorUrl(canonical),
+ status: "alert",
+ metadata: eventMeta,
+ });
}
const meaningful = sources.filter(
@@ -268,7 +317,11 @@ export async function runSearchTarget(params: {
subject,
evidence: sources
.filter(s => s.status === "alert")
- .map(s => ({ title: s.title, url: s.url, rationale: s.rationale ?? "" })),
+ .map(s => ({
+ title: s.title,
+ url: s.url,
+ rationale: s.rationale ?? "",
+ })),
});
summary = out.summary;
}