Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M5-001): insight module (AI engine): services + insights queue + 3 cron fragments into core

ralph4fdbb04b0492
diff --git a/apps/worker/src/jobs/cron.insight-cleanup.ts b/apps/worker/src/jobs/cron.insight-cleanup.ts
index 4dc1fad7d..6e45c983a 100644
--- a/apps/worker/src/jobs/cron.insight-cleanup.ts
+++ b/apps/worker/src/jobs/cron.insight-cleanup.ts
@@ -1,90 +1,13 @@
-import { db } from '@openpanel/db';
+// Dissolved into @openpanel/core's insight module (M5-001): the retention
+// rules moved to
+// packages/core/src/modules/insight/insight.service.ts#cleanupStaleInsights.
+// This file stays (DELEGATE PATTERN) — it is the `insightCleanup` case of
+// `cron.ts`'s dispatcher.
+import { cleanupStaleInsights } from '@openpanel/core';
import { logger as baseLogger } from '@/utils/logger';
const logger = baseLogger.child({ job: 'insight-cleanup' });
-const RETENTION_DAYS = Number.parseInt(
- process.env.INSIGHTS_RETENTION_DAYS || '90',
- 10,
-);
-
-// Delete in chunks so the first (large) purge never holds a single long
-// transaction / lock on these tables.
-const BATCH_SIZE = 5000;
-
-async function deleteInBatches(
- label: string,
- runBatch: () => Promise<number>,
-): Promise<number> {
- let total = 0;
- // Cap iterations as a runaway backstop (BATCH_SIZE * 2000 = 10M rows).
- for (let i = 0; i < 2000; i++) {
- const deleted = await runBatch();
- total += deleted;
- if (deleted < BATCH_SIZE) break;
- }
- if (total > 0) {
- logger.info({ table: label, deleted: total }, 'Deleted stale rows');
- }
- return total;
-}
-
-/**
- * Keeps the insights tables bounded. They otherwise grow forever:
- * `insight_events` is append-only (one row per detection/material change),
- * and `project_insights` keeps a row per dimension ever seen.
- *
- * Retention rules (default 90 days, override via INSIGHTS_RETENTION_DAYS):
- * - project_insights `suppressed`: deleted unconditionally. The engine no
- * longer creates suppressed rows (below-top-N insights are deleted inline);
- * any remaining ones are legacy leftovers nothing reads or revives.
- * - project_insights `closed`: dropped once not seen since the cutoff.
- * `active` rows are the live dataset and are never touched.
- * - insight_events: drop rows older than the cutoff. Only the latest 20 per
- * insight are ever read (the AI explain tool), so old events are dead
- * weight. Deleting the parent insight above already cascades its events;
- * this sweep also trims old history off still-active insights.
- */
export async function insightCleanupCronJob() {
- const cutoff = new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1000);
-
- const suppressed = await deleteInBatches(
- 'project_insights:suppressed',
- () => db.$executeRaw`
- DELETE FROM "project_insights"
- WHERE "id" IN (
- SELECT "id" FROM "project_insights"
- WHERE "state" = 'suppressed'
- LIMIT ${BATCH_SIZE}
- )`,
- );
-
- const closed = await deleteInBatches(
- 'project_insights:closed',
- () => db.$executeRaw`
- DELETE FROM "project_insights"
- WHERE "id" IN (
- SELECT "id" FROM "project_insights"
- WHERE "state" = 'closed'
- AND "lastSeenAt" < ${cutoff}
- LIMIT ${BATCH_SIZE}
- )`,
- );
- const insights = suppressed + closed;
-
- const events = await deleteInBatches(
- 'insight_events',
- () => db.$executeRaw`
- DELETE FROM "insight_events"
- WHERE "id" IN (
- SELECT "id" FROM "insight_events"
- WHERE "createdAt" < ${cutoff}
- LIMIT ${BATCH_SIZE}
- )`,
- );
-
- logger.info(
- { retentionDays: RETENTION_DAYS, insights, events },
- 'Insight cleanup complete',
- );
+ await cleanupStaleInsights(logger);
}
diff --git a/apps/worker/src/jobs/cron.weekly-digest.ts b/apps/worker/src/jobs/cron.weekly-digest.ts
index b214c479e..6c5965562 100644
--- a/apps/worker/src/jobs/cron.weekly-digest.ts
+++ b/apps/worker/src/jobs/cron.weekly-digest.ts
@@ -1,251 +1,16 @@
-import { generateWeeklyNarrative } from '@openpanel/core';
-import { db, getAnalyticsOverviewCore } from '@openpanel/db';
-import { type EmailData, sendEmail } from '@openpanel/email';
+// Dissolved into @openpanel/core's insight module (M5-001): the digest
+// assembly, narrative call and send loop moved to
+// packages/core/src/modules/insight/insight.service.ts. This file stays
+// (DELEGATE PATTERN) — it is the `weeklyDigest` case of `cron.ts`'s
+// dispatcher, and `previewWeeklyDigestForProject` backs boot-debug.ts's
+// single-project preview route.
+import { previewWeeklyDigest, sendWeeklyDigests } from '@openpanel/core';
import { logger as baseLogger } from '@/utils/logger';
const logger = baseLogger.child({ job: 'weekly-digest' });
-const DAY_MS = 24 * 60 * 60 * 1000;
-// Keep this low: the digest is our main "value without logging in" touchpoint,
-// and the old 5000 gate excluded customers on smaller plans — exactly the ones
-// who benefit most from the reminder. Zero-visitor weeks are still skipped per
-// send, so quiet projects don't get empty emails.
-const MIN_EVENTS = 100;
-const MAX_INSIGHTS = 5;
-
-type DigestData = EmailData<'weekly-digest'>;
-interface ProjectRow {
- id: string;
- name: string;
- organizationId: string;
-}
-
-function formatCount(n: number): string {
- return Math.round(n).toLocaleString();
-}
-
-function pctDelta(
- current: number,
- previous: number
-): { delta?: string; direction: 'up' | 'down' | 'flat' } {
- if (previous <= 0) {
- return { direction: 'flat' };
- }
- const pct = ((current - previous) / previous) * 100;
- const direction = pct > 0.5 ? 'up' : pct < -0.5 ? 'down' : 'flat';
- const sign = pct >= 0 ? '+' : '';
- return { delta: `${sign}${pct.toFixed(0)}%`, direction };
-}
-
-function ppDelta(
- current: number,
- previous: number
-): { delta?: string; direction: 'up' | 'down' | 'flat' } {
- const diff = current - previous;
- const direction = diff > 0.5 ? 'up' : diff < -0.5 ? 'down' : 'flat';
- const sign = diff >= 0 ? '+' : '';
- return { delta: `${sign}${diff.toFixed(0)}pp`, direction };
-}
-
-function formatRange(startMs: number, endMs: number): string {
- const opts: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' };
- const start = new Date(startMs).toLocaleDateString('en-US', opts);
- const end = new Date(endMs).toLocaleDateString('en-US', {
- ...opts,
- year: 'numeric',
- });
- return `${start} – ${end}`;
-}
-
-/**
- * Assemble the digest payload for one project (no sending). Returns `skipped`
- * with a reason when there's nothing worth mailing — unless `force` is set.
- */
-async function buildDigestData(
- project: ProjectRow,
- opts: { force?: boolean } = {}
-): Promise<{ skipped?: string; data?: DigestData }> {
- const now = Date.now();
- const curStart = now - 7 * DAY_MS;
- const prevStart = now - 14 * DAY_MS;
- const iso = (ms: number) => new Date(ms).toISOString();
-
- const [cur, prev] = await Promise.all([
- getAnalyticsOverviewCore({
- projectId: project.id,
- startDate: iso(curStart),
- endDate: iso(now),
- interval: 'day',
- }),
- getAnalyticsOverviewCore({
- projectId: project.id,
- startDate: iso(prevStart),
- endDate: iso(curStart),
- interval: 'day',
- }),
- ]);
-
- const c = cur.summary;
- const p = prev.summary;
-
- if (!opts.force && c.unique_visitors === 0) {
- return { skipped: 'no visitors in the last 7 days' };
- }
-
- const stats = [
- {
- label: 'visitors',
- value: formatCount(c.unique_visitors),
- ...pctDelta(c.unique_visitors, p.unique_visitors),
- },
- {
- label: 'sessions',
- value: formatCount(c.total_sessions),
- ...pctDelta(c.total_sessions, p.total_sessions),
- },
- {
- label: 'pageviews',
- value: formatCount(c.total_screen_views),
- ...pctDelta(c.total_screen_views, p.total_screen_views),
- },
- {
- label: 'bounce rate',
- value: `${Math.round(c.bounce_rate)}%`,
- ...ppDelta(c.bounce_rate, p.bounce_rate),
- },
- ];
-
- const insightRows = await db.projectInsight.findMany({
- where: {
- projectId: project.id,
- state: 'active',
- emailWorthy: true,
- windowKind: { in: ['rolling_7d'] },
- },
- orderBy: [
- { relevanceScore: { sort: 'desc', nulls: 'last' } },
- { impactScore: 'desc' },
- ],
- take: MAX_INSIGHTS,
- select: { title: true, aiSummary: true, summary: true },
- });
-
- const insights = insightRows.map((i) => ({
- title: i.aiSummary ?? i.title,
- summary: i.summary ?? undefined,
- }));
-
- const dateRange = formatRange(curStart, now);
-
- let narrative = '';
- try {
- narrative = await generateWeeklyNarrative({
- projectName: project.name,
- dateRange,
- stats: [
- {
- label: 'visitors',
- current: c.unique_visitors,
- previous: p.unique_visitors,
- },
- {
- label: 'sessions',
- current: c.total_sessions,
- previous: p.total_sessions,
- },
- {
- label: 'pageviews',
- current: c.total_screen_views,
- previous: p.total_screen_views,
- },
- {
- label: 'bounce rate',
- current: c.bounce_rate,
- previous: p.bounce_rate,
- unit: '%',
- },
- ],
- insights,
- });
- } catch (err) {
- logger.warn({ err, projectId: project.id }, 'Narrative generation failed');
- }
-
- const dashboardUrl = `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${project.organizationId}/${project.id}`;
-
- return {
- data: {
- projectName: project.name,
- dashboardUrl,
- dateRange,
- narrative: narrative || undefined,
- stats,
- insights,
- },
- };
-}
-
-async function recipientsForOrg(organizationId: string): Promise<string[]> {
- const members = await db.member.findMany({
- where: { organizationId },
- select: { email: true },
- });
- return [...new Set(members.map((m) => m.email).filter(Boolean))];
-}
-
-/**
- * Weekly digest: per active project, week-over-week stats + the AI's
- * email-worthy insights + a generated narrative, mailed to org members.
- * `sendEmail` skips anyone unsubscribed from the `weekly_digest` category.
- */
export async function weeklyDigestCronJob() {
- // Prefilter on the raw status column (computed fields can't be used in
- // `where`), then refine with the canonical subscription state below.
- const projects = await db.project.findMany({
- where: {
- deleteAt: null,
- eventsCount: { gt: MIN_EVENTS },
- organization: { subscriptionStatus: { in: ['active', 'trialing'] } },
- },
- select: {
- id: true,
- name: true,
- organizationId: true,
- organization: { select: { subscriptionState: true } },
- },
- });
-
- let sent = 0;
- for (const project of projects) {
- try {
- // Single source of truth (`getSubscriptionState`): mail paid orgs and
- // live trials (the digest nudges trial→paid conversion), but skip
- // `trial_expired` — a 30-day trial that lapsed weeks ago is an abandoned
- // org we shouldn't keep emailing. `trialing` already implies the trial
- // end date is still in the future.
- const state = project.organization.subscriptionState;
- if (state !== 'active' && state !== 'trialing') {
- continue;
- }
-
- const { skipped, data } = await buildDigestData(project);
- if (skipped || !data) {
- continue;
- }
- const emails = await recipientsForOrg(project.organizationId);
- if (emails.length === 0) {
- continue;
- }
- for (const to of emails) {
- await sendEmail('weekly-digest', { to, data });
- }
- sent++;
- } catch (err) {
- logger.error({ err, projectId: project.id }, 'Weekly digest failed');
- }
- }
-
- logger.info({ projects: projects.length, sent }, 'Weekly digest complete');
+ await sendWeeklyDigests(logger);
}
/**
@@ -257,31 +22,6 @@ export async function weeklyDigestCronJob() {
export async function previewWeeklyDigestForProject(
projectId: string,
opts: { to?: string; force?: boolean } = {}
-): Promise<{
- sent: boolean;
- to?: string;
- skipped?: string;
- data?: DigestData;
-}> {
- const project = await db.project.findUnique({
- where: { id: projectId },
- select: { id: true, name: true, organizationId: true },
- });
- if (!project) {
- return { sent: false, skipped: 'project not found' };
- }
-
- const { skipped, data } = await buildDigestData(project, {
- force: opts.force,
- });
- if (skipped || !data) {
- return { sent: false, skipped, data };
- }
-
- if (opts.to) {
- await sendEmail('weekly-digest', { to: opts.to, data });
- return { sent: true, to: opts.to, data };
- }
-
- return { sent: false, data };
+) {
+ return previewWeeklyDigest(projectId, opts);
}
diff --git a/apps/worker/src/jobs/insights-enrich.ts b/apps/worker/src/jobs/insights-enrich.ts
deleted file mode 100644
index ad87a4d4b..000000000
--- a/apps/worker/src/jobs/insights-enrich.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import {
- ENRICH_VERSION,
- enrichInsights,
- type InsightToEnrich,
-} from '@openpanel/core';
-import { db } from '@openpanel/db';
-import { logger as baseLogger } from '@/utils/logger';
-
-const logger = baseLogger.child({ job: 'insights-enrich' });
-
-// Modest batches keep the prompt small and the id-mapping reliable. At Tier 3
-// limits (4M TPM / 5k RPM) even the first-run backlog clears comfortably.
-const BATCH_SIZE = 25;
-
-function clamp01(n: number): number {
- if (Number.isNaN(n)) {
- return 0;
- }
- return Math.max(0, Math.min(1, n));
-}
-
-/**
- * Tier-1 enrichment for one project's active insights. Runs after the insight
- * engine finishes a project, scoring anything new, materially-changed, or
- * enriched under an older prompt version. Failures are logged and skipped — a
- * bad enrichment batch must never fail the insights job itself.
- */
-export async function enrichProjectInsights(projectId: string): Promise<void> {
- const stale = await db.projectInsight.findMany({
- where: {
- projectId,
- state: 'active',
- OR: [
- { enrichedAt: null },
- { enrichVersion: null },
- { enrichVersion: { lt: ENRICH_VERSION } },
- ],
- },
- select: {
- id: true,
- moduleKey: true,
- dimensionKey: true,
- windowKind: true,
- title: true,
- summary: true,
- displayName: true,
- direction: true,
- impactScore: true,
- severityBand: true,
- payload: true,
- },
- });
-
- if (stale.length === 0) {
- return;
- }
-
- let enriched = 0;
- for (let i = 0; i < stale.length; i += BATCH_SIZE) {
- const batch = stale.slice(i, i + BATCH_SIZE);
- const input: InsightToEnrich[] = batch.map((r) => ({
- id: r.id,
- moduleKey: r.moduleKey,
- dimensionKey: r.dimensionKey,
- windowKind: r.windowKind,
- title: r.title,
- summary: r.summary,
- displayName: r.displayName,
- direction: r.direction,
- impactScore: r.impactScore,
- severityBand: r.severityBand,
- payload: r.payload,
- }));
-
- let results: Awaited<ReturnType<typeof enrichInsights>>;
- try {
- results = await enrichInsights(input);
- } catch (err) {
- logger.error(
- { err, projectId, batchSize: batch.length },
- 'Enrichment call failed; skipping batch'
- );
- continue;
- }
-
- const byId = new Map(results.map((r) => [r.id, r]));
- for (const row of batch) {
- const e = byId.get(row.id);
- if (!e) {
- continue;
- }
- await db.projectInsight.update({
- where: { id: row.id },
- data: {
- relevanceScore: clamp01(e.relevanceScore),
- aiSummary: e.summary,
- aiCategory: e.category,
- emailWorthy: e.emailWorthy,
- referenceWorthy: e.referenceWorthy,
- enrichedAt: new Date(),
- enrichVersion: ENRICH_VERSION,
- },
- });
- enriched++;
- }
- }
-
- logger.info(
- { projectId, candidates: stale.length, enriched },
- 'Insight enrichment complete'
- );
-}
diff --git a/apps/worker/src/jobs/insights.ts b/apps/worker/src/jobs/insights.ts
index 66de5f28f..23d0739c7 100644
--- a/apps/worker/src/jobs/insights.ts
+++ b/apps/worker/src/jobs/insights.ts
@@ -1,82 +1,44 @@
-import { ch } from '@openpanel/db/src/clickhouse/client';
+// Dissolved into @openpanel/core's insight module (M5-001): the engine run +
+// tier-1 AI enrichment moved to
+// packages/core/src/modules/insight/insight.service.ts. This file stays
+// (DELEGATE PATTERN) — it is the BullMQ job body V1's worker registers
+// (boot-workers.ts, boot-debug.ts) and the `cron.ts` dispatcher's
+// `insightsDaily` case, both thin wrappers around the core functions.
import {
- createEngine,
- devicesModule,
- entryPagesModule,
- geoModule,
- insightStore,
- pageTrendsModule,
- referrersModule,
-} from '@openpanel/db/src/services/insights';
+ listDailyInsightCandidates,
+ runProjectInsights,
+} from '@openpanel/core';
import type {
CronQueuePayload,
InsightsQueuePayloadProject,
} from '@openpanel/queue';
import { insightsQueue } from '@openpanel/queue';
import type { Job } from 'bullmq';
-import { enrichProjectInsights } from './insights-enrich';
-import { logger } from '@/utils/logger';
+import { logger as baseLogger } from '@/utils/logger';
-const defaultEngineConfig = {
- keepTopNPerModuleWindow: 20,
- closeStaleAfterDays: 7,
- dimensionBatchSize: 50,
- globalThresholds: {
- minTotal: 200,
- minAbsDelta: 80,
- minPct: 0.15,
- },
-};
+const logger = baseLogger.child({ job: 'insights' });
-export async function insightsDailyJob(job: Job<CronQueuePayload>) {
- const projectIds = await insightStore.listProjectIdsForCadence('daily');
+export async function insightsDailyJob(_job: Job<CronQueuePayload>) {
const date = new Date().toISOString().slice(0, 10);
+ const candidates = await listDailyInsightCandidates(date);
- for (const projectId of projectIds) {
+ for (const { projectId, date: candidateDate } of candidates) {
await insightsQueue.add(
'insightsProject',
{
type: 'insightsProject',
- payload: { projectId, date },
+ payload: { projectId, date: candidateDate },
},
{
- jobId: `daily:${date}:${projectId}`, // idempotent
- },
+ jobId: `daily:${candidateDate}:${projectId}`, // idempotent
+ }
);
}
}
export async function insightsProjectJob(
- job: Job<InsightsQueuePayloadProject>,
+ job: Job<InsightsQueuePayloadProject>
) {
const { projectId, date } = job.data.payload;
- const engine = createEngine({
- store: insightStore,
- modules: [
- referrersModule,
- entryPagesModule,
- pageTrendsModule,
- geoModule,
- devicesModule,
- ],
- db: ch,
- config: defaultEngineConfig,
- });
-
- const projectCreatedAt = await insightStore.getProjectCreatedAt(projectId);
-
- await engine.runProject({
- projectId,
- cadence: 'daily',
- now: new Date(date),
- projectCreatedAt,
- });
-
- // Tier-1 AI enrichment of this project's active insights. Isolated so a
- // provider outage or rate-limit never fails the insights computation.
- try {
- await enrichProjectInsights(projectId);
- } catch (err) {
- logger.error({ err, projectId }, 'Insight enrichment failed');
- }
+ await runProjectInsights({ projectId, date, logger });
}
diff --git a/packages/core/package.json b/packages/core/package.json
index 306b6fd7a..2c24357f1 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -28,7 +28,10 @@
"@maxmind/geoip2-node": "^6.1.0",
"@node-rs/argon2": "^2.0.2",
"@openpanel/common": "workspace:*",
+ "@openpanel/constants": "workspace:*",
+ "@openpanel/db": "workspace:*",
"@openpanel/email": "workspace:*",
+ "@openpanel/redis": "workspace:*",
"@openpanel/validation": "workspace:*",
"@oslojs/crypto": "^1.0.1",
"@oslojs/encoding": "^1.1.0",
@@ -52,7 +55,7 @@
"zod": "catalog:"
},
"devDependencies": {
- "@openpanel/db": "workspace:*",
+ "@clickhouse/client": "^1.18.5",
"@openpanel/tsconfig": "workspace:*",
"@types/qrcode": "^1.5.6",
"bun-types": "1.4.0",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8b84bb5fd..dd4992e9b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -145,6 +145,29 @@ export {
verifyPasswordHash,
verifyTotpCode,
} from './modules/auth/auth.service';
+// Dissolved from @openpanel/db's services/insights* + referrer-spikes.service
+// (M5-001) — apps/worker's insight job files and packages/trpc's insight
+// router call these directly, the same way V1 reaches every other dissolved
+// service here.
+export type {
+ DailyInsightCandidate,
+ GetReferrerSpikesInput,
+ ReferrerSpikeCluster,
+ WeeklyDigestPreview,
+ WeeklyDigestResult,
+} from './modules/insight/insight.service';
+export {
+ cleanupStaleInsights,
+ explainInsight,
+ getReferrerSpikes,
+ listAllInsights,
+ listDailyInsightCandidates,
+ listInsights,
+ previewWeeklyDigest,
+ runProjectInsights,
+ scanLegacyInsights,
+ sendWeeklyDigests,
+} from './modules/insight/insight.service';
export { dashboardRoutes, opsRoutes, publicApiRoutes } from './rest.routes';
// The RPC base is on the barrel because it is the seam `@openpanel/trpc`
// builds its 28 routers on: ONE tRPC instance, mounted by V1's Fastify
diff --git a/packages/core/src/jobs.registry.test.ts b/packages/core/src/jobs.registry.test.ts
index 722a0eb25..5c3f79545 100644
--- a/packages/core/src/jobs.registry.test.ts
+++ b/packages/core/src/jobs.registry.test.ts
@@ -65,3 +65,28 @@ test('every queue has a compat hook — the cutover has no drain step', () => {
expect(typeof definition.compat).toBe('function');
}
});
+
+// M5-001: the insight module's job — the BullMQ job *name* IS the registry
+// key (defineQueue stamps it), and legacyCompat.insights already discriminates
+// on this exact name (jobs/compat.ts), so this pins the two in agreement.
+test('the insights queue carries the insight module job', () => {
+ expect(Object.keys(queues.insights.jobs)).toEqual(['insightsProject']);
+ expect(queues.insights.jobs.insightsProject).toMatchObject({
+ queue: 'insights',
+ name: 'insightsProject',
+ });
+});
+
+// The insight module's cron fragment (insight.jobs.ts), spread into the ONE
+// cron queue (ADR-005: "no cron module"). legacyCompat.cron maps a legacy
+// job's `type` straight onto its name, so these three ids double as job names.
+test('the cron queue carries the insight module cron fragment', () => {
+ expect(Object.keys(queues.cron.jobs).sort()).toEqual(
+ ['insightCleanup', 'insightsDaily', 'weeklyDigest'].sort()
+ );
+ for (const name of ['insightsDaily', 'insightCleanup', 'weeklyDigest']) {
+ expect(
+ queues.cron.jobs[name as keyof typeof queues.cron.jobs]
+ ).toMatchObject({ queue: 'cron', name });
+ }
+});
diff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.ts
index b3585fbb7..5e3c41877 100644
--- a/packages/core/src/jobs.registry.ts
+++ b/packages/core/src/jobs.registry.ts
@@ -14,6 +14,10 @@ import { legacyCompat } from './jobs/compat';
import type { Producers } from './jobs/define';
import { defineQueue } from './jobs/define';
import type { ProducerHandle } from './jobs/producers';
+import {
+ insightCronJobs,
+ insightQueueJobs,
+} from './modules/insight/insight.jobs';
const HOUR_IN_SECONDS = 3600;
const DAY_IN_SECONDS = 86_400;
@@ -46,7 +50,10 @@ const cron = defineQueue('cron', {
defaults: { removeOnComplete: 10 },
worker: { concurrency: CONCURRENCY.cron },
compat: legacyCompat.cron,
- jobs: {},
+ // Every module's cron fragment spreads in here (ADR-005: "no cron module").
+ jobs: {
+ ...insightCronJobs,
+ },
});
const notification = defineQueue('notification', {
@@ -67,7 +74,9 @@ const insights = defineQueue('insights', {
defaults: { removeOnComplete: 100 },
worker: { concurrency: CONCURRENCY.insights },
compat: legacyCompat.insights,
- jobs: {},
+ jobs: {
+ ...insightQueueJobs,
+ },
});
const gsc = defineQueue('gsc', {
diff --git a/packages/core/src/jobs/schedulers.ts b/packages/core/src/jobs/schedulers.ts
index f6894ad83..81c291543 100644
--- a/packages/core/src/jobs/schedulers.ts
+++ b/packages/core/src/jobs/schedulers.ts
@@ -5,6 +5,7 @@
// locking of our own needed.
import type { Logger } from '../logger';
+import { insightCronSchedules } from '../modules/insight/insight.jobs';
import { wrap } from './envelope';
export type RepeatSchedule = { pattern: string } | { every: number };
@@ -61,17 +62,15 @@ export const CRON_SCHEDULES: readonly SchedulerDefinition[] = [
{ id: 'flushProfileBackfill', schedule: { every: 30_000 } },
{ id: 'flushReplay', schedule: { every: 10_000 } },
{ id: 'flushGroups', schedule: { every: 10_000 } },
- { id: 'insightsDaily', schedule: { pattern: '0 2 * * *' } },
{ id: 'onboarding', schedule: { pattern: '0 * * * *' } },
{ id: 'gscSync', schedule: { pattern: '0 3 * * *' } },
{ id: 'cohortRefresh', schedule: { pattern: '*/30 * * * *' } },
{ id: 'sessionReaper', schedule: { every: 5 * MINUTE_MS } },
// Daily 04:00 UTC — backstop for cleanup leaks.
{ id: 'sessionVacuum', schedule: { pattern: '0 4 * * *' } },
- // Daily 04:30 UTC — prunes stale insights/events.
- { id: 'insightCleanup', schedule: { pattern: '30 4 * * *' } },
- // Mondays 08:00 UTC — weekly analytics digest email.
- { id: 'weeklyDigest', schedule: { pattern: '0 8 * * 1' } },
+ // insightsDaily / insightCleanup / weeklyDigest — owned by the insight
+ // module, declared next to its jobs (modules/insight/insight.jobs.ts).
+ ...insightCronSchedules,
// Daily 07:30 UTC — no-data / data-stopped rescue emails. Owner: misc
// (ADR-005 acceptance note completes the ownership map).
{ id: 'dataHealth', schedule: { pattern: '30 7 * * *' } },
diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.ts
new file mode 100644
index 000000000..a8c9034a1
--- /dev/null
+++ b/packages/core/src/modules/insight/insight.jobs.test.ts
@@ -0,0 +1,175 @@
+// Job/cron-fragment wiring — no ClickHouse/Postgres touched. The service
+// methods themselves are exercised in insight.service.test.ts.
+
+import { expect, test } from 'bun:test';
+import type { JobCtx } from '../../context';
+import { createRecordingProducers } from '../../jobs/testing';
+import { queues } from '../../jobs.registry';
+import type { Logger } from '../../logger';
+import type { Services } from '../../services';
+import {
+ insightCronJobs,
+ insightCronSchedules,
+ insightQueueJobs,
+} from './insight.jobs';
+import type { InsightService } from './insight.service';
+
+function stubLogger(): Logger {
+ const noop = () => undefined;
+ const logger: Logger = {
+ fatal: noop,
+ error: noop,
+ warn: noop,
+ info: noop,
+ debug: noop,
+ trace: noop,
+ child: () => logger,
+ };
+ return logger;
+}
+
+// A plain object literal, not createCtx/extendCtx: `services` is installed
+// there as a getter with no setter (the lazy-build seam, ADR-007), which
+// makes it unassignable afterwards — exactly what a fake `services.insight`
+// needs to be for a handler test.
+function stubJobCtx(
+ insight: Partial<InsightService>,
+ jobName = 'test'
+): JobCtx {
+ const services: Services = {
+ auth: {} as Services['auth'],
+ insight: insight as InsightService,
+ };
+ return {
+ db: {},
+ ch: {},
+ redis: {},
+ clients: {},
+ buffers: {},
+ logger: stubLogger(),
+ queues: createRecordingProducers(queues).queues,
+ services,
+ requestId: 'req_1',
+ job: { id: 'job_1', attempt: 0, queue: 'cron', name: jobName },
+ };
+}
+
+test('the insight jobs registry declares insightsProject on the insights queue', () => {
+ expect(queues.insights.jobs.insightsProject).toMatchObject({
+ queue: 'insights',
+ name: 'insightsProject',
+ });
+});
+
+test('the insight cron fragment is spread into the cron queue', () => {
+ expect(Object.keys(queues.cron.jobs).sort()).toEqual(
+ ['insightCleanup', 'insightsDaily', 'weeklyDigest'].sort()
+ );
+});
+
+test('insightsProject validates its payload', () => {
+ expect(() =>
+ insightQueueJobs.insightsProject.payload.parse({ projectId: 'p1' })
+ ).toThrow();
+ expect(
+ insightQueueJobs.insightsProject.payload.parse({
+ projectId: 'p1',
+ date: '2026-09-03',
+ })
+ ).toEqual({ projectId: 'p1', date: '2026-09-03' });
+});
+
+test('insightsProject delegates to runProjectInsights', async () => {
+ const calls: unknown[] = [];
+ const ctx = stubJobCtx({
+ runProjectInsights: async (args) => {
+ calls.push(args);
+ },
+ });
+
+ await insightQueueJobs.insightsProject.handler({
+ payload: { projectId: 'p1', date: '2026-09-03' },
+ ctx,
+ });
+
+ expect(calls).toEqual([{ projectId: 'p1', date: '2026-09-03' }]);
+});
+
+test('insightsDaily fans out one insightsProject enqueue per candidate, jobId deduped by day+project', async () => {
+ const producers = createRecordingProducers(queues);
+ const ctx: JobCtx = {
+ db: {},
+ ch: {},
+ redis: {},
+ clients: {},
+ buffers: {},
+ logger: stubLogger(),
+ queues: producers.queues,
+ services: {
+ auth: {} as Services['auth'],
+ insight: {
+ listDailyInsightCandidates: async (date) => [
+ { projectId: 'p1', date },
+ { projectId: 'p2', date },
+ ],
+ } as InsightService,
+ },
+ requestId: 'req_1',
+ job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'insightsDaily' },
+ };
+
+ await insightCronJobs.insightsDaily.handler({ payload: null, ctx });
+
+ expect(producers.recorded).toHaveLength(2);
+ expect(producers.recorded.map((r) => r.job)).toEqual([
+ 'insightsProject',
+ 'insightsProject',
+ ]);
+ const today = new Date().toISOString().slice(0, 10);
+ expect(producers.recorded.map((r) => r.payload)).toEqual([
+ { projectId: 'p1', date: today },
+ { projectId: 'p2', date: today },
+ ]);
+});
+
+test('insightCleanup delegates to cleanupStaleInsights', async () => {
+ let called = false;
+ const ctx = stubJobCtx(
+ {
+ cleanupStaleInsights: async () => {
+ called = true;
+ return { insights: 0, events: 0 };
+ },
+ },
+ 'insightCleanup'
+ );
+
+ await insightCronJobs.insightCleanup.handler({ payload: null, ctx });
+ expect(called).toBe(true);
+});
+
+test('weeklyDigest delegates to sendWeeklyDigests', async () => {
+ let called = false;
+ const ctx = stubJobCtx(
+ {
+ sendWeeklyDigests: async () => {
+ called = true;
+ return { projects: 0, sent: 0 };
+ },
+ },
+ 'weeklyDigest'
+ );
+
+ await insightCronJobs.weeklyDigest.handler({ payload: null, ctx });
+ expect(called).toBe(true);
+});
+
+// Byte-identity with the ids/cadences schedulers.test.ts's golden snapshot
+// pins (apps/worker/src/boot-cron.ts).
+test('the insight cron fragment carries V1 ids and cadences unchanged', () => {
+ expect(insightCronSchedules).toEqual([
+ { id: 'insightsDaily', schedule: { pattern: '0 2 * * *' } },
+ { id: 'insightCleanup', schedule: { pattern: '30 4 * * *' } },
+ { id: 'weeklyDigest', schedule: { pattern: '0 8 * * 1' } },
+ ]);
+});
diff --git a/packages/core/src/modules/insight/insight.jobs.ts b/packages/core/src/modules/insight/insight.jobs.ts
new file mode 100644
index 000000000..ec145addd
--- /dev/null
+++ b/packages/core/src/modules/insight/insight.jobs.ts
@@ -0,0 +1,71 @@
+// Ported from apps/worker/src/jobs/insights.ts, insights-enrich.ts,
+// cron.insight-cleanup.ts and cron.weekly-digest.ts (M5-001).
+//
+// `insightsProject` is this module's own queue (`insights` in the registry —
+// ADR-005's registry key). `insightsDaily` / `insightCleanup` / `weeklyDigest`
+// are cron fragments: declared here, spread into the ONE `cron` queue by
+// jobs.registry.ts and into `CRON_SCHEDULES` by jobs/schedulers.ts. Scheduler
+// ids and cadences are V1's, unchanged (apps/worker/src/boot-cron.ts).
+
+import { z } from 'zod';
+import { defineJob } from '../../jobs/define';
+import type { SchedulerDefinition } from '../../jobs/schedulers';
+
+const insightsProjectPayload = z.object({
+ projectId: z.string(),
+ date: z.string(),
+});
+
+/** The `insights` queue's own jobs. */
+export const insightQueueJobs = {
+ insightsProject: defineJob({
+ payload: insightsProjectPayload,
+ handler: async ({ payload, ctx }) => {
+ await ctx.services.insight.runProjectInsights(payload);
+ },
+ }),
+};
+
+/** This module's fragment of the `cron` queue's jobs. */
+export const insightCronJobs = {
+ // Fans out one `insightsProject` job per eligible project. Jobs are
+ // deduplicated by a per-day, per-project jobId — matches V1
+ // (apps/worker/src/jobs/insights.ts).
+ insightsDaily: defineJob({
+ payload: z.null(),
+ handler: async ({ ctx }) => {
+ const date = new Date().toISOString().slice(0, 10);
+ const candidates =
+ await ctx.services.insight.listDailyInsightCandidates(date);
+
+ for (const candidate of candidates) {
+ await ctx.queues.insights.insightsProject.add(candidate, {
+ jobId: `daily:${candidate.date}:${candidate.projectId}`,
+ });
+ }
+ },
+ }),
+
+ insightCleanup: defineJob({
+ payload: z.null(),
+ handler: async ({ ctx }) => {
+ await ctx.services.insight.cleanupStaleInsights();
+ },
+ }),
+
+ weeklyDigest: defineJob({
+ payload: z.null(),
+ handler: async ({ ctx }) => {
+ await ctx.services.insight.sendWeeklyDigests();
+ },
+ }),
+};
+
+/** This module's fragment of `CRON_SCHEDULES` — ids and cadences unchanged. */
+export const insightCronSchedules: readonly SchedulerDefinition[] = [
+ { id: 'insightsDaily', schedule: { pattern: '0 2 * * *' } },
+ // Daily 04:30 UTC — prunes stale insights/events.
+ { id: 'insightCleanup', schedule: { pattern: '30 4 * * *' } },
+ // Mondays 08:00 UTC — weekly analytics digest email.
+ { id: 'weeklyDigest', schedule: { pattern: '0 8 * * 1' } },
+];
diff --git a/packages/core/src/modules/insight/insight.rpc.test.ts b/packages/core/src/modules/insight/insight.rpc.test.ts
new file mode 100644
index 000000000..c17627001
--- /dev/null
+++ b/packages/core/src/modules/insight/insight.rpc.test.ts
@@ -0,0 +1,53 @@
+// Only the "is anyone logged in" boundary is exercised here — no database.
+// list/listAll/explain's actual access-check + business logic ride on
+// @openpanel/db (lazy-loaded, see insight.service.ts's header) and are
+// covered at the unit level in insight.service.test.ts; wiring this router
+// end-to-end against a real Postgres is P6's (protectedProcedure) job, not
+// this one's — see insight.rpc.ts's header.
+
+import { expect, test } from 'bun:test';
+import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import { makeTrpcContext } from '../../rpc/base';
+import type { CookieOptions } from '../../shared/cookie';
+import { insightRouter } from './insight.rpc';
+
+const COOKIE_OPTIONS: CookieOptions = {
+ domain: '.openpanel.dev',
+ secure: true,
+ sameSite: 'lax',
+ httpOnly: true,
+ path: '/',
+};
+
+// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —
+// `TrpcContext.session` is never literally `null`, only its `userId` is.
+const EMPTY_SESSION = { session: null, user: null, userId: null };
+
+async function anonCaller() {
+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return insightRouter.createCaller(trpcCtx);
+}
+
+test('list rejects an unauthenticated caller before touching a project', async () => {
+ const caller = await anonCaller();
+ await expect(caller.list({ projectId: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('listAll rejects an unauthenticated caller before touching a project', async () => {
+ const caller = await anonCaller();
+ await expect(caller.listAll({ projectId: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('explain rejects an unauthenticated caller before reading an insight', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.explain({ insightId: 'insight_1' })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
diff --git a/packages/core/src/modules/insight/insight.rpc.ts b/packages/core/src/modules/insight/insight.rpc.ts
new file mode 100644
index 000000000..baa439b4d
--- /dev/null
+++ b/packages/core/src/modules/insight/insight.rpc.ts
@@ -0,0 +1,265 @@
+// Ported from packages/trpc/src/routers/insight.ts (M5-001).
+//
+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
+// stack — lands in core with auth (rpc/base.ts: "those need the resolved
+// Session shape and the access rules, so they land with auth (P6)"). Until
+// then this router does its own minimal "is anyone logged in" check inline,
+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
+// through packages/trpc's own `protectedProcedure` (full stack included) and
+// delegates its handler bodies to `ctx.services.insight` (DELEGATE PATTERN),
+// so nothing here is a live regression.
+//
+// The per-project access ladder itself IS shared: `./src/access.ts` binds
+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same
+// way packages/trpc/src/access.ts does for V1.
+
+import type { InsightPayload } from '@openpanel/validation';
+import { z } from 'zod';
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError } from '../../rpc/errors';
+
+// Lazy, deliberately: ./src/access reaches @openpanel/db's real lookups,
+// which (like insight.service.ts's db/ch access) construct a real pino
+// logger — with a transport worker thread — at import time. See
+// insight.service.ts's header for the full reasoning.
+function loadAccessChecks() {
+ return import('./src/access');
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const EXPLAIN_COLUMNS = [
+ 'referrer_name',
+ 'country',
+ 'device',
+ 'utm_source',
+] as const;
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+export const insightRouter = createTRPCRouter({
+ list: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ limit: z.number().min(1).max(100).optional().default(50),
+ })
+ )
+ .query(async ({ input: { projectId, limit }, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({ userId, projectId, level: 'read' });
+
+ // Fetch more than needed to account for deduplication. AI
+ // relevanceScore leads (un-enriched insights sort last via
+ // nulls:last), with the statistical impactScore as the tiebreaker.
+ const allInsights = await ctx.services.insight.listInsights({
+ projectId,
+ limit: limit * 3,
+ });
+
+ // WindowKind priority: yesterday (1) > rolling_7d (2) > rolling_30d (3)
+ const windowKindPriority: Record<string, number> = {
+ yesterday: 1,
+ rolling_7d: 2,
+ rolling_30d: 3,
+ };
+
+ // Group by moduleKey + dimensionKey, keep only the highest-priority
+ // windowKind.
+ const deduplicated = new Map<string, (typeof allInsights)[0]>();
+ for (const insight of allInsights) {
+ const key = `${insight.moduleKey}:${insight.dimensionKey}`;
+ const existing = deduplicated.get(key);
+ const currentPriority = windowKindPriority[insight.windowKind] ?? 999;
+ const existingPriority = existing
+ ? (windowKindPriority[existing.windowKind] ?? 999)
+ : 999;
+
+ if (!existing || currentPriority < existingPriority) {
+ deduplicated.set(key, insight);
+ }
+ }
+
+ return Array.from(deduplicated.values())
+ .sort(
+ (a, b) =>
+ (b.relevanceScore ?? -1) - (a.relevanceScore ?? -1) ||
+ (b.impactScore ?? 0) - (a.impactScore ?? 0)
+ )
+ .slice(0, limit)
+ .map(({ impactScore, ...rest }) => rest); // strip impactScore from the response
+ }),
+
+ listAll: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ limit: z.number().min(1).max(500).optional().default(200),
+ })
+ )
+ .query(async ({ input: { projectId, limit }, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({ userId, projectId, level: 'read' });
+
+ return ctx.services.insight.listAllInsights({ projectId, limit });
+ }),
+
+ // Phase 5: the "why". Decompose the insight's change across referrer/
+ // country/device/utm (current vs baseline window), pull nearby references,
+ // and have the AI explain which sub-segment drove it. Cached per insight
+ // version so repeat clicks don't re-bill the LLM.
+ explain: procedure
+ .input(z.object({ insightId: z.string() }))
+ .mutation(async ({ input: { insightId }, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+
+ // `overview` hasn't moved to core yet — deep-imported like the rest of
+ // @openpanel/db's internals until it does.
+ const { db } = await import('@openpanel/db/src/prisma-client');
+ const { getSegmentDailySeriesCore, getTrafficBreakdownCore } =
+ await import('@openpanel/db/src/services/overview.service');
+
+ const insight = await db.projectInsight.findUniqueOrThrow({
+ where: { id: insightId },
+ select: {
+ projectId: true,
+ title: true,
+ aiSummary: true,
+ summary: true,
+ dimensionKey: true,
+ windowKind: true,
+ windowStart: true,
+ windowEnd: true,
+ payload: true,
+ lastUpdatedAt: true,
+ },
+ });
+
+ // Reads an existing insight and explains it. Nothing about the project
+ // changes, so a read-level member may do it.
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({
+ userId,
+ projectId: insight.projectId,
+ level: 'read',
+ });
+
+ const cacheKey = `insight-explain:${insightId}:${insight.lastUpdatedAt.getTime()}`;
+
+ const end = insight.windowEnd ?? new Date();
+ const start = insight.windowStart ?? new Date(end.getTime() - 7 * DAY_MS);
+ const spanMs = Math.max(end.getTime() - start.getTime(), DAY_MS);
+ const baseEnd = new Date(start.getTime());
+ const baseStart = new Date(start.getTime() - spanMs);
+ const iso = (d: Date) => d.toISOString();
+
+ const breakdowns = await Promise.all(
+ EXPLAIN_COLUMNS.map(async (column) => {
+ const [cur, base] = await Promise.all([
+ getTrafficBreakdownCore({
+ projectId: insight.projectId,
+ column,
+ startDate: iso(start),
+ endDate: iso(end),
+ }),
+ getTrafficBreakdownCore({
+ projectId: insight.projectId,
+ column,
+ startDate: iso(baseStart),
+ endDate: iso(baseEnd),
+ }),
+ ]);
+ const compact = (rows: typeof cur) =>
+ rows.slice(0, 8).map((r) => ({
+ name: r.name ?? null,
+ sessions: Number(r.sessions ?? 0),
+ }));
+ return { column, current: compact(cur), baseline: compact(base) };
+ })
+ );
+
+ // Daily series for the insight's own segment, so the model can read
+ // the shape of the change (a one-off spike vs sustained growth)
+ // instead of only current-vs-baseline totals. Best-effort.
+ const payload = insight.payload as InsightPayload | null;
+ const segment = payload?.dimensions?.[0];
+ const primaryMetric = payload?.primaryMetric ?? 'sessions';
+ let dailySeries:
+ | {
+ metric: string;
+ current: { date: string; sessions: number }[];
+ baseline: { date: string; sessions: number }[];
+ }
+ | undefined;
+
+ if (segment?.key && segment.value) {
+ const [curSeries, baseSeries] = await Promise.all([
+ getSegmentDailySeriesCore({
+ projectId: insight.projectId,
+ column: segment.key,
+ value: segment.value,
+ startDate: iso(start),
+ endDate: iso(end),
+ }),
+ getSegmentDailySeriesCore({
+ projectId: insight.projectId,
+ column: segment.key,
+ value: segment.value,
+ startDate: iso(baseStart),
+ endDate: iso(baseEnd),
+ }),
+ ]);
+
+ const toMetric = (points: typeof curSeries) =>
+ points.map((p) => ({
+ date: p.date.slice(0, 10),
+ sessions: primaryMetric === 'pageviews' ? p.pageviews : p.sessions,
+ }));
+
+ if (curSeries.length > 0) {
+ dailySeries = {
+ metric: primaryMetric,
+ current: toMetric(curSeries),
+ baseline: toMetric(baseSeries),
+ };
+ }
+ }
+
+ const references = await db.reference.findMany({
+ where: {
+ projectId: insight.projectId,
+ date: {
+ gte: new Date(start.getTime() - 3 * DAY_MS),
+ lte: new Date(end.getTime() + DAY_MS),
+ },
+ },
+ orderBy: { date: 'desc' },
+ take: 10,
+ select: { title: true, date: true },
+ });
+
+ return ctx.services.insight.explainInsight(
+ {
+ insight: {
+ title: insight.aiSummary ?? insight.title,
+ dimension: insight.dimensionKey,
+ window: insight.windowKind,
+ summary: insight.summary ?? undefined,
+ },
+ dailySeries,
+ breakdowns,
+ references: references.map((r) => ({
+ title: r.title,
+ date: r.date.toISOString().slice(0, 10),
+ })),
+ },
+ cacheKey
+ );
+ }),
+});
diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.ts
new file mode 100644
index 000000000..663aa7f37
--- /dev/null
+++ b/packages/core/src/modules/insight/insight.service.test.ts
@@ -0,0 +1,175 @@
+// insight.service.ts's db/ch access is lazy (`await import(...)` inside each
+// function — see the file's header), which is exactly what makes
+// `mock.module` work here with no import-time side effects to race: every
+// mock below is registered before the subject's first call, not before its
+// (side-effect-free) import.
+
+import { beforeAll, expect, mock, test } from 'bun:test';
+
+const listProjectIdsForCadence = mock(async () => ['p1', 'p2']);
+const getProjectCreatedAt = mock(async () => null);
+mock.module('./src/store', () => ({
+ insightStore: { listProjectIdsForCadence, getProjectCreatedAt },
+}));
+
+const executeRawCalls: unknown[] = [];
+let executeRawReturns: number[] = [];
+const $executeRaw = mock((..._args: unknown[]) => {
+ executeRawCalls.push(_args);
+ return Promise.resolve(executeRawReturns.shift() ?? 0);
+});
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ db: { $executeRaw },
+}));
+
+mock.module('@openpanel/db/src/clickhouse/client', () => ({ ch: {} }));
+
+const spikesQuery = mock(async () => [
+ { anchorDate: '2026-09-01', spikes: [] },
+]);
+mock.module('./src/referrer-spikes', () => ({
+ getReferrerSpikes: spikesQuery,
+}));
+
+const legacyGenerateInsights = mock(async () => [
+ { type: 'traffic_spike', message: 'test', data: {} },
+]);
+mock.module('./src/legacy-scan', () => ({
+ InsightsService: class {
+ generateInsights = legacyGenerateInsights;
+ },
+}));
+
+const generateInsightExplanation = mock(async () => ({
+ summary: 'x',
+ drivers: [],
+ relatedReference: '',
+ confidence: 'low' as const,
+}));
+mock.module('../../clients/ai/explain', () => ({
+ generateInsightExplanation,
+}));
+
+const redisStore = new Map<string, string>();
+const getRedisCache = mock(() => ({
+ get: mock((key: string) => Promise.resolve(redisStore.get(key) ?? null)),
+ setex: mock((key: string, _ttl: number, value: string) => {
+ redisStore.set(key, value);
+ return Promise.resolve();
+ }),
+}));
+mock.module('@openpanel/redis', () => ({ getRedisCache }));
+
+let subject: typeof import('./insight.service');
+beforeAll(async () => {
+ subject = await import('./insight.service');
+});
+
+test('listDailyInsightCandidates pairs every eligible project with the given date', async () => {
+ const candidates = await subject.listDailyInsightCandidates('2026-09-03');
+
+ expect(listProjectIdsForCadence).toHaveBeenCalledWith('daily');
+ expect(candidates).toEqual([
+ { projectId: 'p1', date: '2026-09-03' },
+ { projectId: 'p2', date: '2026-09-03' },
+ ]);
+});
+
+test('cleanupStaleInsights stops each batch loop once a batch returns fewer than the page size', async () => {
+ executeRawReturns = [5000, 5000, 1200, 5000, 0, 5000, 5000, 3];
+ const noop = () => undefined;
+ const logger: import('../../logger').Logger = {
+ fatal: noop,
+ error: noop,
+ warn: noop,
+ info: noop,
+ debug: noop,
+ trace: noop,
+ child: () => logger,
+ };
+ const result = await subject.cleanupStaleInsights(logger);
+
+ // suppressed: 5000+5000+1200 (stops <5000); closed: 5000+0 (stops <5000)
+ expect(result.insights).toBe(5000 + 5000 + 1200 + 5000 + 0);
+ // events: 5000+5000+3 (stops <5000)
+ expect(result.events).toBe(5000 + 5000 + 3);
+});
+
+test('getReferrerSpikes delegates to the ClickHouse query', async () => {
+ const input = {
+ projectId: 'p1',
+ filters: [],
+ startDate: '2026-08-01',
+ endDate: '2026-09-01',
+ interval: 'day' as const,
+ timezone: 'UTC',
+ };
+ const result = await subject.getReferrerSpikes(input);
+
+ expect(spikesQuery).toHaveBeenCalledWith(input);
+ expect(result).toEqual([{ anchorDate: '2026-09-01', spikes: [] }]);
+});
+
+test('scanLegacyInsights delegates to the pre-engine detector, kept for parity', async () => {
+ const result = await subject.scanLegacyInsights('p1');
+
+ expect(legacyGenerateInsights).toHaveBeenCalledWith('p1');
+ expect(result).toEqual([
+ { type: 'traffic_spike', message: 'test', data: {} },
+ ]);
+});
+
+test('explainInsight is a cache-aside over the AI call, keyed by the caller-supplied cacheKey', async () => {
+ const input = {
+ insight: { title: 't', dimension: 'd', window: 'yesterday' },
+ breakdowns: [],
+ references: [],
+ };
+
+ const first = await subject.explainInsight(input, 'insight-explain:i1:100');
+ expect(generateInsightExplanation).toHaveBeenCalledTimes(1);
+ expect(first?.summary).toBe('x');
+
+ // Second call with the same key is served from the cache, not the LLM.
+ const second = await subject.explainInsight(input, 'insight-explain:i1:100');
+ expect(generateInsightExplanation).toHaveBeenCalledTimes(1);
+ expect(second).toEqual(first);
+});
+
+test('createInsightService binds every InsightService method', () => {
+ const noop = () => undefined;
+ const logger: import('../../logger').Logger = {
+ fatal: noop,
+ error: noop,
+ warn: noop,
+ info: noop,
+ debug: noop,
+ trace: noop,
+ child: () => logger,
+ };
+ const service = subject.createInsightService({
+ db: undefined,
+ ch: undefined,
+ redis: undefined,
+ clients: undefined,
+ buffers: undefined,
+ logger,
+ queues:
+ undefined as unknown as import('../../jobs.registry').QueueProducers,
+ });
+
+ for (const method of [
+ 'listDailyInsightCandidates',
+ 'runProjectInsights',
+ 'cleanupStaleInsights',
+ 'sendWeeklyDigests',
+ 'previewWeeklyDigest',
+ 'listInsights',
+ 'listAllInsights',
+ 'explainInsight',
+ 'getReferrerSpikes',
+ 'scanLegacyInsights',
+ ] as const) {
+ expect(typeof service[method]).toBe('function');
+ }
+});
diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.ts
new file mode 100644
index 000000000..aa5e83483
--- /dev/null
+++ b/packages/core/src/modules/insight/insight.service.ts
@@ -0,0 +1,748 @@
+// Moved from packages/db/src/services/insights* + referrer-spikes.service.ts
+// (M5-001, the AI engine module). ADR-007: "Moves to core: src/services/**
+// (33 services + insights/)".
+//
+// Plain exported functions, not only methods on `createInsightService`'s
+// container — the same shape as modules/auth/auth.service.ts, because V1's
+// worker (apps/worker, no core Ctx today) and V1's trpc router both need a
+// direct call, not one that requires building a Ctx first. `createInsightService`
+// is the `ctx.services.insight` binding for code that already has a Ctx.
+//
+// db/ch access is LAZY (`load*` below), not a static top-level import: both
+// @openpanel/db/src/prisma-client and .../clickhouse/client construct a real
+// pino logger — WITH a pino-pretty transport worker thread — the moment they
+// are imported (M4-008's self-contained db logger). A static import here
+// would spawn one of those per core test FILE, since jobs.registry.ts and
+// services.ts pull this module into the eager barrel chain nearly every test
+// reaches. Same shape as @openpanel/core/clients/email.ts's lazy import, one
+// more reason for it. None of these deep paths import @openpanel/core, so
+// there is no db <-> core runtime *cycle* — this is a side-effect problem,
+// not a cycle.
+//
+// ClickHouse queries here still go through clix, not the `sql` tag: ADR-013
+// converts the analytics read path one query per P7 task, and this module's
+// queries haven't been converted yet.
+
+import { getRedisCache } from '@openpanel/redis';
+import {
+ ENRICH_VERSION,
+ enrichInsights,
+ type InsightToEnrich,
+} from '../../clients/ai/enrich';
+import {
+ type ExplainInsightInput,
+ generateInsightExplanation,
+ type InsightExplanation,
+} from '../../clients/ai/explain';
+import { generateWeeklyNarrative } from '../../clients/ai/narrative';
+import { sendEmail } from '../../clients/email';
+import type { Logger } from '../../logger';
+import type { ServiceDeps } from '../../services';
+import type { EngineConfig } from './src/engine';
+import type { Insight as LegacyInsight } from './src/legacy-scan';
+import type {
+ GetReferrerSpikesInput,
+ ReferrerSpikeCluster,
+} from './src/referrer-spikes';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const EXPLAIN_CACHE_TTL_SEC = 24 * 60 * 60;
+
+// Tier-1 enrichment batch size, kept modest so the prompt stays small and the
+// id-mapping reliable.
+const ENRICH_BATCH_SIZE = 25;
+
+// Postgres batch-delete chunk — bounds the first (large) purge to never hold a
+// single long-lived transaction/lock.
+const CLEANUP_BATCH_SIZE = 5000;
+const CLEANUP_MAX_BATCHES = 2000; // runaway backstop: 5000 * 2000 = 10M rows
+const DEFAULT_INSIGHTS_RETENTION_DAYS = 90;
+
+// Weekly digest: quiet threshold + how many email-worthy insights to surface.
+const WEEKLY_DIGEST_MIN_EVENTS = 100;
+const WEEKLY_DIGEST_MAX_INSIGHTS = 5;
+
+const DEFAULT_ENGINE_CONFIG: EngineConfig = {
+ keepTopNPerModuleWindow: 20,
+ closeStaleAfterDays: 7,
+ dimensionBatchSize: 50,
+ globalThresholds: {
+ minTotal: 200,
+ minAbsDelta: 80,
+ minPct: 0.15,
+ },
+};
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client');
+}
+
+function loadCh() {
+ return import('@openpanel/db/src/clickhouse/client').then((m) => m.ch);
+}
+
+function loadEngine() {
+ return import('./src/engine');
+}
+
+function loadStore() {
+ return import('./src/store').then((m) => m.insightStore);
+}
+
+function loadDetectionModules() {
+ return import('./src/modules');
+}
+
+function loadReferrerSpikesQuery() {
+ return import('./src/referrer-spikes').then((m) => m.getReferrerSpikes);
+}
+
+function loadLegacyDetector() {
+ return import('./src/legacy-scan').then((m) => m.InsightsService);
+}
+
+export interface DailyInsightCandidate {
+ projectId: string;
+ date: string;
+}
+
+export interface WeeklyDigestResult {
+ projects: number;
+ sent: number;
+}
+
+export interface WeeklyDigestPreview {
+ sent: boolean;
+ to?: string;
+ skipped?: string;
+ data?: unknown;
+}
+
+function clamp01(n: number): number {
+ if (Number.isNaN(n)) {
+ return 0;
+ }
+ return Math.max(0, Math.min(1, n));
+}
+
+/** The `insightsDaily` cron fan-out: eligible project ids, paired with `date`. */
+export async function listDailyInsightCandidates(
+ date: string
+): Promise<DailyInsightCandidate[]> {
+ const insightStore = await loadStore();
+ const projectIds = await insightStore.listProjectIdsForCadence('daily');
+ return projectIds.map((projectId) => ({ projectId, date }));
+}
+
+/**
+ * Tier-1 AI enrichment for one project's active insights: scores anything
+ * new, materially-changed, or enriched under an older prompt version.
+ * Failures are logged and skipped — a bad batch must never fail the insights
+ * job itself.
+ */
+async function enrichProjectInsights(
+ projectId: string,
+ logger: Logger
+): Promise<void> {
+ const { db } = await loadDb();
+
+ const stale = await db.projectInsight.findMany({
+ where: {
+ projectId,
+ state: 'active',
+ OR: [
+ { enrichedAt: null },
+ { enrichVersion: null },
+ { enrichVersion: { lt: ENRICH_VERSION } },
+ ],
+ },
+ select: {
+ id: true,
+ moduleKey: true,
+ dimensionKey: true,
+ windowKind: true,
+ title: true,
+ summary: true,
+ displayName: true,
+ direction: true,
+ impactScore: true,
+ severityBand: true,
+ payload: true,
+ },
+ });
+
+ if (stale.length === 0) {
+ return;
+ }
+
+ let enriched = 0;
+ for (let i = 0; i < stale.length; i += ENRICH_BATCH_SIZE) {
+ const batch = stale.slice(i, i + ENRICH_BATCH_SIZE);
+ const input: InsightToEnrich[] = batch.map((r) => ({
+ id: r.id,
+ moduleKey: r.moduleKey,
+ dimensionKey: r.dimensionKey,
+ windowKind: r.windowKind,
+ title: r.title,
+ summary: r.summary,
+ displayName: r.displayName,
+ direction: r.direction,
+ impactScore: r.impactScore,
+ severityBand: r.severityBand,
+ payload: r.payload,
+ }));
+
+ let results: Awaited<ReturnType<typeof enrichInsights>>;
+ try {
+ results = await enrichInsights(input);
+ } catch (err) {
+ logger.error(
+ { err, projectId, batchSize: batch.length },
+ 'insight enrichment call failed; skipping batch'
+ );
+ continue;
+ }
+
+ const byId = new Map(results.map((r) => [r.id, r]));
+ for (const row of batch) {
+ const e = byId.get(row.id);
+ if (!e) {
+ continue;
+ }
+ await db.projectInsight.update({
+ where: { id: row.id },
+ data: {
+ relevanceScore: clamp01(e.relevanceScore),
+ aiSummary: e.summary,
+ aiCategory: e.category,
+ emailWorthy: e.emailWorthy,
+ referenceWorthy: e.referenceWorthy,
+ enrichedAt: new Date(),
+ enrichVersion: ENRICH_VERSION,
+ },
+ });
+ enriched++;
+ }
+ }
+
+ logger.info(
+ { projectId, candidates: stale.length, enriched },
+ 'insight enrichment complete'
+ );
+}
+
+/** The `insightsProject` job body: engine run + tier-1 AI enrichment. */
+export async function runProjectInsights(args: {
+ projectId: string;
+ date: string;
+ logger: Logger;
+}): Promise<void> {
+ const { projectId, date, logger } = args;
+ const [{ createEngine }, insightStore, detectionModules, ch] =
+ await Promise.all([
+ loadEngine(),
+ loadStore(),
+ loadDetectionModules(),
+ loadCh(),
+ ]);
+
+ const engine = createEngine({
+ store: insightStore,
+ modules: [
+ detectionModules.referrersModule,
+ detectionModules.entryPagesModule,
+ detectionModules.pageTrendsModule,
+ detectionModules.geoModule,
+ detectionModules.devicesModule,
+ ],
+ db: ch,
+ config: DEFAULT_ENGINE_CONFIG,
+ });
+
+ const projectCreatedAt = await insightStore.getProjectCreatedAt(projectId);
+
+ await engine.runProject({
+ projectId,
+ cadence: 'daily',
+ now: new Date(date),
+ projectCreatedAt,
+ });
+
+ // Isolated so a provider outage or rate-limit never fails the insights
+ // computation itself.
+ try {
+ await enrichProjectInsights(projectId, logger);
+ } catch (err) {
+ logger.error({ err, projectId }, 'insight enrichment failed');
+ }
+}
+
+async function deleteInBatches(
+ runBatch: () => Promise<number>
+): Promise<number> {
+ let total = 0;
+ for (let i = 0; i < CLEANUP_MAX_BATCHES; i++) {
+ const deleted = await runBatch();
+ total += deleted;
+ if (deleted < CLEANUP_BATCH_SIZE) {
+ break;
+ }
+ }
+ return total;
+}
+
+/**
+ * Keeps the insights tables bounded (they otherwise grow forever — see the
+ * original packages/db/src/services/insights.service.ts header for the
+ * retention rules). The `insightCleanup` cron job body.
+ */
+export async function cleanupStaleInsights(
+ logger: Logger
+): Promise<{ insights: number; events: number }> {
+ const { db } = await loadDb();
+ const retentionDays = Number.parseInt(
+ process.env.INSIGHTS_RETENTION_DAYS ||
+ String(DEFAULT_INSIGHTS_RETENTION_DAYS),
+ 10
+ );
+ const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000);
+
+ const suppressed = await deleteInBatches(
+ () => db.$executeRaw`
+ DELETE FROM "project_insights"
+ WHERE "id" IN (
+ SELECT "id" FROM "project_insights"
+ WHERE "state" = 'suppressed'
+ LIMIT ${CLEANUP_BATCH_SIZE}
+ )`
+ );
+
+ const closed = await deleteInBatches(
+ () => db.$executeRaw`
+ DELETE FROM "project_insights"
+ WHERE "id" IN (
+ SELECT "id" FROM "project_insights"
+ WHERE "state" = 'closed'
+ AND "lastSeenAt" < ${cutoff}
+ LIMIT ${CLEANUP_BATCH_SIZE}
+ )`
+ );
+ const insights = suppressed + closed;
+
+ const events = await deleteInBatches(
+ () => db.$executeRaw`
+ DELETE FROM "insight_events"
+ WHERE "id" IN (
+ SELECT "id" FROM "insight_events"
+ WHERE "createdAt" < ${cutoff}
+ LIMIT ${CLEANUP_BATCH_SIZE}
+ )`
+ );
+
+ logger.info({ retentionDays, insights, events }, 'insight cleanup complete');
+ return { insights, events };
+}
+
+function pctDelta(
+ current: number,
+ previous: number
+): { delta?: string; direction: 'up' | 'down' | 'flat' } {
+ if (previous <= 0) {
+ return { direction: 'flat' };
+ }
+ const pct = ((current - previous) / previous) * 100;
+ const direction = pct > 0.5 ? 'up' : pct < -0.5 ? 'down' : 'flat';
+ const sign = pct >= 0 ? '+' : '';
+ return { delta: `${sign}${pct.toFixed(0)}%`, direction };
+}
+
+function ppDelta(
+ current: number,
+ previous: number
+): { delta?: string; direction: 'up' | 'down' | 'flat' } {
+ const diff = current - previous;
+ const direction = diff > 0.5 ? 'up' : diff < -0.5 ? 'down' : 'flat';
+ const sign = diff >= 0 ? '+' : '';
+ return { delta: `${sign}${diff.toFixed(0)}pp`, direction };
+}
+
+function formatCount(n: number): string {
+ return Math.round(n).toLocaleString();
+}
+
+function formatRange(startMs: number, endMs: number): string {
+ const opts: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' };
+ const start = new Date(startMs).toLocaleDateString('en-US', opts);
+ const end = new Date(endMs).toLocaleDateString('en-US', {
+ ...opts,
+ year: 'numeric',
+ });
+ return `${start} – ${end}`;
+}
+
+interface DigestProjectRow {
+ id: string;
+ name: string;
+ organizationId: string;
+}
+
+/** Assembles one project's digest payload (no sending). */
+async function buildDigestData(
+ project: DigestProjectRow,
+ opts: { force?: boolean } = {}
+): Promise<{ skipped?: string; data?: Record<string, unknown> }> {
+ const now = Date.now();
+ const curStart = now - 7 * DAY_MS;
+ const prevStart = now - 14 * DAY_MS;
+ const iso = (ms: number) => new Date(ms).toISOString();
+
+ const { db } = await loadDb();
+ // `overview` hasn't moved to core yet — deep-imported like the rest of
+ // @openpanel/db's internals until it does.
+ const { getAnalyticsOverviewCore } = await import(
+ '@openpanel/db/src/services/overview.service'
+ );
+
+ const [cur, prev] = await Promise.all([
+ getAnalyticsOverviewCore({
+ projectId: project.id,
+ startDate: iso(curStart),
+ endDate: iso(now),
+ interval: 'day',
+ }),
+ getAnalyticsOverviewCore({
+ projectId: project.id,
+ startDate: iso(prevStart),
+ endDate: iso(curStart),
+ interval: 'day',
+ }),
+ ]);
+
+ const c = cur.summary;
+ const p = prev.summary;
+
+ if (!opts.force && c.unique_visitors === 0) {
+ return { skipped: 'no visitors in the last 7 days' };
+ }
+
+ const stats = [
+ {
+ label: 'visitors',
+ value: formatCount(c.unique_visitors),
+ ...pctDelta(c.unique_visitors, p.unique_visitors),
+ },
+ {
+ label: 'sessions',
+ value: formatCount(c.total_sessions),
+ ...pctDelta(c.total_sessions, p.total_sessions),
+ },
+ {
+ label: 'pageviews',
+ value: formatCount(c.total_screen_views),
+ ...pctDelta(c.total_screen_views, p.total_screen_views),
+ },
+ {
+ label: 'bounce rate',
+ value: `${Math.round(c.bounce_rate)}%`,
+ ...ppDelta(c.bounce_rate, p.bounce_rate),
+ },
+ ];
+
+ const insightRows = await db.projectInsight.findMany({
+ where: {
+ projectId: project.id,
+ state: 'active',
+ emailWorthy: true,
+ windowKind: { in: ['rolling_7d'] },
+ },
+ orderBy: [
+ { relevanceScore: { sort: 'desc', nulls: 'last' } },
+ { impactScore: 'desc' },
+ ],
+ take: WEEKLY_DIGEST_MAX_INSIGHTS,
+ select: { title: true, aiSummary: true, summary: true },
+ });
+
+ const insights = insightRows.map((i) => ({
+ title: i.aiSummary ?? i.title,
+ summary: i.summary ?? undefined,
+ }));
+
+ const dateRange = formatRange(curStart, now);
+
+ let narrative = '';
+ try {
+ narrative = await generateWeeklyNarrative({
+ projectName: project.name,
+ dateRange,
+ stats: [
+ {
+ label: 'visitors',
+ current: c.unique_visitors,
+ previous: p.unique_visitors,
+ },
+ {
+ label: 'sessions',
+ current: c.total_sessions,
+ previous: p.total_sessions,
+ },
+ {
+ label: 'pageviews',
+ current: c.total_screen_views,
+ previous: p.total_screen_views,
+ },
+ {
+ label: 'bounce rate',
+ current: c.bounce_rate,
+ previous: p.bounce_rate,
+ unit: '%',
+ },
+ ],
+ insights,
+ });
+ } catch {
+ // Narrative is best-effort — the digest still sends without it.
+ }
+
+ const dashboardUrl = `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${project.organizationId}/${project.id}`;
+
+ return {
+ data: {
+ projectName: project.name,
+ dashboardUrl,
+ dateRange,
+ narrative: narrative || undefined,
+ stats,
+ insights,
+ },
+ };
+}
+
+async function recipientsForOrg(organizationId: string): Promise<string[]> {
+ const { db } = await loadDb();
+ const members = await db.member.findMany({
+ where: { organizationId },
+ select: { email: true },
+ });
+ return [...new Set(members.map((m) => m.email).filter(Boolean))];
+}
+
+/**
+ * Per active project: week-over-week stats + the AI's email-worthy insights +
+ * a generated narrative, mailed to org members. The `weeklyDigest` cron job
+ * body.
+ */
+export async function sendWeeklyDigests(
+ logger: Logger
+): Promise<WeeklyDigestResult> {
+ const { db } = await loadDb();
+
+ // Prefilter on the raw status column (computed fields can't be used in
+ // `where`), then refine with the canonical subscription state below.
+ const projects = await db.project.findMany({
+ where: {
+ deleteAt: null,
+ eventsCount: { gt: WEEKLY_DIGEST_MIN_EVENTS },
+ organization: { subscriptionStatus: { in: ['active', 'trialing'] } },
+ },
+ select: {
+ id: true,
+ name: true,
+ organizationId: true,
+ organization: { select: { subscriptionState: true } },
+ },
+ });
+
+ let sent = 0;
+ for (const project of projects) {
+ try {
+ const state = project.organization.subscriptionState;
+ if (state !== 'active' && state !== 'trialing') {
+ continue;
+ }
+
+ const { skipped, data } = await buildDigestData(project);
+ if (skipped || !data) {
+ continue;
+ }
+ const emails = await recipientsForOrg(project.organizationId);
+ if (emails.length === 0) {
+ continue;
+ }
+ for (const to of emails) {
+ await sendEmail('weekly-digest', { to, data: data as never });
+ }
+ sent++;
+ } catch (err) {
+ logger.error({ err, projectId: project.id }, 'weekly digest failed');
+ }
+ }
+
+ logger.info({ projects: projects.length, sent }, 'weekly digest complete');
+ return { projects: projects.length, sent };
+}
+
+/**
+ * Debug/testing helper for a SINGLE project, bypassing eligibility.
+ * - opts.to → send only to that address (safe for testing)
+ * - no opts.to → assemble and return the payload without sending (preview)
+ * - opts.force → build even if the project had 0 visitors this week
+ */
+export async function previewWeeklyDigest(
+ projectId: string,
+ opts: { to?: string; force?: boolean } = {}
+): Promise<WeeklyDigestPreview> {
+ const { db } = await loadDb();
+ const project = await db.project.findUnique({
+ where: { id: projectId },
+ select: { id: true, name: true, organizationId: true },
+ });
+ if (!project) {
+ return { sent: false, skipped: 'project not found' };
+ }
+
+ const { skipped, data } = await buildDigestData(project, {
+ force: opts.force,
+ });
+ if (skipped || !data) {
+ return { sent: false, skipped, data };
+ }
+
+ if (opts.to) {
+ await sendEmail('weekly-digest', { to: opts.to, data: data as never });
+ return { sent: true, to: opts.to, data };
+ }
+
+ return { sent: false, data };
+}
+
+export async function listInsights(args: { projectId: string; limit: number }) {
+ const { db } = await loadDb();
+ return db.projectInsight.findMany({
+ where: { projectId: args.projectId, state: 'active' },
+ orderBy: [
+ { relevanceScore: { sort: 'desc', nulls: 'last' } },
+ { impactScore: 'desc' },
+ ],
+ take: args.limit,
+ });
+}
+
+export async function listAllInsights(args: {
+ projectId: string;
+ limit: number;
+}) {
+ const { db } = await loadDb();
+ return db.projectInsight.findMany({
+ where: { projectId: args.projectId, state: 'active' },
+ orderBy: [
+ { relevanceScore: { sort: 'desc', nulls: 'last' } },
+ { impactScore: 'desc' },
+ ],
+ take: args.limit,
+ });
+}
+
+/**
+ * Explains one insight, cached per insight version (`cacheKey` already
+ * carries the insight id + `lastUpdatedAt`) so repeat clicks don't re-bill
+ * the LLM.
+ */
+export async function explainInsight(
+ input: ExplainInsightInput,
+ cacheKey: string
+): Promise<InsightExplanation | null> {
+ const cached = await getRedisCache().get(cacheKey);
+ if (cached) {
+ return JSON.parse(cached) as InsightExplanation;
+ }
+
+ const explanation = await generateInsightExplanation(input);
+
+ // Only cache a successful explanation — a null is a transient LLM failure
+ // and should be retried on the next click.
+ if (explanation) {
+ await getRedisCache().setex(
+ cacheKey,
+ EXPLAIN_CACHE_TTL_SEC,
+ JSON.stringify(explanation)
+ );
+ }
+
+ return explanation;
+}
+
+export async function getReferrerSpikes(
+ input: GetReferrerSpikesInput
+): Promise<ReferrerSpikeCluster[]> {
+ const query = await loadReferrerSpikesQuery();
+ return query(input);
+}
+
+/** Pre-engine detector, kept for parity with V1 — no live callers today. */
+export async function scanLegacyInsights(
+ projectId: string
+): Promise<LegacyInsight[]> {
+ const [LegacyInsightsDetector, ch] = await Promise.all([
+ loadLegacyDetector(),
+ loadCh(),
+ ]);
+ return new LegacyInsightsDetector(ch).generateInsights(projectId);
+}
+
+// Re-exported at each type's own import site (noExportedImports): a type
+// that is also used locally still gets `export type {} from '<module>'`
+// rather than a second `import`-then-`export` pair gathered here.
+export type {
+ ExplainInsightInput,
+ InsightExplanation,
+} from '../../clients/ai/explain';
+export type {
+ GetReferrerSpikesInput,
+ ReferrerSpikeCluster,
+} from './src/referrer-spikes';
+
+export interface InsightService {
+ listDailyInsightCandidates(date: string): Promise<DailyInsightCandidate[]>;
+ runProjectInsights(args: { projectId: string; date: string }): Promise<void>;
+ cleanupStaleInsights(): Promise<{ insights: number; events: number }>;
+ sendWeeklyDigests(): Promise<WeeklyDigestResult>;
+ previewWeeklyDigest(
+ projectId: string,
+ opts?: { to?: string; force?: boolean }
+ ): Promise<WeeklyDigestPreview>;
+ listInsights(args: {
+ projectId: string;
+ limit: number;
+ }): ReturnType<typeof listInsights>;
+ listAllInsights(args: {
+ projectId: string;
+ limit: number;
+ }): ReturnType<typeof listAllInsights>;
+ explainInsight(
+ input: ExplainInsightInput,
+ cacheKey: string
+ ): Promise<InsightExplanation | null>;
+ getReferrerSpikes(
+ input: GetReferrerSpikesInput
+ ): Promise<ReferrerSpikeCluster[]>;
+ scanLegacyInsights(projectId: string): Promise<LegacyInsight[]>;
+}
+
+/** `ctx.services.insight` — a thin binding of the functions above to a Ctx's logger. */
+export function createInsightService(deps: ServiceDeps): InsightService {
+ const logger = deps.logger.child({ module: 'insight' });
+
+ return {
+ listDailyInsightCandidates,
+ runProjectInsights: (args) => runProjectInsights({ ...args, logger }),
+ cleanupStaleInsights: () => cleanupStaleInsights(logger),
+ sendWeeklyDigests: () => sendWeeklyDigests(logger),
+ previewWeeklyDigest,
+ listInsights,
+ listAllInsights,
+ explainInsight,
+ getReferrerSpikes,
+ scanLegacyInsights,
+ };
+}
diff --git a/packages/core/src/modules/insight/src/access.ts b/packages/core/src/modules/insight/src/access.ts
new file mode 100644
index 000000000..de4a4168e
--- /dev/null
+++ b/packages/core/src/modules/insight/src/access.ts
@@ -0,0 +1,21 @@
+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
+// this module's own router — the same binding packages/trpc/src/access.ts
+// does for V1, self-contained here because the general core -> db binding
+// itself moves with auth (P6), not this wave.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { getProjectById } from '@openpanel/db/src/services/project.service';
+import { createAccessChecks } from '../../../shared/access';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/db/src/services/insights/cached-clix.ts b/packages/core/src/modules/insight/src/cached-clix.ts
similarity index 96%
rename from packages/db/src/services/insights/cached-clix.ts
rename to packages/core/src/modules/insight/src/cached-clix.ts
index 2dd772d68..332d2c965 100644
--- a/packages/db/src/services/insights/cached-clix.ts
+++ b/packages/core/src/modules/insight/src/cached-clix.ts
@@ -1,9 +1,9 @@
import crypto from 'node:crypto';
import type { ClickHouseClient } from '@clickhouse/client';
import {
- type Query,
clix as originalClix,
-} from '../../clickhouse/query-builder';
+ type Query,
+} from '@openpanel/db/src/clickhouse/query-builder';
/**
* Creates a cached wrapper around clix that automatically caches query results
@@ -17,7 +17,7 @@ import {
export function createCachedClix(
client: ClickHouseClient,
cache?: Map<string, any>,
- timezone?: string,
+ timezone?: string
) {
function clixCached(): Query {
const query = originalClix(client, timezone);
diff --git a/packages/db/src/services/insights/engine.ts b/packages/core/src/modules/insight/src/engine.ts
similarity index 92%
rename from packages/db/src/services/insights/engine.ts
rename to packages/core/src/modules/insight/src/engine.ts
index 2a2f34921..4c4a3738a 100644
--- a/packages/db/src/services/insights/engine.ts
+++ b/packages/core/src/modules/insight/src/engine.ts
@@ -42,7 +42,7 @@ export interface EngineConfig {
function passesThresholds(
r: ComputeResult,
mod: InsightModule,
- cfg: EngineConfig,
+ cfg: EngineConfig
): boolean {
const t = mod.thresholds ?? {};
const minTotal = t.minTotal ?? cfg.globalThresholds.minTotal;
@@ -53,16 +53,26 @@ function passesThresholds(
const total = cur + cmp;
const absDelta = Math.abs(cur - cmp);
const pct = Math.abs(r.changePct ?? 0);
- if (total < minTotal) return false;
- if (absDelta < minAbsDelta) return false;
- if (pct < minPct) return false;
+ if (total < minTotal) {
+ return false;
+ }
+ if (absDelta < minAbsDelta) {
+ return false;
+ }
+ if (pct < minPct) {
+ return false;
+ }
return true;
}
function chunk<T>(arr: T[], size: number): T[][] {
- if (size <= 0) return [arr];
+ if (size <= 0) {
+ return [arr];
+ }
const out: T[][] = [];
- for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
+ for (let i = 0; i < arr.length; i += size) {
+ out.push(arr.slice(i, i + size));
+ }
return out;
}
@@ -78,9 +88,11 @@ export function createEngine(args: {
function isProjectOldEnoughForWindow(
projectCreatedAt: Date | null | undefined,
- baselineStart: Date,
+ baselineStart: Date
): boolean {
- if (!projectCreatedAt) return true; // best-effort; don't block if unknown
+ if (!projectCreatedAt) {
+ return true; // best-effort; don't block if unknown
+ }
return projectCreatedAt.getTime() <= baselineStart.getTime();
}
@@ -147,7 +159,9 @@ export function createEngine(args: {
continue;
}
const maxDims = mod.thresholds?.maxDims ?? 25;
- if (dims.length > maxDims) dims = dims.slice(0, maxDims);
+ if (dims.length > maxDims) {
+ dims = dims.slice(0, maxDims);
+ }
if (dims.length === 0) {
// Still do lifecycle close / suppression based on "nothing emitted"
@@ -189,14 +203,20 @@ export function createEngine(args: {
}
for (const r of results) {
- if (!r?.ok) continue;
- if (!r.dimensionKey) continue;
+ if (!r?.ok) {
+ continue;
+ }
+ if (!r.dimensionKey) {
+ continue;
+ }
// Sanitize dimensionKey to remove null bytes that PostgreSQL can't handle
r.dimensionKey = sanitizeForPostgres(r.dimensionKey);
// 3) gate noise
- if (!passesThresholds(r, mod, config)) continue;
+ if (!passesThresholds(r, mod, config)) {
+ continue;
+ }
// 4) score
const impact = mod.score
diff --git a/packages/db/src/services/insights/index.ts b/packages/core/src/modules/insight/src/insight-modules.ts
similarity index 100%
rename from packages/db/src/services/insights/index.ts
rename to packages/core/src/modules/insight/src/insight-modules.ts
index 2d6065044..8c1a7b533 100644
--- a/packages/db/src/services/insights/index.ts
+++ b/packages/core/src/modules/insight/src/insight-modules.ts
@@ -1,8 +1,8 @@
-export * from './types';
-export * from './windows';
-export * from './scoring';
-export * from './material';
export * from './engine';
+export * from './material';
+export * from './modules';
+export * from './scoring';
export * from './store';
+export * from './types';
export * from './utils';
-export * from './modules';
+export * from './windows';
diff --git a/packages/db/src/services/insights.service.ts b/packages/core/src/modules/insight/src/legacy-scan.ts
similarity index 93%
rename from packages/db/src/services/insights.service.ts
rename to packages/core/src/modules/insight/src/legacy-scan.ts
index 8778da4c1..efa806f0d 100644
--- a/packages/db/src/services/insights.service.ts
+++ b/packages/core/src/modules/insight/src/legacy-scan.ts
@@ -1,5 +1,5 @@
import type { ClickHouseClient } from '@clickhouse/client';
-import { clix } from '../clickhouse/query-builder';
+import { clix } from '@openpanel/db/src/clickhouse/query-builder';
export interface Insight {
type: string;
@@ -70,7 +70,7 @@ interface EventCompletionResult {
}
export class InsightsService {
- constructor(private client: ClickHouseClient) {}
+ constructor(private readonly client: ClickHouseClient) {}
private async getTrafficSpikes(projectId: string): Promise<Insight[]> {
const query = clix(this.client)
@@ -84,7 +84,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.groupBy(['referrer_name', 'date'])
@@ -110,7 +110,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.groupBy(['date'])
@@ -136,7 +136,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 60 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 60 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.where('is_new', '=', true)
@@ -153,7 +153,7 @@ export class InsightsService {
}
private async getReferralSourceHighlights(
- projectId: string,
+ projectId: string
): Promise<Insight[]> {
const query = clix(this.client)
.select([
@@ -177,7 +177,7 @@ export class InsightsService {
}
private async getSessionDurationChanges(
- projectId: string,
+ projectId: string
): Promise<Insight[]> {
const query = clix(this.client)
.select([
@@ -189,7 +189,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 14 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 14 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.groupBy(['week'])
@@ -215,7 +215,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.groupBy(['path'])
@@ -231,7 +231,7 @@ export class InsightsService {
}
private async getBounceRateImprovements(
- projectId: string,
+ projectId: string
): Promise<Insight[]> {
const query = clix(this.client)
.select([
@@ -243,7 +243,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 60 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 60 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.groupBy(['month'])
@@ -259,7 +259,7 @@ export class InsightsService {
}
private async getReturningVisitorTrends(
- projectId: string,
+ projectId: string
): Promise<Insight[]> {
const query = clix(this.client)
.select([
@@ -271,7 +271,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 180 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 180 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.where('is_returning', '=', true)
@@ -288,7 +288,7 @@ export class InsightsService {
}
private async getGeographicInterestShifts(
- projectId: string,
+ projectId: string
): Promise<Insight[]> {
const query = clix(this.client)
.select([
@@ -300,7 +300,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 14 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 14 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.groupBy(['country', 'toWeek(created_at)'])
@@ -316,7 +316,7 @@ export class InsightsService {
}
private async getEventCompletionChanges(
- projectId: string,
+ projectId: string
): Promise<Insight[]> {
const query = clix(this.client)
.select([
@@ -329,7 +329,7 @@ export class InsightsService {
.where(
'created_at',
'>=',
- new Date(Date.now() - 60 * 24 * 60 * 60 * 1000),
+ new Date(Date.now() - 60 * 24 * 60 * 60 * 1000)
)
.where('project_id', '=', projectId)
.where('status', '=', 'completed')
@@ -384,10 +384,10 @@ export class InsightsService {
].sort((a, b) => {
// Sort by most recent data first
const dateA = new Date(
- a.data.date || a.data.month || a.data.week || a.data.quarter,
+ a.data.date || a.data.month || a.data.week || a.data.quarter
);
const dateB = new Date(
- b.data.date || b.data.month || b.data.week || b.data.quarter,
+ b.data.date || b.data.month || b.data.week || b.data.quarter
);
return dateB.getTime() - dateA.getTime();
});
diff --git a/packages/db/src/services/insights/material.ts b/packages/core/src/modules/insight/src/material.ts
similarity index 99%
rename from packages/db/src/services/insights/material.ts
rename to packages/core/src/modules/insight/src/material.ts
index 13699b319..96c66e064 100644
--- a/packages/db/src/services/insights/material.ts
+++ b/packages/core/src/modules/insight/src/material.ts
@@ -6,7 +6,7 @@ export function materialDecision(
next: {
changePct?: number;
direction?: 'up' | 'down' | 'flat';
- },
+ }
): MaterialDecision {
const nextBand = band(next.changePct);
if (!prev) {
diff --git a/packages/db/src/services/insights/modules/devices.module.ts b/packages/core/src/modules/insight/src/modules/devices.module.ts
similarity index 95%
rename from packages/db/src/services/insights/modules/devices.module.ts
rename to packages/core/src/modules/insight/src/modules/devices.module.ts
index 9afea524a..08a4806f6 100644
--- a/packages/db/src/services/insights/modules/devices.module.ts
+++ b/packages/core/src/modules/insight/src/modules/devices.module.ts
@@ -1,4 +1,7 @@
-import { TABLE_NAMES, formatClickhouseDate } from '../../../clickhouse/client';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
import type {
ComputeContext,
ComputeResult,
@@ -55,7 +58,7 @@ async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`,
+ `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -117,10 +120,10 @@ async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{
.select<{ device: string; cur: number; base: number }>([
'device',
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
),
])
.from(TABLE_NAMES.sessions)
@@ -136,10 +139,10 @@ async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number; base_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -155,13 +158,13 @@ async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
results,
(r) => r.device,
- (r) => Number(r.cur ?? 0),
+ (r) => Number(r.cur ?? 0)
);
const baselineMap = buildLookupMap(
results,
(r) => r.device,
- (r) => Number(r.base ?? 0),
+ (r) => Number(r.base ?? 0)
);
const totalCurrent = totals[0]?.cur_total ?? 0;
@@ -180,7 +183,7 @@ export const devicesModule: InsightModule = {
const topDims = selectTopDimensions(
currentMap,
baselineMap,
- this.thresholds?.maxDims ?? 5,
+ this.thresholds?.maxDims ?? 5
);
return topDims.map((dim) => `device:${dim}`);
},
@@ -191,7 +194,9 @@ export const devicesModule: InsightModule = {
const results: ComputeResult[] = [];
for (const dimKey of dimensionKeys) {
- if (!dimKey.startsWith('device:')) continue;
+ if (!dimKey.startsWith('device:')) {
+ continue;
+ }
const deviceType = dimKey.replace('device:', '');
const currentValue = currentMap.get(deviceType) ?? 0;
diff --git a/packages/db/src/services/insights/modules/entry-pages.module.ts b/packages/core/src/modules/insight/src/modules/entry-pages.module.ts
similarity index 95%
rename from packages/db/src/services/insights/modules/entry-pages.module.ts
rename to packages/core/src/modules/insight/src/modules/entry-pages.module.ts
index ea92df935..ecfbfd83e 100644
--- a/packages/db/src/services/insights/modules/entry-pages.module.ts
+++ b/packages/core/src/modules/insight/src/modules/entry-pages.module.ts
@@ -1,4 +1,7 @@
-import { TABLE_NAMES, formatClickhouseDate } from '../../../clickhouse/client';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
import type {
ComputeContext,
ComputeResult,
@@ -67,7 +70,7 @@ async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`,
+ `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -82,20 +85,20 @@ async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
currentResults,
- (r) => `${r.entry_origin || ''}${DELIMITER}${r.entry_path || '/'}`,
+ (r) => `${r.entry_origin || ''}${DELIMITER}${r.entry_path || '/'}`
);
const targetWeekday = getWeekday(ctx.window.start);
const baselineMap = computeWeekdayMedians(
baselineResults,
targetWeekday,
- (r) => `${r.entry_origin || ''}${DELIMITER}${r.entry_path || '/'}`,
+ (r) => `${r.entry_origin || ''}${DELIMITER}${r.entry_path || '/'}`
);
const totalCurrent = totals[0]?.cur_total ?? 0;
const totalBaseline = Array.from(baselineMap.values()).reduce(
(sum, val) => sum + val,
- 0,
+ 0
);
return { currentMap, baselineMap, totalCurrent, totalBaseline };
@@ -118,10 +121,10 @@ async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
'entry_origin',
'entry_path',
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
),
])
.from(TABLE_NAMES.sessions)
@@ -137,10 +140,10 @@ async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number; base_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -156,13 +159,13 @@ async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
results,
(r) => `${r.entry_origin || ''}${DELIMITER}${r.entry_path || '/'}`,
- (r) => Number(r.cur ?? 0),
+ (r) => Number(r.cur ?? 0)
);
const baselineMap = buildLookupMap(
results,
(r) => `${r.entry_origin || ''}${DELIMITER}${r.entry_path || '/'}`,
- (r) => Number(r.base ?? 0),
+ (r) => Number(r.base ?? 0)
);
const totalCurrent = totals[0]?.cur_total ?? 0;
@@ -181,7 +184,7 @@ export const entryPagesModule: InsightModule = {
const topDims = selectTopDimensions(
currentMap,
baselineMap,
- this.thresholds?.maxDims ?? 100,
+ this.thresholds?.maxDims ?? 100
);
return topDims.map((dim) => `entry:${dim}`);
},
@@ -192,7 +195,9 @@ export const entryPagesModule: InsightModule = {
const results: ComputeResult[] = [];
for (const dimKey of dimensionKeys) {
- if (!dimKey.startsWith('entry:')) continue;
+ if (!dimKey.startsWith('entry:')) {
+ continue;
+ }
const originPath = dimKey.replace('entry:', '');
const currentValue = currentMap.get(originPath) ?? 0;
diff --git a/packages/db/src/services/insights/modules/geo.module.ts b/packages/core/src/modules/insight/src/modules/geo.module.ts
similarity index 93%
rename from packages/db/src/services/insights/modules/geo.module.ts
rename to packages/core/src/modules/insight/src/modules/geo.module.ts
index e848507f6..3b750578a 100644
--- a/packages/db/src/services/insights/modules/geo.module.ts
+++ b/packages/core/src/modules/insight/src/modules/geo.module.ts
@@ -1,5 +1,8 @@
import { getCountry } from '@openpanel/constants';
-import { TABLE_NAMES, formatClickhouseDate } from '../../../clickhouse/client';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
import type {
ComputeContext,
ComputeResult,
@@ -59,7 +62,7 @@ async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`,
+ `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -74,20 +77,20 @@ async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
currentResults,
- (r) => r.country || 'unknown',
+ (r) => r.country || 'unknown'
);
const targetWeekday = getWeekday(ctx.window.start);
const baselineMap = computeWeekdayMedians(
baselineResults,
targetWeekday,
- (r) => r.country || 'unknown',
+ (r) => r.country || 'unknown'
);
const totalCurrent = totals[0]?.cur_total ?? 0;
const totalBaseline = Array.from(baselineMap.values()).reduce(
(sum, val) => sum + val,
- 0,
+ 0
);
return { currentMap, baselineMap, totalCurrent, totalBaseline };
@@ -104,10 +107,10 @@ async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
.select<{ country: string; cur: number; base: number }>([
'country',
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
),
])
.from(TABLE_NAMES.sessions)
@@ -123,10 +126,10 @@ async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number; base_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -142,13 +145,13 @@ async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
results,
(r) => r.country || 'unknown',
- (r) => Number(r.cur ?? 0),
+ (r) => Number(r.cur ?? 0)
);
const baselineMap = buildLookupMap(
results,
(r) => r.country || 'unknown',
- (r) => Number(r.base ?? 0),
+ (r) => Number(r.base ?? 0)
);
const totalCurrent = totals[0]?.cur_total ?? 0;
@@ -167,7 +170,7 @@ export const geoModule: InsightModule = {
const topDims = selectTopDimensions(
currentMap,
baselineMap,
- this.thresholds?.maxDims ?? 30,
+ this.thresholds?.maxDims ?? 30
);
return topDims.map((dim) => `country:${dim}`);
},
@@ -178,7 +181,9 @@ export const geoModule: InsightModule = {
const results: ComputeResult[] = [];
for (const dimKey of dimensionKeys) {
- if (!dimKey.startsWith('country:')) continue;
+ if (!dimKey.startsWith('country:')) {
+ continue;
+ }
const country = dimKey.replace('country:', '');
const currentValue = currentMap.get(country) ?? 0;
@@ -232,9 +237,7 @@ export const geoModule: InsightModule = {
displayName,
payload: {
kind: 'insight_v1',
- dimensions: [
- { key: 'country', value: country, displayName: displayName },
- ],
+ dimensions: [{ key: 'country', value: country, displayName }],
primaryMetric: 'sessions',
metrics: {
sessions: {
diff --git a/packages/db/src/services/insights/modules/index.ts b/packages/core/src/modules/insight/src/modules/index.ts
similarity index 100%
rename from packages/db/src/services/insights/modules/index.ts
rename to packages/core/src/modules/insight/src/modules/index.ts
index 72b451470..074110dea 100644
--- a/packages/db/src/services/insights/modules/index.ts
+++ b/packages/core/src/modules/insight/src/modules/index.ts
@@ -1,5 +1,5 @@
-export { referrersModule } from './referrers.module';
+export { devicesModule } from './devices.module';
export { entryPagesModule } from './entry-pages.module';
-export { pageTrendsModule } from './page-trends.module';
export { geoModule } from './geo.module';
-export { devicesModule } from './devices.module';
+export { pageTrendsModule } from './page-trends.module';
+export { referrersModule } from './referrers.module';
diff --git a/packages/db/src/services/insights/modules/page-trends.module.ts b/packages/core/src/modules/insight/src/modules/page-trends.module.ts
similarity index 94%
rename from packages/db/src/services/insights/modules/page-trends.module.ts
rename to packages/core/src/modules/insight/src/modules/page-trends.module.ts
index 483630076..b1ecf4422 100644
--- a/packages/db/src/services/insights/modules/page-trends.module.ts
+++ b/packages/core/src/modules/insight/src/modules/page-trends.module.ts
@@ -1,4 +1,7 @@
-import { TABLE_NAMES, formatClickhouseDate } from '../../../clickhouse/client';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
import type {
ComputeContext,
ComputeResult,
@@ -62,7 +65,7 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`,
+ `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
),
])
.from(TABLE_NAMES.events)
@@ -77,20 +80,20 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
currentResults,
- (r) => `${r.origin || ''}${DELIMITER}${r.path || '/'}`,
+ (r) => `${r.origin || ''}${DELIMITER}${r.path || '/'}`
);
const targetWeekday = getWeekday(ctx.window.start);
const baselineMap = computeWeekdayMedians(
baselineResults,
targetWeekday,
- (r) => `${r.origin || ''}${DELIMITER}${r.path || '/'}`,
+ (r) => `${r.origin || ''}${DELIMITER}${r.path || '/'}`
);
const totalCurrent = totals[0]?.cur_total ?? 0;
const totalBaseline = Array.from(baselineMap.values()).reduce(
(sum, val) => sum + val,
- 0,
+ 0
);
return { currentMap, baselineMap, totalCurrent, totalBaseline };
@@ -108,10 +111,10 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
'origin',
'path',
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
),
])
.from(TABLE_NAMES.events)
@@ -127,10 +130,10 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number; base_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
),
])
.from(TABLE_NAMES.events)
@@ -146,13 +149,13 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
results,
(r) => `${r.origin || ''}${DELIMITER}${r.path || '/'}`,
- (r) => Number(r.cur ?? 0),
+ (r) => Number(r.cur ?? 0)
);
const baselineMap = buildLookupMap(
results,
(r) => `${r.origin || ''}${DELIMITER}${r.path || '/'}`,
- (r) => Number(r.base ?? 0),
+ (r) => Number(r.base ?? 0)
);
const totalCurrent = totals[0]?.cur_total ?? 0;
@@ -178,7 +181,7 @@ export const pageTrendsModule: InsightModule = {
const topDims = selectTopDimensions(
currentMap,
baselineMap,
- this.thresholds?.maxDims ?? 100,
+ this.thresholds?.maxDims ?? 100
);
return topDims.map((dim) => `page:${dim}`);
},
@@ -189,7 +192,9 @@ export const pageTrendsModule: InsightModule = {
const results: ComputeResult[] = [];
for (const dimKey of dimensionKeys) {
- if (!dimKey.startsWith('page:')) continue;
+ if (!dimKey.startsWith('page:')) {
+ continue;
+ }
const originPath = dimKey.replace('page:', '');
const pageviewsCurrent = currentMap.get(originPath) ?? 0;
@@ -202,8 +207,8 @@ export const pageTrendsModule: InsightModule = {
// Use share values in basis points (100 = 1%) for thresholding
// This makes thresholds intuitive: minAbsDelta=50 means 0.5pp shift
- const currentShareBp = currentShare * 10000;
- const compareShareBp = compareShare * 10000;
+ const currentShareBp = currentShare * 10_000;
+ const compareShareBp = compareShare * 10_000;
const shareShiftPp = (currentShare - compareShare) * 100;
// changePct is relative change in share, not absolute pageviews
diff --git a/packages/db/src/services/insights/modules/referrers.module.ts b/packages/core/src/modules/insight/src/modules/referrers.module.ts
similarity index 94%
rename from packages/db/src/services/insights/modules/referrers.module.ts
rename to packages/core/src/modules/insight/src/modules/referrers.module.ts
index 2b9d4efd0..18ad10fe8 100644
--- a/packages/db/src/services/insights/modules/referrers.module.ts
+++ b/packages/core/src/modules/insight/src/modules/referrers.module.ts
@@ -1,4 +1,7 @@
-import { TABLE_NAMES, formatClickhouseDate } from '../../../clickhouse/client';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
import type {
ComputeContext,
ComputeResult,
@@ -58,7 +61,7 @@ async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`,
+ `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -73,20 +76,20 @@ async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
currentResults,
- (r) => r.referrer_name || 'direct',
+ (r) => r.referrer_name || 'direct'
);
const targetWeekday = getWeekday(ctx.window.start);
const baselineMap = computeWeekdayMedians(
baselineResults,
targetWeekday,
- (r) => r.referrer_name || 'direct',
+ (r) => r.referrer_name || 'direct'
);
const totalCurrent = totals[0]?.cur_total ?? 0;
const totalBaseline = Array.from(baselineMap.values()).reduce(
(sum, val) => sum + val,
- 0,
+ 0
);
return { currentMap, baselineMap, totalCurrent, totalBaseline };
@@ -103,10 +106,10 @@ async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
.select<{ referrer_name: string; cur: number; base: number }>([
'referrer_name',
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
),
])
.from(TABLE_NAMES.sessions)
@@ -122,10 +125,10 @@ async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
.clix()
.select<{ cur_total: number; base_total: number }>([
ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`,
+ `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
),
ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`,
+ `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
),
])
.from(TABLE_NAMES.sessions)
@@ -141,13 +144,13 @@ async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
const currentMap = buildLookupMap(
results,
(r) => r.referrer_name || 'direct',
- (r) => Number(r.cur ?? 0),
+ (r) => Number(r.cur ?? 0)
);
const baselineMap = buildLookupMap(
results,
(r) => r.referrer_name || 'direct',
- (r) => Number(r.base ?? 0),
+ (r) => Number(r.base ?? 0)
);
const totalCurrent = totals[0]?.cur_total ?? 0;
@@ -166,7 +169,7 @@ export const referrersModule: InsightModule = {
const topDims = selectTopDimensions(
currentMap,
baselineMap,
- this.thresholds?.maxDims ?? 50,
+ this.thresholds?.maxDims ?? 50
);
return topDims.map((dim) => `referrer:${dim}`);
},
@@ -177,7 +180,9 @@ export const referrersModule: InsightModule = {
const results: ComputeResult[] = [];
for (const dimKey of dimensionKeys) {
- if (!dimKey.startsWith('referrer:')) continue;
+ if (!dimKey.startsWith('referrer:')) {
+ continue;
+ }
const referrerName = dimKey.replace('referrer:', '');
const currentValue = currentMap.get(referrerName) ?? 0;
diff --git a/packages/db/src/services/referrer-spikes.service.ts b/packages/core/src/modules/insight/src/referrer-spikes.ts
similarity index 92%
rename from packages/db/src/services/referrer-spikes.service.ts
rename to packages/core/src/modules/insight/src/referrer-spikes.ts
index a5092add7..1166471b1 100644
--- a/packages/db/src/services/referrer-spikes.service.ts
+++ b/packages/core/src/modules/insight/src/referrer-spikes.ts
@@ -1,11 +1,13 @@
-import type { IChartEventFilter, IInterval } from '@openpanel/validation';
import {
- TABLE_NAMES,
ch,
convertClickhouseDateToJs,
-} from '../clickhouse/client';
-import { clix } from '../clickhouse/query-builder';
-import { overviewService } from './overview.service';
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
+import { clix } from '@openpanel/db/src/clickhouse/query-builder';
+// `overview` hasn't moved to core yet (a later wave) — deep-imported like the
+// rest of @openpanel/db's internals until it does.
+import { overviewService } from '@openpanel/db/src/services/overview.service';
+import type { IChartEventFilter, IInterval } from '@openpanel/validation';
// Spike detection thresholds. Conservative defaults — markers should be rare
// and obviously meaningful when they appear. Tune here if real usage shows
@@ -71,7 +73,7 @@ export interface GetReferrerSpikesInput {
}
export async function getReferrerSpikes(
- input: GetReferrerSpikesInput,
+ input: GetReferrerSpikesInput
): Promise<ReferrerSpikeCluster[]> {
const { projectId, filters, startDate, endDate, interval, timezone } = input;
const filtersWhere = overviewService.getRawWhereClause('sessions', filters);
@@ -158,7 +160,7 @@ export async function getReferrerSpikes(
}
const bucketTotalByDate = new Map(
- bucketTotalRows.map((r) => [r.date, r.total]),
+ bucketTotalRows.map((r) => [r.date, r.total])
);
const rowsByReferrer = new Map<
@@ -190,15 +192,19 @@ export async function getReferrerSpikes(
const p75 = percentile(sorted, 0.75);
const ratioThreshold = Math.max(
median * RATIO_MULTIPLIER,
- p75 * P75_MULTIPLIER,
+ p75 * P75_MULTIPLIER
);
for (const row of rows) {
- if (row.sessions < MIN_SESSIONS_FLOOR) continue;
+ if (row.sessions < MIN_SESSIONS_FLOOR) {
+ continue;
+ }
const total = bucketTotalByDate.get(row.date) ?? row.sessions;
const share = total > 0 ? row.sessions / total : 0;
- if (share < MIN_SHARE) continue;
+ if (share < MIN_SHARE) {
+ continue;
+ }
const baseline = isNewReferrer ? 0 : median;
const ratio = isNewReferrer
@@ -206,7 +212,9 @@ export async function getReferrerSpikes(
: row.sessions / Math.max(median, 1);
const isSpike = isNewReferrer || row.sessions >= ratioThreshold;
- if (!isSpike) continue;
+ if (!isSpike) {
+ continue;
+ }
candidates.push({
date: row.date,
@@ -239,7 +247,9 @@ export async function getReferrerSpikes(
for (const [date, arr] of byBucket) {
arr.sort((a, b) => b.score - a.score);
const top = arr[0];
- if (!top) continue;
+ if (!top) {
+ continue;
+ }
perBucketSpikes.push({
date,
top,
@@ -290,12 +300,18 @@ export async function getReferrerSpikes(
}
function percentile(sortedAsc: number[], p: number): number {
- if (sortedAsc.length === 0) return 0;
- if (sortedAsc.length === 1) return sortedAsc[0]!;
+ if (sortedAsc.length === 0) {
+ return 0;
+ }
+ if (sortedAsc.length === 1) {
+ return sortedAsc[0]!;
+ }
const idx = (sortedAsc.length - 1) * p;
const lo = Math.floor(idx);
const hi = Math.ceil(idx);
- if (lo === hi) return sortedAsc[lo]!;
+ if (lo === hi) {
+ return sortedAsc[lo]!;
+ }
return sortedAsc[lo]! * (hi - idx) + sortedAsc[hi]! * (idx - lo);
}
diff --git a/packages/db/src/services/insights/scoring.ts b/packages/core/src/modules/insight/src/scoring.ts
similarity index 75%
rename from packages/db/src/services/insights/scoring.ts
rename to packages/core/src/modules/insight/src/scoring.ts
index 7aff4a615..59a72ec0a 100644
--- a/packages/db/src/services/insights/scoring.ts
+++ b/packages/core/src/modules/insight/src/scoring.ts
@@ -8,11 +8,17 @@ export function defaultImpactScore(r: ComputeResult): number {
}
export function severityBand(
- changePct?: number | null,
+ changePct?: number | null
): 'low' | 'moderate' | 'severe' | null {
const p = Math.abs(changePct ?? 0);
- if (p < 0.1) return null;
- if (p < 0.5) return 'low';
- if (p < 1) return 'moderate';
+ if (p < 0.1) {
+ return null;
+ }
+ if (p < 0.5) {
+ return 'low';
+ }
+ if (p < 1) {
+ return 'moderate';
+ }
return 'severe';
}
diff --git a/packages/db/src/services/insights/store.ts b/packages/core/src/modules/insight/src/store.ts
similarity index 92%
rename from packages/db/src/services/insights/store.ts
rename to packages/core/src/modules/insight/src/store.ts
index 8f57787aa..26705ab93 100644
--- a/packages/db/src/services/insights/store.ts
+++ b/packages/core/src/modules/insight/src/store.ts
@@ -1,15 +1,15 @@
-import { Prisma, db } from '../../prisma-client';
+import { db, Prisma } from '@openpanel/db/src/prisma-client';
import type {
Cadence,
InsightStore,
PersistedInsight,
- RenderedCard,
WindowKind,
- WindowRange,
} from './types';
export const insightStore: InsightStore = {
- async listProjectIdsForCadence(cadence: Cadence): Promise<string[]> {
+ // `cadence` isn't read — there is only one today ('daily') — but it stays
+ // on the signature because InsightStore's contract names it (V1 parity).
+ async listProjectIdsForCadence(_cadence: Cadence): Promise<string[]> {
const projects = await db.project.findMany({
where: {
deleteAt: null,
@@ -48,7 +48,9 @@ export const insightStore: InsightStore = {
},
});
- if (!insight) return null;
+ if (!insight) {
+ return null;
+ }
return {
id: insight.id,
@@ -176,12 +178,12 @@ export const insightStore: InsightStore = {
};
},
+ // projectId/moduleKey/dimensionKey/windowKind aren't persisted here — the
+ // insight_events row is scoped by insightId alone, they're derivable from
+ // the parent (V1 parity) — but the engine passes them for identity/logging
+ // symmetry with the store's other methods, so they stay on the signature.
async insertEvent({
- projectId,
insightId,
- moduleKey,
- dimensionKey,
- windowKind,
eventKind,
changeFrom,
changeTo,
diff --git a/packages/db/src/services/insights/types.ts b/packages/core/src/modules/insight/src/types.ts
similarity index 96%
rename from packages/db/src/services/insights/types.ts
rename to packages/core/src/modules/insight/src/types.ts
index 7e6cc1f7e..5dd9983b2 100644
--- a/packages/db/src/services/insights/types.ts
+++ b/packages/core/src/modules/insight/src/types.ts
@@ -1,9 +1,4 @@
-import type {
- InsightDimension,
- InsightMetricEntry,
- InsightMetricKey,
- InsightPayload,
-} from '@openpanel/validation';
+import type { InsightPayload } from '@openpanel/validation';
export type Cadence = 'daily';
@@ -78,7 +73,7 @@ export interface InsightModule {
/** Preferred path: batch compute many dimensions in one go. */
computeMany(
ctx: ComputeContext,
- dimensionKeys: string[],
+ dimensionKeys: string[]
): Promise<ComputeResult[]>;
/** Must not do DB reads; just format output. */
render(result: ComputeResult, ctx: ComputeContext): RenderedCard;
@@ -87,7 +82,7 @@ export interface InsightModule {
/** Optional: compute "drivers" for AI explain step */
drivers?(
result: ComputeResult,
- ctx: ComputeContext,
+ ctx: ComputeContext
): Promise<Record<string, unknown>>;
}
diff --git a/packages/db/src/services/insights/utils.ts b/packages/core/src/modules/insight/src/utils.ts
similarity index 91%
rename from packages/db/src/services/insights/utils.ts
rename to packages/core/src/modules/insight/src/utils.ts
index 3dc5eb578..60330a506 100644
--- a/packages/db/src/services/insights/utils.ts
+++ b/packages/core/src/modules/insight/src/utils.ts
@@ -13,7 +13,9 @@ export function getWeekday(date: Date): number {
* Compute median of a sorted array of numbers
*/
export function computeMedian(sortedValues: number[]): number {
- if (sortedValues.length === 0) return 0;
+ if (sortedValues.length === 0) {
+ return 0;
+ }
const mid = Math.floor(sortedValues.length / 2);
return sortedValues.length % 2 === 0
? ((sortedValues[mid - 1] ?? 0) + (sortedValues[mid] ?? 0)) / 2
@@ -32,14 +34,16 @@ export function computeMedian(sortedValues: number[]): number {
export function computeWeekdayMedians<T>(
data: T[],
targetWeekday: number,
- getDimension: (row: T) => string,
+ getDimension: (row: T) => string
): Map<string, number> {
// Group by dimension, filtered to target weekday
const byDimension = new Map<string, number[]>();
for (const row of data) {
const rowWeekday = getWeekday(new Date((row as any).date));
- if (rowWeekday !== targetWeekday) continue;
+ if (rowWeekday !== targetWeekday) {
+ continue;
+ }
const dim = getDimension(row);
const values = byDimension.get(dim) ?? [];
@@ -62,7 +66,7 @@ export function computeWeekdayMedians<T>(
*/
export function computeChangePct(
currentValue: number,
- compareValue: number,
+ compareValue: number
): number {
return compareValue > 0
? (currentValue - compareValue) / compareValue
@@ -76,7 +80,7 @@ export function computeChangePct(
*/
export function computeDirection(
changePct: number,
- threshold = 0.05,
+ threshold = 0.05
): 'up' | 'down' | 'flat' {
return changePct > threshold
? 'up'
@@ -107,7 +111,7 @@ export function getEndOfDay(date: Date): Date {
export function buildLookupMap<T>(
results: T[],
getKey: (row: T) => string,
- getCount: (row: T) => number = (row) => Number((row as any).cnt ?? 0),
+ getCount: (row: T) => number = (row) => Number((row as any).cnt ?? 0)
): Map<string, number> {
const map = new Map<string, number>();
for (const row of results) {
@@ -130,12 +134,16 @@ export function buildLookupMap<T>(
export function selectTopDimensions(
currentMap: Map<string, number>,
baselineMap: Map<string, number>,
- maxDims: number,
+ maxDims: number
): string[] {
// Merge all dimensions from both maps
const allDims = new Set<string>();
- for (const dim of currentMap.keys()) allDims.add(dim);
- for (const dim of baselineMap.keys()) allDims.add(dim);
+ for (const dim of currentMap.keys()) {
+ allDims.add(dim);
+ }
+ for (const dim of baselineMap.keys()) {
+ allDims.add(dim);
+ }
// Rank by greatest(current, baseline)
const ranked = Array.from(allDims)
diff --git a/packages/db/src/services/insights/windows.ts b/packages/core/src/modules/insight/src/windows.ts
similarity index 100%
rename from packages/db/src/services/insights/windows.ts
rename to packages/core/src/modules/insight/src/windows.ts
diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.ts
index 650977c74..317665686 100644
--- a/packages/core/src/rpc.router.ts
+++ b/packages/core/src/rpc.router.ts
@@ -5,10 +5,12 @@
// land with their module waves (P5-P8).
import { healthRouter } from './modules/health/health.rpc';
+import { insightRouter } from './modules/insight/insight.rpc';
import { createTRPCRouter } from './rpc/base';
export const appRouter = createTRPCRouter({
health: healthRouter,
+ insight: insightRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts
index 25c7b80c0..2c049de16 100644
--- a/packages/core/src/services.ts
+++ b/packages/core/src/services.ts
@@ -7,6 +7,10 @@ import {
type AuthService,
createAuthService,
} from './modules/auth/auth.service';
+import {
+ createInsightService,
+ type InsightService,
+} from './modules/insight/insight.service';
/** What every service factory receives — derived from Ctx, so it cannot drift. */
export type ServiceDeps = Pick<
@@ -25,6 +29,7 @@ export type ServiceDeps = Pick<
// typecheck fails with ts7022/ts7023 naming the method.
export interface Services {
auth: AuthService;
+ insight: InsightService;
}
export function createServices(deps: ServiceDeps): Services {
@@ -33,5 +38,6 @@ export function createServices(deps: ServiceDeps): Services {
// call each other without a cycle.
return {
auth: createAuthService(deps),
+ insight: createInsightService(deps),
};
}
diff --git a/packages/db/index.ts b/packages/db/index.ts
index ea5ab01d4..de55fe19f 100644
--- a/packages/db/index.ts
+++ b/packages/db/index.ts
@@ -24,7 +24,6 @@ export * from './src/services/group.service';
export * from './src/services/gsc.service';
export * from './src/services/id.service';
export * from './src/services/import.service';
-export * from './src/services/insights';
export * from './src/services/notification.service';
export * from './src/services/organization.service';
export * from './src/services/overview.service';
@@ -32,7 +31,6 @@ export * from './src/services/pages.service';
export * from './src/services/profile.service';
export * from './src/services/project.service';
export * from './src/services/reference.service';
-export * from './src/services/referrer-spikes.service';
export * from './src/services/registration.service';
export * from './src/services/reports.service';
export * from './src/services/retention.service';
diff --git a/packages/trpc/src/routers/insight.ts b/packages/trpc/src/routers/insight.ts
index d9edaef7e..b0d398235 100644
--- a/packages/trpc/src/routers/insight.ts
+++ b/packages/trpc/src/routers/insight.ts
@@ -1,10 +1,12 @@
-import { generateInsightExplanation } from '@openpanel/core';
-import {
- db,
- getSegmentDailySeriesCore,
- getTrafficBreakdownCore,
-} from '@openpanel/db';
-import { getRedisCache } from '@openpanel/redis';
+// Dissolved into @openpanel/core's insight module (M5-001): the business
+// logic — the query/detection engine, the AI enrich/explain/narrative calls,
+// the digest and cleanup jobs — moved to
+// packages/core/src/modules/insight/insight.service.ts. This router stays
+// (DELEGATE PATTERN): it keeps V1's protectedProcedure stack (session/access/
+// logger/rate-limit middleware) untouched and delegates each handler body to
+// the core service.
+import { explainInsight, listAllInsights, listInsights } from '@openpanel/core';
+import { db } from '@openpanel/db';
import type { InsightPayload } from '@openpanel/validation';
import { z } from 'zod';
import { getProjectAccess, requireProjectAccess } from '../access';
@@ -12,10 +14,6 @@ import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
const DAY_MS = 24 * 60 * 60 * 1000;
-// The explanation is a paid LLM call. Cache it keyed by the insight's
-// lastUpdatedAt so repeat clicks within the window are free, while any recompute
-// that changes the insight produces a new key and a fresh explanation.
-const EXPLAIN_CACHE_TTL_SEC = 24 * 60 * 60;
const EXPLAIN_COLUMNS = [
'referrer_name',
'country',
@@ -44,16 +42,9 @@ export const insightRouter = createTRPCRouter({
// Fetch more insights than needed to account for deduplication.
// AI relevanceScore leads (un-enriched insights sort last via nulls:last),
// with the statistical impactScore as the tiebreaker / fallback.
- const allInsights = await db.projectInsight.findMany({
- where: {
- projectId,
- state: 'active',
- },
- orderBy: [
- { relevanceScore: { sort: 'desc', nulls: 'last' } },
- { impactScore: 'desc' },
- ],
- take: limit * 3, // Fetch 3x to account for deduplication
+ const allInsights = await listInsights({
+ projectId,
+ limit: limit * 3,
});
// WindowKind priority: yesterday (1) > rolling_7d (2) > rolling_30d (3)
@@ -110,19 +101,7 @@ export const insightRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this project');
}
- const insights = await db.projectInsight.findMany({
- where: {
- projectId,
- state: 'active',
- },
- orderBy: [
- { relevanceScore: { sort: 'desc', nulls: 'last' } },
- { impactScore: 'desc' },
- ],
- take: limit,
- });
-
- return insights;
+ return listAllInsights({ projectId, limit });
}),
// Phase 5: the "why". Decompose the insight's change across referrer/country/
@@ -156,16 +135,6 @@ export const insightRouter = createTRPCRouter({
level: 'read',
});
- // Serve a cached explanation if the insight hasn't changed since we
- // computed it. Skips both the ClickHouse queries and the LLM call.
- const cacheKey = `insight-explain:${insightId}:${insight.lastUpdatedAt.getTime()}`;
- const cached = await getRedisCache().get(cacheKey);
- if (cached) {
- return JSON.parse(cached) as Awaited<
- ReturnType<typeof generateInsightExplanation>
- >;
- }
-
// Current window from the insight; baseline = same span immediately before.
const end = insight.windowEnd ?? new Date();
const start = insight.windowStart ?? new Date(end.getTime() - 7 * DAY_MS);
@@ -174,6 +143,9 @@ export const insightRouter = createTRPCRouter({
const baseStart = new Date(start.getTime() - spanMs);
const iso = (d: Date) => d.toISOString();
+ const { getSegmentDailySeriesCore, getTrafficBreakdownCore } =
+ await import('@openpanel/db');
+
const breakdowns = await Promise.all(
EXPLAIN_COLUMNS.map(async (column) => {
const [cur, base] = await Promise.all([
@@ -260,31 +232,26 @@ export const insightRouter = createTRPCRouter({
select: { title: true, date: true },
});
- const explanation = await generateInsightExplanation({
- insight: {
- title: insight.aiSummary ?? insight.title,
- dimension: insight.dimensionKey,
- window: insight.windowKind,
- summary: insight.summary ?? undefined,
- },
- dailySeries,
- breakdowns,
- references: references.map((r) => ({
- title: r.title,
- date: r.date.toISOString().slice(0, 10),
- })),
- });
-
- // Only cache a successful explanation — a null is a transient LLM failure
- // and should be retried on the next click.
- if (explanation) {
- await getRedisCache().setex(
- cacheKey,
- EXPLAIN_CACHE_TTL_SEC,
- JSON.stringify(explanation)
- );
- }
+ // `explainInsight` owns the cache-aside (keyed by insight id +
+ // lastUpdatedAt, so a recompute invalidates it automatically).
+ const cacheKey = `insight-explain:${insightId}:${insight.lastUpdatedAt.getTime()}`;
- return explanation;
+ return explainInsight(
+ {
+ insight: {
+ title: insight.aiSummary ?? insight.title,
+ dimension: insight.dimensionKey,
+ window: insight.windowKind,
+ summary: insight.summary ?? undefined,
+ },
+ dailySeries,
+ breakdowns,
+ references: references.map((r) => ({
+ title: r.title,
+ date: r.date.toISOString().slice(0, 10),
+ })),
+ },
+ cacheKey
+ );
}),
});
diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.ts
index 0bb74a47e..bce44f13b 100644
--- a/packages/trpc/src/routers/overview.ts
+++ b/packages/trpc/src/routers/overview.ts
@@ -1,3 +1,5 @@
+// Dissolved into @openpanel/core's insight module (M5-001).
+import { getReferrerSpikes } from '@openpanel/core';
import {
ch,
clix,
@@ -6,7 +8,6 @@ import {
getChartStartEndDate,
getConversionEventNames,
getOrganizationSubscriptionChartEndDate,
- getReferrerSpikes,
getSettingsForProject,
overviewService,
TABLE_NAMES,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e9bfb9a9d..ed9ddc735 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1114,9 +1114,18 @@ importers:
'@openpanel/common':
specifier: workspace:*
version: link:../common
+ '@openpanel/constants':
+ specifier: workspace:*
+ version: link:../constants
+ '@openpanel/db':
+ specifier: workspace:*
+ version: link:../db
'@openpanel/email':
specifier: workspace:*
version: link:../email
+ '@openpanel/redis':
+ specifier: workspace:*
+ version: link:../redis
'@openpanel/validation':
specifier: workspace:*
version: link:../validation
@@ -1181,9 +1190,9 @@ importers:
specifier: 'catalog:'
version: 4.3.6
devDependencies:
- '@openpanel/db':
- specifier: workspace:*
- version: link:../db
+ '@clickhouse/client':
+ specifier: ^1.18.5
+ version: 1.18.5
'@openpanel/tsconfig':
specifier: workspace:*
version: link:../../tooling/typescript