OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
chore(core): trim comments in the remaining modules
Carl-Gerhard Lindesvärdf70da9489aef
diff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.tsindex 37b57abc7..cb96dde82 100644--- a/packages/core/src/modules/assistant/assistant.constants.ts+++ b/packages/core/src/modules/assistant/assistant.constants.ts@@ -1,18 +1,5 @@import { z } from 'zod';-/**- * The full `ChatApp` type (Better Agent's inferred app type) lives in- * `./src/app.ts` — it's `ReturnType<typeof createChatApp>` and inherently bound- * to the server-side agent definition, so it stays out of this constants file- * (a Prisma/Better-Agent type would follow it into a browser bundle). The- * frontend type-imports it from the core barrel instead- * (`apps/start/src/agents/client.ts`); see that file for why.- */--// ────────────────────────────────────────────────────────────────────-// Page context — "what the user is looking at right now"-// ────────────────────────────────────────────────────────────────────-export const pageContextPageSchema = z.enum(['overview','insights',@@ -60,12 +47,9 @@ export type PageContext = z.infer<typeof pageContextSchema>;export type PageContextPage = z.infer<typeof pageContextPageSchema>;/**- * Agent context shared by every agent. The client sends all three fields;- * `assistant.routes.ts` re-reads the body, checks the session user's access- * to (projectId, organizationId) and 403s a mismatch before handing the- * request to the agent — so tools may trust these values. That check is the- * module's ONLY tenancy gate: all 65 server tools use `context.projectId` as- * their key without re-checking it.+ * Agent context shared by every agent. `assistant.routes.ts` checks the session+ * user's access to (projectId, organizationId) before a run; that is the+ * module's only tenancy gate, so tools trust `context.projectId`.*/export const chatContextSchema = z.object({projectId: z.string(),@@ -75,13 +59,6 @@ export const chatContextSchema = z.object({export type ChatAgentContext = z.infer<typeof chatContextSchema>;-// ────────────────────────────────────────────────────────────────────-// Model whitelist — single source of truth, consumed by:-// - src/app.ts (builds an agent per entry)-// - apps/start (model picker)-// Adding a new model = add an entry here. No other changes required.-// ────────────────────────────────────────────────────────────────────-export type ChatProvider = 'OpenAI' | 'Anthropic';export type ChatModelEntry = {@@ -91,12 +68,7 @@ export type ChatModelEntry = {modelId: string;label: string;group: ChatProvider;- /**- * When true, the agent is configured with the provider's `reasoning`- * options so the model returns reasoning tokens as streamed text- * events. Only set this on reasoning-capable models (o-series,- * gpt-5 / gpt-5.x, etc.). Non-reasoning models reject the option.- */+ /** Only for reasoning-capable models; others reject the `reasoning` option. */reasoning?: boolean;};@@ -138,24 +110,15 @@ export const CHAT_MODELS = [export type ChatModelId = (typeof CHAT_MODELS)[number]['id'];/**- * localStorage key holding the user's preferred chat model id.- *- * Bumped to `v2` when the default was switched from `gpt-4-1` to- * `gpt-4-1-mini` (April 2026). Existing users had `gpt-4-1` pinned in- * their v1 key and hit rate-limit errors almost immediately on Tier 1- * OpenAI accounts; invalidating the old key is the only way to- * migrate them to the new default without a UI prompt. If you change- * the default again, bump the suffix.+ * localStorage key for the preferred chat model id. Bump the suffix when the+ * default changes: it invalidates models users had pinned (gpt-4-1 hit Tier 1+ * rate limits almost immediately).*/export const MODEL_STORAGE_KEY = 'op-chat-model-v2';/**- * Preferred default model id. The tRPC `chat.models` endpoint picks- * this when it's available in the configured provider set, falling- * back to the first entry in `CHAT_MODELS` otherwise. Picked for its- * much higher per-minute token budget (OpenAI Tier 1 gives gpt-4.1- * just 30k TPM — one user exhausts it with a single long turn —- * whereas gpt-4.1-mini gets 200k TPM for the same tier).+ * Preferred default model id when its provider is configured. gpt-4.1-mini has+ * a far higher per-minute token budget than gpt-4.1 on OpenAI Tier 1 (200k vs 30k TPM).*/export const PREFERRED_DEFAULT_MODEL_ID = 'gpt-4-1-mini';@@ -169,11 +132,7 @@ export function getModelLabel(id: string): string {return CHAT_MODELS.find((m) => m.id === id)?.label ?? id;}-/**- * Filter the whitelist to models whose provider has an API key configured.- * Returned in the same order as `CHAT_MODELS` (OpenAI first, then Anthropic)- * so the first entry is a stable default.- */+/** Models whose provider has an API key configured, in `CHAT_MODELS` order so the first entry is a stable default. */export function getAvailableChatModels(providers: {openai: boolean;anthropic: boolean;@@ -189,13 +148,6 @@ export function getAvailableChatModels(providers: {});}-// ────────────────────────────────────────────────────────────────────-// Client-side tool schemas — the three URL-param mutators the LLM can-// call on the page. Defined here because both the server (wraps them-// with `defineTool().client()`) and the client (types handler inputs)-// need the same Zod schema.-// ────────────────────────────────────────────────────────────────────-export const applyFiltersSchema = z.object({range: z.enum([@@ -296,16 +248,9 @@ export type SetEventNamesFilterInput = z.infer<>;/**- * Handler-map type for the client-side UI-mutator tools.- *- * Better Agent's `toolHandlers` expects each value to be- * `(input: unknown, ctx?: ...) => unknown`, so the input is typed as- * `unknown` here — the concrete handlers narrow with a cast using the- * matching `*Input` type exported above. The point of this type is- * the *key set*: adding a new `.client()` tool on the server surfaces- * an unused-property error here, forcing us to register a handler- * rather than silently returning undefined. It avoids the frontend- * needing to cross the app boundary for its handler typing.+ * Handler map for the client-side UI tools. Inputs are `unknown` to match Better+ * Agent's `toolHandlers`; the key set makes a new `.client()` tool fail to+ * compile until a handler is registered.*/export type ChatClientToolHandlers = {apply_filters: (input: unknown) => unknown | Promise<unknown>;diff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.tsindex 100972240..9fb9f57a7 100644--- a/packages/core/src/modules/assistant/assistant.routes.ts+++ b/packages/core/src/modules/assistant/assistant.routes.ts@@ -1,20 +1,8 @@-// Better Agent chat, mounted under `/ai/agents/*` inside `dashboardRoutes`-// (rest.routes.ts), which `apps/api/src/main.ts` mounts.-//-// Elysia has no adapter in `@better-agent/adapters` (only express/fastify), but-// `BetterAgentApp.handler` already speaks the Web `Request`/`Response` pair-// Elysia's own handlers do, so this route calls it directly instead of waiting-// on one. `parse: 'none'` is load-bearing, as on the /trpc mount in-// apps/api/src/main.ts: the global request-logging hook references `body`,-// which makes Elysia infer body parsing for every route and consume the stream-// before the handler runs; `request.clone` then throws "Body is disturbed or-// locked". With parsing off, the body is read via `request.clone` for the-// project-access check below and `chatApp.handler` gets the original,-// unconsumed `request` so it can re-read it itself.-//-// This route is where `deps` lives, so everything below it reaches-// Postgres/ClickHouse through `ctx` — the chat app, the conversation lookup and-// the access check included.+// `parse: 'none'` is load-bearing: the global request-logging hook references+// `body`, so Elysia would consume the stream before the handler runs and+// `request.clone` would throw "Body is disturbed or locked". With parsing off,+// the body is read via `request.clone` for the access check and+// `chatApp.handler` gets the original request to re-read itself.import { defineRoutes } from '../../http/define';import { getProjectAccess } from '../../shared/access-lookups';diff --git a/packages/core/src/modules/assistant/assistant.rpc.test.ts b/packages/core/src/modules/assistant/assistant.rpc.test.tsindex 9fbefab14..8456c6790 100644--- a/packages/core/src/modules/assistant/assistant.rpc.test.ts+++ b/packages/core/src/modules/assistant/assistant.rpc.test.ts@@ -1,8 +1,5 @@-// Only the "is anyone logged in" boundary and the deterministic model-list-// shape are exercised here — no LLM call, no database. `chat.models` reads-// only `ctx.config.ai` + the static whitelist (assistant.constants.ts);-// wiring the live-model whitelist against real provider keys is out of-// scope for a unit test — see assistant.rpc.ts's header.+// No LLM call and no database: `chat.models` reads only `ctx.config.ai` and the+// static whitelist.import { expect, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -19,7 +16,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex c3c0f0a9c..422144437 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -1,16 +1,6 @@-// The bulk of the logic lives under./src — this file is the module's public-// entry point, the same shape as insight.service.ts drawing from insight/src/*.-//-// Every export takes `deps`. `./src/app.ts` and `./src/filter-command.ts`-// construct nothing at import time any more, so the three lazy loaders that-// used to stand between this file and them are gone (R15) — a static import-// here builds no agent, opens no provider client and reaches no database.-//-// The chat app is memoized PER `deps` object rather than per process: a Ctx-// builds one `ServiceDeps` per unit of work (context.ts's-// `installLazyServices`), so two calls inside one chat request share an app-// while two requests do not — the same trade `cacheable-per-deps.ts` records-// for the cross-module caches.+// The chat app is memoized per `deps` object, not per process: a Ctx builds one+// `ServiceDeps` per unit of work, so calls inside one chat request share an app+// and separate requests do not.import type { ServiceDeps, Services } from '../../services';import type { PageContext } from './assistant.constants';diff --git a/packages/core/src/modules/assistant/src/app.ts b/packages/core/src/modules/assistant/src/app.tsindex ec4d11656..64b155121 100644--- a/packages/core/src/modules/assistant/src/app.ts+++ b/packages/core/src/modules/assistant/src/app.ts@@ -1,8 +1,5 @@-// The app is built from the `deps` `assistant.routes.ts` already holds, not-// constructed at module scope. Importing this file opens nothing — no-// provider client, no agent, no conversation store — and every tool handler-// closes over the same `deps`, which is what `@better-agent/core`'s-// context-free tool-handler signature ruled out doing as an argument.+// Tool handlers close over `deps` because @better-agent/core's tool handler+// signature has no context parameter.import { betterAgent, defineAgent } from '@better-agent/core';import type { ServiceDeps } from '../../../services';import { type ChatAgentContext, chatContextSchema } from './context';@@ -17,22 +14,11 @@ import {import { composeChatTools } from './tools';/**- * Create one agent per model in the whitelist. All agents share the- * same context schema, instruction builder, and dynamic tool composer- * — they only differ by which provider model runs the conversation.- *- * The frontend "model picker" is an "agent picker" in disguise: it- * just selects which agent name to pass to `useAgent()`.- *- * The whole config is `any`-cast because `resolveModel` returns a- * union of provider model types, and `defineAgent`'s conditional- * generics (`InstructionEnabled`, `DefineAgentToolFields`) can't- * narrow over the union — they fall back to `object`, which strips- * the `instruction` and `tools` fields from the inferred config type.- * All providers in our whitelist support both at runtime; the cast- * just sidesteps the TS narrowing limit. `defineAgent` itself runs- * a runtime `validateAgentDefinition` check so misconfigurations- * still throw at startup.+ * One agent per whitelisted model; they differ only in the provider model. The+ * config is `any`-cast because `resolveModel` returns a union and+ * `defineAgent`'s conditional generics fall back to `object`, which strips+ * `instruction` and `tools` from the inferred type. `defineAgent` still+ * validates the definition at runtime.*/function createChatAgent(deps: ServiceDeps, entry: ChatModelEntry) {return defineAgent({@@ -43,10 +29,7 @@ function createChatAgent(deps: ServiceDeps, entry: ChatModelEntry) {instruction: (context: ChatAgentContext) => buildSystemPrompt(context),tools: (context: ChatAgentContext) => composeChatTools(deps, context),maxSteps: 20,- // Reasoning-capable models (gpt-5.x / o-series) need the- // `reasoning.summary` option to stream reasoning text back; the- // client's REASONING_MESSAGE_* events feed our `ReasoningBlock`- // UI. Non-reasoning models skip this block entirely.+ // Reasoning-capable models need `reasoning.summary` to stream reasoning text....(entry.reasoning? {defaultModelOptions: {@@ -61,11 +44,7 @@ function createChatAgent(deps: ServiceDeps, entry: ChatModelEntry) {} as any);}-/**- * Dedicated cheap agent for generating 3-5 word conversation titles.- * Called fire-and-forget by the route after the first turn of a new- * conversation completes.- */+/** Cheap agent that titles a new conversation (3-5 words) after its first turn. */function createTitlerAgent(deps: ServiceDeps) {return defineAgent({name: '__titler',@@ -80,14 +59,8 @@ function createTitlerAgent(deps: ServiceDeps) {}/**- * The Better Agent app for one unit of work. Exposes a `.handler` that- * `assistant.routes.ts` calls under `/ai/agents/*`. Holds:- * - one agent per allowed model- * - the Prisma-backed conversation store for persistence- * - a dedicated titler agent for conversation titles- *- * Auth + project-access are enforced by `assistant.routes.ts` before this- * handler runs.+ * The Better Agent app for one unit of work; `.handler` is mounted by+ * `assistant.routes.ts`, which checks auth and project access first.*/export function createChatApp(deps: ServiceDeps) {return betterAgent({diff --git a/packages/core/src/modules/assistant/src/context.ts b/packages/core/src/modules/assistant/src/context.tsindex 26f62b127..a1b4e8e91 100644--- a/packages/core/src/modules/assistant/src/context.ts+++ b/packages/core/src/modules/assistant/src/context.ts@@ -1,8 +1,3 @@-// Re-export the shared chat schemas from `../assistant.constants` so the-// rest of the agent code can keep importing from `./context`. The schemas-// themselves live in the module's constants file because the frontend needs-// them too (isomorphic — see assistant.constants.ts's header).-export type {ChatAgentContext,PageContext,diff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.tsindex 858382953..8f83cc508 100644--- a/packages/core/src/modules/assistant/src/filter-command.ts+++ b/packages/core/src/modules/assistant/src/filter-command.ts@@ -1,10 +1,5 @@-// The one caller is `overview.rpc.ts`'s `runFilterCommand` procedure, which-// reaches it through `ctx.services.assistant`.-//-// The agent app and its five tools are BUILT from the `deps` that procedure-// already holds — importing this file constructs nothing, and the tool-// handlers close over `deps` because `@better-agent/core`'s tool-handler-// signature has no slot for them.+// Tool handlers close over `deps` because @better-agent/core's tool handler+// signature has no context parameter.import {type AgentToolDefinition,betterAgent,@@ -35,7 +30,6 @@ import {} from '../assistant.constants';import { resolveModel } from './providers';-// Helper, not vocabulary — copy locally rather than import from a module.function objectToZodEnums<K extends string>(obj: Record<K, unknown>): [K, ...K[]] {diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.tsindex 388c5248d..6693c4a1e 100644--- a/packages/core/src/modules/assistant/src/persistence.ts+++ b/packages/core/src/modules/assistant/src/persistence.ts@@ -3,34 +3,17 @@ import type { ConversationItem } from '@better-agent/core/providers';import type { ServiceDeps } from '../../../services';import { chatRunContext } from './run-context';-// `ConversationStore`'s `load`/`save` signatures are @better-agent/core's own-// interface — betterAgent calls them with no `Ctx`/`ServiceDeps` to thread-// through, so the store is BUILT from the deps the route already holds and-// closes over them.+// Built from the route's deps and closing over them: `ConversationStore`'s+// load/save signatures leave no room for a `Ctx`./**- * Prisma-backed `ConversationStore` for Better Agent.+ * Prisma-backed `ConversationStore`: one `ConversationItem` per `ChatMessage`+ * row, the whole item in `parts`.*- * One Better Agent `ConversationItem` (message, tool call, or tool- * result) is stored as one `ChatMessage` row. The `parts` JSON column- * holds the entire item; `role` is a discriminator for analytics.- *- * Save semantics: Better Agent hands us the FULL item list every save.- * In steady state the list is append-only — earlier items don't change,- * only new ones get added. We exploit that invariant with a cheap- * row-count comparison, which is O(1) instead of deep-equaling every- * prior item on every turn.- *- * If `items.length >= existingCount`, we insert only the tail. Any- * other case (shrank, or user-initiated edit/retry) falls back to a- * full wipe-and-rewrite. The trade-off: if Better Agent ever mutates- * a prior item in place while keeping the total count the same, we'd- * miss that change — but Better Agent's ConversationStore contract- * documents that prior items are immutable, so this is safe.- *- * Cursor is the `updatedAt` timestamp. Better Agent uses it for- * optimistic concurrency — we trust the single-writer-per-conversation- * invariant and don't check it explicitly.+ * Better Agent hands over the full item list on every save and prior items are+ * immutable, so when the list is not shorter than the stored count only the+ * tail is inserted; otherwise (edit, retry) the rows are rewritten. The cursor+ * is `updatedAt`; a single writer per conversation is assumed, not checked.*/function roleOf(item: ConversationItem): string {if (item.type === 'message') {@@ -43,10 +26,7 @@ function itemToRow(conversationId: string, item: ConversationItem) {return {conversationId,role: roleOf(item),- // Prisma's `IPrismaUIMessageParts` narrows to `unknown[]`, but our- // JSON column stores a single `ConversationItem` object. The- // runtime is fine — Prisma accepts any JSON-serializable value —- // so we cast past the generator.+ // Prisma types the column as `unknown[]` but it stores one `ConversationItem`.// biome-ignore lint/suspicious/noExplicitAny: see comment aboveparts: item as any,};@@ -97,8 +77,6 @@ export function createConversationStore(deps: ServiceDeps): ConversationStore {});if (items.length >= existingCount) {- // Append-only fast path: Better Agent guarantees prior items- // are immutable, so we can safely insert only the tail.const newItems = items.slice(existingCount);if (newItems.length > 0) {await tx.chatMessage.createMany({@@ -106,8 +84,6 @@ export function createConversationStore(deps: ServiceDeps): ConversationStore {});}} else {- // Incoming list is shorter than what's stored — an edit,- // retry, or deletion. Rewrite.await tx.chatMessage.deleteMany({ where: { conversationId } });if (items.length > 0) {await tx.chatMessage.createMany({diff --git a/packages/core/src/modules/assistant/src/prompt.ts b/packages/core/src/modules/assistant/src/prompt.tsindex 9632c5d05..5e2618afa 100644--- a/packages/core/src/modules/assistant/src/prompt.ts+++ b/packages/core/src/modules/assistant/src/prompt.ts@@ -136,11 +136,6 @@ When you call a chart tool, keep prose SHORT — a one-line caption like "Here's\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "previous": true, "series": [{ "type": "event", "name": "subscription_charge", "segment": "property_sum", "property": "amount" }], "unit": "$", "title": "MRR vs last month" }\``;}-/**- * Build the system prompt for an agent run, layering page context onto- * the base behavioral rules. Called by the agent factory's `instruction`- * function.- */export function buildSystemPrompt(context: ChatAgentContext): string {return [buildBasePrompt(), buildPageContextSection(context.pageContext)].join('\n\n'@@ -148,10 +143,8 @@ export function buildSystemPrompt(context: ChatAgentContext): string {}function buildPageContextSection(pc?: PageContext): string {- // The date varies every day, so we keep it out of the cached prefix- // and render it at the bottom of the prompt together with the rest- // of the per-request context. UTC is fine — analytics queries bucket- // by day boundaries, not user timezone.+ // The date changes daily, so it goes at the bottom, out of the cached prefix.+ // UTC: queries bucket by day, not by user timezone.const today = new Date();const todayIso = today.toISOString().slice(0, 10);const dayName = today.toLocaleDateString('en-US', {@@ -172,9 +165,8 @@ function buildPageContextSection(pc?: PageContext): string {if (pc.filters?.range) {const range = pc.filters.range;- // Resolve presets ("6m", "7d", …) to actual dates in the project's- // timezone so the model sees the same window the dashboard shows.- // Falls through gracefully if the range isn't a preset.+ // Resolve presets ("6m", "7d") in the project's timezone so the model sees+ // the window the dashboard shows.const resolved = resolveDateRange(pc.filters);const dates = ` (${resolved.startDate} to ${resolved.endDate})`;const interval = pc.filters.interval ?? 'day';diff --git a/packages/core/src/modules/assistant/src/providers.ts b/packages/core/src/modules/assistant/src/providers.tsindex 92a99964e..ac8f46391 100644--- a/packages/core/src/modules/assistant/src/providers.ts+++ b/packages/core/src/modules/assistant/src/providers.ts@@ -1,7 +1,4 @@-// SERVER-ONLY. This module instantiates `@better-agent/providers` clients-// from the credentials the config loader parsed. Never value-import it from-// the browser (apps/start) — import the model catalog/types from-// `@openpanel/core/modules/assistant/assistant.constants` instead.+// Server-only: browser code imports the model catalog from `assistant.constants`.import { createAnthropic } from '@better-agent/providers/anthropic';import { createOpenAI } from '@better-agent/providers/openai';import type { CoreConfig } from '../../../config';@@ -10,17 +7,9 @@ import type { ChatModelEntry } from '../assistant.constants';export type { ChatModelEntry } from '../assistant.constants';export { CHAT_MODELS as ALLOWED_MODELS } from '../assistant.constants';-// A provider client is memoized per `CoreConfig`, not per process: what a-// thing owns dies with its owner, and nothing outlives the thing that opened-// it. `loadConfig` runs once per boot, so a running API still builds each-// client exactly once; a second config in the same process — a test, a-// second boot — gets a client carrying ITS credentials rather than the first-// config's, and both are collected with the config that produced them.-//-// There is nothing here to close: `createOpenAI`/`createAnthropic` return a-// closure over a base URL and a header set that calls the global `fetch`.-// They hold no socket, so there is no connection to close — only a lifetime,-// which is what the WeakMap key fixes.+// Memoized per `CoreConfig`, so a second config in one process (a test, a+// reboot) gets clients with its own credentials. Nothing to close: the clients+// are closures over `fetch` and hold no socket.const openaiClients = new WeakMap<CoreConfig,ReturnType<typeof createOpenAI>diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.tsindex 4fc6fc1cc..902fe815b 100644--- a/packages/core/src/modules/assistant/src/report-runner.ts+++ b/packages/core/src/modules/assistant/src/report-runner.ts@@ -1,10 +1,5 @@-// Explicitly defers unifying MCP's tool definitions with assistant's, so-// `modules/mcp/src/tools/analytics/reports.ts` keeps its own copy of this-// dispatch — reaching into another module's tool tree is not the fix.-//-// The result is a second copy of this dispatch logic, kept as an accepted-// trade-off: both copies call the same @openpanel/db primitives and must be-// kept in sync by hand.+// Intentionally separate from `modules/mcp/src/tools/analytics/reports.ts`: both+// call the same @openpanel/db primitives and must be kept in sync by hand.import type { CoreConfig } from '../../../config';import type { ServiceDeps } from '../../../services';@@ -34,13 +29,9 @@ function reportUrl(}/**- * Execute a saved report by ID. Dispatches on chart type:- * - funnel → getFunnel- * - metric → executeAggregateChart- * - others → executeChart- *- * Deliberately returns the raw engine output — the chat renderer needs the- * full chart, unlike MCP's copy which reshapes it for LLM consumption.+ * Execute a saved report by ID, dispatching on chart type. Returns the raw+ * engine output: the chat renderer needs the full chart, unlike MCP's copy,+ * which reshapes it for an LLM.*/export async function runReport(deps: ServiceDeps,@@ -60,11 +51,7 @@ export async function runReport(startDate: string;endDate: string;dashboard_url: string;- /**- * The saved config in the same `zReportInput` shape `runReportFromConfig`- * returns, so the chat renderer can draw the chart instead of only- * reading the numbers off `data`.- */+ /** The saved config as `zReportInput`, so the renderer can draw the chart. */report: Omit<NonNullable<IServiceReport>, 'layout'>;data: unknown;}@@ -86,10 +73,8 @@ export async function runReport(const { startDate, endDate } = getChartStartEndDate(report, timezone);const chartInput = { ...report, startDate, endDate, timezone };- // `layout` is the dashboard grid position, not part of the chart config —- // everything else `transformReport` returns already matches `zReportInput`- // (the DB `events` column arrives here as `series`). `id` stays on, so the- // renderer can tell an already-saved report from an ad-hoc one.+ // `layout` is the dashboard grid position, not chart config. `id` stays so the+ // renderer can tell a saved report from an ad-hoc one.const { layout: _layout, ...config } = report;const meta = {@@ -118,17 +103,12 @@ export async function runReport(return { ...meta, data: await executeChart(deps, chartInput) };}-/**- * Execute an ad-hoc report config (no DB lookup — config is supplied- * directly). Used by the `generate_report` / `preview_report_with_changes`- * chat tools.- */+/** Execute an ad-hoc report config (no DB lookup). */export async function runReportFromConfig(deps: ServiceDeps,input: {organizationId: string;projectId: string;- /** Full zReportInput shape, with required startDate/endDate */config: {chartType: string;interval: string;diff --git a/packages/core/src/modules/assistant/src/run-context.ts b/packages/core/src/modules/assistant/src/run-context.tsindex 56d5a1761..f009a0d90 100644--- a/packages/core/src/modules/assistant/src/run-context.ts+++ b/packages/core/src/modules/assistant/src/run-context.ts@@ -1,18 +1,9 @@import { AsyncLocalStorage } from 'node:async_hooks';/**- * Per-request context for chat runs. Populated by `assistant.routes.ts`- * (which validates the session + project access) before the Better- * Agent handler runs, and read by:- * - the persistence store, to upsert the `Conversation` row with- * the right owner on first save- * - `resolveDateRange` / the prompt builder, to turn page-context- * range presets (`"6m"`, `"7d"`, …) into actual dates in the- * user's project timezone- *- * Using AsyncLocalStorage means we don't have to thread these values- * through Better Agent's plugin hooks — which don't expose the agent- * `context` field to `onBeforeSave`.+ * Per-request context set by `assistant.routes.ts` after its access checks, read+ * by the persistence store and the date-range/prompt code. AsyncLocalStorage+ * because Better Agent's `onBeforeSave` hook does not expose the agent `context`.*/export type ChatRunContext = {userId: string;diff --git a/packages/core/src/modules/assistant/src/tools/base.ts b/packages/core/src/modules/assistant/src/tools/base.tsindex 1d64e2f7c..d0dc46aee 100644--- a/packages/core/src/modules/assistant/src/tools/base.ts+++ b/packages/core/src/modules/assistant/src/tools/base.ts@@ -40,7 +40,6 @@ import {/** Series label for `get_rolling_active_users`' chart — always daily uniques. */const DAILY_ACTIVE_USERS_SERIES_LABEL = 'Daily active users';-// Helper, not vocabulary — copied locally rather than imported from a module.function objectToZodEnums<K extends string>(obj: Record<K, unknown>): [K, ...K[]] {@@ -48,10 +47,6 @@ function objectToZodEnums<K extends string>(return [firstKey!, ...otherKeys];}-// ─────────────────────────────────────────────────────────────────-// DISCOVERY-// ─────────────────────────────────────────────────────────────────-export const listEventNames = (deps: ServiceDeps) =>chatTool({@@ -111,10 +106,6 @@ export const getEventPropertyValues = (deps: ServiceDeps) =>}));-// ─────────────────────────────────────────────────────────────────-// SAVED DASHBOARDS & REPORTS (PREFER THESE OVER generate_report)-// ─────────────────────────────────────────────────────────────────-export const listDashboards = (deps: ServiceDeps) =>chatTool({@@ -409,10 +400,8 @@ export const generateReport = (deps: ServiceDeps) =>...(options ? { options } : {}),};- // Pre-validate against the real report schema so invalid shapes- // (bad operator, wrong filter value type, unknown chartType) are- // returned to the model as a structured error, letting the agent- // loop self-correct instead of producing a broken chart.+ // Pre-validate so an invalid shape is returned to the model as a structured+ // error it can self-correct from, instead of producing a broken chart.const parsed = zReportInput.safeParse(config);if (!parsed.success) {return {@@ -433,8 +422,7 @@ export const generateReport = (deps: ServiceDeps) =>>[1]['config'],});return {- // Use the model-supplied title when present; the frontend- // falls back to a derived title from input if this is empty.+ // The frontend derives a title when this is empty....(input.title?.trim() ? { name: input.title.trim() } : {}),...chart,};@@ -472,10 +460,6 @@ const ALPHABET_IDS = ['Z',] as const;-// ─────────────────────────────────────────────────────────────────-// AGGREGATE ANALYTICS — default to current page's filters-// ─────────────────────────────────────────────────────────────────-export const getAnalyticsOverview = (deps: ServiceDeps) =>chatTool({@@ -665,15 +649,10 @@ export const getRollingActiveUsers = (deps: ServiceDeps) =>const window = windowDays ?? 1;const range = days ?? 30;- // Build a chart config that represents "unique users per day".- // We use a user-segment on `screen_view` — OpenPanel's standard- // pageview event — with a linear chart. The ChartEngine dedupes- // per profile_id because of `segment: 'user'`.- //- // The chart is daily uniques regardless of `windowDays`: the chart- // engine has no rolling-window series type. `windowDays` shapes the- // `summary` below and nothing else, which is why the series is- // labelled for what it is rather than for the requested window.+ // Unique users per day: a user-segment on `screen_view` with a linear chart.+ // The chart is daily uniques whatever `windowDays` is, since the engine has+ // no rolling-window series type; `windowDays` only shapes the `summary`+ // below, so the series is labelled for what it is.const endDate = new Date().toISOString().slice(0, 10);const startDate = new Date(Date.now() - (range - 1) * 86_400_000).toISOString()@@ -714,26 +693,19 @@ export const getRollingActiveUsers = (deps: ServiceDeps) =>config: config as Parameters<typeof runReportFromConfig>[1]['config'],});- // Also keep the rolling summary so the model can quote the- // single-number "MAU is 205,127" line.const summary = await getRollingActiveUsersCore(deps, {projectId: context.projectId,days: window,});return {- // `name` is the title the frontend `ChatReportResult` uses for- // the card header. The model is asked to supply a `title` —- // we use it when present, falling back to a generic label. The- // fallback names the CHART, not the summary: the two measure- // different windows.+ // Names the CHART, not the summary: the two measure different windows.name:title?.trim() ||`${DAILY_ACTIVE_USERS_SERIES_LABEL} — last ${range} days`,label: summaryLabel,window,summary,- // Keys the frontend report renderer knows about....chart,};}@@ -777,8 +749,6 @@ export const getFunnel = (deps: ServiceDeps) =>endDate: endDate ?? pageContext?.filters?.endDate,});- // Raw funnel numbers — step-by-step breakdown for the model to- // reason about.const numbers = await getFunnelCore(deps, {projectId: context.projectId,steps,@@ -788,9 +758,7 @@ export const getFunnel = (deps: ServiceDeps) =>groupBy,});- // Chart config — same shape `generate_report` returns, so the- // frontend's `ChatReportResult` renderer draws an actual funnel- // chart via `<ReportChart>`.+ // Same shape `generate_report` returns, so `ChatReportResult` draws a funnel.const chartConfig = {chartType: 'funnel' as const,interval: 'day' as const,@@ -823,7 +791,6 @@ export const getFunnel = (deps: ServiceDeps) =>return {name: title?.trim() || `Funnel: ${steps.join(' → ')}`,numbers,- // Keys the frontend report renderer knows about....chart,};}@@ -877,10 +844,6 @@ export const getUserFlow = (deps: ServiceDeps) =>});-// ─────────────────────────────────────────────────────────────────-// FREE-FORM QUERIES (escape hatches when nothing else fits)-// ─────────────────────────────────────────────────────────────────-export const queryEvents = (deps: ServiceDeps) =>chatTool({diff --git a/packages/core/src/modules/assistant/src/tools/dashboard.ts b/packages/core/src/modules/assistant/src/tools/dashboard.tsindex 41e1080d8..1fdcaf931 100644--- a/packages/core/src/modules/assistant/src/tools/dashboard.ts+++ b/packages/core/src/modules/assistant/src/tools/dashboard.ts@@ -12,9 +12,8 @@ import { getReportsByDashboardId } from '../../../report/report.service';import { getChartStartEndDate } from '../../../report/src/chart-dates';import { chatTool, dashboardUrl } from './helpers';-// Cap on parallel report execution. Real dashboards rarely exceed this,-// but we don't want a runaway 100-report dashboard to blow our 30s tool-// timeout or hammer ClickHouse with one request.+// Caps parallel report execution so a huge dashboard cannot blow the 30s tool+// timeout or hammer ClickHouse.const MAX_REPORTS_PER_SUMMARY = 30;export const summarizeDashboard = (deps: ServiceDeps) =>@@ -82,10 +81,8 @@ export const summarizeDashboard = (deps: ServiceDeps) =>const results = await Promise.all(reports.map(async (report) => {try {- // Apply the dashboard's global range picker to each report.- // If both startDate + endDate are set, that wins; otherwise- // the preset range is used. Mirrors how ReportItem behaves- // when the page-level range/interval flow into a report.+ // The dashboard's global range applies to each report; explicit+ // start+end dates win over the preset.const useCustom = !!(overrideStart && overrideEnd);const merged = {...report,diff --git a/packages/core/src/modules/assistant/src/tools/events.ts b/packages/core/src/modules/assistant/src/tools/events.tsindex f13102b75..d0d0a9b98 100644--- a/packages/core/src/modules/assistant/src/tools/events.ts+++ b/packages/core/src/modules/assistant/src/tools/events.ts@@ -37,7 +37,6 @@ export const analyzeEventDistribution = (deps: ServiceDeps) =>limit: DISTRIBUTION_SAMPLE_LIMIT,});- // Tally frequency by event nameconst frequency = new Map<string, number>();const byCountry = new Map<string, number>();const byDevice = new Map<string, number>();@@ -90,7 +89,6 @@ export const correlateEvents = (deps: ServiceDeps) =>limit: CORRELATION_SAMPLE_LIMIT,});- // Group events by sessionId, then count co-occurring event-name pairsconst bySession = new Map<string, Set<string>>();for (const e of events) {if (!e.session_id) {diff --git a/packages/core/src/modules/assistant/src/tools/groups.ts b/packages/core/src/modules/assistant/src/tools/groups.tsindex f5402532c..c57d9a503 100644--- a/packages/core/src/modules/assistant/src/tools/groups.ts+++ b/packages/core/src/modules/assistant/src/tools/groups.ts@@ -42,9 +42,7 @@ export const getGroupFull = (deps: ServiceDeps) =>memberLimit: 10,});- // Pull a few recent events from any members. We use the- // `profileIds IN (...)` filter on queryEventsCore so the DB does- // the narrowing instead of us post-filtering a generic feed.+ // `profileIds IN (...)` lets the DB narrow instead of post-filtering a feed.const memberIds = group.members.map((m) => m.id);const recentEvents = memberIds.length? await queryEventsCore(deps, {@@ -159,10 +157,8 @@ export const getGroupMetrics = (deps: ServiceDeps) =>return { group_id: id, total_members: 0, note: 'Group has no members' };}- // Pull events for this group's members over the last 30 days, then- // bucket by 7d vs 30d. `profileIds IN (...)` lets ClickHouse do the- // narrowing — a generic project-wide feed would miss members whose- // activity falls outside the last N raw events.+ // `profileIds IN (...)` lets ClickHouse narrow: a project-wide feed would+ // miss members whose activity falls outside the last N raw events.const memberIds = members.data.map((m) => m.id);const recentEvents = await queryEventsCore(deps, {projectId: context.projectId,@@ -224,11 +220,8 @@ export const compareGroups = (deps: ServiceDeps) =>return { this_group: thisGroup, peers: [], note: 'No peer groups' };}- // `findGroupsCore` returns `IServiceGroup[]` without a memberCount- // — that lives on `IServiceGroupStats` via a separate query. We- // don't fetch it here, so we report peer count + this group's- // count and list a handful of peers without rankings. If "rank by- // members" becomes useful, fetch `getGroupStats` for each peer.+ // `findGroupsCore` returns no memberCount (that is `IServiceGroupStats`, a+ // separate query), so peers are listed without rankings.return {this_group: {id: thisGroup.group.id,diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.tsindex e5079ad7d..4e5cbe1d6 100644--- a/packages/core/src/modules/assistant/src/tools/helpers.ts+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts@@ -18,28 +18,19 @@ import { chatRunContext } from '../run-context';const TOOL_TIMEOUT_MS = 30_000;/**- * Thin wrapper around `defineTool().server()` that bakes in our typed- * agent context and enforces a time ceiling. Three things this gives- * us over the raw API:+ * Wrapper around `defineTool().server()` that types the agent context and+ * enforces a time ceiling.*- * 1. The agent's `contextSchema` only types itself — `defineTool` has- * no idea which agent it'll be bound to, so its `runCtx.context`- * is `unknown`. We cast it to `ChatAgentContext` here so every- * handler sees a typed context.- * 2. The handler input is `any` (validated at runtime by Zod). We- * deliberately don't try to infer it from the schema generic —- * mixing TInput inference with the `BivariantFn` parameter shape- * hits TypeScript's "type instantiation is excessively deep" limit- * and breaks. Tools that need typed input destructure with an- * inline annotation, or use `z.infer<typeof mySchema>`.- * 3. A 30-second timeout wraps every handler. A slow ClickHouse query- * or a stalled external fetch would otherwise hold the turn for- * the full latency of the tool. We throw with a known shape so- * the agent sees a clear "tool took too long" message and can- * decide whether to retry with narrower params or move on. It- * bounds the TURN, not the work: the race abandons the handler- * rather than cancelling it, so the query behind a timed-out- * tool keeps running to completion on the server.+ * - `defineTool` does not know which agent it is bound to, so `runCtx.context`+ * is `unknown`; it is cast to `ChatAgentContext` here.+ * - The handler input is `any` (validated at runtime by Zod): inferring it from+ * the schema generic hits TypeScript's "type instantiation is excessively+ * deep" limit. Tools that need typed input annotate it inline or use+ * `z.infer`.+ * - A 30-second timeout wraps every handler so a slow query or stalled fetch+ * cannot hold the turn; the agent gets a clear "tool took too long" error.+ * It bounds the TURN, not the work: the race abandons the handler, so the+ * query behind a timed-out tool keeps running on the server.*/export function chatTool(config: {@@ -82,10 +73,7 @@ export function chatTool(}) as AgentToolDefinition;}-/**- * Cap an array result to `max` items and append a truncation marker so the- * frontend renderer + the LLM both know there's more data.- */+/** Cap an array result to `max` items and append a truncation marker so the renderer and the LLM know there is more. */export function truncateRows<T>(rows: T[],max = 500@@ -97,19 +85,14 @@ export function truncateRows<T>(}/**- * Compact output from `listEventPropertiesCore` for consumption by the LLM.+ * Compact `listEventPropertiesCore` output for the LLM. `columns` are top-level+ * event columns, used bare in filters; `properties` are keys of the JSON+ * `properties` map, used as `properties.<key>`.*- * `columns` are top-level event columns, used bare in filters/breakdowns.- * `properties` are custom keys from the JSON `properties` map, used as- * `properties.<key>`.- *- * The raw `properties` rows are ordered alphabetically and capped at 500,- * which is token-hungry: a property with dynamic sub-paths (`__query.foo`,- * `__query.<uuid>`, …) can flood the list with hundreds of rows before an- * unrelated property like `country` appears, and `event_name` repeats on- * every row even when it's a filter-supplied constant. This collapses- * dotted keys to their root, dedupes, orders by frequency, and caps the- * list to the ~50 roots the model needs for filter/breakdown discovery.+ * The raw rows are alphabetical and capped at 500, so a property with dynamic+ * sub-paths (`__query.<uuid>`, ...) can flood the list before `country`+ * appears. This collapses dotted keys to their root, dedupes, orders by+ * frequency and keeps the ~50 roots the model needs.*/export function compactEventProperties(raw: {@@ -144,11 +127,7 @@ export function compactEventProperties(};}-/**- * Known range presets that map to date windows via `getDatesFromRange`.- * Anything outside this set (including `"custom"`) is treated as "no- * preset" and we fall through to explicit dates / the 30-day default.- */+/** Range presets `getDatesFromRange` understands; anything else (including `"custom"`) falls through to explicit dates or the 30-day default. */const PRESET_RANGES: ReadonlySet<IChartRange> = new Set(['30min','lastHour',@@ -165,21 +144,10 @@ const PRESET_RANGES: ReadonlySet<IChartRange> = new Set([]);/**- * Resolve a date range from `PageContext.filters`.- *- * Precedence:- * 1. Explicit `startDate` + `endDate` → use as-is (either one alone- * falls back to the other via `resolveDateRangeCore`).- * 2. `range` is a known preset (`"7d"`, `"6m"`, …) → expand via- * `getDatesFromRange(range, projectTimezone)` so a preset-only- * URL (as set by the dashboard's `useOverviewOptions`) produces- * the same window the dashboard is displaying.- * 3. Nothing → default to the last 30 days (via- * `resolveDateRangeCore`).- *- * Timezone comes from `chatRunContext` (populated by- * `assistant.routes.ts` once per request). Outside that context we fall- * back to UTC — only relevant in tests / direct calls.+ * Resolve a date range from `PageContext.filters`: explicit start/end dates+ * first, then a known preset expanded in the project timezone (so a+ * preset-only URL gives the window the dashboard shows), else the last 30+ * days. The timezone comes from `chatRunContext`, UTC outside it (tests).*/export function resolveDateRange(filters?: PageContext['filters']): {startDate: string;@@ -199,14 +167,10 @@ export function resolveDateRange(filters?: PageContext['filters']): {}/**- * Extract `IChartEventFilter[]` from the chat's page context. The- * context schema keeps filters loose (Zod `record`), but the frontend- * always ships the real chart-filter shape — so we cast here. Invalid- * entries (missing `name`) are dropped defensively.- *- * Tools use this so the assistant sees the user's active filters ("I- * see you're filtered to mobile") instead of returning project-wide- * numbers that contradict the dashboard.+ * Extract `IChartEventFilter[]` from the page context so the assistant sees the+ * user's active filters instead of returning project-wide numbers that+ * contradict the dashboard. The context schema keeps filters loose, so this+ * casts and drops entries without a `name`.*/export function pageContextFilters(pageContext: ChatAgentContext['pageContext']diff --git a/packages/core/src/modules/assistant/src/tools/index.ts b/packages/core/src/modules/assistant/src/tools/index.tsindex 9710c54e2..e37e64df6 100644--- a/packages/core/src/modules/assistant/src/tools/index.ts+++ b/packages/core/src/modules/assistant/src/tools/index.ts@@ -14,30 +14,21 @@ import * as seo from './seo';import * as session from './session';import * as ui from './ui';-// A tool is BUILT per unit of work, from the `deps` the route already holds:-// `@better-agent/core`'s tool-handler signature has no context parameter, so-// each handler closes over them instead. The lists are typed loosely as-// `(deps) => AgentToolDefinition` — without the cast, TypeScript tries to-// compute the union of every tool's schema + result type and hits its-// instantiation depth limit.+// `@better-agent/core`'s tool handler signature has no context parameter, so+// handlers close over `deps`. Lists are typed loosely: without the cast,+// TypeScript hits its instantiation depth limit computing the union of every+// tool's schema and result type.type ToolFactory = (deps: ServiceDeps) => AgentToolDefinition;type ToolList = ToolFactory[];-/**- * Always-available base tool set: discovery + saved reports + aggregate- * analytics + free-form queries. Every chat session starts here.- */const BASE_TOOLS: ToolList = [- // Discoverybase.listEventNames,base.listEventProperties,base.getEventPropertyValues,- // Saved dashboards & reportsbase.listDashboards,base.listReports,base.getReportData,base.generateReport,- // Aggregate analyticsbase.getAnalyticsOverview,base.getTopPages,base.getTopReferrers,@@ -47,14 +38,10 @@ const BASE_TOOLS: ToolList = [base.getFunnel,base.getRetentionCohort,base.getUserFlow,- // Free-form queriesbase.queryEvents,base.querySessions,base.findProfiles,- // References — manual annotations the user adds for real-world- // events (campaigns, deploys, announcements). Available everywhere- // because "what happened around X?" is a useful question on- // every page, not just the overview.+ // Available on every page: "what happened around X?" is not overview-specific.references.listReferences,references.getReferencesAround,] as ToolList;@@ -105,10 +92,7 @@ const SEO_TOOLS: ToolList = [seo.correlateSeoWithTraffic,] as ToolList;-// No property-listing tool here on purpose: `base.listEventProperties` is in-// BASE_TOOLS, so it is already registered on this page. `list_properties_for_event`-// was a second wire name over the same handler, and the events page offered the-// model both at once.+// No property-listing tool here: `base.listEventProperties` is already in BASE_TOOLS.const EVENTS_TOOLS: ToolList = [events.analyzeEventDistribution,events.correlateEvents,@@ -131,11 +115,7 @@ const GROUP_TOOLS: ToolList = [const DASHBOARD_TOOLS: ToolList = [dashboard.summarizeDashboard] as ToolList;-// Client-side UI mutators. Available on pages that have user--// settable filters (date range, event names, property filters) so-// the assistant can act on requests like "filter to last 7 days",-// "show me only signups", or "referrers from GitHub" instead of-// just describing data.+// Client-side UI mutators, for pages with user-settable filters.const UI_TOOLS: ToolList = [ui.applyFilters,ui.setEventNamesFilter,@@ -143,15 +123,9 @@ const UI_TOOLS: ToolList = [] as ToolList;/**- * Compose the chat tool set for a given request. Base tools are always- * present; page-specific tools layer on top.- *- * Page-specific tools are only included when the corresponding entity- * id is present in pageContext (e.g. profile tools require profileId),- * so the LLM doesn't see tools it can't usefully call.- *- * The LLM sees fewer-but-more-focused tools per page, which produces- * better tool selection than one giant flat registry.+ * Compose the chat tool set for a request: base tools always, page-specific+ * tools only when their entity id is in pageContext, so the model is not+ * offered tools it cannot usefully call.*/export function composeChatTools(deps: ServiceDeps,diff --git a/packages/core/src/modules/assistant/src/tools/profile.ts b/packages/core/src/modules/assistant/src/tools/profile.tsindex d98980831..0cd8d2145 100644--- a/packages/core/src/modules/assistant/src/tools/profile.ts+++ b/packages/core/src/modules/assistant/src/tools/profile.ts@@ -245,7 +245,6 @@ export const compareProfileToAverage = (deps: ServiceDeps) =>async ({ profileId }, context) => {const id = profileId || context.pageContext?.ids?.profileId || '';- // Get this profile's metrics + a sample of other profiles' metricsconst [thisMetrics, allProfiles] = await Promise.all([getProfileMetricsCore(deps, {projectId: context.projectId,@@ -261,11 +260,9 @@ export const compareProfileToAverage = (deps: ServiceDeps) =>return { error: 'Profile not found or has no events', profileId: id };}- // Compute averages from a sample of other profiles: of the- // AVERAGE_CANDIDATE_LIMIT fetched above we query metrics for the first- // AVERAGE_SAMPLE_SIZE, in parallel. For a precise project-wide average- // we'd want a dedicated db helper, but this gives the LLM a useful- // comparison without extra schema work.+ // Average over a sample: metrics for the first AVERAGE_SAMPLE_SIZE of the+ // AVERAGE_CANDIDATE_LIMIT profiles fetched, in parallel. Not a precise+ // project-wide average.const sampleIds = allProfiles.filter((p) => p.id !== id).slice(0, AVERAGE_SAMPLE_SIZE)diff --git a/packages/core/src/modules/assistant/src/tools/references.ts b/packages/core/src/modules/assistant/src/tools/references.tsindex 9cf60d8e4..925087f60 100644--- a/packages/core/src/modules/assistant/src/tools/references.ts+++ b/packages/core/src/modules/assistant/src/tools/references.ts@@ -3,18 +3,9 @@ import type { ServiceDeps } from '../../../../services';import { chatTool, resolveDateRange, truncateRows } from './helpers';/**- * References are manual annotations the user adds — e.g.- * "Launched new marketing campaign" on 2026-03-15. They mark- * real-world events so the AI can correlate traffic changes with- * things that happened off-platform.- *- * Use these tools whenever the user asks things like:- * - "What caused this spike?"- * - "Are any recent launches affecting the numbers?"- * - "Show me what happened around [date]"- *- * Or proactively when you notice a traffic anomaly and want to see- * if a reference explains it.+ * References are manual annotations the user adds (e.g. "Launched new marketing+ * campaign" on 2026-03-15) so the AI can correlate traffic changes with+ * off-platform events.*/export const listReferences = (deps: ServiceDeps) =>diff --git a/packages/core/src/modules/assistant/src/tools/report.ts b/packages/core/src/modules/assistant/src/tools/report.tsindex 7bf0929ad..c770e81d4 100644--- a/packages/core/src/modules/assistant/src/tools/report.ts+++ b/packages/core/src/modules/assistant/src/tools/report.ts@@ -143,7 +143,6 @@ export const suggestBreakdowns = (deps: ServiceDeps) =>));- // Aggregate property keys across eventsconst keyCount = new Map<string, number>();for (const r of propsPerEvent) {for (const p of r.properties) {@@ -151,7 +150,6 @@ export const suggestBreakdowns = (deps: ServiceDeps) =>}}- // Filter out keys that are already used as breakdownsconst used = new Set((draft.breakdowns ?? []).map((b) => b.name));const suggestions = Array.from(keyCount.entries()).filter(([k]) => !used.has(k))@@ -251,8 +249,7 @@ export const findAnomaliesInCurrentReport = (deps: ServiceDeps) =>} as unknown as Parameters<typeof runReportFromConfig>[1]['config'],});- // Best-effort anomaly detection on the first series of the result.- // The data shape varies by chart type — we look for an array of+ // Best-effort anomaly detection on the first series, if it is an array of// { date, count } points.// biome-ignore lint/suspicious/noExplicitAny: chart engine output shape is variedconst data = result.data as any;diff --git a/packages/core/src/modules/assistant/src/tools/seo.ts b/packages/core/src/modules/assistant/src/tools/seo.tsindex 934aff770..ba2d7be51 100644--- a/packages/core/src/modules/assistant/src/tools/seo.ts+++ b/packages/core/src/modules/assistant/src/tools/seo.ts@@ -16,11 +16,9 @@ import { chatTool, resolveDateRange, truncateRows } from './helpers';const DATE_ONLY_LENGTH = 10;/**- * The GSC tables store `date` as a ClickHouse `Date` and Google's- * searchAnalytics API takes `YYYY-MM-DD`, so the datetime bounds- * `resolveDateRange` returns — right for the event and session tables — are- * refused here with "Cannot convert string ... to type Date"- * (main a0e122e8).+ * The GSC tables store `date` as a ClickHouse `Date`, so the datetime bounds+ * `resolveDateRange` returns for the event and session tables are refused here+ * ("Cannot convert string ... to type Date").*/function toGscRange(range: { startDate: string; endDate: string }) {return {@@ -244,9 +242,8 @@ export const correlateSeoWithTraffic = (deps: ServiceDeps) =>}),]);- // The OP `getTopPagesCore` and GSC `gscGetTopPagesCore` return- // different row shapes — the fields we actually read are captured- // in these local types, keeping the lookup map typed.+ // The two functions return different row shapes; these types cover the+ // fields read.type OpPage = {name?: string;path?: string;diff --git a/packages/core/src/modules/assistant/src/tools/session.ts b/packages/core/src/modules/assistant/src/tools/session.tsindex 0c3ec740b..824cbcd5e 100644--- a/packages/core/src/modules/assistant/src/tools/session.ts+++ b/packages/core/src/modules/assistant/src/tools/session.ts@@ -125,7 +125,6 @@ export const getSimilarSessions = (deps: ServiceDeps) =>device: session.device ?? undefined,limit: (limit ?? 10) + 1,});- // Drop the session itselfconst filtered = similar.filter((s) => s.id !== id).slice(0, limit ?? 10);return {@@ -162,7 +161,6 @@ export const compareSessionToTypical = (deps: ServiceDeps) =>const id = sessionId || context.pageContext?.ids?.sessionId || '';const session = await getSessionById(deps, id, context.projectId);- // Sample recent sessions to compute project averages.const sample = await querySessionsCore(deps, {projectId: context.projectId,limit: 100,diff --git a/packages/core/src/modules/assistant/src/tools/ui.ts b/packages/core/src/modules/assistant/src/tools/ui.tsindex 5c2a4beef..cbe16727e 100644--- a/packages/core/src/modules/assistant/src/tools/ui.ts+++ b/packages/core/src/modules/assistant/src/tools/ui.ts@@ -7,25 +7,15 @@ import {} from '../../assistant.constants';/**- * Client-side UI-mutator tools.- *- * Better Agent emits each call as a `tool-call` part with no server- * execution; the frontend (`useAgent({ toolHandlers })`) handles them- * by updating the URL params the dashboard's hooks read. Zod schemas- * are imported from `assistant.constants.ts` so the frontend handler- * types stay in sync with what the LLM calls.- *- * Each is exported as a `(deps) => AgentToolDefinition` for uniformity with- * every other tool bucket (`./index.ts`'s `ToolFactory`); these three touch- * nothing, so `_deps` is genuinely unused here.+ * Client-side UI-mutator tools: Better Agent emits each call as a `tool-call`+ * part with no server execution, and the frontend handles it by updating the+ * URL params the dashboard reads. Factories take an unused `_deps` to match the+ * other tool buckets.*/-// Cast to `any` before `.client()` for the same reason `chatTool`-// does in `helpers.ts`: TS otherwise fully instantiates-// `ClientToolDefinition<TSchema, ...>` for the deeply-nested Zod-// schema and trips its instantiation depth limit. The runtime is-// fine; the AgentToolDefinition cast on the way out restores a-// usable type for downstream code.+// Cast to `any` before `.client()`: TS otherwise fully instantiates+// `ClientToolDefinition` for the deeply nested Zod schema and trips its+// instantiation depth limit.// biome-ignore lint/suspicious/noExplicitAny: see comment aboveconst applyFiltersContract: any = defineTool({name: 'apply_filters',diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.tsindex 4f6381ecc..05165ea62 100644--- a/packages/core/src/modules/auth/auth.routes.ts+++ b/packages/core/src/modules/auth/auth.routes.ts@@ -1,11 +1,3 @@-// The github/google OAuth callbacks, same shape as gsc.routes.ts:-// token-exchange/session logic lives in auth.service.ts's-// `completeOAuthCallback`. `main.ts` mounts `dashboardRoutes` unconditionally-// on every HTTP-serving boot, so this route is live.-//-// Per-route cookie signing is not wired yet (gsc.routes.ts's header names the-// same gap), so `ctx.cookies.get` here reads the raw, unsigned cookie value.-import { redirect } from 'elysia';import { z } from 'zod';import { defineRoutes } from '../../http/define';@@ -18,8 +10,7 @@ import {OAuthCallbackError,} from './auth.service';-// Both come from the provider's redirect, so they are attacker-supplied in-// the sense that anyone can call this URL directly.+// Anyone can call this URL directly, so both values are attacker-controlled.const callbackQuery = z.object({code: z.string().max(MAX_TOKEN),state: z.string().max(MAX_TOKEN),diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.tsindex ad8de3950..54096319c 100644--- a/packages/core/src/modules/auth/auth.rpc.test.ts+++ b/packages/core/src/modules/auth/auth.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The sign-up/sign-in/reset-password/share bodies ride on @openpanel/db-// (lazy-loaded through ./auth.service); wiring this router end-to-end-// against a real Postgres is P6's (protectedProcedure) job, not this one's —-// see auth.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here, with no database.import { expect, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -19,8 +15,7 @@ const COOKIE_OPTIONS: CookieOptions = {path: '/',};-// EMPTY_SESSION's shape (./src/login-session.ts) — `TrpcContext.session` is-// never literally `null`, only its `userId` is.+// `TrpcContext.session` is never literally `null`, only its `userId` is.const EMPTY_SESSION = { session: null, user: null, userId: null };async function anonCaller() {diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.tsindex d3cda9dac..8d20d355a 100644--- a/packages/core/src/modules/auth/auth.rpc.ts+++ b/packages/core/src/modules/auth/auth.rpc.ts@@ -1,14 +1,5 @@-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. The explicit checks in the handlers below stay: `enforceAccess`-// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved-// from another id needs its own.-//-// Rate limits are mounted below through `createRateLimitMiddleware`-// (rpc/base.ts), procedure for procedure. Blocks are keyed per procedure and-// per trusted IP, and escalate on repeat offence — see rpc/rate-limit.ts.-//-// This module has no queue/cron of its own, so there is no `ctx.services.auth`-// entry here — same shape as `user`/`project`.+// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so+// anything resolved from another id needs its own explicit check in the handler.import { z } from 'zod';import {@@ -50,9 +41,8 @@ const rateLimit = createRateLimitMiddleware(enforceRateLimit);export const authRouter = createTRPCRouter({/**- * Which optional OAuth-backed features this instance has credentials for.- * The dashboard hides the social login buttons and the Search Console- * settings on a self-hosted instance that has not configured them.+ * Which optional OAuth features this instance has credentials for, so the+ * dashboard can hide the social login and Search Console settings.* Booleans only: the client id/secret never leave the API.*/providers: publicProcedure.query(({ ctx }) =>diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.tsindex 0385bd701..f782e403c 100644--- a/packages/core/src/modules/auth/auth.service.access.test.ts+++ b/packages/core/src/modules/auth/auth.service.access.test.ts@@ -1,9 +1,5 @@-// Auth.service.ts is the only place the ladder is bound to real lookups, via-// the lazy, memoized `getAccessChecks`. This proves that seam still takes a-// fake `AccessLookups` cleanly — mocking `../../shared/access-lookups`, which-// auth.service.ts reaches only through a dynamic import and which owns all-// four lookups — and that the fail-closed ordering, messages and write-level-// gate are unchanged.+// Proves `getAccessChecks` accepts fake `AccessLookups`, and that the+// fail-closed ordering, messages and write-level gate hold.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -24,11 +20,8 @@ const canWriteProject = mock();const getProjectById = mock(async () => projectById);-// Snapshotted BEFORE `mock.module` below, not after — restoring by-// re-`import`ing later would resolve the already-mocked registry entry, not-// the real module (bare `bun test` shares one module registry across every-// file, and this one is reached by plenty of other modules — client.rpc.ts,-// project.rpc.ts, integration.service.ts, ...).+// Snapshotted before `mock.module`: bare `bun test` shares one module registry+// across files, so re-importing later would return the mocked entry.const realAccessLookups = { ...(await import('../../shared/access-lookups')) };mock.module('../../shared/access-lookups', () => ({@@ -49,15 +42,12 @@ beforeAll(async () => {afterAll(() => {mock.module('../../shared/access-lookups', () => realAccessLookups);- // `getAccessChecks()` memoizes for the life of the process — clear it so a- // later file in this bare run rebuilds against the real lookups just- // restored above, not this file's fakes.+ // `getAccessChecks()` memoizes per process; clear it so later files in a bare+ // run use the real lookups.resetAccessChecksForTests();});function authService() {- // Both arguments are ignored by `createAuthService`. Every member reaches- // the mocked lookups above.return createAuthService({} as import('../../services').ServiceDeps,testServices()diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 38f7a1a01..f80bb350d 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -1,17 +1,6 @@-// Token issuance/hashing, argon2 password hashing, TOTP, the OAuth clients and-// cookie helpers. The Prisma-touching half — creating, validating and-// invalidating a `sessions` row — moved here too (`./src/login-session.ts`).-//-// The permission ladder (`modules/auth/src/access.ts`) is bound to its real-// lookups exactly here, once, instead of once per module in a-// `modules/*/src/access.ts` copy — see `getAccessChecks` below for the binding-// itself.-import { z } from 'zod';import type { CoreConfig } from '../../config';import type { ServiceDeps, Services } from '../../services';-// Aliased: three members of `createAuthService` below carry the same names,-// and this file is the ONE place the ladder is bound to these lookups.import {canWriteProject,getClientAccess as getClientAccessLookup,@@ -46,10 +35,8 @@ import {verifyTotpCode,} from './src/totp';-// Re-exported straight from source (not through the imports above, which-// exist for `createAuthService` below) — `noExportedImports` would otherwise-// flag every one of those imports as "only re-exported", which is false;-// they are also the members `createAuthService` returns.+// Re-exported from source: the imports above are also used by+// `createAuthService`, so re-exporting them would trip `noExportedImports`.export { COOKIE_MAX_AGE, cookieOptions } from './src/constants';export {deleteSessionTokenCookie,@@ -87,18 +74,11 @@ type ProjectAccessChecks = AccessChecks<IProjectAccess>;let accessChecksPromise: Promise<ProjectAccessChecks> | undefined;/**- * The single binding of the ladder to real lookups — memoized:- * `createAccessChecks` runs exactly once per process, on however many requests,- * no matter how many of this function's callers invoke it. Nothing runs at- * module-import time or at `createAuthService` construction time; the binding- * is built on the first actual check. An earlier attempt bound it at module- * scope and hung `bun test` for 30 minutes.- *- * Still a `Promise` because the contract is awaited at every call site.+ * Memoized: the ladder is bound once per process, on the first check. Binding+ * at module scope hung `bun test`.** `integration.service.ts` and `subscription.service.ts` import this directly- * instead of going through `ctx.services.auth`: both are called with a bare- * `userId` and no `ctx`. Operator-authorized.+ * because they are called with a bare `userId` and no `ctx`.*/export function getAccessChecks(): Promise<ProjectAccessChecks> {if (!accessChecksPromise) {@@ -115,26 +95,17 @@ export function getAccessChecks(): Promise<ProjectAccessChecks> {}/**- * Test-only escape hatch. `accessChecksPromise` is a true process-lifetime- * singleton by design (see `getAccessChecks` above), so a test that mocks- * `access-lookups`/`project.service` to prove the injection seam works must- * clear it afterward — otherwise, under a bare (non-`--isolate`) `bun test`,- * the fake closures it built would answer every later file's real access- * checks too.+ * Test-only. The binding is a process-lifetime singleton, so a test that mocks+ * the lookups must clear it or, without `--isolate`, later files get the fakes.*/export function resetAccessChecksForTests(): void {accessChecksPromise = undefined;}/**- * The one login check in the tree.- *- * `protectedProcedure` already refuses an anonymous caller and hands the- * handler a `session.userId` that is a `string`, so a protected procedure needs- * nothing here. This is for the paths the builder cannot decide: the- * share-aware `chartProcedure` / `overviewProcedure`, which are public because- * a valid share link is an alternative to being signed in, and only demand a- * user when no share was presented.+ * Login check for the share-aware procedures, which are public because a valid+ * share link is an alternative to being signed in. `protectedProcedure`+ * already refuses anonymous callers.*/export function requireLogin(userId: string | null | undefined): string {if (!userId) {@@ -144,20 +115,13 @@ export function requireLogin(userId: string | null | undefined): string {}/**- * Registered in `services.ts`. Ignores BOTH arguments: every member here- * is either pure, reads its own env, or — for the access checks — reaches the- * shared, memoized `getAccessChecks` above, whose lookups are `cacheable`- * (their key is derived from the call's arguments, so they cannot take a- * leading `deps`; see shared/access-lookups.ts). A member that later needs `db`- * / `logger` drops the underscore and reads the parameter.+ * Ignores both arguments: the access lookups are `cacheable`, keyed by call+ * arguments, so they cannot take a leading `deps`.*/export function createAuthService(deps: ServiceDeps,_services: () => Services) {- // One function per member, closing over `deps`, so the return statement below- // stays a plain index — nothing here is a `return {... }` literal with logic- // inside it.async function requireProjectAccess(args: Parameters<ProjectAccessChecks['requireProjectAccess']>[0]): ReturnType<ProjectAccessChecks['requireProjectAccess']> {@@ -195,11 +159,6 @@ export function createAuthService(return getClientAccessLookup(...args);}- /**- * The session cookie's other half. `http/session.ts` reaches it here rather- * than deep-importing `./src/login-session`, which is also what keeps the- * demo-user branch inside one function.- */function checkSessionToken(token: string | null | undefined): Promise<SessionValidationResult> {@@ -260,22 +219,6 @@ export function createAuthService(};}-// ---------------------------------------------------------------------- The-// Prisma-touching half: sign-up/sign-in, TOTP challenges, password reset,-// share unlock and the github/google OAuth callback.-//-// Session/registration access is `deps.db`, via static imports of-// `./src/login-session` and `./src/registration` — neither cycles back to this-// file, so there is nothing to keep lazy there. Share is the one real cycle —-// share.service.ts statically imports this file's own `hashPassword` — so-// `signInToShare` reaches it through the composition root's `services` thunk-// instead of importing it at all.-//-// None of these functions take a `TrpcContext`/`Ctx` directly — they take a-// `deps: ServiceDeps` plus exactly the other primitives they touch-// (`setCookie`, `cookies.get`, `logger`), so this file has no dependency on the-// rpc layer that calls it.-import { generateSecureId } from '@openpanel/shared';import { decrypt, encrypt } from '@openpanel/shared/server';import { sendEmail } from '../../clients/email';@@ -307,8 +250,6 @@ const RESET_PASSWORD_TTL_MS = 1000 * 60 * 10;export type AuthProvider = 'email' | 'google' | 'github';-/** `HttpCtx.cookies`'s shape (`shared/cookie.ts`'s `CookieJar`), named locally- * so this file has no import from the rpc/http layer that calls it. */interface CookieReader {get(name: string): string | undefined;}@@ -388,9 +329,8 @@ export function startOAuthSignIn(input: StartOAuthSignInInput,setCookie: ISetCookie): StartOAuthSignInResult {- // Without this an unconfigured provider still returned a URL, with an empty- // `client_id` in it — the caller only found out when the provider rejected- // the redirect. `providers` reports the same test, so the two agree.+ // An unconfigured provider would otherwise yield a URL with an empty+ // `client_id`.const configured = getConfiguredProviders(deps.config);if ((input.provider === 'github' && !configured.github) ||@@ -505,9 +445,7 @@ export async function signInWithEmail(throw new TRPCNotFoundError('User does not exists');}- // If the password starts with $argon2 we use the new password hashing;- // any other value is a legacy bcrypt row (from Clerk) that has been- // nulled, so this is now just a generic reject.+ // Anything but argon2 is a legacy row whose password was nulled.if (!user.account.password?.startsWith('$argon2')) {throw new TRPCBadRequestError('Reset your password, old password has expired'@@ -874,9 +812,8 @@ export interface SignInShareInput {shareType?: 'overview' | 'dashboard' | 'report';}-/** Share's three lookups arrive through the composition root's thunk.- * Not a dynamic import: `share.service.ts` statically imports this file's- * `hashPassword`, so a static edge back would be a real cycle. */+/** `share.service.ts` statically imports `hashPassword` from this file, so+ * share is reached through the `services` thunk to avoid an import cycle. */const SHARE_ACCESS_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;export async function signInToShare(@@ -929,12 +866,6 @@ export async function signInToShare(return true;}-// ------------------------------------------------------------------------// The github/google OAuth callback (apps/api's /oauth/{github,google}/callback,-// same shape as gsc.service.ts#completeGscOAuthCallback). State/query parsing-// and cookie reads stay in each transport: only the token exchange, user-// lookup/creation and session issuance live here.-export interface OAuthUser {id: string;email: string;@@ -1082,11 +1013,6 @@ export interface CompleteOAuthCallbackInput {logger: Pick<Logger, 'error'>;}-/**- * State/token-exchange validation stays with the caller (`assertOAuthState`,- * then the provider-specific `fetch*OAuthUser`); this is the shared half —- * find-or-create the account and issue a session.- */export async function completeOAuthCallback(deps: ServiceDeps,input: CompleteOAuthCallbackInputdiff --git a/packages/core/src/modules/auth/src/access.ts b/packages/core/src/modules/auth/src/access.tsindex 0e5533aed..647a52c11 100644--- a/packages/core/src/modules/auth/src/access.ts+++ b/packages/core/src/modules/auth/src/access.ts@@ -1,15 +1,9 @@-// The permission ladder. It lives in the auth module, not in `shared/` — it-// throws a transport error (`TRPCForbiddenError`) from the bottom layer, and-// R10 puts every access check in the auth service and the procedure-// builders.+// Lives in the auth module, not `shared/`: it throws a transport error+// (`TRPCForbiddenError`).//-// The four data lookups arrive as an injected `AccessLookups` instead of-// being imported from `@openpanel/db`. That injection is not decoration:-// core must stay importable without a database — `bun test` loads this-// package with no DATABASE_URL and no Prisma client — and it is the same-// seam `createCacheMiddleware` and `createRateLimitMiddleware` already use-// in rpc/base.ts. `auth.service.ts`'s `createAccessChecks` call binds it to-// the real services; a test binds it to two functions.+// The data lookups are injected rather than imported from `@openpanel/db` so+// core stays importable without a database: `bun test` loads this package with+// no DATABASE_URL and no Prisma client.import { TRPCForbiddenError } from '../../../rpc/errors';@@ -71,20 +65,17 @@ export interface AccessChecks<const ORGANIZATION_ADMIN_ROLE = 'org:admin';/**- * The permission ladder.- *- * Two independent controls, each with one job:+ * The permission ladder. Two independent controls:** - ADMIN is the organization role (`member.role === 'org:admin'`). It gates* destruction and billing.- * - WRITE is the per-project access level. It gates every mutation. `admin`+ * - WRITE is the per-project access level. It gates every mutation; `admin`* level counts as a superset of `write`.- * - READ is the floor: membership of the project, which is what queries need.+ * - READ is the floor: membership of the project.*- * They are deliberately separate. Project levels were unenforced for so long- * that the value stored on most rows was never chosen by anyone, so hanging- * destructive operations off the org role avoids retroactively giving meaning- * to that data.+ * They are separate because project levels were unenforced for so long that+ * the stored value on most rows was never chosen by anyone, so hanging+ * destructive operations off the org role avoids giving meaning to that data.*/export function createAccessChecks<TProjectAccess extends ProjectAccessLike,diff --git a/packages/core/src/modules/auth/src/constants.ts b/packages/core/src/modules/auth/src/constants.tsindex f3617f2d2..dac2b3bab 100644--- a/packages/core/src/modules/auth/src/constants.ts+++ b/packages/core/src/modules/auth/src/constants.ts@@ -1,6 +1,3 @@-// Deployment-derived: the session cookie's domain and `secure` flag come from-// the dashboard's own URL, so they are computed from the config the boot path-// already holds rather than read at import.import type { CoreConfig } from '../../../config';import type { CookieOptions } from '../../../shared/cookie';import { parseCookieDomain } from './cookie-domain';diff --git a/packages/core/src/modules/auth/src/cookie-domain.ts b/packages/core/src/modules/auth/src/cookie-domain.tsindex 8ef93801d..e61c0ee54 100644--- a/packages/core/src/modules/auth/src/cookie-domain.ts+++ b/packages/core/src/modules/auth/src/cookie-domain.ts@@ -40,7 +40,6 @@ export const parseCookieDomain = (config: CoreConfig, url: string) => {const domain = new URL(url);const hostname = domain.hostname;- // For localhost or IP addresses, don't set domainif (hostname === 'localhost' || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {return {domain: undefined,@@ -50,12 +49,9 @@ export const parseCookieDomain = (config: CoreConfig, url: string) => {const parts = hostname.split('.');- // Handle multi-part TLDs like co.uk, com.au, etc.if (parts.length >= 3) {const potentialTLD = parts.slice(-2).join('.');if (isMultiPartTLD(config, potentialTLD)) {- // For domains like example.co.uk or subdomain.example.co.uk- // Use the last 3 parts: .example.co.ukreturn {domain: `.${parts.slice(-3).join('.')}`,secure: domain.protocol === 'https:',@@ -63,7 +59,6 @@ export const parseCookieDomain = (config: CoreConfig, url: string) => {}}- // For regular subdomains, use the last 2 partsif (parts.length > 2) {return {domain: `.${parts.slice(-2).join('.')}`,@@ -71,7 +66,6 @@ export const parseCookieDomain = (config: CoreConfig, url: string) => {};}- // For root domains, use the full domain with leading dotreturn {domain: `.${hostname}`,secure: domain.protocol === 'https:',diff --git a/packages/core/src/modules/auth/src/login-session.ts b/packages/core/src/modules/auth/src/login-session.tsindex 16fdfc48d..8965c10ca 100644--- a/packages/core/src/modules/auth/src/login-session.ts+++ b/packages/core/src/modules/auth/src/login-session.ts@@ -1,18 +1,11 @@// Postgres-backed login sessions (a `sessions` row keyed by the hash of a-// browser's cookie). Not to be confused with session.service.ts's ClickHouse-// visitor sessions.-//-// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the-// `loadDb` lazy loader is gone. `http/session.ts`'s `resolveSession` already-// carried an (until-now-unused) `AppDeps` for exactly this.+// browser's cookie). Not to be confused with ClickHouse visitor sessions.import type { Session, User } from '@openpanel/db/src/prisma-client';import type { ServiceDeps } from '../../../services';import { EMPTY_SESSION } from '../../../shared/session';import { decodeSessionToken, hashSessionToken } from './token';-/** Only Postgres — narrowed so `AppDeps` (http/session.ts, before- * `ServiceDeps.queues` exists) satisfies it with no cast. */type LoginSessionDeps = Pick<ServiceDeps, 'db' | 'config'>;const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30;diff --git a/packages/core/src/modules/auth/src/oauth.ts b/packages/core/src/modules/auth/src/oauth.tsindex fc51b33c4..44d0a9c1d 100644--- a/packages/core/src/modules/auth/src/oauth.ts+++ b/packages/core/src/modules/auth/src/oauth.ts@@ -3,14 +3,11 @@ import { GitHub } from 'arctic';import type { CoreConfig } from '../../../config';export type { OAuth2Tokens } from 'arctic';-// Re-exported straight from source, not the `Arctic` import above — that one-// is also used below for `Arctic.Google`, so `export { Arctic }` would trip-// `noExportedImports` over a binding that genuinely has a second use.+// Re-exported from source: `Arctic` is also used below, so `export { Arctic }`+// would trip `noExportedImports`.export * as Arctic from 'arctic';-// Built per call, not at import: an arctic client is a credential holder with-// no socket, so there is nothing to keep alive and nothing to construct at-// module scope.+// Built per call: an arctic client only holds credentials.export function githubClient(config: CoreConfig): GitHub {const { clientId, clientSecret, redirectUri } = config.auth.github;return new GitHub(clientId, clientSecret, redirectUri);diff --git a/packages/core/src/modules/auth/src/registration.ts b/packages/core/src/modules/auth/src/registration.tsindex 1da439bec..b495acdb9 100644--- a/packages/core/src/modules/auth/src/registration.ts+++ b/packages/core/src/modules/auth/src/registration.ts@@ -1,7 +1,5 @@import type { ServiceDeps } from '../../../services';-/** Only Postgres — narrowed so any of this module's several callers, none of- * which carry a full `ServiceDeps`, satisfy it with no cast. */type RegistrationDeps = Pick<ServiceDeps, 'db' | 'config'>;/**@@ -16,13 +14,11 @@ export async function getIsRegistrationAllowed(deps: RegistrationDeps,inviteId?: string | null) {- // ALLOW_REGISTRATION is always undefined in cloudconst { allowRegistration, allowInvitation } = deps.config.auth;if (allowRegistration === undefined) {return true;}- // Self-hosting logic// 1. First user is always allowedconst count = await deps.db.user.count();if (count === 0) {@@ -44,6 +40,5 @@ export async function getIsRegistrationAllowed(return !!invite;}- // 3. Otherwise, check if general registration is allowedreturn allowRegistration;}diff --git a/packages/core/src/modules/auth/src/token.ts b/packages/core/src/modules/auth/src/token.tsindex f2c442c36..cfcc1c4a8 100644--- a/packages/core/src/modules/auth/src/token.ts+++ b/packages/core/src/modules/auth/src/token.ts@@ -1,8 +1,7 @@-// Session bearer tokens: the browser holds `token`, Postgres stores only its-// hash — a leaked `sessions` row is not a leaked cookie. `hashSessionToken` is-// the single source for that hash so @openpanel/db's session CRUD (which-// cannot live here without a core -> db cycle, see auth.service.ts) and this-// package's own token issuance always agree on the session id.+// The browser holds `token`, Postgres stores only its hash, so a leaked+// `sessions` row is not a leaked cookie. `hashSessionToken` is the single source+// of that hash so @openpanel/db's session CRUD (which cannot live here without+// a core -> db cycle) and this package's token issuance agree on the session id.import crypto from 'node:crypto';import { sha256 } from '@oslojs/crypto/sha2';diff --git a/packages/core/src/modules/client/client.routes.ts b/packages/core/src/modules/client/client.routes.tsindex 4318c0705..4383b2025 100644--- a/packages/core/src/modules/client/client.routes.ts+++ b/packages/core/src/modules/client/client.routes.ts@@ -1,12 +1,3 @@-// The /manage/clients REST surface, delegating its CRUD bodies to-// client.service.ts's createClientForOrganization/updateClientForOrganization/-// etc — the same functions the tRPC router (client.rpc.ts) calls. Response-// envelopes (`{ data }` / `{ success }`) keep a byte-unchanged URL surface.-//-// Body schemas are local, not in a client.constants.ts file: unlike project,-// whose zCreateProject / zUpdateProject moved with ProjectTypeNames, this-// module has no rpc-shared constants to publish.-//// Auth goes through `authenticateAllowedClient` (http/client-auth.ts);// `allow: ['root']` means only root clients may manage resources.diff --git a/packages/core/src/modules/client/client.rpc.test.ts b/packages/core/src/modules/client/client.rpc.test.tsindex 1da796ca0..19d2a8981 100644--- a/packages/core/src/modules/client/client.rpc.test.ts+++ b/packages/core/src/modules/client/client.rpc.test.ts@@ -1,9 +1,5 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// `list` has no access check of its own, so it is not exercised here either —-// the access-check + mutation bodies ride on @openpanel/db (lazy-loaded-// through ./src/access and client.service.ts); wiring this router end-to-end-// against a real Postgres is protectedProcedure's job, not this one's — see-// client.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here; no database. `list` has+// no access check of its own, so it is not exercised either.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -19,8 +15,7 @@ const COOKIE_OPTIONS: CookieOptions = {path: '/',};-// EMPTY_SESSION's shape matters: `TrpcContext.session` is never literally-// `null`, only its `userId` is.+// `TrpcContext.session` is never literally `null`, only its `userId` is.const EMPTY_SESSION = { session: null, user: null, userId: null };async function anonCaller() {diff --git a/packages/core/src/modules/client/client.rpc.ts b/packages/core/src/modules/client/client.rpc.tsindex 727b62eeb..74880b412 100644--- a/packages/core/src/modules/client/client.rpc.ts+++ b/packages/core/src/modules/client/client.rpc.ts@@ -2,11 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// `ctx.services.client` carries this module's factory.-//-// The permission ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/client/client.service.test.ts b/packages/core/src/modules/client/client.service.test.tsindex 277a13609..5807a681f 100644--- a/packages/core/src/modules/client/client.service.test.ts+++ b/packages/core/src/modules/client/client.service.test.ts@@ -1,10 +1,7 @@-// The subject is built by its factory over a fake `ServiceDeps`, so Postgres-// needs no module mock at all — `deps.db` IS the fake below, same idiom as-// reference.service.test.ts. `@openpanel/redis` is still stubbed:-// `getClientByIdCached` calls `cacheable(...)` inside `createClientService`-// itself now (not at this module's import time), but the binding is resolved at-// `client.service.ts`'s own import time, so the mock must still land before-// that import — hence the `await import` in `beforeAll`.+// The subject is built over a fake `ServiceDeps`, so `deps.db` IS the fake below.+// `@openpanel/redis` is still stubbed: the `cacheable` binding resolves at+// `client.service.ts`'s import time, so the mock must land first (the `await import`+// in `beforeAll`).import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -111,10 +108,8 @@ const client = {}),};-// Bypasses the Redis cache-aside entirely — this module's own logic is-// exercised directly, caching is @openpanel/redis's concern. Same stub as-// organization.service.test.ts, needed because create/update/delete all call-// `.clear()` on getClientByIdCached.+// Bypasses the Redis cache-aside; create/update/delete all call `.clear()` on+// getClientByIdCached.function cacheableStub(fnOrName: ((...args: unknown[]) => unknown) | string,fnOrTtl: ((...args: unknown[]) => unknown) | number@@ -250,10 +245,8 @@ test('deleteClientForOrganization deletes only when the client belongs to the orexpect(clientStore.has('client_a')).toBe(false);});-// The stored secret is a hash, and the published docs promise it is never-// retrievable after creation (docs/api/manage/clients.mdx). The fake Prisma-// above ignores `omit`, so these assert on what the service ASKED FOR rather-// than on the rows it got back.+// The stored secret is a hash and is never retrievable after creation. The fake Prisma+// above ignores `omit`, so these assert on what the service ASKED FOR.const OMIT_SECRET = { secret: true };test('every client read path asks Prisma to omit the secret', async () => {diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.tsindex bb3080179..1cecd73f9 100644--- a/packages/core/src/modules/client/client.service.ts+++ b/packages/core/src/modules/client/client.service.ts@@ -1,17 +1,6 @@-// The /manage REST CRUD bodies (client.routes.ts's listClients/getClient/-// createClient/updateClient/deleteClient) call the same-// create/update/delete/list functions the tRPC router (client.rpc.ts) does.-//-// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`. No-// dependency on project.service.ts here (the reverse direction exists, for-// cache invalidation) — project-ownership checks below query `db.project`-// directly.-//-// `getClientByIdCached` is a module-scope `cacheablePerDb`, keyed on the-// Postgres client rather than on the scope. Its L1 LRU has to survive across-// calls to be worth anything, and the ingest hot path-// (`ingest/src/client-auth.ts`, `http/client-auth.ts`) passes the scope it-// holds on each call. One instance per process to read, one to invalidate.+// `getClientByIdCached` is a module-scope `cacheablePerDb`, keyed on the Postgres+// client rather than the scope: its L1 LRU has to survive across calls, and the+// ingest hot path passes the scope it holds on each call.import crypto from 'node:crypto';import type { Client, Prisma } from '@openpanel/db/src/prisma-client';@@ -22,10 +11,8 @@ import { hashClientSecret } from '../../shared/client-secret';export type IServiceClient = Client;/**- * What a read path may return. The stored `secret` is a hash and the docs- * promise it is never retrievable after creation- * (apps/public/content/docs/api/manage/clients.mdx), so every path but the- * one authentication uses drops it.+ * What a read path may return. The stored `secret` is a hash that is never+ * retrievable after creation, so every path but the one authentication uses drops it.*/export type IPublicClient = Omit<Client, 'secret'>;@@ -37,10 +24,8 @@ export type IServiceClientWithProject = Prisma.ClientGetPayload<{};}>;-// Single source for the three client tiers — Prisma's own `ClientType` enum-// (schema.prisma) is a `@openpanel/db` VALUE import, which-// `core-uses-ctx-not-db-internals` forbids outside the four named seams, so-// this is declared here instead and reused by client.rpc.ts / client.routes.ts.+// Declared here because Prisma's `ClientType` enum would be an `@openpanel/db`+// value import, which core forbids outside the named seams.export const CLIENT_TYPES = ['read', 'write', 'root'] as const;export type ClientType = (typeof CLIENT_TYPES)[number];@@ -94,9 +79,8 @@ export async function getClientById(* invalidates Redis and that LRU; other nodes may serve stale from theirs for* up to 60s.*- * The name is EMPTY on purpose: the in-factory `cacheable(...)` this replaces- * was handed an anonymous arrow, so `fn.name` was `''` and the Redis key is- * `cachable::<id>`. Naming it here would orphan every live entry.+ * The name is EMPTY on purpose: the Redis key is `cachable::<id>` and naming it+ * would orphan every live entry.*/export const getClientByIdCached = cacheablePerDb('',@@ -104,8 +88,6 @@ export const getClientByIdCached = cacheablePerDb(FIVE_MINUTES_IN_SECONDS);-// --- /manage REST CRUD (client.routes.ts) ----export async function listClientsForOrganization(deps: ServiceDeps,organizationId: string,@@ -251,10 +233,7 @@ export function createClientService(id: string): Promise<IServiceClientWithProject | null> =>getClientByIdCached(deps, id),- /** Invalidates a single id in `getClientByIdCached`'s L1 LRU + Redis. Its- * own create/update/delete already call this; `project.service.ts` calls- * the module-scope spelling to invalidate a project's clients on a- * project mutation. */+ /** Invalidates a single id in `getClientByIdCached`'s L1 LRU + Redis. */clearClientByIdCache: (id: string): Promise<number> =>getClientByIdCached.clear(deps, id),listClientsForOrganization: (diff --git a/packages/core/src/modules/conversation/conversation.rpc.test.ts b/packages/core/src/modules/conversation/conversation.rpc.test.tsindex c8cb5e777..63e7865b6 100644--- a/packages/core/src/modules/conversation/conversation.rpc.test.ts+++ b/packages/core/src/modules/conversation/conversation.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + ownership logic ride on @openpanel/db (lazy-loaded, see-// conversation.service.ts's header); wiring this router end-to-end against a-// real Postgres is P6's (protectedProcedure) job, not this one's — see-// conversation.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.tsindex b8172ebc8..83a582bf4 100644--- a/packages/core/src/modules/conversation/conversation.rpc.ts+++ b/packages/core/src/modules/conversation/conversation.rpc.ts@@ -1,13 +1,7 @@-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. `enforceAccess` reads the raw, pre-zod input and only a-// TOP-LEVEL `projectId` — `list` and `rename` both take one, so their project-// access is already enforced before the handler runs. `get` and `delete` take-// only `id`, invisible to `enforceAccess`, so their ownership check stays in-// the handler. `get` denies with NOT_FOUND rather than FORBIDDEN — a-// deliberate choice, not an oversight.-//-// The per-project access ladder itself is bound once, in auth.service.ts;-// every procedure here reaches it through `ctx.services.auth`.+// `protectedProcedure` runs `enforceAccess` BEFORE the input parser, and it only reads a+// TOP-LEVEL `projectId`. `list` and `rename` take one, so their project access is already+// enforced; `get` and `delete` take only `id`, so their ownership check stays in the+// handler. `get` denies with NOT_FOUND rather than FORBIDDEN on purpose.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';@@ -23,12 +17,8 @@ const LIST_LIMIT_MIN = 1;const LIST_LIMIT_MAX = 200;/**- * Conversation management — listing, fetching, renaming, deleting.- * Conversation creation is implicit (lazy) on the first message via the- * /ai/agents/* route, so there's no `create` here.- *- * All procedures enforce ownership via `userId === session.userId` so a- * user can never read or mutate another user's conversations.+ * Listing, fetching, renaming, deleting. Creation is implicit on the first message via+ * the /ai/agents/* route. Every procedure enforces `userId === session.userId`.*/export const conversationRouter = createTRPCRouter({list: protectedProcedurediff --git a/packages/core/src/modules/conversation/conversation.service.test.ts b/packages/core/src/modules/conversation/conversation.service.test.tsindex f51420320..4ca0f7bf7 100644--- a/packages/core/src/modules/conversation/conversation.service.test.ts+++ b/packages/core/src/modules/conversation/conversation.service.test.ts@@ -1,7 +1,3 @@-// The subject is built by its factory over a fake `ServiceDeps`, so Postgres-// needs no module mock at all — `deps.db` IS the fake below, same idiom as-// reference.service.test.ts.-import { beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';import type { ServiceDeps } from '../../services';diff --git a/packages/core/src/modules/conversation/conversation.service.ts b/packages/core/src/modules/conversation/conversation.service.tsindex 57b6748a7..8da5d2b04 100644--- a/packages/core/src/modules/conversation/conversation.service.ts+++ b/packages/core/src/modules/conversation/conversation.service.ts@@ -1,5 +1,3 @@-// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`.-import type {ChatMessage,Conversation,@@ -69,12 +67,9 @@ export async function listConversations(}/**- * Set the title on a conversation, creating the row if it doesn't- * exist yet. Used by the chat titler: on the first turn we stream a- * title in parallel with the agent run, and the titler may finish- * before the agent's `ConversationStore.save()` has inserted the row.- * This upsert makes that race harmless — the row ends up with the- * right owner + title regardless of which side finishes first.+ * Set the title on a conversation, creating the row if it doesn't exist. The chat+ * titler may finish before the agent's `ConversationStore.save()` inserts the row;+ * the upsert makes that race harmless.*/export async function upsertConversationTitle(deps: ServiceDeps,diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.tsindex 5cc01aeef..187e2e106 100644--- a/packages/core/src/modules/dashboard/dashboard.service.ts+++ b/packages/core/src/modules/dashboard/dashboard.service.ts@@ -1,7 +1,3 @@-// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; this-// module value-imports neither `@openpanel/db` nor its own package barrel —-// the Prisma row types below are `import type`, erased at runtime.-import type { Dashboard, Prisma } from '@openpanel/db/src/prisma-client';import { PrismaError } from 'prisma-error-enum';import { TRPCNotFoundError } from '../../rpc/errors';diff --git a/packages/core/src/modules/email/email.rpc.test.ts b/packages/core/src/modules/email/email.rpc.test.tsindex 4daaf1887..192328de0 100644--- a/packages/core/src/modules/email/email.rpc.test.ts+++ b/packages/core/src/modules/email/email.rpc.test.ts@@ -1,8 +1,5 @@-// Only the "is anyone logged in" boundary (+ the token check, which never-// touches a database) is exercised here. `unsubscribe`'s upsert and-// `getPreferences`/`updatePreferences`'s reads ride on @openpanel/db-// (lazy-loaded, see email.rpc.ts's header); wiring this router end-to-end-// against a real Postgres is P6's (protectedProcedure) job, not this one's.+// Only the "is anyone logged in" boundary and the token check (which never+// touches a database) are exercised here.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -19,7 +16,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };@@ -56,11 +52,10 @@ test('unsubscribe rejects an invalid token before touching the database', async).rejects.toMatchObject({ code: 'BAD_REQUEST' });});-// `updatePreferences` used to take `z.record(z.string(), z.boolean())`, so an-// unknown key was written to `emailUnsubscribe` where nothing reads it. The-// first cut of the fix used `z.record(z.enum(...))`, which in zod 4 is-// EXHAUSTIVE — it rejected a single real toggle, which is what the form sends.-// These pin both halves so that trap cannot come back.+// `updatePreferences` once took `z.record(z.string(), z.boolean())`, so an+// unknown key was written to `emailUnsubscribe` where nothing reads it. An+// enum-keyed `z.record` is EXHAUSTIVE in zod 4 and rejected a single real+// toggle, which is what the form sends. These pin both halves.test('updatePreferences accepts a subset of real categories', () => {expect(zUpdateEmailPreferences.safeParse({ categories: { weekly_digest: true } })diff --git a/packages/core/src/modules/email/email.rpc.ts b/packages/core/src/modules/email/email.rpc.tsindex 44f5260f3..08737f78f 100644--- a/packages/core/src/modules/email/email.rpc.ts+++ b/packages/core/src/modules/email/email.rpc.ts@@ -1,23 +1,9 @@-// Deliberately R + C only (no `email.service.ts`): the three procedures' bodies-// are three small `db.emailUnsubscribe` calls, inlined here the same way-// conversation.rpc.ts inlines its organization lookup. Sending/templates stay-// in @openpanel/email; core's `clients/email.ts` already wraps that package-// for the one thing this module doesn't need — sending.+// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so+// anything resolved from another id needs its own explicit check in the handler.//-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. The explicit checks in the handlers below stay: `enforceAccess`-// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved-// from another id needs its own.-//-// This module has no queue/cron of its own, so there is no-// `ctx.services.email`, same as `user`/`reference`.-//-// `verifyUnsubscribeToken` is imported from @openpanel/email's own-// `unsubscribe.ts` file, not its barrel: the barrel (`@openpanel/email` ->-// `./src`) pulls in @openpanel/db, which is exactly the cycle-// `clients/email.ts`'s header describes for `sendEmail`. `unsubscribe.ts`-// itself only touches `node:crypto`, so importing it directly sidesteps the-// cycle instead of deferring it.+// `verifyUnsubscribeToken` is imported from @openpanel/email's `unsubscribe.ts`,+// not its barrel: the barrel pulls in @openpanel/db, a cycle (see+// `clients/email.ts`). `unsubscribe.ts` only touches `node:crypto`.import { verifyUnsubscribeToken } from '@openpanel/email/src/unsubscribe';import { z } from 'zod';diff --git a/packages/core/src/modules/email/src/sequence.test.ts b/packages/core/src/modules/email/src/sequence.test.tsindex bed36ad94..1d024b034 100644--- a/packages/core/src/modules/email/src/sequence.test.ts+++ b/packages/core/src/modules/email/src/sequence.test.ts@@ -118,8 +118,7 @@ test('defers a step whose day gate has not been reached', async () => {});test('completes rather than replays when the pointer is unknown', async () => {- // The whole reason this branch exists: the old findIndex returned -1 for a- // removed step, which restarted the sequence from the top.+ // A removed step must not restart the sequence from the top.const { onAdvance, onComplete, result } = run(makeSteps(), [makeSubject('a-step-that-was-renamed', 40),]);diff --git a/packages/core/src/modules/email/src/sequence.ts b/packages/core/src/modules/email/src/sequence.tsindex ce74a5752..12857b562 100644--- a/packages/core/src/modules/email/src/sequence.ts+++ b/packages/core/src/modules/email/src/sequence.ts@@ -1,9 +1,3 @@-// It sends email, so it sits in the module that owns email, not in the layer-// below every transport. Its two callers — the onboarding drip-// (modules/onboarding) and the wind-down track-// (modules/organization/src/wind-down.ts) — reach it sideways, module to-// module.-//// A day-gated email sequence runner. Each subject carries a pointer (the last// step whose email was sent) and an anchor date. On every tick the runner// resolves the next step, checks the day gate and the step's own guard, sends,diff --git a/packages/core/src/modules/event/event.jobs.ts b/packages/core/src/modules/event/event.jobs.tsindex c9810bb23..397cfcde0 100644--- a/packages/core/src/modules/event/event.jobs.ts+++ b/packages/core/src/modules/event/event.jobs.ts@@ -1,6 +1,4 @@-// The event buffer (Redis → ClickHouse `events`) is this module's domain, so-// its flush cron fragment lives here rather than on the ingest module that-// merely writes to it.+// The event buffer (Redis -> ClickHouse `events`) is this module's domain.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/event/event.rpc.test.ts b/packages/core/src/modules/event/event.rpc.test.tsindex 82b621ecf..3785ed35d 100644--- a/packages/core/src/modules/event/event.rpc.test.ts+++ b/packages/core/src/modules/event/event.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + query bodies ride on @openpanel/db (lazy-loaded, see-// event.service.ts's header); wiring this router end-to-end against a real-// ClickHouse is protectedProcedure's job — see event.rpc.ts's header. Same-// shape as session.rpc.test.ts.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import {diff --git a/packages/core/src/modules/event/event.rpc.ts b/packages/core/src/modules/event/event.rpc.tsindex e58699854..63c48f6ff 100644--- a/packages/core/src/modules/event/event.rpc.ts+++ b/packages/core/src/modules/event/event.rpc.ts@@ -2,9 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// `pages` / `pagesTimeseries` / `previousPages` / `pageTimeseries` read the-// overview module's pages service via `ctx.services.pages`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.tsindex 8b1a3c081..835b584a4 100644--- a/packages/core/src/modules/event/event.service.ts+++ b/packages/core/src/modules/event/event.service.ts@@ -1,7 +1,3 @@-// The event read path. Every query is a `sql` fragment (src/sql.ts); the two-// filter compilers (`getEventFiltersWhereClause`, `buildFilterWhere`) are-// shared, and src/filter-clauses.ts is the bridge.-import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import type { EventMeta, Prisma } from '@openpanel/db/src/prisma-client';import { getCache } from '@openpanel/redis';@@ -145,17 +141,15 @@ export interface IClickhouseEvent {brand: string;model: string;imported_at: string | null;- // Ingestion (ClickHouse-insert) time. Set explicitly at insert time; the- // column DEFAULTs to created_at for rows that omit it. Used as the cursor for- // object-store exports. Optional here because most read queries don't select- // it.+ // Ingestion (ClickHouse-insert) time, the cursor for object-store exports. Optional+ // because most read queries don't select it.inserted_at?: string;sdk_name: string;sdk_version: string;revenue?: number;groups: string[];- // They do not exist here. Just make ts happy for now+ // Not stored on the event row; populated by readers that join them.profile?: IServiceProfile;meta?: EventMeta;}@@ -450,14 +444,9 @@ export async function getEvents(}/**- * Persist an event to ClickHouse (via the buffer) and upsert the profile- * on session boundaries.- *- * Does NOT touch the session-row buffer. Callers producing non-session_start- * / session_end events are responsible for calling `sessionBuffer.ingest()`- * before this. `incoming-event.ts` is the only such caller today; everywhere- * else (session_start, session_end) the session-row update is correctly a- * no-op anyway.+ * Persist an event to ClickHouse (via the buffer) and upsert the profile on session+ * boundaries. Does NOT touch the session-row buffer: callers producing events other+ * than session_start / session_end must call `sessionBuffer.ingest()` first.*/export async function createEvent(deps: ServiceDeps,@@ -536,19 +525,11 @@ export async function createEvent(},};- // Only upsert the profile on session boundaries.- // - session_start covers fresh activity.- // - session_end is synthesized server-side by the worker.- // Identified users' explicit profile writes (op.identify(), op.setProfile())- // go through the controller path and are not affected by this branch.- //- // `isFromEvent=true` activates profile-buffer's cache shortcut: if the- // profile is in the 1h Redis cache (i.e. recently flushed), the add is- // skipped. Trade-off: profile.last_seen_at granularity is capped at the- // cache TTL (~1h) rather than per-session. Accepted because (a) the bulk- // of those writes carry no new information (anonymous profile data is- // event-derived and stable across a session), and (b) recency queries- // should derive from event timestamps, not from profile.last_seen_at.+ // Only upsert the profile on session boundaries (session_start covers fresh+ // activity; session_end is synthesized by the worker). `isFromEvent=true` makes+ // profile-buffer skip the add when the profile is in the 1h Redis cache, so+ // profile.last_seen_at is only as fine as that TTL. Accepted: anonymous profile+ // data is stable across a session, and recency queries should use event timestamps.if (payload.name === 'session_start' || payload.name === 'session_end') {promises.push(upsertProfile(deps, profile, true));}diff --git a/packages/core/src/modules/event/src/create-event-id.test.ts b/packages/core/src/modules/event/src/create-event-id.test.tsindex b56ddb26c..99ec835d4 100644--- a/packages/core/src/modules/event/src/create-event-id.test.ts+++ b/packages/core/src/modules/event/src/create-event-id.test.ts@@ -1,6 +1,5 @@-// `createEvent` takes `ServiceDeps` and writes through `deps.buffers.event`,-// so the buffer is handed in rather than mocked onto a module specifier — no-// `mock.module` and no restore to get wrong.+// `createEvent` writes through `deps.buffers.event`, so the buffer is handed in+// rather than mocked onto a module specifier.import { beforeAll, describe, expect, mock, test } from 'bun:test';import type { ServiceDeps } from '../../../services';diff --git a/packages/core/src/modules/event/src/dates.ts b/packages/core/src/modules/event/src/dates.tsindex 483b42f46..36a41e07e 100644--- a/packages/core/src/modules/event/src/dates.ts+++ b/packages/core/src/modules/event/src/dates.ts@@ -1,7 +1,6 @@-// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs-// a client and a pino logger at import time (see insight.service.ts's header),-// and the fragment builders here must stay pure and synchronous. Same choice-// cohort.service.ts made for its table map.+// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs a+// client and a pino logger at import time, and the fragment builders here must stay+// pure and synchronous.const CLICKHOUSE_DATE_SUFFIX = /(\.\d{3})?Z+$/;diff --git a/packages/core/src/modules/event/src/filter-clauses.ts b/packages/core/src/modules/event/src/filter-clauses.tsindex cb763e7e3..ee8ea7566 100644--- a/packages/core/src/modules/event/src/filter-clauses.ts+++ b/packages/core/src/modules/event/src/filter-clauses.ts@@ -1,10 +1,6 @@-// The ONE place this module splices pre-compiled filter SQL.-//-// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is the-// sessions/profiles/events-table filter compiler; it returns bound-// `SqlFragment`s, as does `getEventFiltersWhereClause`-// (../../chart/src/filter-where.ts). Nothing is bridged any more — this file-// only assembles what the compiler already produced.+// The ONE place this module splices pre-compiled filter SQL: it only assembles what+// the filter compilers (chart/src/table-filter-where.ts, chart/src/filter-where.ts)+// already produced.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/event/src/sql.test.ts b/packages/core/src/modules/event/src/sql.test.tsindex 1480add99..6ae4f75b9 100644--- a/packages/core/src/modules/event/src/sql.test.ts+++ b/packages/core/src/modules/event/src/sql.test.ts@@ -1,7 +1,6 @@// Shape tests for the event module's fragments: every user value binds as a-// `{pN:Type}` parameter (nothing is interpolated), and `sql.id` refuses-// anything off the column whitelists. These run offline, so they assert the-// rendered statement and its params, never a result set.+// `{pN:Type}` parameter, and `sql.id` refuses anything off the column whitelists. These+// run offline.import { describe, expect, test } from 'bun:test';import { sql } from '@openpanel/db/src/clickhouse/sql';@@ -312,8 +311,8 @@ describe('queryEventsQuery', () => {expect(query_params).toEqual({ p1: PROJECT_ID, p2: 100 });});- // Callers label these rows newest-first, so the cut has to happen after the- // sort rather than wherever the scan starts (#476).+ // Callers label these rows newest-first, so the cut has to happen after the sort+ // rather than wherever the scan starts (#476).test('takes the newest rows, not an arbitrary slice', () => {const { query } = queryEventsQuery({projectId: PROJECT_ID,diff --git a/packages/core/src/modules/event/src/sql.ts b/packages/core/src/modules/event/src/sql.tsindex 175c0450a..e8e523211 100644--- a/packages/core/src/modules/event/src/sql.ts+++ b/packages/core/src/modules/event/src/sql.ts@@ -1,15 +1,11 @@-// Every ClickHouse query the event module runs, as pure `sql` fragments.-//// Dates bind as `YYYY-MM-DD HH:mm:ss` strings on purpose: a String param in a// DateTime64 position is parsed exactly like the literal it replaces, so the// result sets cannot drift by a millisecond truncation.//-// Cluster note: `events`, `profiles`, `groups` and `cohort_members` are-// Distributed on Cloud. The identity-stitching and cohort `IN (SELECT...)`-// subqueries, the profile/group LEFT ANY JOINs and any `IN (SELECT...)` a-// filter compiles all run under the client's `distributed_product_mode:-// 'allow'`. Every `IN` list binds as `Array(String)`, a literal list to the-// planner.+// `events`, `profiles`, `groups` and `cohort_members` are Distributed on Cloud. The+// `IN (SELECT...)` subqueries and profile/group LEFT ANY JOINs run under the client's+// `distributed_product_mode: 'allow'`. Every `IN` list binds as `Array(String)`, a+// literal list to the planner.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import {diff --git a/packages/core/src/modules/export/export.routes.ts b/packages/core/src/modules/export/export.routes.tsindex 7c20febe1..749e442a5 100644--- a/packages/core/src/modules/export/export.routes.ts+++ b/packages/core/src/modules/export/export.routes.ts@@ -112,10 +112,6 @@ const zDateRange = z.object({range: zRange.optional(),});-// ----------------------------------------------------------------------------// /export-// ----------------------------------------------------------------------------const zExportEvents = z.object({project_id: z.string().optional(),projectId: z.string().optional(),@@ -303,10 +299,6 @@ export const exportRoutes = defineRoutes((app) =>));-// ----------------------------------------------------------------------------// /insights — analytics overview-// ----------------------------------------------------------------------------const zOverviewQuery = zDateRange.extend({interval: z.enum(['hour', 'day', 'week', 'month']).optional(),});@@ -428,10 +420,6 @@ const zUserFlowQuery = zDateRange.extend({.optional(),});-// ----------------------------------------------------------------------------// /insights — events-// ----------------------------------------------------------------------------const zEventsQuery = zDateRange.extend({eventNames: z.union([z.array(z.string()), z.string().transform((s) => [s])])@@ -457,10 +445,6 @@ const zPropertyValuesQuery = z.object({propertyKey: z.string(),});-// ----------------------------------------------------------------------------// /insights — profiles-// ----------------------------------------------------------------------------const zProfilesQuery = z.object({name: z.string().optional(),email: z.string().optional(),@@ -483,10 +467,6 @@ const zProfileSessionsQuery = z.object({limit: z.number().int().min(1).max(100).default(20),});-// ----------------------------------------------------------------------------// /insights — sessions-// ----------------------------------------------------------------------------const zSessionsQuery = zDateRange.extend({country: z.string().optional(),city: z.string().optional(),@@ -501,10 +481,6 @@ const zSessionsQuery = zDateRange.extend({limit: z.number().int().min(1).max(100).default(20),});-// ----------------------------------------------------------------------------// /insights — groups-// ----------------------------------------------------------------------------const zGroupsQuery = z.object({type: z.string().optional(),search: z.string().optional(),@@ -515,10 +491,6 @@ const zGetGroupQuery = z.object({memberLimit: z.number().int().min(1).max(50).default(10),});-// ----------------------------------------------------------------------------// /insights — Google Search Console-// ----------------------------------------------------------------------------const zGscOverviewQuery = zDateRange.extend({interval: z.enum(['day', 'week', 'month']).default('day'),});diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.tsindex 14c72329f..7150f6bd6 100644--- a/packages/core/src/modules/export/export.service.ts+++ b/packages/core/src/modules/export/export.service.ts@@ -1,12 +1,5 @@-// The export module owns no data of its own — it is the public read API-// (`/export` + `/insights`). Every handler in `export.routes.ts` is a thin-// delegate onto the overview/chart/event/session/profile/group/gsc/report-// services. This file holds only the plumbing every route shares — resolving-// a project id and a date range.-//-// The sibling services these routes delegate to are imported by RELATIVE-// path rather than through this package's own barrel (`@openpanel/core`), to-// avoid re-entering it mid-evaluation, which a relative import cannot do.+// Sibling services are imported by relative path, not through the package barrel,+// to avoid re-entering it mid-evaluation.import { resolveDateRange } from '@openpanel/shared';import type { AuthenticatedClient } from '../../http/client-auth';@@ -127,8 +120,6 @@ export async function resolveGscInsightsDateRange(};}-// --- service -------------------------------------------------------------export function createExportService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/group/group.rpc.test.ts b/packages/core/src/modules/group/group.rpc.test.tsindex 391a7be71..3c8e78963 100644--- a/packages/core/src/modules/group/group.rpc.test.ts+++ b/packages/core/src/modules/group/group.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + query bodies ride on @openpanel/db (lazy-loaded, see-// group.service.ts's header); wiring this router end-to-end against a real-// ClickHouse is P6's (protectedProcedure) job — see group.rpc.ts's header.-// Same shape as session.rpc.test.ts.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import {diff --git a/packages/core/src/modules/group/group.service.ts b/packages/core/src/modules/group/group.service.tsindex 9a913bff5..330fc08a1 100644--- a/packages/core/src/modules/group/group.service.ts+++ b/packages/core/src/modules/group/group.service.ts@@ -357,8 +357,6 @@ export async function getGroupMemberProfiles(return { data, count };}-// ---- the trpc group router's bodies-/** `list`: the page plus each group's member count / last activity. */export async function getGroupListPage(deps: ServiceDeps,@@ -462,8 +460,6 @@ export async function getGroupMemberProfilesPage(};}-// ---- the assistant/mcp tool entry points-export async function listGroupTypesCore(deps: ServiceDeps, projectId: string) {const types = await getGroupTypes(deps, projectId);return { types };diff --git a/packages/core/src/modules/group/src/dates.ts b/packages/core/src/modules/group/src/dates.tsindex c856e0b57..c1ea368a7 100644--- a/packages/core/src/modules/group/src/dates.ts+++ b/packages/core/src/modules/group/src/dates.ts@@ -1,6 +1,6 @@-// @openpanel/db's clickhouse/client.ts owns this, but importing it constructs-// a client and a pino logger at import time (see insight.service.ts's header).-// Same copy session/src/dates.ts carries.+// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs a+// client and a pino logger at import time, and the fragment builders here must stay+// pure and synchronous.const CLICKHOUSE_DATE_SUFFIX = /(\.\d{3})?Z+$/;diff --git a/packages/core/src/modules/group/src/sql.test.ts b/packages/core/src/modules/group/src/sql.test.tsindex 80bf9fa46..61a7040f4 100644--- a/packages/core/src/modules/group/src/sql.test.ts+++ b/packages/core/src/modules/group/src/sql.test.ts@@ -1,7 +1,5 @@// Shape tests for the group module's fragments: every user value binds as a-// `{pN:Type}` parameter (nothing is interpolated), and the optional clauses-// toggle correctly. Result-set equivalence was proven separately, per query,-// on a local prod-copy — not here; these run offline.+// `{pN:Type}` parameter, and the optional clauses toggle correctly. These run offline.import { describe, expect, test } from 'bun:test';import {diff --git a/packages/core/src/modules/group/src/sql.ts b/packages/core/src/modules/group/src/sql.tsindex e74b60e7d..2d33ceaff 100644--- a/packages/core/src/modules/group/src/sql.ts+++ b/packages/core/src/modules/group/src/sql.ts@@ -1,5 +1,3 @@-// Every ClickHouse query the group module runs, as pure `sql` fragments.-//// Cluster note: `groups`, `profiles` and `events` are Distributed on Cloud. No// query here carries an `IN (subquery)`; the `IN` lists bind as `Array(String)`// params, which is a literal list to the planner.diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.tsindex a633cbf41..b52a5fd85 100644--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts@@ -1,5 +1,4 @@-// Job/cron-fragment wiring — no ClickHouse/Postgres touched. The service-// methods themselves are exercised in gsc.service.test.ts.+// Job/cron-fragment wiring only; no ClickHouse/Postgres touched.import { expect, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -216,9 +215,7 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async]);});-// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot-// pins. The cadence now lives on the job itself, so this reads it straight-// off the registry.+// Pins the id/cadence, read straight off the registry.test('the gsc cron fragment keeps its scheduler id and cadence', () => {expect(queues.cron.jobs.gscSync.cron).toEqual({ pattern: '0 3 * * *' });});diff --git a/packages/core/src/modules/gsc/gsc.jobs.ts b/packages/core/src/modules/gsc/gsc.jobs.tsindex 1fec5425c..9dc6a499e 100644--- a/packages/core/src/modules/gsc/gsc.jobs.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.ts@@ -1,7 +1,3 @@-// `gscProjectSync` / `gscProjectBackfill` are this module's own queue (`gsc` in-// the registry). `gscSync` is a cron fragment, spread into the ONE `cron`-// queue by jobs.registry.ts.-import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/gsc/gsc.routes.ts b/packages/core/src/modules/gsc/gsc.routes.tsindex eacda9cbd..6b7e5e29d 100644--- a/packages/core/src/modules/gsc/gsc.routes.ts+++ b/packages/core/src/modules/gsc/gsc.routes.ts@@ -1,11 +1,6 @@-// The GSC OAuth callback. Delegates its token-exchange/upsert logic to-// gsc.service.ts's `completeGscOAuthCallback` — the same function this route-// calls.-//-// Per-route cookie signing is not wired yet, so `ctx.cookies.get` here reads-// the raw, unsigned cookie value; this route only re-checks the state match,-// and should not be treated as a signature-verified equivalent until that-// wiring lands.+// Per-route cookie signing is not wired yet, so `ctx.cookies.get` reads the+// raw, unsigned cookie value; this route only re-checks the state match and is+// not a signature-verified equivalent.import { redirect } from 'elysia';import { z } from 'zod';diff --git a/packages/core/src/modules/gsc/gsc.rpc.test.ts b/packages/core/src/modules/gsc/gsc.rpc.test.tsindex 9df8a62e5..87bfe0bc6 100644--- a/packages/core/src/modules/gsc/gsc.rpc.test.ts+++ b/packages/core/src/modules/gsc/gsc.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + business logic ride on @openpanel/db (lazy-loaded, see-// gsc.service.ts's header) and ctx.services.gsc; wiring this router-// end-to-end against a real Postgres is P6's (protectedProcedure) job, not-// this one's — see gsc.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here, with no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/gsc/gsc.rpc.ts b/packages/core/src/modules/gsc/gsc.rpc.tsindex 645787648..ef1163be7 100644--- a/packages/core/src/modules/gsc/gsc.rpc.ts+++ b/packages/core/src/modules/gsc/gsc.rpc.ts@@ -1,10 +1,5 @@-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. The explicit checks in the handlers below stay: `enforceAccess`-// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved-// from another id needs its own.-//-// The per-project access ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.+// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so+// anything resolved from another id needs its own explicit check in the handler.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/gsc/gsc.service.test.ts b/packages/core/src/modules/gsc/gsc.service.test.tsindex 768af87ae..f5702b19c 100644--- a/packages/core/src/modules/gsc/gsc.service.test.ts+++ b/packages/core/src/modules/gsc/gsc.service.test.ts@@ -1,8 +1,5 @@-// gsc.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.+// `mock.module` is registered before the subject's first call; the subject's+// import is side-effect-free.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -99,12 +96,10 @@ const ch = {insert: mock(async () => undefined),};-// The subject's functions take `ServiceDeps`, so `deps.db`/`deps.ch` ARE the-// fakes above — no `@openpanel/db` module mock is needed for either. The one-// module still mocked is core's own `ch-query`, which is what the subject now-// calls. `mock.module` has no per-file scope under bare `bun test` (AGENTS.md),-// so snapshot the real module into a plain object FIRST and restore it in-// afterAll — restoring via the live import binding would re-apply the mock.+// `deps.db`/`deps.ch` are the fakes above. The one module still mocked is+// core's own `ch-query`. Snapshot the real module into a plain object first and+// restore it in afterAll: restoring via the live import binding would re-apply+// the mock.const realChQuery = { ...(await import('../../ch-query')) };mock.module('../../ch-query', () => ({...realChQuery,diff --git a/packages/core/src/modules/gsc/gsc.service.ts b/packages/core/src/modules/gsc/gsc.service.tsindex 517d3cf33..edcf393a9 100644--- a/packages/core/src/modules/gsc/gsc.service.ts+++ b/packages/core/src/modules/gsc/gsc.service.ts@@ -1,20 +1,9 @@-// The GSC OAuth token lifecycle, the Search Console API client, ClickHouse-// read/write, the AI-tool wrapper functions and the-// gscProjectSync/gscProjectBackfill job bodies.+// `getGscCannibalization` is `cacheablePerDeps`: `cacheable` keys on the call's+// arguments, so the caller's deps travel beside the key rather than inside it.//-// Every exported function takes `ServiceDeps` and reaches Postgres as-// `deps.db` and ClickHouse as `deps.ch`, so the requestId minted at the edge-// reaches the query. `getGscCannibalization` is `cacheablePerDeps`:-// `cacheable` keys on the call's ARGUMENTS, so the caller's deps travel-// beside the key rather than inside it and the Redis key stays-// byte-identical.-//-// `deps.ch` is the round-robin/retry proxy every other core module uses,-// which also applies the shared INSERT_DEFAULT_SETTINGS-// (`wait_end_of_query`, insert block size) to the four sync inserts here.-//-// ClickHouse queries here still go through raw SQL strings, not the `sql`-// tag — this module's queries haven't been converted yet.+// `deps.ch` is the round-robin/retry proxy every core module uses; it also+// applies INSERT_DEFAULT_SETTINGS (`wait_end_of_query`, insert block size) to+// the four sync inserts here.import type { ClickHouseSettings } from '@clickhouse/client';import { decrypt, encrypt } from '@openpanel/shared/server';@@ -710,10 +699,6 @@ export async function getGscQueries(return result.json();}-// ---------------------------------------------------------------------------// Connection CRUD.-// ----------------------------------------------------------------------------export interface GscConnectionSummary {id: string;siteUrl: string;@@ -770,11 +755,6 @@ export async function disconnectGscConnection(await db.gscConnection.deleteMany({ where: { projectId } });}-// ---------------------------------------------------------------------------// Dashboard aggregate queries — date resolution and search/AI-engine-// breakdown logic.-// ----------------------------------------------------------------------------export interface GscDateRangeInput {range: string;startDate?: string | null;@@ -1036,11 +1016,6 @@ export async function getGscPreviousOverview();}-// ----------------------------------------------------------------------------// AI-tool wrappers — consumed by apps/api's assistant SEO tools and the-// /insights REST surface.-// ----------------------------------------------------------------------------export interface GscQueryOpportunity {query: string;clicks: number;@@ -1271,11 +1246,6 @@ export async function gscGetCannibalizationCore();}-// ---------------------------------------------------------------------------// Job bodies. Each fully owns its status-update bookkeeping so the worker-// file is a bare dispatch.-// ----------------------------------------------------------------------------/** The `gscSync` cron fan-out: every project with a connected GSC site. */export async function listGscConnectionsForSync(deps: ServiceDeps@@ -1408,11 +1378,6 @@ export async function runGscProjectBackfill(}}-// ---------------------------------------------------------------------------// OAuth callback business logic. Cookie reading/signing and the redirect-// stay with the transport route; this is the transport-agnostic part.-// ----------------------------------------------------------------------------export interface GscOAuthCallbackInput {code: string;state: string;@@ -1477,10 +1442,6 @@ export async function completeGscOAuthCallback(return { organizationId: project.organizationId };}-// ----------------------------------------------------------------------------// `ctx.services.gsc` binding.-// ----------------------------------------------------------------------------/** A module function's signature with its leading `ServiceDeps` dropped —* what `createGscService` exposes once it has closed over its own. */type WithoutDeps<T extends (deps: ServiceDeps, ...args: never[]) => unknown> =diff --git a/packages/core/src/modules/health/health.routes.ts b/packages/core/src/modules/health/health.routes.tsindex aabbe8b53..038b15546 100644--- a/packages/core/src/modules/health/health.routes.ts+++ b/packages/core/src/modules/health/health.routes.ts@@ -14,11 +14,9 @@ import { chQuery } from '../../ch-query';import { defineRoutes } from '../../http/define';import { currentReadiness } from './src/readiness';-// The first zod schema through the OpenAPI plugin: response schemas generate-// with `io: 'output'`, which is what zod 4's native Standard Schema JSON-// conversion does by default for the `response` slot — no `mapJsonSchema`-// override needed, and none is added, because that hook gets no `io` argument-// and would collapse the input/output split this schema relies on.+// Response schemas generate with `io: 'output'`, which is zod 4's default for the+// `response` slot. No `mapJsonSchema` override: that hook gets no `io` argument and+// would collapse the input/output split this schema relies on.const healthLiveResponseSchema = z.object({ live: z.literal(true) });// Two readiness bodies: `{ready:true}` at 200, anddiff --git a/packages/core/src/modules/health/health.rpc.ts b/packages/core/src/modules/health/health.rpc.tsindex 3ee8125de..a8fcd5e9a 100644--- a/packages/core/src/modules/health/health.rpc.ts+++ b/packages/core/src/modules/health/health.rpc.ts@@ -2,11 +2,7 @@// lands — proves the tRPC surface composes end to end. Public, as a liveness// probe has to be.//-// No frontend caller exists for this procedure, and by the letter of the-// module rule a health module would be routes-only. Left in place because-// `rpc.router.test.ts` pins this exact procedure ("the composed appRouter-// serves the health procedure", asserting a 200 from `/trpc/health.live`),-// which is outside this module's scope to edit.+// No frontend caller exists; kept because `rpc.router.test.ts` pins this procedure.import { createTRPCRouter, publicProcedure } from '../../rpc/base';export const healthRouter = createTRPCRouter({diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.tsindex 114d8df62..99252136b 100644--- a/packages/core/src/modules/import/import.jobs.test.ts+++ b/packages/core/src/modules/import/import.jobs.test.ts@@ -1,5 +1,4 @@-// Job wiring — no ClickHouse/Postgres touched. The service methods-// themselves are exercised in import.service.test.ts.+// Job wiring only; no ClickHouse/Postgres touched.import { expect, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';diff --git a/packages/core/src/modules/import/import.jobs.ts b/packages/core/src/modules/import/import.jobs.tsindex 911278c5d..d9cd36de9 100644--- a/packages/core/src/modules/import/import.jobs.ts+++ b/packages/core/src/modules/import/import.jobs.ts@@ -1,13 +1,9 @@-// `import` is this module's own queue AND its only job — the registry key, the-// Redis name and the BullMQ job name are all `import` (legacyCompat.import-// already discriminates on `{type: 'import', payload}`, jobs/compat.ts). Unlike-// gsc/cohort/insight, this queue has no cron fragment: imports are always-// user-triggered (import.rpc.ts's create/retry).+// `import` is this module's own queue and only job: the registry key, Redis+// name and BullMQ job name are all `import`. There is no cron fragment, imports+// are user-triggered.//-// Core's own worker has no live BullMQ job to hand `updateImportStatus` for-// progress reporting (see import.service.ts's `ImportJobProgress` header), so-// this handler runs with the no-op default — inert until the worker cutover,-// same as gsc/cohort/insight's job handlers today.+// Core's worker has no live BullMQ job to hand `updateImportStatus` for+// progress, so this handler runs with the no-op default.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/import/import.routes.ts b/packages/core/src/modules/import/import.routes.tsindex a53cdfc4f..08eab43f7 100644--- a/packages/core/src/modules/import/import.routes.ts+++ b/packages/core/src/modules/import/import.routes.ts@@ -1,12 +1,9 @@-// This route delegates its ClickHouse insert to import.service.ts's-// `insertRawEventsBatch`.-//// `allow: ['read', 'root']`: a `write`-type client may not import.//// The body is typed but not shape-validated for this route.//-// `client.projectId` is `null` for a root client, which is why the handler-// guards on it explicitly before importing.+// `client.projectId` is `null` for a root client, hence the explicit guard+// before importing.import { z } from 'zod';import { defineRoutes } from '../../http/define';diff --git a/packages/core/src/modules/import/import.rpc.test.ts b/packages/core/src/modules/import/import.rpc.test.tsindex 25c284bab..ccf16e050 100644--- a/packages/core/src/modules/import/import.rpc.test.ts+++ b/packages/core/src/modules/import/import.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + business logic ride on @openpanel/db (lazy-loaded, see-// import.service.ts's header) and ctx.services.import; wiring this router-// end-to-end against a real Postgres is P6's (protectedProcedure) job, not-// this one's — see import.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here, with no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/import/import.rpc.ts b/packages/core/src/modules/import/import.rpc.tsindex 80c11c7f2..cec630297 100644--- a/packages/core/src/modules/import/import.rpc.ts+++ b/packages/core/src/modules/import/import.rpc.ts@@ -1,10 +1,5 @@-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. The explicit checks in the handlers below stay: `enforceAccess`-// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved-// from another id needs its own.-//-// The per-project access ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.+// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so+// anything resolved from another id needs its own explicit check in the handler.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.tsindex df5cc5330..f08f2944c 100644--- a/packages/core/src/modules/import/import.service.test.ts+++ b/packages/core/src/modules/import/import.service.test.ts@@ -1,8 +1,6 @@-// Import.service.ts takes its clients from `ServiceDeps`, so this file hands in-// fakes as `deps.db` / `deps.ch` and mocks NO module at all. That is the point-// of the conversion: a module mock of `@openpanel/db/src/clickhouse/client`-// replaced that specifier for every other FILE in the process (bare `bun test`-// shares one module registry).+// Fakes are handed in as `deps.db` / `deps.ch` and no module is mocked: a mock+// of `@openpanel/db/src/clickhouse/client` would replace that specifier for+// every other file in the process (bare `bun test` shares one module registry).import { beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -40,8 +38,6 @@ const importUpdate = mock(async (_opts: { where: { id: string }; data: unknown }) => undefined);-// The subject's functions take `ServiceDeps`, so `deps.db` / `deps.ch` ARE-// the fakes below.const deps = {db: { import: { update: importUpdate } },ch: {diff --git a/packages/core/src/modules/import/import.service.ts b/packages/core/src/modules/import/import.service.tsindex ec5d958db..3ea66711a 100644--- a/packages/core/src/modules/import/import.service.ts+++ b/packages/core/src/modules/import/import.service.ts@@ -1,10 +1,6 @@-// The provider classes are behind a dynamic `import`: they eagerly import+// The provider classes are behind a dynamic `import`: they import// `formatClickhouseDate` from @openpanel/db's clickhouse client, which-// constructs a real pino transport at import time. See gsc.service.ts's-// header for the full reasoning.-//-// ClickHouse queries here still go through raw `ch`/`chQuery` calls, not the-// `sql` tag — this module's queries haven't been converted yet.+// constructs a real pino transport at import time.import { createHash } from 'node:crypto';import type { Prisma } from '@openpanel/db/src/prisma-client';@@ -36,10 +32,6 @@ function yieldToEventLoop(): Promise<void> {});}-// ----------------------------------------------------------------------------// ClickHouse staging pipeline-// ----------------------------------------------------------------------------export interface ImportStageResult {importId: string;totalEvents: number;@@ -648,9 +640,8 @@ export async function getImportDateBounds(/*** Reports progress on a running import. A BullMQ `Job` satisfies this- * structurally. Core's own job runner (import.jobs.ts) has no BullMQ job- * object to hand over (`JobCtx.job` is the erased `{id, attempt, queue,- * name}`, not the live BullMQ handle), so it falls back to the no-op default.+ * structurally; core's job runner has no live BullMQ job (`JobCtx.job` is the+ * erased `{id, attempt, queue, name}`), so it falls back to the no-op default.*/export interface ImportJobProgress {updateProgress(progress: Record<string, unknown>): unknown;@@ -770,10 +761,6 @@ export async function updateImportStatus(});}-// ----------------------------------------------------------------------------// Provider dispatch + job body-// ----------------------------------------------------------------------------/*** Merge a freshly-derived profile into the bounded dedup map: keep the earliest* created_at (first seen), advance last_seen_at to the latest activity, and fill@@ -848,8 +835,7 @@ async function createImportProvider(/*** The `import` queue job body. Takes `importId` + `progress` rather than a- * BullMQ `Job` directly (see `ImportJobProgress`'s header) so it can run- * under either a real BullMQ job or core's own job runner.+ * BullMQ `Job` so it runs under either a real BullMQ job or core's job runner.*/export async function runImportJob(deps: ServiceDeps,@@ -879,9 +865,7 @@ export async function runImportJob(const canResume =isRetry && RESUMABLE_STEPS.includes(record.currentStep as string);- // -------------------------------------------------------- // STAGING PHASE: clean slate on failure, run from scratch- // -------------------------------------------------------+ // Staging phase: clean slate on failure, run from scratchif (!canResume) {if (isRetry) {jobLogger.info(@@ -890,7 +874,6 @@ export async function runImportJob(await cleanupStagingData(deps, importId);}- // Phase 1: Load events into stagingawait updateImportStatus(deps, jobLogger, progress, importId, {step: 'loading',});@@ -1046,9 +1029,7 @@ export async function runImportJob(}}- // -------------------------------------------------------- // SESSION CREATION PHASE: resumable by cleaning session_start/end- // -------------------------------------------------------+ // Session creation phase: resumable by cleaning session_start/endconst skipSessionCreation =canResume && record.currentStep !== 'creating_sessions';@@ -1070,9 +1051,7 @@ export async function runImportJob(jobLogger.info('Session event creation complete');}- // -------------------------------------------------------- // PRODUCTION PHASE: resume-safe, track progress per batch- // -------------------------------------------------------+ // Production phase: resume-safe, progress tracked per batch// Phase 3: Move staging events to production (per-day)const resumeMovingFrom =@@ -1123,7 +1102,6 @@ export async function runImportJob(jobLogger.info('Session backfill complete');- // Doneawait updateImportStatus(deps, jobLogger, progress, importId, {step: 'completed',});@@ -1150,11 +1128,8 @@ export async function runImportJob(}}-// ----------------------------------------------------------------------------// /import/events — bulk-inserts already-shaped events straight into-// production; unrelated to the provider/staging pipeline above (no Import-// record, no ClickHouse staging table).-// ---------------------------------------------------------------------------+// /import/events bulk-inserts already-shaped events straight into production,+// bypassing the provider/staging pipeline.export interface InsertRawEventsResult {writtenRows: number;@@ -1188,10 +1163,6 @@ export async function insertRawEventsBatch(return { writtenRows };}-// ----------------------------------------------------------------------------// `ctx.services.import` binding.-// ----------------------------------------------------------------------------/** `ctx.services.import` — a thin binding of the job body above to a Ctx's queues. */export function createImportService(deps: ServiceDeps,diff --git a/packages/core/src/modules/import/src/base-provider.ts b/packages/core/src/modules/import/src/base-provider.tsindex 8c2127493..06ab346d1 100644--- a/packages/core/src/modules/import/src/base-provider.ts+++ b/packages/core/src/modules/import/src/base-provider.ts@@ -60,7 +60,6 @@ export abstract class BaseImportProvider<while (cursor <= endDate) {const chunkStart = cursor.toISOString().split('T')[0]!;- // Calculate chunk end: move forward by (chunkSizeDays - 1) to get the last day of the chunkconst chunkEndDate = new Date(cursor);chunkEndDate.setDate(chunkEndDate.getDate() + (chunkSizeDays - 1));diff --git a/packages/core/src/modules/import/src/providers/amplitude.ts b/packages/core/src/modules/import/src/providers/amplitude.tsindex 61246d139..bf4212a48 100644--- a/packages/core/src/modules/import/src/providers/amplitude.ts+++ b/packages/core/src/modules/import/src/providers/amplitude.ts@@ -329,7 +329,6 @@ export class AmplitudeProvider extends BaseImportProvider<AmplitudeRawEvent> {path = String(props[this.config.mapScreenViewProperty] ?? '');}- // Referrer (web only)const referrerUrl = String(props.referrer || props.$referrer || '');const referrer =referrerUrl && !isSameDomain(referrerUrl, rawUrl || '')@@ -516,7 +515,6 @@ export class AmplitudeProvider extends BaseImportProvider<AmplitudeRawEvent> {if (raw.device_manufacturer) {return raw.device_manufacturer;}- // Derive from device_family (e.g. "Apple iPhone" -> "Apple")const family = raw.device_family || raw.device_type || '';if (/apple|iphone|ipad|ios/i.test(family)) {return 'Apple';diff --git a/packages/core/src/modules/import/src/providers/mixpanel.ts b/packages/core/src/modules/import/src/providers/mixpanel.tsindex 812e85e6e..e620aeaed 100644--- a/packages/core/src/modules/import/src/providers/mixpanel.ts+++ b/packages/core/src/modules/import/src/providers/mixpanel.ts@@ -119,8 +119,7 @@ export class MixpanelProvider extends BaseImportProvider<MixpanelRawEvent> {}getTotalEventsCount(): Promise<number> {- // Mixpanel sucks and dont provide a good way to extract total event count within a period- // jql would work but not accurate and will be deprecated end of 2025+ // Mixpanel has no accurate total event count for a period; -1 means unknown.return Promise.resolve(-1);}@@ -143,8 +142,6 @@ export class MixpanelProvider extends BaseImportProvider<MixpanelRawEvent> {): AsyncGenerator<MixpanelRawEvent, void, unknown> {const { serviceAccount, serviceSecret, projectId, from, to } = this.config;- // Split the date range into daily chunks for reliability- // Uses base class utility to avoid timeout issues with large date rangesconst dateChunks = this.getDateChunks(overrideFrom ?? from, to); // 1 day per chunk (default)for (const [chunkFrom, chunkTo] of dateChunks) {@@ -440,7 +437,6 @@ export class MixpanelProvider extends BaseImportProvider<MixpanelRawEvent> {'');- // Build full URL from current_url and current_url_search (web only)const fullUrl = props.$current_url;let path = '';let origin = '';@@ -457,21 +453,18 @@ export class MixpanelProvider extends BaseImportProvider<MixpanelRawEvent> {path = props[this.config.mapScreenViewProperty] || '';}- // Extract referrer information (web only)const referrerUrl = props.$initial_referrer || props.$referrer || '';const referrer =referrerUrl && !isSameDomain(referrerUrl, fullUrl)? parseReferrer(referrerUrl): null;- // Check for UTM referrer in query params (web only)const utmReferrer = getReferrerWithQuery(query);const country = props.$country || props.mp_country_code || '';const city = props.$city || '';const region = props.$region || '';- // For web events, use the standard user agent parsingconst userAgent = props.osVersion || '';const uaInfo = this.isWebEvent(props.mp_lib)? parseUserAgent(userAgent, props)@@ -563,8 +556,7 @@ export class MixpanelProvider extends BaseImportProvider<MixpanelRawEvent> {groups: [],};- // TODO: Remove this- // This is a hack to get utm tags (not sure if this is just the testing project or all mixpanel projects)+ // Workaround: UTM tags can arrive as a query string inside `utm_source`.if (props.utm_source && !properties.__query?.utm_source) {const split = decodeURIComponent(props.utm_source).split('&');const query = Object.fromEntries(split.map((item) => item.split('=')));diff --git a/packages/core/src/modules/import/src/providers/umami.ts b/packages/core/src/modules/import/src/providers/umami.tsindex 39d14700f..a69e4ba21 100644--- a/packages/core/src/modules/import/src/providers/umami.ts+++ b/packages/core/src/modules/import/src/providers/umami.ts@@ -8,11 +8,9 @@ import { parse } from 'csv-parse';import { assocPath } from 'ramda';import { z } from 'zod';import type { Logger } from '../../../../logger';-// Core's own date helper, not @openpanel/db's — importing-// `@openpanel/db/src/clickhouse/client` constructs a ClickHouse client and a-// pino-pretty transport at import time (fatal under bun:test's `--isolate`-// worker threads) and is a value import of `@openpanel/db` from core. See-// shared/ch-dates.ts's header.+// Core's own date helper: importing @openpanel/db's clickhouse client constructs+// a ClickHouse client and pino-pretty transport at import time (fatal under+// bun:test's `--isolate` worker threads).import { formatClickhouseDate } from '../../../../shared/ch-dates';import {getReferrerWithQuery,@@ -23,11 +21,7 @@ import type { IClickhouseEvent } from '../../../event/event.service';import type { IUmamiImportConfig } from '../../import.constants';import { BaseImportProvider } from '../base-provider';-/**- * Bounds for a remote Umami export. `parseRemoteFile` has always accepted these- * but `parseSource` never passed them, so every guard inside it was dead code- * and the download was unbounded.- */+/** Bounds for a remote Umami export. */const MAX_IMPORT_BYTES = 2_000_000_000; // 2 GBconst MAX_IMPORT_ROWS = 50_000_000;/** Bounds the connection and redirect walk only, not the download itself. */diff --git a/packages/core/src/modules/insight/insight.constants.ts b/packages/core/src/modules/insight/insight.constants.tsindex 22665d24c..eb10a15fa 100644--- a/packages/core/src/modules/insight/insight.constants.ts+++ b/packages/core/src/modules/insight/insight.constants.ts@@ -1,6 +1,3 @@-// The two list procedures' page bounds. Vocabulary, not implementation: the-// dashboard pages that call `insight.list` / `insight.listAll` size their own-// requests against the same numbers the procedure enforces.export const INSIGHT_LIST_DEFAULT_LIMIT = 50;export const INSIGHT_LIST_MAX_LIMIT = 100;export const INSIGHT_LIST_ALL_DEFAULT_LIMIT = 200;diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.tsindex 173f831a9..ee261bd51 100644--- a/packages/core/src/modules/insight/insight.jobs.test.ts+++ b/packages/core/src/modules/insight/insight.jobs.test.ts@@ -1,5 +1,4 @@-// Job/cron-fragment wiring — no ClickHouse/Postgres touched. The service-// methods themselves are exercised in insight.service.test.ts.+// Job/cron-fragment wiring only; the service methods are in insight.service.test.ts.import { expect, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -236,9 +235,8 @@ test('weeklyDigest delegates to sendWeeklyDigests', async () => {expect(called).toBe(true);});-// Byte-identity with the ids/cadences schedulers.test.ts's golden snapshot-// pins. The cadences now live on the jobs themselves, so this reads them-// straight off the registry.+// The cadences live on the jobs themselves, so this reads them off the registry;+// schedulers.test.ts's golden snapshot pins the same ids.test('the insight cron fragment keeps its scheduler ids and cadences', () => {expect(queues.cron.jobs.insightsDaily.cron).toEqual({pattern: '0 2 * * *',diff --git a/packages/core/src/modules/insight/insight.jobs.ts b/packages/core/src/modules/insight/insight.jobs.tsindex 850798c6e..c9b371a4b 100644--- a/packages/core/src/modules/insight/insight.jobs.ts+++ b/packages/core/src/modules/insight/insight.jobs.ts@@ -1,7 +1,3 @@-// `insightsProject` is this module's own queue (`insights` in the registry).-// `insightsDaily` / `insightCleanup` / `weeklyDigest` are cron fragments,-// spread into the ONE `cron` queue by jobs.registry.ts.-import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/insight/insight.rpc.test.ts b/packages/core/src/modules/insight/insight.rpc.test.tsindex c17627001..ad212308e 100644--- a/packages/core/src/modules/insight/insight.rpc.test.ts+++ b/packages/core/src/modules/insight/insight.rpc.test.ts@@ -1,9 +1,5 @@-// 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.+// Only the "is anyone logged in" boundary is exercised here, with no database;+// the access checks and business logic are covered in insight.service.test.ts.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -19,7 +15,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/insight/insight.rpc.ts b/packages/core/src/modules/insight/insight.rpc.tsindex f3d1f54d6..c483c7041 100644--- a/packages/core/src/modules/insight/insight.rpc.ts+++ b/packages/core/src/modules/insight/insight.rpc.ts@@ -2,9 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// The permission ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.tsindex d81dc12d0..dcf81fc71 100644--- a/packages/core/src/modules/insight/insight.service.test.ts+++ b/packages/core/src/modules/insight/insight.service.test.ts@@ -1,8 +1,7 @@-// The subject's functions take `ServiceDeps`, so `deps.db` IS the fake below-// and no Prisma module mock is needed. The intra-package modules (store,-// referrer-spikes, legacy-scan) are still `mock.module`'d — that works here-// with no import-time side effects to race because every mock is registered-// before the subject's first call, not before its import.+// The subject's functions take `ServiceDeps`, so `deps.db` is the fake below and+// no Prisma module mock is needed. The intra-package modules (store,+// referrer-spikes, legacy-scan) are `mock.module`'d, registered before the+// subject's first call.import { beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -163,8 +162,7 @@ test('explainInsight is a cache-aside over the AI call, keyed by the caller-suppexpect(generateInsightExplanation).toHaveBeenCalledTimes(1);expect(second).toEqual(first);- // The cache it read and wrote is the one the scope handed it, not a- // module-level `getRedisCache()` connection nobody closes.+ // The cache used is the one the scope handed in, not a module-level connection.expect(redis.setex).toHaveBeenCalledTimes(1);expect(redis.get).toHaveBeenCalledTimes(2);});diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.tsindex 0912e647b..55adcc4c2 100644--- a/packages/core/src/modules/insight/insight.service.ts+++ b/packages/core/src/modules/insight/insight.service.ts@@ -1,18 +1,7 @@// Plain exported functions, not only methods on `createInsightService`'s-// container: a caller with no Ctx yet still needs a direct call.-// `createInsightService` is the `ctx.services.insight` binding for code that-// already has a Ctx.-//-// Every exported function takes `ServiceDeps` and reaches Postgres as `deps.db`-// and ClickHouse as `deps.ch`, so the requestId minted at the edge reaches the-// query.-//-// The engine and its five detection modules run on the `sql` tag;-// `createEngine` therefore takes the scope's deps rather than a bare ClickHouse-// client, so the requestId reaches every module statement.-//-// The explain cache runs on `deps.redis` — the app shell owns that connection's-// lifecycle; this module never opens one of its own.+// container: a caller with no Ctx yet still needs a direct call. They take+// `ServiceDeps` so the requestId minted at the edge reaches every query, and the+// explain cache runs on `deps.redis`, whose lifecycle the app shell owns.import { sendEmail } from '../../clients/email';import type { Logger } from '../../logger';diff --git a/packages/core/src/modules/insight/src/cached-query.test.ts b/packages/core/src/modules/insight/src/cached-query.test.tsindex 4a9fa2580..7ad3b55b3 100644--- a/packages/core/src/modules/insight/src/cached-query.test.ts+++ b/packages/core/src/modules/insight/src/cached-query.test.ts@@ -1,13 +1,10 @@-// The cache-key contract of the wrapper that replaced `cached-clix.ts`.+// The cache key must cover the bound params as well as the rendered text: the+// `sql` tag names placeholders `{p1}, {p2}, …` from a per-render counter, so two+// statements differing only in their values render to the SAME text. The second+// test is the regression a text-only key would fail.//-// The clix wrapper keyed on `sha256(toSQL() + '|' + timezone)`, which was only-// sound because clix inlined every value into the text it hashed. The `sql`-// tag names its placeholders `{p1}, {p2}, …` from a per-render counter, so two-// statements that differ only in their bound values render to the SAME text —-// the second test below is the regression that a text-only key would fail.-//-// No module mock: `chQuery` is a thin wrapper over `deps.ch.query`, so a fake-// client counts the round trips and shows what was actually sent.+// No module mock: `chQuery` wraps `deps.ch.query`, so a fake client counts the+// round trips and shows what was sent.import { expect, test } from 'bun:test';import { sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/insight/src/cached-query.ts b/packages/core/src/modules/insight/src/cached-query.tsindex 24e3c3809..54b1977e1 100644--- a/packages/core/src/modules/insight/src/cached-query.ts+++ b/packages/core/src/modules/insight/src/cached-query.ts@@ -22,10 +22,9 @@ export type StatementRunner = <T extends object>() => Promise<T[]>;/**- * @param deps the scope's ClickHouse client + logger (so the requestId reaches- * the query — ADR-018). @param cache per module+window result cache; omit to- * disable memoisation. @param timezone `session_timezone` for every statement- * run through it.+ * @param deps the scope's ClickHouse client + logger, so the requestId reaches+ * the query. @param cache per module+window result cache; omit to disable+ * memoisation. @param timezone `session_timezone` for every statement run.*/export function createStatementCache(deps: ChScope,diff --git a/packages/core/src/modules/insight/src/engine.ts b/packages/core/src/modules/insight/src/engine.tsindex be84d1231..a7681927c 100644--- a/packages/core/src/modules/insight/src/engine.ts+++ b/packages/core/src/modules/insight/src/engine.ts@@ -37,10 +37,6 @@ function isSeverityIncrease(return SEVERITY_RANK[next] > SEVERITY_RANK[prev];}-/**- * Sanitize a string for PostgreSQL by removing null bytes (0x00).- * PostgreSQL text columns don't accept null bytes in UTF-8 encoding.- */function sanitizeForPostgres(str: string): string {// Remove null bytes which cause "invalid byte sequence for encoding UTF8: 0x00"// Using String.fromCharCode(0) to avoid linter warnings about control characters in regex@@ -58,7 +54,6 @@ export interface EngineConfig {};}-/** Simple gating to cut noise; modules can override via thresholds. */function passesThresholds(r: ComputeResult,mod: InsightModule,@@ -99,7 +94,6 @@ function chunk<T>(arr: T[], size: number): T[][] {export function createEngine(args: {store: InsightStore;modules: InsightModule[];- /** The scope's ClickHouse client + logger; every module query runs on it. */deps: ChScope;logger?: Pick<Console, 'info' | 'warn' | 'error'>;config: EngineConfig;@@ -139,7 +133,6 @@ export function createEngine(args: {) {continue;}- // Garbage collected automatically when this context goes out of scope.const cache = new Map<string, unknown>();ctx = {projectId,@@ -158,13 +151,11 @@ export function createEngine(args: {continue;}- // 1) enumerate dimensionslet dims: string[] = [];try {const rawDims = mod.enumerateDimensions? await mod.enumerateDimensions(ctx): [];- // Sanitize dimension keys to remove null bytes that PostgreSQL can't handledims = rawDims.map(sanitizeForPostgres);} catch (e) {// Important: enumeration failures should not abort the whole project run.@@ -204,7 +195,6 @@ export function createEngine(args: {continue;}- // 2) compute in batchesconst seen: string[] = [];const dimBatches = chunk(dims, config.dimensionBatchSize);for (const batch of dimBatches) {@@ -229,21 +219,17 @@ export function createEngine(args: {continue;}- // Sanitize dimensionKey to remove null bytes that PostgreSQL can't handler.dimensionKey = sanitizeForPostgres(r.dimensionKey);- // 3) gate noiseif (!passesThresholds(r, mod, config)) {continue;}- // 4) scoreconst impact = mod.score? mod.score(r, ctx): defaultImpactScore(r);const sev = severityBand(r.changePct);- // 5) dedupe/material change requires loading prev identityconst prev = await store.getActiveInsightByIdentity({projectId,moduleKey: mod.key,@@ -256,10 +242,8 @@ export function createEngine(args: {direction: r.direction,});- // 6) renderconst card = mod.render(r, ctx);- // 7) upsertconst persisted = await store.upsertInsight({projectId,moduleKey: mod.key,@@ -278,7 +262,6 @@ export function createEngine(args: {seen.push(r.dimensionKey);- // 8) events only when materialif (!prev) {await store.insertEvent({projectId,@@ -331,7 +314,6 @@ export function createEngine(args: {}}- // 10) lifecycle: close missing insights for this module/windowawait store.closeMissingActiveInsights({projectId,moduleKey: mod.key,@@ -341,7 +323,6 @@ export function createEngine(args: {staleDays: config.closeStaleAfterDays,});- // 11) suppression: keep top Nawait store.applySuppression({projectId,moduleKey: mod.key,diff --git a/packages/core/src/modules/insight/src/enrich.ts b/packages/core/src/modules/insight/src/enrich.tsindex 68f2ccdb5..d4b87dd5f 100644--- a/packages/core/src/modules/insight/src/enrich.ts+++ b/packages/core/src/modules/insight/src/enrich.ts@@ -1,8 +1,6 @@// Tier-1 insight enrichment: a one-shot OpenAI call that scores and summarizes-// auto-detected analytics insights so the product can filter noise, select-// email-worthy items, and flag chart-reference candidates. No persistence, no-// tools — pure transform. The worker queries stale insights, calls this, and-// writes the results back (this module stays db-free).+// insights so the product can filter noise, pick email-worthy items and flag+// chart-reference candidates. No persistence: the caller writes results back.import { betterAgent, defineAgent } from '@better-agent/core';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';@@ -113,8 +111,8 @@ function getApp(config: CoreConfig) {}/**- * Enrich a batch of insights in a single model call. Returns one entry per- * insight the model scored (caller maps back by id; missing ids are skipped).+ * Enrich a batch of insights in one model call. Returns one entry per insight+ * the model scored; the caller maps back by id and missing ids are skipped.* Keep batches modest (~25) so the prompt stays small and the mapping reliable.*/export async function enrichInsights(diff --git a/packages/core/src/modules/insight/src/explain.ts b/packages/core/src/modules/insight/src/explain.tsindex 1e5ab1ba7..2a0038aea 100644--- a/packages/core/src/modules/insight/src/explain.ts+++ b/packages/core/src/modules/insight/src/explain.ts@@ -1,18 +1,16 @@-// Given an insight plus a deterministic decomposition of the change (current-// vs baseline breakdowns across referrer/country/device/utm) and any nearby-// references, produce an honest explanation: which sub-segment drove the-// delta, and which off-platform event (reference) might correlate. It-// explains the *internal decomposition*, not invented external causes. The-// caller gathers the data (DB/CH); this module just narrates.+// Explains an insight from a deterministic decomposition of the change (current+// vs baseline across referrer/country/device/utm) plus nearby references: which+// sub-segment drove the delta and which off-platform event might correlate. It+// narrates the internal decomposition, not invented external causes; the caller+// gathers the data.import { betterAgent, defineAgent } from '@better-agent/core';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';import type { CoreConfig } from '../../../config';import { ALLOWED_MODELS, resolveModel } from '../../assistant/src/providers';-// gpt-4.1 (the larger non-reasoning model) synthesizes the supplied breakdown-// well without reasoning-option plumbing. Swap to a reasoning model later if-// deeper inference is wanted.+// gpt-4.1 (larger, non-reasoning) synthesizes the supplied breakdown well+// without reasoning-option plumbing.const EXPLAIN_MODEL_ID = 'gpt-4-1';// Preferred model and fallback are both OpenAI — see enrich.ts.diff --git a/packages/core/src/modules/insight/src/legacy-scan.ts b/packages/core/src/modules/insight/src/legacy-scan.tsindex 27200d7a7..b9abdad40 100644--- a/packages/core/src/modules/insight/src/legacy-scan.ts+++ b/packages/core/src/modules/insight/src/legacy-scan.ts@@ -149,13 +149,7 @@ function since(days: number): SqlParam {);}-/**- * No live callers today; kept only so the defects above stay visible.- *- * The class is no longer exported; `createLegacyInsightsScanner(deps)` below is- * the module's factory, so every service module in core is reached the same way- * and nothing in the tree still exports a `*Service` class.- */+/** No live callers; kept only so the defects above stay visible. */class LegacyInsightsScanner {constructor(private readonly deps: ChScope) {}diff --git a/packages/core/src/modules/insight/src/material.ts b/packages/core/src/modules/insight/src/material.tsindex 4f689ee16..a8452677d 100644--- a/packages/core/src/modules/insight/src/material.ts+++ b/packages/core/src/modules/insight/src/material.ts@@ -38,7 +38,7 @@ export function materialDecision(};}- // Otherwise: treat as non-material (silent refresh). You can add deadband crossing here if you store prior changePct.+ // Otherwise non-material (silent refresh).return {material: false,reason: 'none',diff --git a/packages/core/src/modules/insight/src/modules/devices.module.ts b/packages/core/src/modules/insight/src/modules/devices.module.tsindex 14b3b817c..99a462e93 100644--- a/packages/core/src/modules/insight/src/modules/devices.module.ts+++ b/packages/core/src/modules/insight/src/modules/devices.module.ts@@ -17,8 +17,7 @@ import {selectTopDimensions,} from '../utils';-/** clix inlined the value; `sign = 1` is the sessions table's live-row- * predicate and now binds like every other value. */+/** `sign = 1` is the sessions table's live-row predicate. */const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{diff --git a/packages/core/src/modules/insight/src/modules/entry-pages.module.ts b/packages/core/src/modules/insight/src/modules/entry-pages.module.tsindex 3a3eb126f..ddc654ca1 100644--- a/packages/core/src/modules/insight/src/modules/entry-pages.module.ts+++ b/packages/core/src/modules/insight/src/modules/entry-pages.module.ts@@ -19,8 +19,7 @@ import {const DELIMITER = '|||';-/** clix inlined the value; `sign = 1` is the sessions table's live-row- * predicate and now binds like every other value. */+/** `sign = 1` is the sessions table's live-row predicate. */const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{diff --git a/packages/core/src/modules/insight/src/modules/geo.module.ts b/packages/core/src/modules/insight/src/modules/geo.module.tsindex adcba4726..c9d87a977 100644--- a/packages/core/src/modules/insight/src/modules/geo.module.ts+++ b/packages/core/src/modules/insight/src/modules/geo.module.ts@@ -18,8 +18,7 @@ import {selectTopDimensions,} from '../utils';-/** clix inlined the value; `sign = 1` is the sessions table's live-row- * predicate and now binds like every other value. */+/** `sign = 1` is the sessions table's live-row predicate. */const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);async function fetchGeoAggregates(ctx: ComputeContext): Promise<{diff --git a/packages/core/src/modules/insight/src/modules/page-trends.module.ts b/packages/core/src/modules/insight/src/modules/page-trends.module.tsindex 929b82d50..7c3300621 100644--- a/packages/core/src/modules/insight/src/modules/page-trends.module.ts+++ b/packages/core/src/modules/insight/src/modules/page-trends.module.ts@@ -19,11 +19,9 @@ import {const DELIMITER = '|||';-/** One number, two call sites: the threshold below and `enumerateDimensions`'s- * fallback, which had drifted back to the pre-tightening 100. */+/** One number, two call sites: the threshold below and `enumerateDimensions`'s fallback. */const MAX_PAGES_PER_RUN = 30;-/** clix inlined the value; the pageview event name now binds. */const SCREEN_VIEW_EVENT = sql.string('screen_view');async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{@@ -142,13 +140,10 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{export const pageTrendsModule: InsightModule = {key: 'page-trends',cadence: ['daily'],- // Share-based thresholds (values in basis points: 100 = 1%)- // Tightened to cut noise: page-trends was ~85% of all insight rows because- // a 0.5pp share wiggle on up to 100 pages/run crossed the bar.- // minTotal: require at least 1% combined share (current + baseline)- // minAbsDelta: require at least 1.0 percentage point shift- // minPct: require at least 35% relative change in share- // maxDims: evaluate at most MAX_PAGES_PER_RUN pages/run (was 100)+ // Share-based thresholds (values in basis points: 100 = 1%), tight because a+ // 0.5pp share wiggle on up to 100 pages/run used to flood the insight rows.+ // minTotal: 1% combined share; minAbsDelta: 1.0pp shift; minPct: 35% relative+ // change in share; maxDims: at most MAX_PAGES_PER_RUN pages/run.thresholds: {minTotal: 100,minAbsDelta: 100,@@ -198,13 +193,11 @@ export const pageTrendsModule: InsightModule = {results.push({ok: true,dimensionKey: dimKey,- // Use share in basis points for threshold checkscurrentValue: currentShareBp,compareValue: compareShareBp,changePct: shareChangePct,direction,extra: {- // Keep absolute values for displaypageviewsCurrent,pageviewsCompare,shareShiftPp,diff --git a/packages/core/src/modules/insight/src/modules/referrers.module.ts b/packages/core/src/modules/insight/src/modules/referrers.module.tsindex c5ab9ae71..6677cd6ae 100644--- a/packages/core/src/modules/insight/src/modules/referrers.module.ts+++ b/packages/core/src/modules/insight/src/modules/referrers.module.ts@@ -17,8 +17,7 @@ import {selectTopDimensions,} from '../utils';-/** clix inlined the value; `sign = 1` is the sessions table's live-row- * predicate and now binds like every other value. */+/** `sign = 1` is the sessions table's live-row predicate. */const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{diff --git a/packages/core/src/modules/insight/src/narrative.ts b/packages/core/src/modules/insight/src/narrative.tsindex 9e2663a2d..d8fc85bf6 100644--- a/packages/core/src/modules/insight/src/narrative.ts+++ b/packages/core/src/modules/insight/src/narrative.ts@@ -1,7 +1,5 @@// Weekly-digest narrative: one short OpenAI call that turns a project's-// week-over-week stats + notable insights into a friendly intro paragraph.-// Structured output (a single `narrative` string) reuses the same reliable-// pattern as enrich.ts / filter-command.ts.+// week-over-week stats and notable insights into an intro paragraph.import { betterAgent, defineAgent } from '@better-agent/core';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';diff --git a/packages/core/src/modules/insight/src/referrer-spikes.ts b/packages/core/src/modules/insight/src/referrer-spikes.tsindex 08e7a51d3..bec250919 100644--- a/packages/core/src/modules/insight/src/referrer-spikes.ts+++ b/packages/core/src/modules/insight/src/referrer-spikes.ts@@ -1,9 +1,6 @@-// The ClickHouse client is `deps.ch` (the boot scope's round-robin proxy), so-// the requestId minted at the edge reaches these queries. Table names and the-// date helper are core's own copies (shared/ch-tables.ts, shared/ch-dates.ts).-//-// `getRawWhereClause` returns a `SqlFragment` carrying bound params;-// `chQuery` always sends `session_timezone` in its settings.+// `deps.ch` carries the requestId minted at the edge. `getRawWhereClause`+// returns a `SqlFragment` with bound params; `chQuery` always sends+// `session_timezone`.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { chQuery } from '../../../ch-query';import type { ServiceDeps } from '../../../services';@@ -55,12 +52,9 @@ export interface ReferrerSpike {}/**- * One bucket's worth of spike data. The wire format keeps the cluster- * shape (anchorDate + spikes array) for forward-compatibility, but the- * backend no longer groups across buckets — every entry has- * `spikes.length === 1`. Visual density grouping happens on the frontend,- * where the live `xScale` knows actual pixel distances and the right- * threshold doesn't depend on the chosen interval.+ * One bucket's worth of spike data. The wire format keeps the cluster shape+ * (anchorDate + spikes array), but every entry has `spikes.length === 1`:+ * density grouping happens on the frontend, where `xScale` knows pixel distances.*/export interface ReferrerSpikeCluster {/** Bucket date — used to position the marker. */diff --git a/packages/core/src/modules/insight/src/store.ts b/packages/core/src/modules/insight/src/store.tsindex 31abe4265..3a4a084a4 100644--- a/packages/core/src/modules/insight/src/store.ts+++ b/packages/core/src/modules/insight/src/store.ts@@ -1,8 +1,6 @@-// The store is a FACTORY over `ServiceDeps` — `deps.db` is the boot scope's-// client, so the requestId minted at the edge reaches every insight write.-// `Prisma` here is the namespace's JSON sentinel (`DbNull`), which arrives on-// the same scope as `deps.prisma` rather than by importing `@openpanel/db` from-// core.+// A factory over `ServiceDeps` so the requestId minted at the edge reaches every+// insight write. `Prisma` is the JSON sentinel (`DbNull`), which arrives on the+// scope as `deps.prisma`.import type { Prisma } from '@openpanel/db/src/prisma-client';import type { ServiceDeps } from '../../../services';@@ -250,15 +248,10 @@ export function createInsightStore(deps: ServiceDeps): InsightStore {keepTopN,now,}): Promise<{ deleted: number }> {- // Below-top-N insights are DELETED rather than persisted as `suppressed`- // rows. Nothing reads suppressed insights (every query filters state=active),- // yet they were ~75% of the table. A dimension that later climbs back into- // the top-N is simply re-created on the next run — it loses thread- // continuity, which is cosmetic and not surfaced anywhere.- //- // Nothing here writes `suppressed` any more; the two paths that still read- // it (the reopen lookup above, `cleanupStaleInsights`) exist for rows- // written before that change.+ // Below-top-N insights are DELETED, not stored as `suppressed`: nothing+ // reads them and they were ~75% of the table. A dimension that climbs back+ // into the top-N is re-created next run, losing thread continuity (not+ // surfaced anywhere). `suppressed` is only read for rows written before this.const insights = await db.projectInsight.findMany({where: {projectId,diff --git a/packages/core/src/modules/insight/src/types.ts b/packages/core/src/modules/insight/src/types.tsindex a48d82d0e..f3158c78e 100644--- a/packages/core/src/modules/insight/src/types.ts+++ b/packages/core/src/modules/insight/src/types.ts@@ -115,10 +115,7 @@ export interface MaterialDecision {newSeverityBand?: SeverityBand | null;}-/**- * Persistence interface: implement with Postgres.- * Keep engine independent of query builder choice.- */+/** Persistence interface, implemented with Postgres. */export interface InsightStore {listProjectIdsForCadence(cadence: Cadence): Promise<string[]>;/** Used by the engine/worker to decide if a window has enough baseline history. */diff --git a/packages/core/src/modules/insight/src/utils.ts b/packages/core/src/modules/insight/src/utils.tsindex 62cf9fc7f..f3a242fb9 100644--- a/packages/core/src/modules/insight/src/utils.ts+++ b/packages/core/src/modules/insight/src/utils.ts@@ -1,7 +1,3 @@-/**- * Shared utilities for insight modules- */-export function getWeekday(date: Date): number {return date.getUTCDay();}diff --git a/packages/core/src/modules/integration/integration.constants.ts b/packages/core/src/modules/integration/integration.constants.tsindex 8e8236770..e1d29f521 100644--- a/packages/core/src/modules/integration/integration.constants.ts+++ b/packages/core/src/modules/integration/integration.constants.ts@@ -1,15 +1,5 @@-// `zSlackAuthResponse` does NOT move here even though it is zod-only and would-// pass `constants-stay-isomorphic`: it is Slack's OAuth token-exchange wire-// contract, not integration config a form validates against — nothing in-// apps/start ever sees it. It stays in `./src/slack-contract.ts`, defined as-// `zSlackConfig` minus the persisted `type` discriminant (see that file).-import { z } from 'zod';-// ----------------------------------------------------------------------------// Secret handling-// ----------------------------------------------------------------------------/*** Prefix marking an at-rest ciphertext. Mirrors ENCRYPTION_PREFIX in* `@openpanel/shared/server/encryption.ts`, duplicated because this file is@@ -37,10 +27,6 @@ const zWriteOnlySecret = (label: string) =>message: `${label} looks like a stored, already-encrypted value. Paste the real credential, or leave it blank to keep the current one.`,});-// ----------------------------------------------------------------------------// Google service-account credentials-// ----------------------------------------------------------------------------/** The only credential document shape we accept for GCS. */export interface IServiceAccountKey {type: 'service_account';@@ -110,15 +96,9 @@ export function parseServiceAccountKey(raw: string): IServiceAccountKeyResult {};}-// ----------------------------------------------------------------------------// Per-type config schemas-// -----------------------------------------------------------------------------// The Slack integration's persisted config is exactly Slack's OAuth-// token-exchange response (`oauth.v2.access`) plus our own `type` tag —-// `./src/slack-contract.ts`'s `zSlackAuthResponse` is this schema minus-// `type`, kept the other direction (constants owns the shape, src derives-// from it) so the two can never drift.+// Slack's persisted config is its OAuth token-exchange response+// (`oauth.v2.access`) plus our `type` tag. `./src/slack-contract.ts` derives+// `zSlackAuthResponse` from this schema so the two cannot drift.export const zSlackConfig = z.object({type: z.literal('slack'),ok: z.literal(true),@@ -237,14 +217,9 @@ export const zGCSExportConfig = z.object({});export type IGCSExportConfig = z.infer<typeof zGCSExportConfig>;-// ----------------------------------------------------------------------------// The explicit discriminated union — the SOURCE OF TRUTH for narrowing.-// Do NOT derive this from the registry: deriving via z.infer over a registry-// array can silently widen a member to { type: string } and break every-// config.type narrow downstream (incl. Prisma's IPrismaIntegrationConfig).-// The registry below is forced to MATCH this union via `satisfies`, never the-// other way round.-// ---------------------------------------------------------------------------+// Explicit union, the source of truth for narrowing. Deriving it from the+// registry via z.infer can silently widen a member to `{ type: string }`; the+// registry is forced to match this union via `satisfies`.export type IIntegrationConfig =| ISlackConfig@@ -257,13 +232,9 @@ export type IIntegrationConfig =export type IIntegrationType = IIntegrationConfig['type'];-// ----------------------------------------------------------------------------// Plugin descriptor registry (core layer). Each integration declares its-// capabilities, setup style, config schema and catalog metadata once. The-// server (this module's src/registry.ts) and client-// (apps/start) registries are keyed by the same `type` literal and are-// forced to cover this union.-// ---------------------------------------------------------------------------+// Plugin descriptor registry: each integration declares its capabilities, setup+// style, config schema and catalog metadata once. The server and client+// registries are keyed by the same `type` and forced to cover the union.export type IIntegrationKind = 'notification' | 'export';@@ -411,10 +382,6 @@ export const zIntegrationConfig = z.union([zGCSExportConfig,]);-// ----------------------------------------------------------------------------// Create-integration input schemas-// ----------------------------------------------------------------------------const zCreateIntegrationBase = z.object({id: z.string().optional(),name: z.string().min(1),@@ -443,11 +410,7 @@ export const zCreateGCSExportIntegration = zCreateIntegrationBase.merge(}));-// ----------------------------------------------------------------------------// Compile-time guards (the type-safety gate). These are type aliases, so they-// add no runtime and don't trip unused-locals, but they fail `tsc` if the-// invariant breaks.-// ---------------------------------------------------------------------------+// Compile-time guards: type aliases that fail `tsc` if an invariant breaks.type Assert<T extends true> = T;type Equal<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;diff --git a/packages/core/src/modules/integration/integration.jobs.ts b/packages/core/src/modules/integration/integration.jobs.tsindex 593a8999d..423d805fe 100644--- a/packages/core/src/modules/integration/integration.jobs.ts+++ b/packages/core/src/modules/integration/integration.jobs.ts@@ -1,6 +1,3 @@-// `flushExports` is this module's fragment of the ONE `cron` queue's jobs,-// spread into jobs.registry.ts.-import { z } from 'zod';import { defineJob } from '../../jobs/define';import {diff --git a/packages/core/src/modules/integration/integration.routes.ts b/packages/core/src/modules/integration/integration.routes.tsindex a3339e358..4f37ce2eb 100644--- a/packages/core/src/modules/integration/integration.routes.ts+++ b/packages/core/src/modules/integration/integration.routes.ts@@ -1,7 +1,3 @@-// The Slack OAuth callback, `GET /webhook/slack`. Delegates token-exchange-// and upsert logic to integration.service.ts's `completeSlackOAuthCallback`,-// same shape as gsc.routes.ts / auth.routes.ts's OAuth callbacks.-import { redirect } from 'elysia';import { z } from 'zod';import { defineRoutes } from '../../http/define';@@ -31,11 +27,8 @@ export const integrationRoutes = defineRoutes((app) =>query);- // Integrations are project-scoped; the org-level integrations route no- // longer exists. Newer installs carry projectId in their metadata.- // Older in-flight installs (started before the project-scoped routes- // shipped) may lack it — fall back to the org landing page rather- // than a now-404 integrations URL.+ // Installs started before integrations were project-scoped may lack+ // projectId; fall back to the org landing page.return redirect(projectId? `${ctx.config.dashboardUrl}/${organizationId}/${projectId}/integrations/installed`diff --git a/packages/core/src/modules/integration/integration.rpc.ts b/packages/core/src/modules/integration/integration.rpc.tsindex 156c51a81..aff830438 100644--- a/packages/core/src/modules/integration/integration.rpc.ts+++ b/packages/core/src/modules/integration/integration.rpc.ts@@ -1,11 +1,6 @@-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. The explicit checks in the handlers below stay: `enforceAccess`-// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved-// from another id needs its own.-//-// Every access assertion (including the data-dependent "authorize against the-// EXISTING row" rule) lives in integration.service.ts, not here — see that-// file's header for why.+// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so+// anything resolved from another id needs its own explicit check. Access+// assertions live in integration.service.ts.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';@@ -44,8 +39,6 @@ export const integrationRouter = createTRPCRouter({createOrUpdateSlackIntegration(ctx, ctx.session.userId, input)),- // Generic create/update for any form-configured integration. Per-type- // behavior lives in the server plugin; no switch here.createOrUpdate: protectedProcedure.input(z.object({diff --git a/packages/core/src/modules/integration/integration.service.test.ts b/packages/core/src/modules/integration/integration.service.test.tsindex 27e946f8c..c44598d23 100644--- a/packages/core/src/modules/integration/integration.service.test.ts+++ b/packages/core/src/modules/integration/integration.service.test.ts@@ -3,8 +3,8 @@// the read paths AND the mutation return values — a create/update that echoes// the stored row is how a webhook's Authorization header reached the client.//-// Access is a real `getAccessChecks()` over faked lookups, the same seam-// auth.service.access.test.ts uses; storage is an in-memory fake `deps.db`.+// Access is a real `getAccessChecks()` over faked lookups; storage is an+// in-memory fake `deps.db`.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';diff --git a/packages/core/src/modules/integration/integration.service.ts b/packages/core/src/modules/integration/integration.service.tsindex 1d3852027..4f4dd9cba 100644--- a/packages/core/src/modules/integration/integration.service.ts+++ b/packages/core/src/modules/integration/integration.service.ts@@ -1,10 +1,6 @@-// Authorization here is data-dependent — an update must authorize against the-// EXISTING row's scope, not the attacker-controlled input — so, unlike a-// simple input-shape ladder check, the access assertions travel WITH the-// business logic.-//-// Every exported function takes `ServiceDeps` and reaches Postgres as-// `deps.db`, so a requestId minted at the edge reaches the query.+// Authorization is data-dependent: an update must authorize against the+// EXISTING row's scope, not the attacker-controlled input, so the access+// assertions live here with the business logic.import { z } from 'zod';import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';@@ -129,9 +125,7 @@ export async function listIntegrationsForProject(const db = deps.db;const integrations = await db.integration.findMany({where: {- // The project's own integrations, plus legacy org-wide integrations- // (projectId null) so they stay visible/selectable during the- // transition off org-scoping.+ // Plus legacy org-wide integrations (projectId null).OR: [{ projectId }, { projectId: null, organizationId }],config: {not: {},@@ -378,10 +372,6 @@ export async function deleteIntegration(return { id };}-// - Slack OAuth callback ----------------------------------------------------// The token-exchange/upsert logic behind this module's `/webhook/slack` route-// (integration.routes.ts).-const slackOAuthMetadataSchema = z.object({organizationId: z.string(),integrationId: z.string(),@@ -458,10 +448,6 @@ export async function completeSlackOAuthCallback(return { organizationId, projectId };}-// ----------------------------------------------------------------------------// `ctx.services.integration` binding.-// ----------------------------------------------------------------------------/** A module function's signature with its leading `ServiceDeps` dropped. */type WithoutDeps<T extends (deps: ServiceDeps, ...args: never[]) => unknown> =T extends (deps: ServiceDeps, ...args: infer A) => infer Rdiff --git a/packages/core/src/modules/integration/src/export/batch-creator.ts b/packages/core/src/modules/integration/src/export/batch-creator.tsindex f23957233..0c4412dda 100644--- a/packages/core/src/modules/integration/src/export/batch-creator.ts+++ b/packages/core/src/modules/integration/src/export/batch-creator.ts@@ -129,7 +129,6 @@ export async function createBatch(const { minEventTime, maxEventTime } = eventTimeRange(events);- // Determine partition based on min event timeconst partitionDate = new Date(minEventTime);const dt = partitionDate.toISOString().split('T')[0]!;const hour = partitionDate.getUTCHours().toString().padStart(2, '0');diff --git a/packages/core/src/modules/integration/src/export/export-event.ts b/packages/core/src/modules/integration/src/export/export-event.tsindex 35e2505f8..8ecf50136 100644--- a/packages/core/src/modules/integration/src/export/export-event.ts+++ b/packages/core/src/modules/integration/src/export/export-event.ts@@ -1,8 +1,7 @@import type { IClickhouseEvent } from '../../../event/event.service';-// Local copy for the reason every modules/*/src/dates.ts gives: importing-// @openpanel/db's clickhouse/client constructs a ClickHouse client at import-// time, and this module sits on jobs.registry.ts's eager import chain.+// Local copy: importing @openpanel/db's clickhouse/client constructs a client+// at import time, and this module is on jobs.registry.ts's eager import chain.function convertClickhouseDateToJs(date: string): Date {return new Date(`${date.replace(' ', 'T')}Z`);}diff --git a/packages/core/src/modules/integration/src/flush-exports.test.ts b/packages/core/src/modules/integration/src/flush-exports.test.tsindex 518916590..4f642ebbf 100644--- a/packages/core/src/modules/integration/src/flush-exports.test.ts+++ b/packages/core/src/modules/integration/src/flush-exports.test.ts@@ -1,6 +1,5 @@-// `runFlushExportsCron` now takes injected deps, so the fan-out, the watermark-// advance and the manifest-last upload order can be asserted with no-// infrastructure at all.+// Deps are injected, so the fan-out, watermark advance and manifest-last upload+// order are asserted without infrastructure.import { describe, expect, it, mock } from 'bun:test';import { gunzipSync } from 'node:zlib';@@ -221,7 +220,6 @@ describe.skipIf(!available)('flush-exports -> GCS end to end', () => {};const adapter = createGCSAdapter(config, testCoreConfig());- // --- exactly what processExport() does ---const events = [1, 2, 3].map(chEvent).map(clickhouseEventToExportEvent);const batch = await createBatch(stubLogger(),@@ -256,7 +254,6 @@ describe.skipIf(!available)('flush-exports -> GCS end to end', () => {content: serializeManifest(manifest),contentType: MANIFEST_CONTENT_TYPE,});- // --- end ---const read = async (key: string) => {const res = await fetch(diff --git a/packages/core/src/modules/integration/src/flush-exports.ts b/packages/core/src/modules/integration/src/flush-exports.tsindex 021c8ba54..0a11c7bcf 100644--- a/packages/core/src/modules/integration/src/flush-exports.ts+++ b/packages/core/src/modules/integration/src/flush-exports.ts@@ -1,10 +1,5 @@-// Prisma, the ClickHouse client and the object-store adapter factory arrive-// as injected deps so the orchestration is testable without `mock.module`-// (same idiom as modules/session/src/runtime.ts).-//-// The window query already binds every value through ClickHouse's own-// `{name:Type}` params; converting it to the `sql` tag would change the-// emitted statement, so it stays byte-identical.+// Prisma, ClickHouse and the object-store adapter factory are injected so the+// orchestration is testable without `mock.module`.import { DateTime } from '@openpanel/shared';import { isProviderError } from '../../../clients/provider-error';@@ -45,9 +40,8 @@ const DEFAULT_CONCURRENCY = 4;// would skip all but one row.const NIL_UUID = '00000000-0000-0000-0000-000000000000';-// Local literal, not @openpanel/db's TABLE_NAMES — same choice cohort.service.ts-// made, and for the same reason: importing that module constructs a ClickHouse-// client at import time.+// Local literal, not @openpanel/db's TABLE_NAMES: importing that module+// constructs a ClickHouse client at import time.const EVENTS_TABLE = 'events';const EXPORT_COLUMNS = `@@ -118,11 +112,8 @@ const formatCh = (date: Date): string =>DateTime.fromJSDate(date).setZone('UTC').toFormat('yyyy-MM-dd HH:mm:ss.SSS');/**- * Drain new ClickHouse events into each configured object-store export.- *- * ClickHouse is the single source of truth: this job windows the events- * table by `inserted_at` and uploads batched files. Export never touches the- * ingestion path.+ * Drain new ClickHouse events into each configured object-store export,+ * windowed by `inserted_at`. Never touches the ingestion path.*/export async function runFlushExportsCron(deps: FlushExportsDeps@@ -369,8 +360,8 @@ async function saveCursor(});}-// Local copy for the reason every modules/*/src/dates.ts gives: importing-// @openpanel/db's clickhouse/client constructs a client at import time.+// Local copy: importing @openpanel/db's clickhouse/client constructs a client+// at import time.function convertClickhouseDateToJs(date: string): Date {return new Date(`${date.replace(' ', 'T')}Z`);}diff --git a/packages/core/src/modules/integration/src/object-store/s3-adapter.ts b/packages/core/src/modules/integration/src/object-store/s3-adapter.tsindex ec47a751f..583960536 100644--- a/packages/core/src/modules/integration/src/object-store/s3-adapter.ts+++ b/packages/core/src/modules/integration/src/object-store/s3-adapter.ts@@ -59,7 +59,6 @@ export class S3Adapter implements IObjectStoreAdapter {config: IS3ExportConfig,private readonly coreConfig: CoreConfig) {- // Decrypt secretAccessKey if present and encryptedif (config.authMode === 'access_key') {this.config = {...config,@@ -141,7 +140,6 @@ export class S3Adapter implements IObjectStoreAdapter {: {}),});- // Mark as non-expiringthis.clientExpiresAt = 0;this.clientPromise = Promise.resolve(client);diff --git a/packages/core/src/modules/integration/src/registry.ts b/packages/core/src/modules/integration/src/registry.tsindex 790baae93..d93633567 100644--- a/packages/core/src/modules/integration/src/registry.ts+++ b/packages/core/src/modules/integration/src/registry.ts@@ -1,6 +1,3 @@-// This module dispatches to its own transports, so it lives above them in the-// layer graph — placing it below would have made those imports point upward.-import {type EncryptionKey,encryptCredential,@@ -56,10 +53,8 @@ export interface INotificationDeliverArgs</*** Server-side behavior for one integration type. Capability slots are optional;- * which ones are present is declared by the core descriptor's `kinds`. A new- * integration adds one entry to SERVER_INTEGRATIONS — the `satisfies Record`- * below forces an entry for every union member (a missing one is a compile- * error, not a silent runtime gap).+ * the core descriptor's `kinds` declares which are present. The `satisfies+ * Record` below makes a missing entry a compile error.*/export interface IServerIntegration<T extends IIntegrationConfig['type']> {type: T;@@ -285,16 +280,14 @@ export function getServerIntegration<T extends IIntegrationConfig['type']>(return SERVER_INTEGRATIONS[type] as unknown as IServerIntegration<T>;}-// ---------------------------------------------------------------------------// Generic secret handling, driven by each plugin's `secretFields`.//// Credentials are WRITE-ONLY: blanked before a config is returned to a client,// and restored from the stored row when an update submits a blank. Returning a-// stored credential would hand a project *reader* the org's secrets — `read` is+// stored credential would hand a project *reader* the org's secrets: `read` is// bare project membership. For the encrypted ones it is worse than disclosure:// decryptCredential accepts any `enc:` value under the single global key, so a// returned ciphertext is a portable bearer token, not an opaque handle.-// ---------------------------------------------------------------------------type LooseConfig = Record<string, unknown>;@@ -406,12 +399,6 @@ export function redactConfigSecrets<C>(config: C): C {return mapSecrets(config, (value) => (value === '' ? undefined : ''));}-// Credentials are write-only: they are encrypted at rest and never travel back-// to a client. `read` on a project is bare membership, so returning the stored-// ciphertext would hand every project member the org's object-store keys — and-// because `decryptCredential` accepts any `enc:` blob under the single global-// key, that ciphertext is a replayable bearer token, not an opaque handle.-//// Every function that returns an integration row — here and in the// notification service, which embeds the rows attached to each rule — goes// through this. Returning a row straight from Prisma is how the Slack botdiff --git a/packages/core/src/modules/integration/src/slack-contract.ts b/packages/core/src/modules/integration/src/slack-contract.tsindex 2be616717..acc9ef301 100644--- a/packages/core/src/modules/integration/src/slack-contract.ts+++ b/packages/core/src/modules/integration/src/slack-contract.ts@@ -1,10 +1,6 @@-// Slack's OAuth token-exchange response (`oauth.v2.access`) — the wire-// contract `integration.routes.ts`'s `/webhook/slack` callback parses the-// JSON it gets back from Slack against, before it's ever stored as a-// `zSlackConfig`. Not integration config a frontend form validates against,-// so it doesn't belong in `integration.constants.ts` even though it's-// zod-only (constants are for isomorphic vocabulary, not third-party API-// contracts) — it's exactly `zSlackConfig` minus the persisted `type` tag.+// Slack's OAuth token-exchange response (`oauth.v2.access`): the wire contract+// the `/webhook/slack` callback parses before storing. Exactly `zSlackConfig`+// minus the persisted `type` tag.import { zSlackConfig } from '../integration.constants';diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.tsindex 4f71aaf31..ba6b48f30 100644--- a/packages/core/src/modules/mcp/mcp.service.test.ts+++ b/packages/core/src/modules/mcp/mcp.service.test.ts@@ -1,22 +1,15 @@/**- * `auth.test.ts` covers `authenticateToken`/`extractToken` in isolation, and- * `src/integration/tools.test.ts` covers tool business logic against real- * ClickHouse — neither exercises this file's own logic: turning one HTTP POST- * into a real MCP JSON-RPC exchange (auth → ephemeral server → synthetic- * initialize handshake → dispatch → response), with no session surviving- * between requests. This file is that missing layer: the client lookup is a- * stub on the `Services` handed in, everything from `createMcpServer` down —- * the real SDK server, `InMemoryTransport`, the wire-format handshake, tool- * registration and dispatch — runs for real.+ * Covers what `auth.test.ts` and `src/integration/tools.test.ts` do not: one+ * HTTP POST becoming a real MCP JSON-RPC exchange (auth, ephemeral server,+ * synthetic initialize handshake, dispatch, response), with no session surviving+ * between requests. The client lookup is a stub; everything from+ * `createMcpServer` down (SDK server, `InMemoryTransport`, handshake, tool+ * dispatch) runs for real.*- * `deps` and `services` are now ARGUMENTS, so the Postgres handle and the- * client lookup are supplied by the test rather than mocked into the module- * registry. The only surviving `mock.module` calls are for the two- * process-global seams MCP auth still reaches (`@openpanel/redis`'s `getCache`- * and argon2 verification), and both are restored in `afterAll` from a- * plain-object snapshot taken before the first `mock.module` call — restoring- * via the live `await import(...)` binding itself is a no-op once mocked, since- * namespace bindings track the current mock.+ * `mock.module` is used only for `@openpanel/redis`'s `getCache` and argon2+ * verification, restored in `afterAll` from a plain-object snapshot taken before+ * the first mock: restoring via the live `await import(...)` binding is a no-op+ * once mocked.*/import {@@ -66,10 +59,8 @@ beforeAll(async () => {const mockFindUnique = mock();const mockGetClientByIdCached = mock();-// Real pino would instantiate a pino-pretty transport worker thread whenever-// NODE_ENV isn't 'production' (pino-logger.ts), which intermittently fails-// to spawn under Bun. `deps.logger` is an argument now, so the test simply-// hands in a noop.+// Real pino spawns a pino-pretty worker thread outside production, which+// intermittently fails to start under Bun.const noopLogger = {fatal: () => {// no-opdiff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.tsindex b7e0ff41b..a61d12091 100644--- a/packages/core/src/modules/mcp/mcp.service.ts+++ b/packages/core/src/modules/mcp/mcp.service.ts@@ -1,15 +1,7 @@-// Stateless-POST MCP transport. Every POST authenticates from scratch and-// gets its own ephemeral McpServer; nothing survives between requests, so-// there is no session to store, touch or close, and no cross-instance-// stickiness requirement. GET/SSE and DELETE are not supported.-//-// MCP is not a separate process and has no dependency builder of its own.-// `rest.routes.ts` mounts it with `.use(mcpRoutes(deps))`, so the route-// already holds the API's connections; this factory closes over them and-// hands them to `createMcpServer` per request. The-// `@modelcontextprotocol/sdk` tool-handler signature has no context-// parameter, which is a CLOSURE problem — solved by building the server-// where `deps` is in hand — not a context problem.+// Every POST authenticates from scratch and gets its own ephemeral McpServer,+// so there is no session to store or close and no cross-instance stickiness.+// GET/SSE and DELETE are not supported. Tool handlers close over `deps` because+// the `@modelcontextprotocol/sdk` handler signature has no context parameter.import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import {@@ -33,11 +25,9 @@ export type { McpAuthContext } from './src/auth';export { extractToken, McpAuthError } from './src/auth';/**- * The wire constants of the synthetic handshake. They are a CONTRACT with- * whatever client is on the other end of `/mcp`, not an implementation- * detail: `mcp.service.test.ts` pins them, because bumping- * `@modelcontextprotocol/sdk` does not bump them and nothing else would- * notice if it did.+ * Wire constants of the synthetic handshake. They are a contract with clients+ * of `/mcp`: `mcp.service.test.ts` pins them because bumping+ * `@modelcontextprotocol/sdk` does not bump them.*/const MCP_PROTOCOL_VERSION = '2024-11-05';const MCP_PROXY_CLIENT_INFO = { name: 'mcp-proxy', version: '0' };@@ -70,11 +60,8 @@ function invalidRequest(body: unknown, message: string): McpHttpResult {}/**- * Handle one stateless MCP POST request end-to-end.- *- * Auth failures resolve to a 401 result rather than throwing, so the caller- * (an HTTP framework's route handler) needs only one catch block for- * everything else.+ * Handle one stateless MCP POST request. Auth failures resolve to a 401 result+ * rather than throwing, so callers need one catch block for everything else.*/export async function handleStatelessMcpRequest(deps: ServiceDeps,@@ -155,11 +142,9 @@ async function runOnEphemeralServer(clientTransport.send(message).catch(reject);});} finally {- // This function opened the pair, so this function closes it. `server.close`- // closes `serverTransport`, and an InMemoryTransport closes its linked- // peer, so one call tears down both ends — and with them the SDK's response- // handlers and in-flight abort controllers, which a dropped-on-the-floor- // server would have kept alive until GC.+ // `server.close` closes `serverTransport`, and an InMemoryTransport closes its+ // linked peer, so one call tears down both ends and the SDK's response+ // handlers and abort controllers with them.await server.close();}}@@ -248,10 +233,6 @@ function logToolResult();}-/**- * The MCP tool tree reaches Postgres and ClickHouse through the `deps` this- * factory closes over. `extractToken` is pure and stays a bare re-export.- */export function createMcpService(deps: ServiceDeps, services: () => Services) {return {extractToken,diff --git a/packages/core/src/modules/mcp/src/auth.test.ts b/packages/core/src/modules/mcp/src/auth.test.tsindex a74f739ff..dc4db52e1 100644--- a/packages/core/src/modules/mcp/src/auth.test.ts+++ b/packages/core/src/modules/mcp/src/auth.test.ts@@ -13,12 +13,9 @@ const noopLogger = {child: () => noopLogger,};-// The client lookup and the logger are ARGUMENTS now — `deps` and `services`-// come from the route, so only `@openpanel/redis`'s process-global `getCache`-// and argon2 verification are still mocked at the specifier the source resolves-// to (a whole-barrel replacement would drop every other export those barrels-// carry for any other file sharing this process — bun:test only isolates-// modules per file under `--isolate`, see AGENTS.md).+// Only `@openpanel/redis`'s `getCache` and argon2 verification are mocked, at+// the specifier the source resolves to: a whole-barrel replacement would drop+// every other export for other files sharing this process.const actualRedis = await import('@openpanel/redis');mock.module('@openpanel/redis', () => ({...actualRedis,@@ -75,10 +72,6 @@ const baseClient = {organizationId: 'org-456',};-// ----------------------------------------------------------------------------// extractToken-// ----------------------------------------------------------------------------describe('extractToken', () => {it('returns token from ?token= query param', () => {expect(extractToken({ token: 'abc' }, undefined)).toBe('abc');@@ -103,10 +96,6 @@ describe('extractToken', () => {});});-// ----------------------------------------------------------------------------// authenticateToken-// ----------------------------------------------------------------------------describe('authenticateToken', () => {it('throws McpAuthError when token is missing', async () => {await expect(authenticate(undefined)).rejects.toThrow(McpAuthError);diff --git a/packages/core/src/modules/mcp/src/auth.ts b/packages/core/src/modules/mcp/src/auth.tsindex 37ca97e92..3586e95d7 100644--- a/packages/core/src/modules/mcp/src/auth.ts+++ b/packages/core/src/modules/mcp/src/auth.ts@@ -144,9 +144,7 @@ export function extractToken(if (typeof query['token'] === 'string') {return query['token'];}- // RFC 7235: the auth scheme is case-insensitive, so `bearer` is as valid as- // `Bearer`. Refusing it was non-conformant, and accepting it can only let- // more clients through.+ // RFC 7235: the auth scheme is case-insensitive.const [scheme, value] = (authHeader ?? '').split(' ');if (scheme?.toLowerCase() === 'bearer' && value) {return value;diff --git a/packages/core/src/modules/mcp/src/integration/tools.test.ts b/packages/core/src/modules/mcp/src/integration/tools.test.tsindex 3636d9382..50a41f0b0 100644--- a/packages/core/src/modules/mcp/src/integration/tools.test.ts+++ b/packages/core/src/modules/mcp/src/integration/tools.test.ts@@ -1,28 +1,18 @@/**- * Integration tests for MCP tools against a real ClickHouse instance.- *- * `bunfig.toml`'s preload pins CLICKHOUSE_URL/DATABASE_URL to the isolated- * `openpanel_test` databases (never production) — bun:test has no- * vitest-style globalSetup, so this suite bootstraps and seeds its own- * fixture (test/fixtures.ts) in beforeAll/afterAll, under its own- * project/org id so it can run concurrently with other suites using the- * same fixture helper.- *- * Fixture data (test/fixtures.ts's FIXTURE), seeded and queried with the clock- * pinned to test/fixture-clock.ts's 12:00 UTC anchor so "5 days ago" is one- * calendar day whatever time the suite runs:+ * MCP tools against a real ClickHouse. `bunfig.toml`'s preload pins the+ * isolated `openpanel_test` databases; the suite seeds its own fixture+ * (test/fixtures.ts) under its own project/org id so it can run alongside other+ * suites, with the clock pinned to test/fixture-clock.ts's 12:00 UTC anchor so+ * "5 days ago" is one calendar day whenever it runs:* Alice — 3 events: session_start, page_view(/home), session_end — 2 days ago — country: US, browser: Chrome* Bob — 0 events (inactive) — profile created 90 days ago — country: SE* Charlie — 5 events: session_start, screen_view, page_view(/shop), purchase, session_end — 5 days ago — browser: Firefox* 2 sessions (sess-charlie-1 5d ago, sess-charlie-2 10d ago)*- * get_page_performance also calls getSettingsForProject (Postgres) — real,- * not mocked, which is why setupPostgresFixtures runs alongside the- * ClickHouse fixture.- *- * The fixture import reaches SEVEN levels up, out of this package and into the- * repository root's `test/fixtures.ts`. That is deliberate: copying the- * seeder here would fork the schema the golden harness seeds from.+ * get_page_performance also reads Postgres (getSettingsForProject), unmocked,+ * hence `setupPostgresFixtures`. The fixture is imported from the repository+ * root's `test/fixtures.ts` rather than copied, so the schema the golden harness+ * seeds from cannot fork.*/import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test';@@ -103,9 +93,6 @@ beforeAll(async () => {pinFixtureClock();await fixtures.setupFixtures(TEST_PROJECT_ID);- // The tools take `deps`/`services` as arguments, so the suite builds the same- // graph `mcp.routes.ts` hands them at runtime — no compat seam, no- // process-global registration.const { testServiceDeps } = await import('../../../../../test/service-deps');const { createServices } = await import('../../../../services');const deps = await testServiceDeps();@@ -171,8 +158,6 @@ function rowsOf(result: { columns: string[]; rows: unknown[][] }): any[] {);}-// ─── Discovery ────────────────────────────────────────────────────────────────-describe('list_event_names', () => {it('returns { event_names: string[] }', async () => {const server = makeServer();@@ -212,8 +197,6 @@ describe('get_event_property_values', () => {});});-// ─── Raw data ─────────────────────────────────────────────────────────────────-describe('query_events', () => {it('returns all 8 fixture events', async () => {const server = makeServer();@@ -319,8 +302,6 @@ describe('query_sessions', () => {});});-// ─── Profile tools ────────────────────────────────────────────────────────────-describe('find_profiles', () => {it('returns all 3 fixture profiles', async () => {const server = makeServer();@@ -452,7 +433,6 @@ describe('get_profile_metrics', () => {projectId: TEST_PROJECT_ID,profileId: FIXTURE.profiles.charlie,});- // No error — bug was getProfileMetrics returns single object, not arrayexpect(res.error).toBeUndefined();expect(res.profileId).toBe(FIXTURE.profiles.charlie);expect(res.sessions).toBe(2); // sess-charlie-1 and sess-charlie-2 in the sessions table@@ -478,10 +458,8 @@ describe('get_profile_metrics', () => {expect(res.screenViews).toBe(0);});- // The query aggregates, so an unknown id used to come back as a row of- // zeros and the tool's not-found branch could never fire — a made-up- // profile reported confident zeros, indistinguishable from a real but- // inactive user (ISSUES.md H8e).+ // The query aggregates, so an unknown id must not come back as a row of+ // zeros that reads as a real but inactive user.it('reports not found for a profile that does not exist', async () => {const server = makeServer();registerProfileMetricTools(server as any, TOOLS);@@ -495,8 +473,6 @@ describe('get_profile_metrics', () => {});});-// ─── Groups ───────────────────────────────────────────────────────────────────-describe('list_group_types', () => {it('returns { types: [] } (no groups in fixtures)', async () => {const server = makeServer();@@ -534,8 +510,6 @@ describe('get_group', () => {});});-// ─── Aggregated metrics ───────────────────────────────────────────────────────-describe('get_analytics_overview', () => {it('returns summary with numeric metric fields and a series array', async () => {const server = makeServer();@@ -660,8 +634,6 @@ describe('get_device_breakdown', () => {});});-// ─── User behavior ────────────────────────────────────────────────────────────-describe('get_funnel', () => {it('detects charlie completing session_start → purchase', async () => {const server = makeServer();diff --git a/packages/core/src/modules/mcp/src/server.ts b/packages/core/src/modules/mcp/src/server.tsindex c71db15e4..f82b6080d 100644--- a/packages/core/src/modules/mcp/src/server.ts+++ b/packages/core/src/modules/mcp/src/server.ts@@ -6,12 +6,8 @@ const SERVER_NAME = 'OpenPanel';const SERVER_VERSION = '1.0.0';/**- * Create a fully configured McpServer for one authenticated request.- *- * The API owns every connection (R15, Carl's ruling): the server is- * bootstrapped from the `deps` `mcp.routes.ts` already holds, and each tool- * handler CLOSES OVER them — the SDK's tool-handler signature has no context- * parameter, which is a closure problem, not a context problem.+ * Create a configured McpServer for one authenticated request. Tool handlers+ * close over `deps` because the SDK's handler signature has no context parameter.*/export function createMcpServer(tools: McpToolDeps): McpServer {const server = new McpServer(diff --git a/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.tsindex d2119032f..111633773 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/engagement.test.ts@@ -12,11 +12,11 @@ import type { McpToolDeps } from '../shared';const mockGetRetentionLastSeenSeries = mock();-// Mocked at the specifier the source imports resolve to — a whole-barrel-// replacement would drop every other export those modules carry for any-// other file sharing this process. Restored in `afterAll` from a-// plain-object snapshot taken BEFORE the first `mock.module` call: restoring-// via the live `await import(...)` binding is a no-op once mocked.+// Mocked at the specifier the source imports resolve to: a whole-barrel+// replacement would drop every other export those modules carry for any other+// file sharing this process. Restored in `afterAll` from a plain-object snapshot+// taken BEFORE the first `mock.module`, since restoring via the live+// `await import(...)` binding is a no-op once mocked.const actualRetention = await import('../../../../chart/retention.service');const realRetention = { ...actualRetention };mock.module('../../../../chart/retention.service', () => ({diff --git a/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts b/packages/core/src/modules/mcp/src/tools/analytics/engagement.tsindex 2abc16609..f26c1006b 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/engagement.ts@@ -34,7 +34,6 @@ export function registerEngagementTools(const projectId = await resolveProjectId(deps, context, inputProjectId);const raw = await getRetentionLastSeenSeries(deps, { projectId });- // Bucket into meaningful segments for easier readinglet active_0_7 = 0;let active_8_14 = 0;let active_15_30 = 0;diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.tsindex 38dbad5fd..734003be2 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-conversions.test.ts@@ -12,12 +12,11 @@ import type { McpToolDeps } from '../shared';const mockGetPageConversionsCore = mock();-// Mocked at the specifier the source imports resolve to — a whole-barrel-// replacement would drop every other export those modules carry for any-// other file sharing this process (bun:test only isolates modules per file-// under `--isolate`; see AGENTS.md). Restored in `afterAll` from a-// plain-object snapshot taken BEFORE the first `mock.module` call: restoring-// via the live `await import(...)` binding is a no-op once mocked.+// Mocked at the specifier the source imports resolve to: a whole-barrel+// replacement would drop every other export those modules carry for any other+// file sharing this process. Restored in `afterAll` from a plain-object snapshot+// taken BEFORE the first `mock.module`, since restoring via the live+// `await import(...)` binding is a no-op once mocked.const actualPagesService = await import('../../../../overview/pages.service');const realPagesService = { ...actualPagesService };mock.module('../../../../overview/pages.service', () => ({diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.tsindex c5c3cd625..420b9949f 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts@@ -15,13 +15,11 @@ const mockGetSettingsForProject = mock(() =>Promise.resolve({ timezone: 'UTC' }));-// The tool reads the pages service off the `services` graph handed in with-// `deps`, so `getTopPages` is a plain stub on TOOLS below rather than a module-// mock. Only the two sibling module functions this file drives are still-// replaced, each at the specifier the source imports resolve to, and each is-// restored in `afterAll` from a plain-object snapshot taken BEFORE the first-// `mock.module` call, since restoring via the live `await import(...)`-// binding is a no-op once mocked.+// `getTopPages` is a plain stub on the `services` graph; only the two sibling+// module functions driven here are mocked, at the specifier the source imports+// resolve to, and restored in `afterAll` from a plain-object snapshot taken+// BEFORE the first `mock.module` (restoring via the live `await import(...)`+// binding is a no-op once mocked).const actualOrganizationService = await import('../../../../organization/organization.service');diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.tsindex ea26f49b5..91f45ac05 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.ts@@ -22,10 +22,9 @@ const MAX_PERFORMANCE_LIMIT = 500;const PAGE_SCAN_LIMIT = 1000;/**- * Thresholds the tool used to stamp onto every row as a `seo_signals` object of- * three booleans. They're pure functions of `bounce_rate` and `avg_duration`,- * both of which are already columns — so we state the rule once instead of- * re-deriving it 25 times at ~50 tokens a row.+ * Thresholds for high bounce, low engagement and good landing pages. They are+ * pure functions of `bounce_rate` and `avg_duration`, so the rule is stated once+ * instead of re-derived on every row.*/const SEO_THRESHOLDS = {high_bounce: 'bounce_rate > 70',diff --git a/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.tsindex bff659d69..5189b1dc4 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts@@ -1,10 +1,8 @@import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';import type { ServiceDeps } from '../../../../../services';-// `findProfilesCore` takes `ServiceDeps` and reaches ClickHouse as `deps.ch`-// (through ch-query.ts), so the client is HANDED IN rather than mocked onto-// `@openpanel/db/src/clickhouse/client` process-wide. Same assertions, one less-// shared-registry hazard.+// `findProfilesCore` reaches ClickHouse as `deps.ch`, so the client is handed in+// rather than mocked process-wide.const chQuery = mock(async (_params: {query: string;diff --git a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts b/packages/core/src/modules/mcp/src/tools/analytics/property-values.tsindex d9a142abd..4b7ef9631 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts@@ -32,11 +32,6 @@ const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;* push real properties like `country` off the end. Collapsing to the root* segment and ranking by how many sub-keys fall under it turns 500 near-useless* rows into a few dozen useful ones.- *- * The in-app chat agent solves the same problem in- * `packages/core/src/modules/assistant/src/tools/helpers.ts`; kept as a local- * copy rather than a shared abstraction since the two consumers may want to- * diverge.*/function compactPropertyKeys(rows: Array<{ property_key: string }>,diff --git a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.tsindex b075bc720..7729ce9bd 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts@@ -191,10 +191,8 @@ export function registerReportTools(async ({ projectId: inputProjectId, dashboardId }) =>withErrorHandling(deps, async () => {const projectId = await resolveProjectId(deps, context, inputProjectId);- // Bind the id to the project BEFORE reading, the way every other- // dashboard/report tool here does: the post-hoc check this replaced- // let a foreign dashboard holding zero reports answer with a normal- // empty table instead of an error.+ // Bind the id to the project BEFORE reading, so a foreign dashboard with+ // zero reports cannot answer with a normal empty table.await requireDashboard(deps, projectId, dashboardId);const reports = await getReportsByDashboardId(deps, dashboardId);const rows = reports.map((r) => ({@@ -294,15 +292,9 @@ export function registerReportTools(}/**- * Execute a saved report by ID. Dispatches on chart type: funnel → getFunnel,- * metric → executeAggregateChart, others → executeChart.- *- * The assistant module (`../../assistant/src/report-runner.ts`) carries its- * own copy of this dispatch for its in-app chat tools — MCP's tool- * definitions and assistant's are deliberately not unified, so the two live- * as hand-synced copies rather than a shared helper. Deliberately returns the- * raw engine output here — the MCP tool reshapes it for LLM consumption, the- * chat renderer needs the full chart.+ * Execute a saved report by ID, dispatching on chart type. Returns the raw engine+ * output; the MCP tool reshapes it for an LLM. The assistant module keeps its own+ * hand-synced copy of this dispatch.*/async function runReport(deps: ServiceDeps,diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.tsindex ea43da3a1..21b12cdbc 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts@@ -57,14 +57,11 @@ const mockGetDashboardById = mock();const mockGetProjectById = mock();const mockGetId = mock();-// Postgres arrives on `deps.db` (see TOOLS below), so the only module mocks-// left are the three sibling functions this file asserts calls against. Each is-// replaced at the specifier the source imports resolve to — a whole-barrel-// replacement would drop every other export those modules carry for any other-// file sharing this process (bun:test only isolates modules per file under-// `--isolate`; see AGENTS.md) — and each is restored in `afterAll` from a-// plain-object snapshot taken BEFORE the first `mock.module` call, since-// restoring via the live `await import(...)` binding is a no-op once mocked.+// Only the three sibling functions asserted against are mocked, at the+// specifier the source imports resolve to (a whole-barrel replacement would drop+// every other export for other files sharing this process), and restored in+// `afterAll` from a plain-object snapshot taken BEFORE the first `mock.module`+// (restoring via the live `await import(...)` binding is a no-op once mocked).const actualDashboardService = await import('../../../dashboard/dashboard.service');diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.tsindex 63ec9c48d..489c3aad4 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts@@ -143,11 +143,9 @@ function reportUrl(return `${dashboardBaseUrl(config)}/${organizationId}/${projectId}/reports/${reportId}`;}-// `dbNull` is `Prisma.DbNull` (an explicit SQL NULL on a nullable Json column),-// threaded in as `unknown` rather than importing `@openpanel/db` here — same-// shape notification.service.ts's `isValidPayload` uses for the same sentinel.-// It arrives on `McpToolDeps.dbJsonNull`, resolved once by `mcp.service.ts`-// when it builds the server.+// `dbNull` is `Prisma.DbNull` (explicit SQL NULL on a nullable Json column),+// passed as `unknown` via `McpToolDeps.dbJsonNull` instead of importing+// `@openpanel/db` here.function reportData(report: z.infer<typeof reportSchema>, dbNull: unknown) {return {name: report.name,diff --git a/packages/core/src/modules/mcp/src/tools/index.ts b/packages/core/src/modules/mcp/src/tools/index.tsindex d3e44afe0..162b9d874 100644--- a/packages/core/src/modules/mcp/src/tools/index.ts+++ b/packages/core/src/modules/mcp/src/tools/index.ts@@ -37,18 +37,14 @@ export function registerAllTools(server: McpServer, tools: McpToolDeps): void {registerEventNameTools(server, tools);registerPropertyValueTools(server, tools);- // Analytics — event dataregisterEventTools(server, tools);registerSessionTools(server, tools);- // Analytics — profilesregisterProfileTools(server, tools);registerProfileMetricTools(server, tools);- // Analytics — groups (B2B)registerGroupTools(server, tools);- // Analytics — aggregated metricsregisterOverviewTools(server, tools);registerActiveUserTools(server, tools);registerPageTools(server, tools);@@ -56,13 +52,11 @@ export function registerAllTools(server: McpServer, tools: McpToolDeps): void {registerPageConversionTools(server, tools);registerTrafficTools(server, tools);- // Analytics — user behaviorregisterFunnelTools(server, tools);registerRetentionTools(server, tools);registerEngagementTools(server, tools);registerUserFlowTools(server, tools);- // Google Search ConsoleregisterGscOverviewTools(server, tools);registerGscPageTools(server, tools);registerGscQueryTools(server, tools);diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.tsindex 7e977647e..6b16f538f 100644--- a/packages/core/src/modules/mcp/src/tools/shared.ts+++ b/packages/core/src/modules/mcp/src/tools/shared.ts@@ -4,14 +4,7 @@ import { classifyDriverError } from '../../../../shared/driver-errors';import { resolveClientProjectId } from '../../../project/project.service';import type { McpAuthContext } from '../auth';-/**- * What every MCP tool handler closes over.- *- * `@modelcontextprotocol/sdk`'s tool-handler signature has no context- * parameter, so the API's connections cannot be threaded through it as an- * argument. They are captured in a CLOSURE instead, when the per-request server- * is built from the `deps` the route already holds.- */+/** What every MCP tool handler closes over. */export interface McpToolDeps {/** The API's connections. Postgres and ClickHouse are reached from here. */deps: ServiceDeps;@@ -20,10 +13,8 @@ export interface McpToolDeps {/** The authenticated MCP caller. */context: McpAuthContext;/**- * `Prisma.DbNull` — the explicit-SQL-NULL sentinel for a nullable Json- * column. A frozen constant, not a client: `ServiceDeps` has no field for- * it and `core-uses-ctx-not-db-internals` forbids importing it here, so- * `mcp.service.ts` resolves it once and hands it in with the rest.+ * `Prisma.DbNull`, the explicit-SQL-NULL sentinel for a nullable Json column.+ * Resolved once by `mcp.service.ts` because tools may not import it.*/dbJsonNull: unknown;}@@ -354,8 +345,8 @@ export async function withErrorHandling<T>(} catch (err) {const raw = err instanceof Error ? err.message : String(err);// The model sees this text, so a driver failure must not hand it Prisma's- // invocation dump or a ClickHouse message quoting the generated SQL- // (ISSUES.md H12). The full error still goes to the log.+ // invocation dump or a ClickHouse message quoting the generated SQL. The+ // full error still goes to the log.const failure = classifyDriverError(err);const message = failure ? failure.message : raw;deps.logger.error({ err }, `MCP tool error: ${raw}`);diff --git a/packages/core/src/modules/misc/misc.jobs.ts b/packages/core/src/modules/misc/misc.jobs.tsindex 7433add88..787820f90 100644--- a/packages/core/src/modules/misc/misc.jobs.ts+++ b/packages/core/src/modules/misc/misc.jobs.ts@@ -1,9 +1,5 @@-// `ping` is this module's fragment of the ONE `cron` queue's jobs: declared-// here and spread into jobs.registry.ts, same shape as organization.jobs.ts's-// `delete`. Its `cron` is explicitly `null` (on-demand, not "always-// scheduled") — `PING_SCHEDULE` in jobs/schedulers.ts adds it separately,-// conditionally on `SELF_HOSTED && production`, because it is the one-// scheduler that isn't always-on.+// `cron` is explicitly `null` (on-demand): `PING_SCHEDULE` in jobs/schedulers.ts adds+// it separately, only on `SELF_HOSTED && production`.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/misc/misc.routes.ts b/packages/core/src/modules/misc/misc.routes.tsindex c46fc54b3..befd0917a 100644--- a/packages/core/src/modules/misc/misc.routes.ts+++ b/packages/core/src/modules/misc/misc.routes.ts@@ -1,6 +1,3 @@-// `GET /misc/og/clear` and `GET /misc/favicon/clear` are deliberately absent:-// nothing depends on them.-import { z } from 'zod';import { defineRoutes } from '../../http/define';import {diff --git a/packages/core/src/modules/misc/misc.service.ts b/packages/core/src/modules/misc/misc.service.tsindex d4e63f7ef..7698b4191 100644--- a/packages/core/src/modules/misc/misc.service.ts+++ b/packages/core/src/modules/misc/misc.service.ts@@ -1,16 +1,3 @@-// `GET/POST /misc/og/clear` and `/misc/favicon/clear` are deliberately absent:-// nothing proxies them.-//-// The ClickHouse CLIENT is `deps.ch` — reads through ch-query.ts, the one-// write through `deps.ch.insert`. These three statements are raw strings, not-// `sql` fragments, so they still need `TABLE_NAMES` / `formatClickhouseDate`,-// and core owns its own parity-tested copies of both (shared/ch-tables.ts,-// shared/ch-dates.ts, guarded by their `.parity.test.ts` siblings).-//-// `getCache` is a plain static import. It was lazy to survive core tests that-// partially mock `@openpanel/redis` without a `getCache` export; those mocks-// snapshot the real module and spread it now, so the loader bought nothing.-import crypto from 'node:crypto';import { getCache, getRedisCache } from '@openpanel/redis';import {@@ -88,8 +75,7 @@ function validateUrl(raw?: string): URL | null {}}-// Reaches the redis singleton directly rather than through `deps`/`ctx`:-// nothing calling these two functions today holds a `deps`/`ctx` to thread.+// Reaches the redis singleton directly: callers of these two functions hold no `deps`/`ctx`.async function getFromCacheBinary(key: string): Promise<{ buffer: Buffer; contentType: string } | null> {diff --git a/packages/core/src/modules/misc/src/image-proxy.test.ts b/packages/core/src/modules/misc/src/image-proxy.test.tsindex e97223365..b51ac650e 100644--- a/packages/core/src/modules/misc/src/image-proxy.test.ts+++ b/packages/core/src/modules/misc/src/image-proxy.test.ts@@ -56,8 +56,8 @@ describe('processImage', () => {});it('rasterizes small images rather than passing the bytes through', async () => {- // A sub-5KB body used to be returned verbatim with the upstream content- // type, which let an attacker serve arbitrary content from the API origin.+ // A sub-5KB body must not be returned verbatim with the upstream content type, or an+ // attacker could serve arbitrary content from the API origin.const png = await makePng();expect(png.length).toBeLessThan(5000);diff --git a/packages/core/src/modules/misc/src/parse-url-meta.ts b/packages/core/src/modules/misc/src/parse-url-meta.tsindex 5c088c8ff..2215f210e 100644--- a/packages/core/src/modules/misc/src/parse-url-meta.ts+++ b/packages/core/src/modules/misc/src/parse-url-meta.ts@@ -1,5 +1,3 @@-// Ported verbatim from apps/api/src/utils/parseUrlMeta.ts.-import urlMetadata from 'url-metadata';const URL_METADATA_TIMEOUT_MS = 500;diff --git a/packages/core/src/modules/notification/notification.jobs.ts b/packages/core/src/modules/notification/notification.jobs.tsindex f752f263b..8e3386eaf 100644--- a/packages/core/src/modules/notification/notification.jobs.ts+++ b/packages/core/src/modules/notification/notification.jobs.ts@@ -1,8 +1,5 @@-// `sendNotification` is this module's own queue (`notification` in the-// registry). legacyCompat.notification already discriminates on this exact-// job name (jobs/compat.ts), so this pins the two in agreement. No cron-// fragment — notifications are always triggered by a rule match, never-// scheduled.+// legacyCompat.notification discriminates on this exact job name (jobs/compat.ts).+// No cron fragment: notifications are only triggered by a rule match.import type { Prisma } from '@openpanel/db/src/prisma-client';import { z } from 'zod';diff --git a/packages/core/src/modules/notification/notification.rpc.test.ts b/packages/core/src/modules/notification/notification.rpc.test.tsindex bd506144a..f6861446c 100644--- a/packages/core/src/modules/notification/notification.rpc.test.ts+++ b/packages/core/src/modules/notification/notification.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + CRUD logic ride on @openpanel/db (lazy-loaded, see-// notification.service.ts's header); wiring this router end-to-end against a-// real Postgres is P6's (protectedProcedure) job, not this one's — see-// notification.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/notification/notification.rpc.ts b/packages/core/src/modules/notification/notification.rpc.tsindex 1498465d3..163985e2e 100644--- a/packages/core/src/modules/notification/notification.rpc.ts+++ b/packages/core/src/modules/notification/notification.rpc.ts@@ -6,9 +6,6 @@// `list`/`rules` have no access check here either. `deleteRule` and// `createOrUpdateRule` re-check access against the *existing* rule's project,// not just the input's.-//-// The permission ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/notification/notification.service.test.ts b/packages/core/src/modules/notification/notification.service.test.tsindex 8e527715d..bea30da01 100644--- a/packages/core/src/modules/notification/notification.service.test.ts+++ b/packages/core/src/modules/notification/notification.service.test.ts@@ -1,9 +1,3 @@-// notification.service.ts's db 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 { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import type { IChartEvent } from '../report/report.constants';@@ -43,10 +37,9 @@ function makeRule(overrides: Partial<FakeRule> & { id: string }): FakeRule {}const publishedEvents: unknown[] = [];-// Spread a plain-object SNAPSHOT of the real module and restore it in afterAll-// — `mock.module` has no per-file scope under bare `bun test` (AGENTS.md), and-// a partial factory deletes `getRedisCache` and friends for every file that-// runs next.+// Spread a SNAPSHOT of the real module and restore it in afterAll: `mock.module` has no+// per-file scope under bare `bun test`, and a partial factory deletes `getRedisCache`+// and friends for every file that runs next.const realRedis = { ...(await import('@openpanel/redis')) };mock.module('@openpanel/redis', () => ({...realRedis,diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.tsindex 4bea7daef..ecc5ebf43 100644--- a/packages/core/src/modules/notification/notification.service.ts+++ b/packages/core/src/modules/notification/notification.service.ts@@ -1,14 +1,5 @@-// `createNotification` / `triggerNotification` /-// `checkNotificationRulesForEvent` / `checkNotificationRulesForSessionEnd` —-// the BullMQ-producer orchestration around a rule match — live in this-// module's own `src/notification-dispatch.ts`, built on the rule matching,-// templates, cache and constants exported below. They are a separate file-// only so the enqueue side is not dragged into every import of this one.-//-// Postgres is `deps.db` and `Prisma.DbNull` is `deps.prisma.DbNull`: nothing-// here imports @openpanel/db as a value, which is what keeps constructing a-// client out of the eager barrel chain that jobs.registry.ts and services.ts-// pull this module into.+// Nothing here imports @openpanel/db as a value, so constructing a client stays+// out of the eager barrel chain (jobs.registry.ts, services.ts) that pulls this module in.import type { Integration, Prisma } from '@openpanel/db/src/prisma-client';import { stripLeadingAndTrailingSlashes } from '@openpanel/shared';@@ -66,12 +57,8 @@ export type INotificationPayload =| { type: 'event'; event: IServiceCreateEventPayload }| { type: 'funnel'; funnel: IServiceEvent[] };-// `getNotificationRulesByProjectId` is `cacheablePerDeps` — `cacheable` keys on-// the call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps-// travel beside the key rather than inside it and the Redis key stays-// byte-identical. Every function in this file reads `deps.db`.--// -- Rule cache --------------------------------------------------------+// `cacheable` keys on the call's arguments, so deps travel beside the key and+// the Redis key stays unchanged.export type INotificationRuleCached = Awaited<ReturnType<typeof getNotificationRulesByProjectId>@@ -96,8 +83,6 @@ export const getNotificationRulesByProjectId = cacheablePerDeps({ cacheEmptyArray: true });-// -- Rule matching (pure) ------------------------------------------------export function matchEventFilters(payload: IServiceCreateEventPayload,filters: IChartEventFilter[]@@ -192,8 +177,6 @@ export function getFunnelRules(return rules.filter(isFunnelRule);}-// -- Templates (pure) ------------------------------------------------------export function notificationTemplateEvent({payload,rule,@@ -240,13 +223,7 @@ export function notificationTemplateFunnel({.replaceAll('$RULE_NAME', rule.name);}-// -- Dispatch (the delivery job body) ----------------------------------------/**- * `Prisma.JsonNull`/`Prisma.DbNull` sentinels don't narrow away from a union- * through plain `!==` control flow — an explicit type predicate is what makes- * `payload` usable as `INotificationPayload` afterward.- */+/** `Prisma.JsonNull`/`DbNull` don't narrow through `!==`; this predicate does. */function isValidPayload<T>(value: T | Prisma.NullableJsonNullValueInput | null | undefined,jsonNull: unknown,@@ -260,7 +237,6 @@ function isValidPayload<T>();}-/** apps/worker/src/jobs/notification.ts's `sendNotification` job body. *//** Where a notification email links when DASHBOARD_URL is not set. */const DEFAULT_DASHBOARD_URL = 'https://dashboard.openpanel.dev';@@ -270,11 +246,8 @@ export async function deliverNotification(): Promise<unknown> {const db = deps.db;- // App + email are pseudo-integrations dispatched by flags, not real rows.- // Lazy: @openpanel/redis is otherwise pulled in eagerly through this- // module's place in the barrel (services.ts, jobs.registry.ts), and a- // static import here would demand `publishEvent` from every core test- // file's `@openpanel/redis` mock, not just this module's own.+ // Lazy: a static @openpanel/redis import would force every core test's redis+ // mock to provide `publishEvent`.if (notification.sendToApp) {const { publishEvent } = await import('@openpanel/redis');publishEvent('notification', 'created', notification);@@ -299,8 +272,6 @@ export async function deliverNotification());for (const to of emails) {- // Per-recipient unsubscribe (product_alerts category) is handled- // inside sendEmail.await sendEmail('notification-rule', {to,data: {@@ -323,12 +294,8 @@ export async function deliverNotification(});const payload = notification.payload;- // Returning rather than throwing here (and in the missing-config branch- // below) resolves `notificationQueueJobs.sendNotification`'s promise- // normally, so BullMQ records the job as completed instead of failed —- // the delivery is silently dropped. Left as-is deliberately: flipping the- // job outcome from success to failure is a behavior change, and no test- // exercises either branch today.+ // Returning (rather than throwing) completes the BullMQ job, so the delivery+ // is dropped silently instead of failing.if (!isValidPayload<INotificationPayload>(payload,@@ -347,8 +314,6 @@ export async function deliverNotification(return;}- // Generic registry dispatch — no per-type switch. A new notification- // integration just registers a `notification.deliver` plugin.const plugin = getServerIntegration(config.type);if (!plugin.notification) {throw new Error(`Integration ${config.type} is not a notification sink`);@@ -364,8 +329,6 @@ export async function deliverNotification(});}-// -- RPC-facing CRUD ---------------------------------------------------------export function listNotifications(deps: ServiceDeps, projectId: string) {return Promise.resolve(deps.db).then((db) =>db.notification.findMany({@@ -416,10 +379,9 @@ export async function getNotificationRuleByIdOrThrow(}/**- * Authorization (`requireProjectAccess`) is the caller's job — same split as- * reference.service.ts. This validates that every connected integration- * belongs to `input.projectId` or is a legacy org-wide one in the same org,- * then writes the rule.+ * Authorization (`requireProjectAccess`) is the caller's job. Validates that every+ * connected integration belongs to `input.projectId` or is a legacy org-wide one+ * in the same org, then writes the rule.*/export async function createOrUpdateNotificationRule(deps: ServiceDeps,@@ -511,12 +473,7 @@ export async function deleteNotificationRule(deps: ServiceDeps, id: string) {return await deps.db.notificationRule.delete({ where: { id } });}-// -- Services surface ----------------------------------------------------// This wraps only `dispatch` (what notification.jobs.ts needs). Every other-// function above and in ./src/notification-dispatch.ts is called directly —-// by notification.rpc.ts, by session/ingest as siblings, and by index.ts's-// barrel — not through ctx.services.notification.+// Only `dispatch` goes through ctx.services; everything else is called directly.export function createNotificationService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/onboarding/onboarding.jobs.ts b/packages/core/src/modules/onboarding/onboarding.jobs.tsindex b485dce5e..7d30af810 100644--- a/packages/core/src/modules/onboarding/onboarding.jobs.ts+++ b/packages/core/src/modules/onboarding/onboarding.jobs.ts@@ -1,6 +1,3 @@-// `onboarding` is this module's fragment of the ONE `cron` queue's jobs,-// spread into jobs.registry.ts — same shape as organization.jobs.ts.-import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.test.ts b/packages/core/src/modules/onboarding/onboarding.rpc.test.tsindex f876aa451..8090a05d8 100644--- a/packages/core/src/modules/onboarding/onboarding.rpc.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The org+project+client creation rides on @openpanel/db (lazy-loaded-// through ./onboarding.service); wiring this router end-to-end against a-// real Postgres is P6's (protectedProcedure) job, not this one's — see-// onboarding.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/onboarding/onboarding.service.test.ts b/packages/core/src/modules/onboarding/onboarding.service.test.tsindex f4a5891dc..672c58738 100644--- a/packages/core/src/modules/onboarding/onboarding.service.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.test.ts@@ -1,8 +1,6 @@-// Onboarding email cron: the sequential drip driven by the-// `organization.onboarding` pointer. Db, the organization module's event-count-// lookup, and email are mocked; asserts template selection, day gating, early-// completion on active subs, and usage personalization. `mock.module` is not-// hoisted, so the subject is imported inside `beforeAll` — see AGENTS.md.+// Onboarding email cron: the sequential drip driven by the `organization.onboarding`+// pointer. Db, the event-count lookup and email are mocked. `mock.module` is not+// hoisted, so the subject is imported inside `beforeAll`.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { subDays } from 'date-fns';@@ -13,8 +11,6 @@ const organizationUpdate = mock(async () => ({}));const dbMock = {organization: { findMany: organizationFindMany, update: organizationUpdate },};-// `runOnboardingCron` takes `ServiceDeps` now, so `deps.db` IS the fake below —-// no Prisma module mock needed.const deps = {db: dbMock,config: testCoreConfig(),@@ -23,12 +19,10 @@ const deps = {const getOrganizationEventsCount = mock(async (_deps: unknown, _projectIds: string[]) => 0);-// Spread a plain-object SNAPSHOT of the real module, not a partial factory:-// `mock.module` replaces this specifier process-wide under bare `bun test`-// (AGENTS.md), and every cross-module caller reaches-// `getSettingsForProject` / `getOrganizationByProjectIdCached` through this-// deep path rather than the package barrel — a partial factory here silently-// deleted them for every file that ran afterwards.+// Spread a SNAPSHOT of the real module, not a partial factory: `mock.module` replaces+// this specifier process-wide, and every cross-module caller reaches+// `getSettingsForProject` / `getOrganizationByProjectIdCached` through this deep path;+// a partial factory silently deleted them for every later file.const realOrganizationService = {...(await import('../organization/organization.service')),};@@ -173,8 +167,8 @@ test('completes onboarding when the org subscribed before the trial emails', asy});test('populates recommendedPlan and trial stats in the trial-ending email', async () => {- // Regression: recommendedPlan used to read subscriptionPeriodEventsCount,- // which is always 0 for trial orgs (no Polar billing period).+ // `recommendedPlan` must not read subscriptionPeriodEventsCount, which is always 0+ // for trial orgs (no Polar billing period).getOrganizationEventsCount.mockResolvedValue(84_211);organizationFindMany.mockResolvedValue([org({@@ -220,10 +214,9 @@ test('marks onboarding completed once every email has been sent', async () => {});test('completes orgs left on the retired trial-ended pointer', async () => {- // The day-30 'onboarding-trial-ended' step moved to the wind-down sequence.- // Orgs still holding that pointer must finish the drip, not restart it from- // the welcome email. Code migration 21 settles these, but the runner has to- // be safe on its own for any that slip through.+ // The day-30 'onboarding-trial-ended' step belongs to the wind-down sequence. Orgs+ // still holding that pointer must finish the drip, not restart it from the welcome+ // email; the runner has to be safe on its own for any that slip through.organizationFindMany.mockResolvedValue([org({onboarding: 'onboarding-trial-ended',diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsindex 7b4910422..f3d38df64 100644--- a/packages/core/src/modules/onboarding/onboarding.service.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -1,6 +1,3 @@-// Every exported function takes `ServiceDeps` and reaches Postgres as-// `deps.db`, so the requestId minted at the edge reaches the query.-import crypto from 'node:crypto';import { getRecommendedPlan } from '@openpanel/payments';import { stripTrailingSlash } from '@openpanel/shared';@@ -35,11 +32,8 @@ export async function canSkipOnboarding(return { canSkip: false };}- // Sequential, not Promise.all: the early return below skips the- // projectAccess query entirely for any user with a membership, which a- // parallel fetch would give up. Changing this trades a real- // memberships-found saving for the all-false path's latency — a behavior- // change, out of scope here.+ // Sequential, not Promise.all: the early return below skips the projectAccess query+ // for any user with a membership, which a parallel fetch would give up.const db = deps.db;const members = await db.member.findMany({ where: { userId } });if (members.length > 0) {@@ -168,7 +162,6 @@ export async function createOnboardingProject(return { ...client, secret };}-// -----------------------------------------------------------------------// The onboarding email drip cron. The `organization.onboarding` column// stores the last sent step, and step names are equal to template names for// historical reasons: in-flight orgs already hold those values. Renaming one@@ -410,10 +403,7 @@ export async function runOnboardingCron(return summary;}-/** Registered in `services.ts`. Closes over `deps.logger`, the same value- * `ctx.logger` is, so `ctx.services.onboarding.runOnboardingCron()` takes no- * arguments — same shape as organization's `runDeleteCron`, which needs no- * logger of its own at all. */+/** Closes over `deps.logger`, so `ctx.services.onboarding.runOnboardingCron()` takes no arguments. */export function createOnboardingService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.tsindex 31f7c29b3..1abbc7fb6 100644--- a/packages/core/src/modules/organization/organization.constants.ts+++ b/packages/core/src/modules/organization/organization.constants.ts@@ -1,9 +1,3 @@-// `zProjectAccessGrant` is a per-project grant but every consumer is-// organization-shaped (organization.rpc.ts's invite/access mutations), so it-// lives here and `zInviteUser` embeds it without a cross-file constants import.-// @openpanel/db's `code-migrations/constants.ts` keeps its own frozen copy of-// the schema — it is not a consumer.-import { z } from 'zod';import { MAX_EMAIL, MAX_ID, MAX_NAME } from '../../shared/limits.constants';@@ -50,7 +44,7 @@ export function canonicalTimezone(value: string): string {.timeZone;}-// An unknown zone stored on the organization used to turn every date-driven+// An unknown zone stored on the organization would turn every date-driven// query in it into `Invalid Date` 500s, so the zone is checked at the door.export const zTimezone = z.string()diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.tsindex 3bf71d2f2..d101a8a60 100644--- a/packages/core/src/modules/organization/organization.jobs.test.ts+++ b/packages/core/src/modules/organization/organization.jobs.test.ts@@ -1,5 +1,4 @@-// Job/cron-fragment wiring — no ClickHouse/Postgres touched. The service-// method itself is exercised in organization.service.test.ts.+// Job/cron-fragment wiring only; no ClickHouse/Postgres touched.import { expect, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -109,9 +108,7 @@ test('delete delegates to runDeleteCron', async () => {expect(called).toBe(true);});-// Byte-identity with schedulers.test.ts's golden snapshot pins. The cadences-// now live on the jobs themselves, so this reads them straight off the-// registry.+// Pins the cadences, read straight off the registry.test('the organization cron fragment keeps its scheduler id and cadence', () => {expect(queues.cron.jobs.delete.cron).toEqual({ pattern: '0 * * * *' });expect(queues.cron.jobs.windDown.cron).toEqual({ pattern: '0 * * * *' });diff --git a/packages/core/src/modules/organization/organization.jobs.ts b/packages/core/src/modules/organization/organization.jobs.tsindex a236dd767..cf08485a7 100644--- a/packages/core/src/modules/organization/organization.jobs.ts+++ b/packages/core/src/modules/organization/organization.jobs.ts@@ -1,6 +1,3 @@-// `delete` is this module's fragment of the ONE `cron` queue's jobs, spread-// into jobs.registry.ts.-import { z } from 'zod';import type { Ctx } from '../../context';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/organization/organization.rpc.test.ts b/packages/core/src/modules/organization/organization.rpc.test.tsindex 8e3229ded..ff7e42da1 100644--- a/packages/core/src/modules/organization/organization.rpc.test.ts+++ b/packages/core/src/modules/organization/organization.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The admin-access-check + mutation bodies ride on @openpanel/db (lazy-loaded-// through ./src/access and organization.service.ts); wiring this router-// end-to-end against a real Postgres is P6's (protectedProcedure) job, not-// this one's — see organization.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here, with no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/organization/organization.rpc.ts b/packages/core/src/modules/organization/organization.rpc.tsindex 79870365f..08d5ea4aa 100644--- a/packages/core/src/modules/organization/organization.rpc.ts+++ b/packages/core/src/modules/organization/organization.rpc.ts@@ -1,13 +1,7 @@-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the-// input parser. The explicit checks in the handlers below stay: `enforceAccess`-// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved-// from another id needs its own.+// `enforceAccess` only sees a top-level `projectId` / `organizationId`, so+// anything resolved from another id needs its own explicit check in the handler.//-// The organization-admin ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.-//-// `getInvite` has no rate limiting yet. `createRateLimitMiddleware` in-// rpc/base.ts is the seam that will carry it.+// `getInvite` has no rate limiting yet.import { z } from 'zod';import {diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.tsindex 8b9215480..a814ec834 100644--- a/packages/core/src/modules/organization/organization.service.test.ts+++ b/packages/core/src/modules/organization/organization.service.test.ts@@ -1,8 +1,3 @@-// organization.service.ts reaches Postgres/ClickHouse through the `ServiceDeps`-// it is handed, and its module body has no import-time side effects, which is-// what makes `mock.module` work here with nothing to race: every mock below is-// registered before the subject's first call, not before its import.-import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';import { recordingLogger } from '../../../test/service-deps';@@ -19,8 +14,7 @@ interface FakeOrganization {subscriptionEndsAt: Date | null;subscriptionChartEndDate: Date | null;createdAt: Date;- // Prisma $extends computed fields — set directly on the fixture rather- // than derived, since the mock never touches the real extension.+ // Prisma `$extends` computed fields, set directly on the fixture.hasSubscription: boolean;isWillBeCanceled: boolean;}@@ -410,10 +404,8 @@ const projectAccess = {const $transaction = mock(async (ops: Promise<unknown>[]) => Promise.all(ops));-// Every function under test takes `ServiceDeps`, so `deps.db` and `deps.ch` ARE-// the fakes below. `connectUserToOrganization` reaches `shared/access-lookups.ts`-// (cacheable, on the unscoped db), which is why the `@openpanel/redis` stand-in-// below stays.+// `connectUserToOrganization` reaches `shared/access-lookups.ts` (cacheable, on+// the unscoped db), which is why the `@openpanel/redis` stand-in below stays.const chCommand = mock(async () => undefined);const deps = {logger: recordingLogger(),@@ -430,14 +422,9 @@ const deps = {config: testCoreConfig(),} as unknown as import('../../services').ServiceDeps;-// Bypasses the Redis cache-aside entirely — this module's own logic is-// exercised directly, caching is @openpanel/redis's concern. `access.service.ts`-// (reached via connectUserToOrganization's dynamic import) calls `.clear()` on-// its cacheable-wrapped lookups, so the stand-in needs that method too, not-// just the bare passthrough gsc.service.test.ts's identical mock gets away with.-// Real `cacheable` overloads on `(fn, ttl)` OR `(name, fn, ttl)` — this-// module uses the first form, access.service.ts (reached via-// connectUserToOrganization) the second.+// Bypasses the Redis cache-aside. The access lookups call `.clear()` on their+// cacheable-wrapped functions, so the stand-in needs that method too. Real+// `cacheable` overloads on `(fn, ttl)` or `(name, fn, ttl)`; both are used.const clearedCacheKeys: string[] = [];function cacheableStub(fnOrName: ((...args: unknown[]) => unknown) | string,@@ -494,11 +481,8 @@ afterAll(() => {mock.module('@openpanel/redis', () => realRedis);});-// Mocks core's own clients/email.ts wrapper, not @openpanel/email itself:-// that package statically imports @openpanel/db's full barrel (Resend/SMTP-// setup aside), an eager side-effecting chain this test avoids by mocking-// at this depth. mcp.service.test.ts mocks the same relative depth for the-// same reason.+// Mocks core's `clients/email.ts` wrapper, not @openpanel/email: that package+// statically imports @openpanel/db's full barrel, an eager side-effecting chain.const sentEmails: { templateKey: string; to: string; data: unknown }[] = [];mock.module('../../clients/email', () => ({sendEmail: async (@@ -721,9 +705,8 @@ test('updateOrganizationMemberAccess replaces project access with the given granexpect(remaining[0]).toMatchObject({ projectId: 'proj_new', level: 'write' });});-// These two guards did not exist: access rows were written for a user who was-// never confirmed to be a member, naming a project that need not belong to the-// organization the grant is scoped to.+// Guards: access rows must not be written for a user never confirmed as a+// member, or for a project outside the organization the grant is scoped to.test('updateOrganizationMemberAccess refuses a user who is not a member', async () => {projectStore.set('proj_new', {id: 'proj_new',diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex 336189d02..50fc447af 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -1,10 +1,6 @@-// Organizations, their projects, the invite/member mutations, and the-// deletion cron that reaps organizations left without an admin.-//// The two `cacheable` wrappers are `cacheablePerDeps`: `cacheable` keys on the-// call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps have to-// travel beside the key rather than inside it, or the Redis key would change-// per request.+// call's arguments, so the caller's deps travel beside the key rather than+// inside it, or the Redis key would change per request.import { sql } from '@openpanel/db/src/clickhouse/sql';import type {@@ -142,9 +138,8 @@ export async function getInviteById(deps: ServiceDeps, inviteId: string) {},});- // Spreading a null result produced `{isExpired: undefined}` — a TRUTHY- // object — so the onboarding page rendered its invitation banner for a- // bogus id, with the organization name blank.+ // Spreading a null result gave `{isExpired: undefined}`, a truthy object, so+ // the onboarding page showed an invitation banner for a bogus id.if (!res) {throw new TRPCNotFoundError('Invite not found');}@@ -288,10 +283,6 @@ export async function connectUserToOrganization(return member;}-/**- * Get the total number of events during the- * current subscription period for an organization- */export async function getOrganizationBillingEventsCount(deps: ServiceDeps,organization: IServiceOrganization & { projects: { id: string }[] }@@ -950,9 +941,8 @@ export async function updateOrganizationMemberAccess(},}),db.projectAccess.createMany({- // The level comes from the admin's choice. This used to be hardcoded- // to 'read', which was harmless only because nothing enforced the- // level (GHSA-f9rx-pxgw-c6rg).+ // The level the admin chose; a hardcoded 'read' hid that nothing enforced+ // levels (GHSA-f9rx-pxgw-c6rg).data: input.access.map((grant) => ({userId: input.targetUserId,organizationId: input.organizationId,diff --git a/packages/core/src/modules/organization/src/win-back-highlight.test.ts b/packages/core/src/modules/organization/src/win-back-highlight.test.tsindex 71710211b..77fa95fe0 100644--- a/packages/core/src/modules/organization/src/win-back-highlight.test.ts+++ b/packages/core/src/modules/organization/src/win-back-highlight.test.ts@@ -1,7 +1,5 @@-// Asserts the gating and fallback decisions, which are the point of the module:-// a highlight is a bonus, never a reason an email fails or embarrasses us with-// tiny numbers. The stats lookups and the AI call are injected stubs — no-// `mock.module`, so every assertion is on a call the code under test made.+// Asserts the gating and fallback decisions: a highlight is a bonus, never a+// reason an email fails or shows tiny numbers. Stats and AI are injected stubs.import { beforeEach, describe, expect, it, mock } from 'bun:test';import type { Logger } from '../../../logger';diff --git a/packages/core/src/modules/organization/src/win-back-highlight.ts b/packages/core/src/modules/organization/src/win-back-highlight.tsindex 3fcaeb9eb..e55cb694a 100644--- a/packages/core/src/modules/organization/src/win-back-highlight.ts+++ b/packages/core/src/modules/organization/src/win-back-highlight.ts@@ -1,31 +1,20 @@-// The two stats lookups and the AI call arrive as injected deps-// (`WinBackHighlightDeps`) instead of static imports, the same idiom the-// session lifecycle uses (modules/session/src/runtime.ts):-// `organization.jobs.ts` binds them off the job's ctx, and tests hand in-// stubs, so no `mock.module` is needed anywhere.+// Deps are injected rather than imported so tests need no `mock.module`.import { format, subDays } from 'date-fns';import type { Logger } from '../../../logger';/*** The personalized paragraph in the wind-down emails: a couple of concrete- * facts from the org's own recent data ("your busiest day was...", "your- * most-viewed page is...") turned into prose by a small AI call.+ * facts from the org's own recent data turned into prose by a small AI call.+ * Recipients stopped opening the dashboard long ago, so a specific fact only+ * the product could tell them is the reminder that it does something.*- * The reasoning: the people this sequence targets stopped opening their- * dashboard long ago, so deadlines alone read as noise. A specific fact they- * didn't know — one only the product could tell them — is the reminder that- * the thing they're about to lose actually *does* something.- *- * Three deliberate properties:- * - Gated on volume. Below HIGHLIGHT_MIN_RECENT_EVENTS the "facts" are- * trivia ("your busiest day had 3 visitors") and would undercut the email,- * so low-volume orgs simply get no highlight paragraph.- * - Never fails the email. AI throwing, or the stats queries throwing, falls- * back to a deterministic sentence or to nothing at all.- * - Facts come from the org's most recently active project only. One project- * keeps the queries bounded and the copy concrete ("on acme-web") instead- * of a mush of totals across projects.+ * - Gated on volume: below HIGHLIGHT_MIN_RECENT_EVENTS the facts are trivia+ * that would undercut the email, so low-volume orgs get no paragraph.+ * - Never fails the email: an AI or stats-query error falls back to a+ * deterministic sentence or to nothing.+ * - Facts come from the most recently active project only, which keeps the+ * queries bounded and the copy concrete.*/export const HIGHLIGHT_MIN_RECENT_EVENTS = 1000;diff --git a/packages/core/src/modules/organization/src/win-back-pitch.ts b/packages/core/src/modules/organization/src/win-back-pitch.tsindex 6e4512cd9..296003ced 100644--- a/packages/core/src/modules/organization/src/win-back-pitch.ts+++ b/packages/core/src/modules/organization/src/win-back-pitch.ts@@ -1,9 +1,6 @@-// Wind-down win-back pitch: one short OpenAI call that turns a lapsed trial's-// recent stats into a two-sentence selling argument for the wind-down emails.-// Same one-shot structured-output pattern as narrative.ts — and like the-// narrative, the caller must treat a throw as "no pitch", never as a failed-// email: the wind-down job falls back to a deterministic sentence built from-// the same facts.+// One short OpenAI call that turns a lapsed trial's recent stats into a+// two-sentence pitch. A throw means "no pitch", never a failed email: the job+// falls back to a deterministic sentence built from the same facts.import { betterAgent, defineAgent } from '@better-agent/core';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';@@ -12,7 +9,7 @@ import { ALLOWED_MODELS, resolveModel } from '../../assistant/src/providers';const WIN_BACK_MODEL_ID = 'gpt-4-1-mini';-// Preferred model and fallback are both OpenAI — see insight/src/enrich.ts.+// Preferred model and fallback are both OpenAI.const WIN_BACK_PROVIDER = 'openai';function winBackModel(config: CoreConfig) {diff --git a/packages/core/src/modules/organization/src/wind-down.test.ts b/packages/core/src/modules/organization/src/wind-down.test.tsindex de60024ce..12f762c82 100644--- a/packages/core/src/modules/organization/src/wind-down.test.ts+++ b/packages/core/src/modules/organization/src/wind-down.test.ts@@ -1,7 +1,5 @@-// Prisma, the event counts, the last-event lookup, the highlight builder and-// the email transport are injected stubs — these assert the job's decisions-// (who enters, which step fires, what gets written), not any real persistence.-// No `mock.module`, so nothing this file does leaks into another test file.+// Everything the job touches is an injected stub; these assert its decisions+// (who enters, which step fires, what gets written). No `mock.module`.import { beforeEach, describe, expect, it, mock } from 'bun:test';import { subDays } from 'date-fns';diff --git a/packages/core/src/modules/organization/src/wind-down.ts b/packages/core/src/modules/organization/src/wind-down.tsindex 2021c1735..b9030f3de 100644--- a/packages/core/src/modules/organization/src/wind-down.ts+++ b/packages/core/src/modules/organization/src/wind-down.ts@@ -12,23 +12,18 @@ import {import type { HighlightProject } from './win-back-highlight';/**- * Wind-down: what happens to a trial that expired without a purchase.+ * What happens to a trial that expired without a purchase: four emails over 44+ * days, then deletion. Ingestion keeps flowing until day 21 so the first two+ * emails have something to be about; from day 21 the ingestion hook rejects+ * events (it reads `windDownStep`). Day 44 arms `deleteAt`, which the delete+ * cron sweeps seven days later.*- * Four emails over 44 days, then deletion. Ingestion keeps flowing until day- * 21 so the first two emails have something to be about; from day 21 the- * ingestion hook rejects events (it reads `windDownStep`). Day 44 arms- * `deleteAt`, and the existing delete cron sweeps it seven days later.+ * The schedule is measured from `windDownStartedAt`, not `subscriptionEndsAt`:+ * for the existing backlog that is hundreds of days old and would put every org+ * past day 44 on the first tick.*- * The schedule is measured from `windDownStartedAt`, stamped when an org- * enters. That is the whole reason the column exists: `subscriptionEndsAt` for- * the existing backlog is hundreds of days old, so anchoring there would put- * every one of them past day 44 on the first tick.- *- * The population this is really aimed at is the org whose trial lapsed months- * ago and whose SDKs never stopped — still sending events, still costing- * storage, never billed. Those orgs are the ones worth converting, so they- * enter the sequence first and their emails lead with what they are currently- * sending rather than with a lifetime total.+ * Orgs whose SDKs never stopped sending are the ones worth converting, so they+ * enter first and their emails lead with current volume, not a lifetime total.*/const BLOCK_DAY = 21;@@ -142,8 +137,6 @@ function createUsageGetter(org: WindDownOrganization, deps: WindDownDeps) {let promise: Promise<WindDownUsage> | null = null;return () => {const projectIds = org.projects.map((project) => project.id);- // Only orgs that clear a day gate pay for these two ClickHouse counts, and- // each org pays at most once per tick.promise ??= Promise.all([deps.getOrganizationEventsCount(projectIds),deps.getOrganizationEventsCountSince(@@ -408,7 +401,6 @@ export async function runWindDownCron(const startedAt = org.windDownStartedAt ?? now;const seen = activity.get(org.id);- // Most recently active project carries the highlight facts.let highlightProject: HighlightProject | null = null;let highlightSeen: Date | null = null;for (const project of org.projects) {diff --git a/packages/core/src/modules/profile/profile.jobs.ts b/packages/core/src/modules/profile/profile.jobs.tsindex 40b999f57..0afd11eb2 100644--- a/packages/core/src/modules/profile/profile.jobs.ts+++ b/packages/core/src/modules/profile/profile.jobs.ts@@ -1,7 +1,6 @@-// Both buffers are this module's domain: the profile buffer (Redis → ClickHouse-// `profiles`) and the profile-backfill buffer, which patches a session's-// `profile_id` once a device is identified after the session row was already-// written.+// Both buffers are this module's domain: the profile buffer (Redis -> ClickHouse+// `profiles`) and the profile-backfill buffer, which patches a session's `profile_id`+// once a device is identified after the session row was written.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/profile/profile.routes.test.ts b/packages/core/src/modules/profile/profile.routes.test.tsindex ec002e4b4..2ecdf2779 100644--- a/packages/core/src/modules/profile/profile.routes.test.ts+++ b/packages/core/src/modules/profile/profile.routes.test.ts@@ -1,8 +1,5 @@-// The three /profile routes run end to end through `app.handle()`.-// `../../http/client-auth`'s `authenticateClient` is mocked so the client-// principal is deterministic, same as http/auth.test.ts does; the service-// and the geo lookup are mocked so nothing reaches a database. Every mock is-// registered before the subject's first (dynamic) import — AGENTS.md.+// The three /profile routes end to end through `app.handle()`, with client auth, the+// service and the geo lookup mocked so nothing reaches a database.import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { stubAppDeps } from '../../../test/http-fixtures';@@ -153,15 +150,10 @@ test('a client without a project answers 400 before touching the service', asyncexpect(identifyProfile).not.toHaveBeenCalled();});-// These bodies used to reach the service and throw on `input.property.split`,-// so the caller saw a 500 with a raw TypeError (ISSUES.md H5). Elysia's schema-// refuses them instead.-//-// This suite mounts the routes alone, so it sees Elysia's own VALIDATION-// status. The assembled app maps that to 400 — see http/errors.ts, which-// documents the mapping — and the live API was verified answering-// `400 {"message":"body/property Invalid input: expected string, received-// undefined"}` for these same bodies.+// These bodies used to reach the service and throw on `input.property.split`, giving+// a 500 with a raw TypeError; Elysia's schema now refuses them. This suite mounts the+// routes alone, so it sees Elysia's own VALIDATION status; the assembled app maps it+// to 400 (http/errors.ts).const ELYSIA_VALIDATION_STATUS = 422;test('the adjust routes reject a body that cannot name a property', async () => {@@ -197,11 +189,8 @@ test('increment still accepts a negative delta', async () => {expect(adjustProfileProperty).toHaveBeenCalled();});-// Each path gets a body its schema accepts, so the 401 under test is the auth-// check and not the body validation. Elysia validates the body before the-// clientAuth hook — `/track` has behaved that way since it got-// `zTrackHandlerPayload`, so an anonymous caller with a malformed body sees a-// 400 there too.+// Each path gets a body its schema accepts, so the 401 under test is the auth check,+// not body validation (Elysia validates the body before the clientAuth hook).const VALID_BODY_FOR: Record<string, Record<string, unknown>> = {'/profile': { profileId: 'prof-1' },'/profile/increment': { profileId: 'prof-1', property: 'score', value: 1 },diff --git a/packages/core/src/modules/profile/profile.routes.ts b/packages/core/src/modules/profile/profile.routes.tsindex fcdcb2af7..457b76d86 100644--- a/packages/core/src/modules/profile/profile.routes.ts+++ b/packages/core/src/modules/profile/profile.routes.ts@@ -24,12 +24,10 @@ const TAGS = ['Profile'];type StatusFn = (code: 400 | 404, body: string) => unknown;/**- * Deliberately NOT `zIncrementPayload` from ingest.constants: that schema is- * `/track`'s, where `value` is optional and must be positive. This route has- * always accepted a negative delta and has always needed a value — without- * one the service writes NaN. So the schema below is exactly as permissive as- * the paths that work today, and rejects only the bodies that reached- * `input.property.split` and answered 500.+ * Deliberately NOT `zIncrementPayload` from ingest.constants: that is `/track`'s, where+ * `value` is optional and positive. This route accepts a negative delta and needs a+ * value (without one the service writes NaN), so this schema rejects only the bodies+ * that reached `input.property.split` and answered 500.*/const zAdjustProperty = z.object({profileId: zProfileId,diff --git a/packages/core/src/modules/profile/profile.rpc.test.ts b/packages/core/src/modules/profile/profile.rpc.test.tsindex ca642af2c..22e9f2e6e 100644--- a/packages/core/src/modules/profile/profile.rpc.test.ts+++ b/packages/core/src/modules/profile/profile.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + query bodies ride on @openpanel/db (lazy-loaded, see-// profile.service.ts's header); wiring this router end-to-end against a real-// ClickHouse is P6's (protectedProcedure) job — see profile.rpc.ts's header.-// Same shape as session.rpc.test.ts.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import {diff --git a/packages/core/src/modules/profile/profile.rpc.ts b/packages/core/src/modules/profile/profile.rpc.tsindex 0f79d02c8..22f847708 100644--- a/packages/core/src/modules/profile/profile.rpc.ts+++ b/packages/core/src/modules/profile/profile.rpc.ts@@ -26,11 +26,9 @@ const DEFAULT_LIST_TAKE = 50;const MAX_LIST_TAKE = 1000;/**- * `list` and `powerUsers` had no date filter at all, so their cost grew with- * the tenant's lifetime rather than with anything the caller chose (44.2 M- * rows read for one page of 50, measured). Both now take the report- * vocabulary's window; this is the default when the caller names none — "a- * power user over 90 days is not the same set as over all time".+ * `list` and `powerUsers` need a date window: without one their cost grows with the+ * tenant's lifetime (44.2 M rows read for one page of 50). This is the default when+ * the caller names none; a power user over 90 days is not the same set as over all time.*/const PROFILE_WINDOW_DEFAULT_RANGE = '3m';diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.tsindex 711cc528f..3c48d3bfd 100644--- a/packages/core/src/modules/profile/profile.service.ts+++ b/packages/core/src/modules/profile/profile.service.ts@@ -1,7 +1,3 @@-// Every query is a `sql` fragment (src/sql.ts). The exception is-// `buildFilterWhere`, the shared filter compiler; src/filter-clauses.ts is the-// bridge to it.-import { round, strip, toObject } from '@openpanel/shared';import { assocPath, flatten, map, pathOr, pipe, prop, sort, uniq } from 'ramda';import { cacheablePerDeps } from '../../cacheable-per-deps';@@ -54,8 +50,7 @@ const FIND_PROFILES_DEFAULT_LIMIT = 20;const FIND_PROFILES_MAX_LIMIT = 100;const SECONDS_PER_MINUTE = 60;-// clix always sent `session_timezone: 'UTC'`; the queries converted from clix-// keep sending it so their result sets stay identical.+// Keeps sending `session_timezone: 'UTC'` so result sets are consistent.const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;const PROFILE_FILTER_TARGET = {@@ -504,8 +499,6 @@ export const getProfilePropertyKeysCached = cacheablePerDeps(PROPERTY_KEYS_CACHE_SECONDS);-// ---- the trpc profile router's bodies-export async function getProfileActivity(deps: ServiceDeps,profileId: string,@@ -638,8 +631,6 @@ export async function getProfileValues(return { values };}-// ---- apps/api's /profile controller bodies-export interface IdentifyProfileInput {/** `string | number` because /track's identify payload allows both* (ingest.constants' `IProfileId`) and `upsertProfile` stores either. */diff --git a/packages/core/src/modules/profile/src/dates.ts b/packages/core/src/modules/profile/src/dates.tsindex 26f81dff3..061dffb14 100644--- a/packages/core/src/modules/profile/src/dates.ts+++ b/packages/core/src/modules/profile/src/dates.ts@@ -1,7 +1,6 @@-// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs-// a client and a pino logger at import time (see insight.service.ts's header),-// and the fragment builders here must stay pure and synchronous. Same choice-// cohort.service.ts made for its table map.+// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs a+// client and a pino logger at import time, and the fragment builders here must stay+// pure and synchronous.const CLICKHOUSE_DATE_SUFFIX = /(\.\d{3})?Z+$/;diff --git a/packages/core/src/modules/profile/src/filter-clauses.ts b/packages/core/src/modules/profile/src/filter-clauses.tsindex cb763e7e3..ee8ea7566 100644--- a/packages/core/src/modules/profile/src/filter-clauses.ts+++ b/packages/core/src/modules/profile/src/filter-clauses.ts@@ -1,10 +1,6 @@-// The ONE place this module splices pre-compiled filter SQL.-//-// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is the-// sessions/profiles/events-table filter compiler; it returns bound-// `SqlFragment`s, as does `getEventFiltersWhereClause`-// (../../chart/src/filter-where.ts). Nothing is bridged any more — this file-// only assembles what the compiler already produced.+// The ONE place this module splices pre-compiled filter SQL: it only assembles what+// the filter compilers (chart/src/table-filter-where.ts, chart/src/filter-where.ts)+// already produced.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/profile/src/sql.test.ts b/packages/core/src/modules/profile/src/sql.test.tsindex 64b35421b..c4caf63ca 100644--- a/packages/core/src/modules/profile/src/sql.test.ts+++ b/packages/core/src/modules/profile/src/sql.test.ts@@ -1,7 +1,6 @@// Shape tests for the profile module's fragments: every user value binds as a-// `{pN:Type}` parameter (nothing is interpolated), and `sql.id` refuses-// anything off the column whitelist. These run offline, so they assert the-// rendered statement and its params, never a result set.+// `{pN:Type}` parameter, and `sql.id` refuses anything off the column whitelist. These+// run offline.import { describe, expect, test } from 'bun:test';import { sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/profile/src/sql.ts b/packages/core/src/modules/profile/src/sql.tsindex d189fa8a5..b96a93880 100644--- a/packages/core/src/modules/profile/src/sql.ts+++ b/packages/core/src/modules/profile/src/sql.ts@@ -1,9 +1,6 @@-// Every ClickHouse query the profile module runs, as pure `sql` fragments.-//-// Cluster note: `profiles`, `events` and `sessions` are Distributed on Cloud.-// `findProfilesQuery`'s three `IN (SELECT...)` subqueries, and any a filter-// compiles to, run under the client's `distributed_product_mode: 'allow'`.-// Every `IN` list binds as `Array(String)`, a literal list to the planner.+// `profiles`, `events` and `sessions` are Distributed on Cloud. The `IN (SELECT...)`+// subqueries run under the client's `distributed_product_mode: 'allow'`. Every `IN`+// list binds as `Array(String)`, a literal list to the planner.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';@@ -48,7 +45,6 @@ function optional(return condition ? fragment() : sql.empty;}-/** Same spelling `overview/src/pages.sql.ts` uses, so the two read alike. */function dateRangeWhere(column: string,startDate: string,@@ -57,7 +53,7 @@ function dateRangeWhere(return sql`${sql.id(column)} BETWEEN toDateTime(${sql.string(toRangeBoundaryLiteral(startDate, 'start'))}) AND toDateTime(${sql.string(toRangeBoundaryLiteral(endDate, 'end'))})`;}-/** The window every profile-list / power-user statement is now bounded to. */+/** The window every profile-list / power-user statement is bounded to. */export interface ProfileWindow {startDate: string;endDate: string;@@ -352,8 +348,6 @@ export function profilePropertyKeysQuery(projectId: string): SqlFragment {return sql`SELECT DISTINCT arrayJoin(mapKeys(properties)) as key FROM ${sql.id(TABLE.profiles)} WHERE project_id = ${sql.string(projectId)} AND is_external = ${sql.bool(true)}`;}-// ---- packages/trpc/src/routers/profile.ts's inline queries-export function profileActivityQuery(query: {projectId: string;profileId: string;@@ -381,11 +375,7 @@ export function profilePropertyNamesQuery(projectId: string): SqlFragment {return sql`SELECT distinct mapKeys(properties) as keys from ${sql.id(TABLE.profiles)} where project_id = ${sql.string(projectId)};`;}-/**- * Bounded to the caller's window. Unbounded this ranked every event the project- * ever recorded (44.2 M rows on the busiest anchor), so "power users of all- * time" is now "power users of the range".- */+/** Bounded to the caller's window: unbounded, it ranked every event the project ever recorded. */export function powerUsersQuery(query: ProfileWindow & {projectId: string;diff --git a/packages/core/src/modules/project/project.constants.ts b/packages/core/src/modules/project/project.constants.tsindex cce2c90cd..a7a165852 100644--- a/packages/core/src/modules/project/project.constants.ts+++ b/packages/core/src/modules/project/project.constants.ts@@ -1,7 +1,4 @@-// `zCreateProject`/`zUpdateProject` are the /manage REST body schemas-// (apps/api/src/controllers/manage.controller.ts), moved here with the CRUD-// bodies they validate (project.service.ts's-// createProjectForOrganization/updateProjectForOrganization).+// `zCreateProject`/`zUpdateProject` are the /manage REST body schemas.//// `zChartEvent` is imported by name, not re-exported: `zProjectFilterEvent`// extends it as a bound identifier.diff --git a/packages/core/src/modules/project/project.routes.ts b/packages/core/src/modules/project/project.routes.tsindex 25aa09554..f15d66db5 100644--- a/packages/core/src/modules/project/project.routes.ts+++ b/packages/core/src/modules/project/project.routes.ts@@ -1,10 +1,5 @@// The /manage/projects REST surface: root-only project CRUD, delegating to// project.service.ts's create/update functions.-//-// NAMED GAP, same as import.routes.ts: this route is not yet reachable.-// `authenticateClient` (http/client-auth.ts) is a stub that always returns-// null, so `clientAuth` 401s every request until it is filled in; main.ts-// also does not mount `publicApiRoutes` until a real `AppDeps` exists.// `allow: ['root']` restricts project management to root clients.import { z } from 'zod';diff --git a/packages/core/src/modules/project/project.rpc.test.ts b/packages/core/src/modules/project/project.rpc.test.tsindex 7a087bde8..ff6f827f7 100644--- a/packages/core/src/modules/project/project.rpc.test.ts+++ b/packages/core/src/modules/project/project.rpc.test.ts@@ -19,7 +19,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.tsindex d85f8cbef..30fbf5485 100644--- a/packages/core/src/modules/project/project.rpc.ts+++ b/packages/core/src/modules/project/project.rpc.ts@@ -2,11 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// `ctx.services.project` carries this module's factory.-//-// The project-access ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.tsindex 1b17ae247..80c94f9d4 100644--- a/packages/core/src/modules/project/project.service.test.ts+++ b/packages/core/src/modules/project/project.service.test.ts@@ -1,13 +1,9 @@-// The subject is built by its factory over a fake `ServiceDeps`, so Postgres-// needs no module mock at all — `deps.db` IS the fake below, same idiom as-// reference.service.test.ts. `getProjectEventsCount` / `getLastEventPerProject`-// (ClickHouse) stay a lazy-loaded, unmocked call — exercised against local-// ClickHouse manually, not re-tested here.+// The subject is built over a fake `ServiceDeps`, so `deps.db` IS the fake below and+// Postgres needs no module mock. The ClickHouse readers (`getProjectEventsCount`,+// `getLastEventPerProject`) are not covered here.//-// `createProjectForOrganization`/`updateProjectForOrganization` invalidate a-// project's clients through `client.service.ts`'s module-scope-// `getClientByIdCached`, which is built from the `cacheable` stub below — so-// there is no seam left to mock here.+// Create/update invalidate a project's clients through `client.service.ts`'s+// module-scope `getClientByIdCached`, built from the `cacheable` stub below.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -145,9 +141,7 @@ const member = {),};-// Bypasses the Redis cache-aside entirely — this module's own logic is-// exercised directly, caching is @openpanel/redis's concern. Same stub as-// organization.service.test.ts.+// Bypasses the Redis cache-aside: this module's own logic is exercised directly.function cacheableStub(fnOrName: ((...args: unknown[]) => unknown) | string,fnOrTtl: ((...args: unknown[]) => unknown) | numberdiff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.tsindex b05c0f84e..153ae7e2f 100644--- a/packages/core/src/modules/project/project.service.ts+++ b/packages/core/src/modules/project/project.service.ts@@ -1,7 +1,3 @@-// `getProjectByIdCached` is a module-scope `cacheablePerDb` for the same-// reason `getClientByIdCached` is in client.service.ts — see that file's-// header.-import crypto from 'node:crypto';import { sql } from '@openpanel/db/src/clickhouse/sql';import type {@@ -21,14 +17,8 @@ import { getId } from '../../slug-id';import { getClientByIdCached } from '../client/client.service';import type { IProjectFilters } from './project.constants';-// The `sql` tag is a value import of `@openpanel/db` and stays one: it is a-// compile-time template tag holding no client (see ch-query.ts).-// `TABLE_NAMES` and the date helper are core's own copies-// (shared/ch-tables.ts, shared/ch-dates.ts).-//-// `getLastEventPerProject` explicitly sends session_timezone=UTC so its-// result set stays consistent; `getProjectEventsCount` is a raw `chQuery`-// call and sends none.+// `getLastEventPerProject` sends session_timezone=UTC; `getProjectEventsCount` is a+// raw `chQuery` and sends none.const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;// Session bookkeeping rows are worker-generated (the reaper can emit// session_end after tracking already stopped) — only real tracking activity@@ -57,12 +47,7 @@ export async function getProjectById(deps: DbScope, id: string) {return res;}-/**- * L1 LRU (60s) + L2 Redis, one instance per Postgres client — the ingest- * consumer, `/track` and mcp all read and invalidate the same one. The name- * is EMPTY, same as `getClientByIdCached`'s, so the Redis key is- * `cachable::<id>`.- */+/** L1 LRU (60s) + L2 Redis, one instance per Postgres client. Empty cache name, so the Redis key is `cachable::<id>`. */export const getProjectByIdCached = cacheablePerDb('',getProjectById,@@ -198,12 +183,8 @@ export const getLastEventPerProject = async (/*** Resolve and validate a projectId for an API client.- *- * - Read clients: returns the fixed projectId from the client (ignores any supplied value).- * - Root clients: validates that the supplied projectId belongs to the client's organization.- *- * Throws if the project is not found or does not belong to the organization.- * Use this as the single source of truth for projectId resolution across the API and MCP.+ * Read clients get their fixed projectId (any supplied value is ignored); root clients+ * must supply a projectId belonging to their organization. Throws otherwise.*/export async function resolveClientProjectId(deps: ServiceDeps,@@ -254,7 +235,6 @@ export interface ProjectActivationStatus {hasTeammate: boolean;}-/** Powers the activation checklist on the project overview (trpc project.activationStatus). */export async function getProjectActivationStatus(deps: ServiceDeps,projectId: string@@ -285,8 +265,6 @@ export async function getProjectActivationStatus(};}-// --- /manage REST CRUD (project.routes.ts) ----export interface CreatedProjectClient {id: string;secret: string;@@ -465,10 +443,8 @@ export function createProjectService(return true;}- // --- trpc project.delete / project.cancelDeletion ---- // Caller has already been proven a project (or organization) admin by- // requireProjectAdmin, so unlike the /manage functions above these take no- // organizationId and do no ownership re-check.+ // Caller is already proven a project (or organization) admin, so no organizationId+ // and no ownership re-check.async function scheduleProjectDeletion(id: string): Promise<void> {await deps.db.project.update({@@ -507,9 +483,7 @@ export function createProjectService(getProjectById(deps, id),getProjectByIdCached: (id: string): ReturnType<typeof getProjectById> =>getProjectByIdCached(deps, id),- /** Invalidates a single id in `getProjectByIdCached`'s L1 LRU + Redis —- * `ingest/src/incoming-event-handler.ts` calls the module-scope spelling- * right after marking a project's first event. */+ /** Also called by ingest right after a project's first event. */clearProjectByIdCache: (id: string): Promise<number> =>getProjectByIdCached.clear(deps, id),getProjectWithClients: (diff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.tsindex dc623220f..5c780fde3 100644--- a/packages/core/src/modules/realtime/realtime.routes.test.ts+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts@@ -1,25 +1,12 @@-// `app.handle` cannot exercise a websocket upgrade (no real HTTP connection to-// upgrade), so this boots the actual Elysia app with `.listen` (== `Bun.serve`-// under the hood, same as main.ts) on an ephemeral port and drives it with a-// real `WebSocket` client — the same shape `apps/api/e2e/boot-proof.sh` uses-// for the plain-HTTP ops surface, extended to a ws handshake.+// `app.handle` cannot do a websocket upgrade, so this boots the Elysia app with+// `.listen` on an ephemeral port and drives it with a real `WebSocket` client.//-// The harness buffers messages/close events from the moment the socket is-// constructed: the server can send its "No active session" / "No access" frame-// and close the connection before the test ever gets to `await` a listener, and-// a listener attached after the fact misses an event that already fired.+// The harness buffers messages/close events from construction: the server can send+// its reject frame and close before the test awaits a listener.//-// `./realtime.service` and `../../shared/access-lookups` (the real lookups-// auth.service.ts's `createAuthService` binds `ctx.services.auth` to) are-// mocked (not a real Postgres/ClickHouse/Redis), and `../../http/session` is-// mocked for the same reason http/auth.test.ts mocks it: `resolveSession` is-// still a stub.-//-// Every import here is STATIC. Bun 1.4.0's `mock.module` swaps an-// already-loaded module's exports in place, so a subject imported above the-// `mock.module` calls still sees them; the "not called" and "called with"-// assertions on every mock below are what would go red if that ever stopped-// holding.+// Subjects are imported statically: Bun's `mock.module` swaps an already-loaded+// module's exports in place, and the "not called" / "called with" assertions would go+// red if that stopped holding.import { afterAll, afterEach, beforeEach, expect, mock, test } from 'bun:test';import { getSuperJson } from '@openpanel/shared';@@ -56,13 +43,9 @@ const subscribeToOrganizationSubscriptionUpdates = mock(let activeVisitorCount = 0;const getActiveVisitorCount = mock(async () => activeVisitorCount);-// Spread the real module rather than hand-listing every export:-// `mock.module` replaces this specifier process-wide (bun shares one module-// registry across files without `--isolate` — see AGENTS.md), and-// realtime.service.test.ts imports `./realtime.service` expecting the real-// implementation. A plain snapshot, not the live import binding — see-// gsc.service.test.ts's clickhouse/client mock for why the live binding would-// make a same-binding "restore" a no-op.+// Spread the real module rather than hand-listing exports: `mock.module` replaces+// the specifier process-wide, and realtime.service.test.ts expects the real+// implementation. A snapshot, not the live binding, so a same-binding restore is not a no-op.const realService = { ...actualService };mock.module('./realtime.service', () => ({...realService,@@ -77,10 +60,8 @@ afterAll(() => {mock.module('./realtime.service', () => realService);});-// `ctx.services.auth` binds these same lookups in auth.service.ts, so-// mocking them here is what makes-// `ws.data.ctx.services.auth.getProjectAccess`/`getOrganizationAccess`-// observable from the test.+// `ctx.services.auth` binds these lookups, so mocking them makes+// `getProjectAccess`/`getOrganizationAccess` observable from the test.let projectAccess: { level: string } | null = null;let organizationAccess: { role: string } | null = null;const getProjectAccess = mock(async () => projectAccess);@@ -145,11 +126,7 @@ interface WsHarness {nextClose(): Promise<CloseInfo>;}-/**- * Buffers messages/close events from construction, not from whenever the- * test happens to `await` for one — the server can send its reject frame- * and close the socket before the test's next line runs.- */+/** Buffers from construction: the server can reject and close before the test's next line runs. */function connect(path: string): Promise<WsHarness> {return new Promise((resolve, reject) => {const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);@@ -307,12 +284,9 @@ test('wsOrganizationEvents: session but no org access -> "No access" then close'});});-// `organization:subscription_updated` is an instance-wide channel. Before-// this fix the open handler subscribed to it unscoped, so a member of org_1-// was sent the `organizationId` of every OTHER organization whose-// subscription changed. The scope handed to the subscription must be the id-// `getOrganizationAccess` just proved this caller is a member of — the filter-// itself is asserted in realtime.service.test.ts.+// `organization:subscription_updated` is instance-wide: the subscription must be scoped+// to the organization `getOrganizationAccess` proved the caller belongs to, or members+// receive other organizations' ids (the filter itself is asserted in realtime.service.test.ts).test('wsOrganizationEvents: subscribes scoped to the organization the caller is a member of', async () => {session = { userId: 'user_1' };organizationAccess = { role: 'org:member' };diff --git a/packages/core/src/modules/realtime/realtime.rpc.test.ts b/packages/core/src/modules/realtime/realtime.rpc.test.tsindex 8bdc7bbeb..0ce427c1c 100644--- a/packages/core/src/modules/realtime/realtime.rpc.test.ts+++ b/packages/core/src/modules/realtime/realtime.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database. The-// query bodies run on `deps.ch` (statically imported `sql` fragments, no-// @openpanel/db client anywhere in the module); wiring this router end-to-end-// against a real ClickHouse is protectedProcedure's job, not this one's — see-// realtime.rpc.ts's header. Same shape as cohort.rpc.test.ts.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -18,8 +14,7 @@ const COOKIE_OPTIONS: CookieOptions = {path: '/',};-// EMPTY_SESSION's shape matters: `TrpcContext.session` is never literally-// `null`, only its `userId` is.+// `TrpcContext.session` is never literally `null`, only its `userId` is.const EMPTY_SESSION = { session: null, user: null, userId: null };async function anonCaller() {diff --git a/packages/core/src/modules/realtime/realtime.rpc.ts b/packages/core/src/modules/realtime/realtime.rpc.tsindex 0ee922e12..c420481ee 100644--- a/packages/core/src/modules/realtime/realtime.rpc.ts+++ b/packages/core/src/modules/realtime/realtime.rpc.ts@@ -6,9 +6,6 @@// Each procedure also calls `requireProjectAccess({ level: 'read' })`// explicitly; `enforceAccess` already does the same off the `projectId` input,// and the redundant call is kept deliberately.-//-// The permission ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsindex eba46f476..45567df77 100644--- a/packages/core/src/modules/realtime/realtime.service.ts+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -1,11 +1,5 @@-// The realtime queries plus the `/live` websocket glue:-// `getActiveVisitorCount` and the four `subscribeToPublishedEvent` calls,-// filtered by projectId.-//-// `TABLE_NAMES` and the date helpers come from core's own pure copies-// (shared/ch-tables.ts, shared/ch-dates.ts) rather than @openpanel/db, which-// is what lets the import stay static: db's clickhouse/client.ts constructs a-// real client and a pino transport at module load.+// `TABLE_NAMES` and the date helpers come from core's own copies rather than+// @openpanel/db, whose clickhouse client constructs a real client at module load.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import {@@ -41,11 +35,8 @@ const EXCLUDED_BADGE_EVENT_NAMES = ['session_start','session_end',];-// clix built these queries with no timezone argument, and `clix(client)`-// defaults to `'UTC'`, sending it as `clickhouse_settings.session_timezone`-// on every `execute()`. The seven statements that came off clix keep sending-// it so their result sets stay identical; the three that were already raw-// `chQuery` calls sent no `session_timezone` and still send none.+// Statements that send `session_timezone: 'UTC'` keep sending it so result sets stay+// consistent; the raw `chQuery` ones send none.const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;function since(): Date {@@ -131,10 +122,8 @@ function adaptiveCluster(return points.slice(0, target);}-// --- location filters -------------------------------------------------------//-// These are `SqlFragment`s, so the same fragment object composes into every-// statement and each one numbers its own params at `toStatement()`.+// `SqlFragment`s compose into every statement; each statement numbers its own+// params at `toStatement()`.function coordinateTuples(locations: RealtimeLocation[]): SqlFragment[] {return locations@@ -436,11 +425,7 @@ export function getRealtimeGeo(deps: ServiceDeps, projectId: string) {CLIX_SESSION_TIMEZONE);}-// --- /live websocket glue --------------------------------------------------//-// Framework-agnostic: resolve to an unsubscribe function each, exactly-// `subscribeToPublishedEvent`'s own shape. realtime.routes.ts (Elysia/Bun)-// awaits these directly; nothing here is HTTP- or ws-library-specific.+// Each resolves to an unsubscribe function; nothing here is HTTP- or ws-library-specific.export function getActiveVisitorCount(deps: ServiceDeps,@@ -491,13 +476,9 @@ export async function subscribeToProjectNotifications(}/**- * Scoped to the single organization the caller's membership was verified- * against, exactly as the three siblings above scope to a verified- * `projectId`.- *- * The channel is instance-wide: without this filter every subscriber saw the- * `organizationId` of every organization whose subscription changed, which is- * a cross-tenant identifier leak.+ * Scoped to the single organization the caller's membership was verified against.+ * The channel is instance-wide: unscoped, every subscriber saw the `organizationId`+ * of every organization whose subscription changed (a cross-tenant leak).*/export async function subscribeToOrganizationSubscriptionUpdates(organizationId: string,diff --git a/packages/core/src/modules/reference/reference.constants.ts b/packages/core/src/modules/reference/reference.constants.tsindex ad6c21ee9..5dbe1daf9 100644--- a/packages/core/src/modules/reference/reference.constants.ts+++ b/packages/core/src/modules/reference/reference.constants.ts@@ -1,6 +1,3 @@-// Two diverged `zCreateReference` copies were a drift bug this file exists to-// prevent; this is now the only one.-import { z } from 'zod';export const zCreateReference = z.object({diff --git a/packages/core/src/modules/reference/reference.rpc.test.ts b/packages/core/src/modules/reference/reference.rpc.test.tsindex 8ab945cb3..fc787ce90 100644--- a/packages/core/src/modules/reference/reference.rpc.test.ts+++ b/packages/core/src/modules/reference/reference.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + CRUD logic ride on @openpanel/db (lazy-loaded, see-// reference.service.ts's header); wiring this router end-to-end against a-// real Postgres is P6's (protectedProcedure) job, not this one's — see-// reference.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, mock, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -19,7 +15,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.tsindex 2634a5d22..5d4e4bb0d 100644--- a/packages/core/src/modules/reference/reference.rpc.ts+++ b/packages/core/src/modules/reference/reference.rpc.ts@@ -2,12 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// The handler bodies reach the module through `ctx.services.reference`, so the-// requestId minted at the edge reaches the Postgres call.-//-// The permission ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import {diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsindex 797392e0f..1abe4796a 100644--- a/packages/core/src/modules/reference/reference.service.test.ts+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -105,11 +105,8 @@ const getChartStartEndDate = mock(() => ({startDate: '2026-08-25 00:00:00',endDate: '2026-09-01 23:59:59',}));-// The module no longer reaches either through a lazy `@openpanel/core` hop —-// Postgres arrives as `deps.db` and these two are plain relative imports, so-// each is mocked at the specifier the source actually resolves through.-// Snapshot-before-mock so `afterAll` restores the real module rather than-// re-applying the mock.+// Each is mocked at the specifier the source resolves through, snapshot-before-mock so+// `afterAll` restores the real module rather than re-applying the mock.const actualOrganization = await import('../organization/organization.service');const realOrganization = { ...actualOrganization };mock.module('../organization/organization.service', () => ({diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsindex c4bb11ce4..88535a906 100644--- a/packages/core/src/modules/reference/reference.service.ts+++ b/packages/core/src/modules/reference/reference.service.ts@@ -1,8 +1,3 @@-// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`.-// Nothing here value-imports `@openpanel/db` or this package's own barrel (the-// Prisma row type below is `import type`, erased at runtime), so there is no-// import-time client — and no pino-pretty worker per test file — to defer.-import type { Reference } from '@openpanel/db/src/prisma-client';import type { ServiceDeps, Services } from '../../services';import { getSettingsForProject } from '../organization/organization.service';diff --git a/packages/core/src/modules/salt/salt.jobs.ts b/packages/core/src/modules/salt/salt.jobs.tsindex 2d896df2f..2bf3f62c0 100644--- a/packages/core/src/modules/salt/salt.jobs.ts+++ b/packages/core/src/modules/salt/salt.jobs.ts@@ -1,6 +1,3 @@-// `salt` is this module's fragment of the ONE `cron` queue's jobs, spread into-// jobs.registry.ts.-import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/salt/salt.service.test.ts b/packages/core/src/modules/salt/salt.service.test.tsindex 13ec299a4..176e8401c 100644--- a/packages/core/src/modules/salt/salt.service.test.ts+++ b/packages/core/src/modules/salt/salt.service.test.ts@@ -1,15 +1,10 @@-// The subject is built over a fake `ServiceDeps`, so Postgres needs no module-// mock at all — `deps.db` IS the fake below, same idiom as-// reference.service.test.ts. `@openpanel/redis`'s `cacheable` is still stubbed-// (module-level `getSalts` binds it at this file's first import), so-// `rotateSalt`'s `getSalts.clear` never reaches a real Redis connection.+// The subject is built over a fake `ServiceDeps`, so `deps.db` IS the fake below.+// `@openpanel/redis`'s `cacheable` is still stubbed (module-level `getSalts` binds it+// at first import) so `rotateSalt`'s `getSalts.clear` never reaches a real Redis.//-// `getSalts` itself stays untested here: it is bare (no `deps` argument)-// because ingest.service.ts's hot path calls it with none — see the module-// header — and its `cacheable(...)` wrapping binds at this module's first-ever-// evaluation, which a bare (non `--isolate`) `bun test` run does not let this-// file control. `fetchSalts` (the uncached read it wraps) is exercised directly-// instead.+// `getSalts` itself is untested: it takes no `deps` (ingest's hot path calls it bare)+// and its `cacheable(...)` wrapping binds at first evaluation, which a non-`--isolate`+// run does not let this file control. `fetchSalts` is exercised directly instead.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -65,9 +60,7 @@ const $transaction = mock(fn({ salt: saltDelegate }));-// Bypasses the Redis cache-aside entirely, same as organization.service.test.ts's-// `cacheableStub` — this module's own logic is exercised directly, caching is-// @openpanel/redis's concern. Only the `cacheable(name, fn, ttl)` overload+// Bypasses the Redis cache-aside; only the `cacheable(name, fn, ttl)` overload// salt.service.ts uses needs covering.function cacheableStub<T extends (...args: unknown[]) => unknown>(_name: string,diff --git a/packages/core/src/modules/salt/salt.service.ts b/packages/core/src/modules/salt/salt.service.tsindex 60704387c..29c855477 100644--- a/packages/core/src/modules/salt/salt.service.ts+++ b/packages/core/src/modules/salt/salt.service.ts@@ -1,12 +1,6 @@-// `main.ts` passes its own `deps` to `createInitialSalts` at boot;-// `salt.jobs.ts`'s handler passes its `JobCtx` (a `ServiceDeps` by-// construction) to `rotateSalt`.-//-// `getSalts` is a module-scope `cacheablePerDb`, keyed on the Postgres client-// rather than on the scope — its L1 LRU has to survive across calls to be-// worth anything, so `ingest.service.ts`'s `/track` hot path passes the-// scope it holds rather than a boot-scoped singleton. `generateNewSalt`-// clears the same instance.+// `getSalts` is a module-scope `cacheablePerDb`, keyed on the Postgres client rather+// than the scope: its L1 LRU has to survive across calls, so the `/track` hot path+// passes the scope it holds. `generateNewSalt` clears the same instance.import { generateSalt } from '@openpanel/shared/server';import { cacheablePerDb } from '../../cacheable-per-deps';@@ -28,9 +22,7 @@ export interface Salts {previous: string;}-/** Only Postgres — narrowed so `main.ts`'s `AppDeps` (which never carries- * `queues`; that field only exists on the per-request/per-job `Ctx`)- * satisfies it with no cast. */+/** Only Postgres, so `main.ts`'s `AppDeps` (which has no `queues`) satisfies it without a cast. */type SaltDeps = Pick<ServiceDeps, 'db'>;function sleep(ms: number): Promise<void> {@@ -51,9 +43,7 @@ export async function fetchSalts(deps: SaltDeps): Promise<Salts> {return { current: curr.salt, previous: prev?.salt ?? curr.salt };}-/** L1 LRU (60s) + L2 Redis, one instance per Postgres client. No arguments, so- * the Redis key stays the single `cachable:op:salt:[]` the in-factory- * `cacheable(SALT_CACHE_NAME, () => fetchSalts(deps), ...)` produced. */+/** L1 LRU (60s) + L2 Redis, one instance per Postgres client. No arguments, so the Redis key is the single `cachable:op:salt:[]`. */export const getSalts = cacheablePerDb(SALT_CACHE_NAME,fetchSalts,diff --git a/packages/core/src/modules/session/session.jobs.ts b/packages/core/src/modules/session/session.jobs.tsindex 7c0d2f00f..7fc24db5e 100644--- a/packages/core/src/modules/session/session.jobs.ts+++ b/packages/core/src/modules/session/session.jobs.ts@@ -1,15 +1,3 @@-// `sessions` is this module's own queue — registry key and Redis name-// `sessions`, job name `session`, `removeOnComplete: true`, concurrency 1-// (jobs.registry.ts). Its wire payload is `{ event, snapshot }`, which is-// what `legacyCompat.sessions` maps the legacy `{type:'createSessionEnd',-// payload, snapshot}` shape onto. `flushSessions` / `flushReplay` /-// `sessionReaper` / `sessionVacuum` are cron fragments, spread into the ONE-// `cron` queue by jobs.registry.ts, ids and cadences unchanged.-//-// Every handler reads its clients off `ctx` — the buffers and the Redis-// connection main.ts built once, and the ClickHouse client the job's own-// requestId is bound to.-import { z } from 'zod';import { chQuery } from '../../ch-query';import type { Ctx } from '../../context';@@ -39,15 +27,11 @@ const SESSION_VACUUM_CRON = '0 4 * * *';const FLUSH_SESSIONS_INTERVAL_MS = 10_000;const FLUSH_REPLAY_INTERVAL_MS = 10_000;-// Wire-shape check only — tightening it now would reject payloads the-// running system currently accepts (see jobs/compat.test.ts).+// Wire-shape check only: tightening it would reject payloads currently accepted.//-// The schema's INPUT is what the producer holds (`SessionEndJobData`, a real-// `Date` on `event.createdAt`) and its OUTPUT is what a handler is actually-// handed after BullMQ's JSON round-trip (`SessionEndJobWire`, a string there).-// `PayloadOf` reads the input and the handler reads the output, so the two stay-// honest without either side casting. The transform is a type seam only — it-// returns the value it was given.+// The schema's INPUT is what the producer holds (`SessionEndJobData`, a real `Date`);+// its OUTPUT is what a handler gets after BullMQ's JSON round-trip (`SessionEndJobWire`,+// a string). The transform is a type seam only.const sessionEndWireShape = z.object({event: z.object({ projectId: z.string(), deviceId: z.string() }),snapshot: z.object({@@ -65,11 +49,8 @@ const sessionEndPayload = z.transform((value) => value as unknown as SessionEndJobWire);/**- * The session-end job's dependencies, bound to the run's own ctx.- *- * Two lookups stay dynamic to keep `notification.service.ts` — and the- * dispatch module built on it — out of jobs.registry.ts's eager import- * graph, which every core test file walks.+ * The session-end job's dependencies, bound to the run's own ctx. Two lookups stay+ * dynamic to keep `notification.service.ts` out of jobs.registry.ts's eager import graph.*/async function sessionEndDeps(ctx: Ctx,diff --git a/packages/core/src/modules/session/session.rpc.test.ts b/packages/core/src/modules/session/session.rpc.test.tsindex 978802fa9..57b3d75a5 100644--- a/packages/core/src/modules/session/session.rpc.test.ts+++ b/packages/core/src/modules/session/session.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The access-check + query bodies ride on @openpanel/db (lazy-loaded, see-// session.service.ts's header); wiring this router end-to-end against a real-// ClickHouse is P6's (protectedProcedure) job — see session.rpc.ts's header.-// Same shape as realtime.rpc.test.ts.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import {@@ -21,7 +17,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 8234fc99a..9a8c60e1d 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -1,11 +1,5 @@-// The session read path. Every query is a `sql` fragment (src/sql.ts);-// `buildFilterWhere` is the shared filter compiler and src/filter-clauses.ts is-// the bridge to it.-//-// `getSessionsCountCached` is `cacheablePerDeps`: `cacheable` keys on the-// call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps have to-// travel beside the key rather than inside it, or the Redis key would change-// per request.+// `getSessionsCountCached` is `cacheablePerDeps`: `cacheable` keys on the call's+// arguments, so deps travel beside the key or the Redis key would change per request.import { getSafeJson, resolveDateRange } from '@openpanel/shared';import { cacheablePerDeps } from '../../cacheable-per-deps';@@ -151,8 +145,7 @@ const REPLAY_CHUNKS_PAGE_SIZE = 40;const DISTINCT_VALUES_DEFAULT_LIMIT = 200;const QUERY_SESSIONS_DEFAULT_LIMIT = 20;-// clix always sent `session_timezone: 'UTC'`; the two queries converted from-// clix keep sending it so their result sets stay identical.+// Keeps sending `session_timezone: 'UTC'` so result sets are consistent.const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;export function withReadableCountry<Row extends { country: string }>(@@ -368,10 +361,8 @@ export async function getSessionReplayChunksFrom(}));- // `chunkIndex` is the row's position, not `row.chunk_index`, and `hasMore`- // counts rows the JSON filter may drop — so an unparseable chunk rewinds- // the client. Correcting either changes what the endpoint returns, so it- // is reported, not fixed.+ // `chunkIndex` is the row's position, not `row.chunk_index`, and `hasMore` counts rows+ // the JSON filter may drop, so an unparseable chunk rewinds the client.return {data: rows.slice(0, REPLAY_CHUNKS_PAGE_SIZE)@@ -455,10 +446,8 @@ export async function querySessionsCore(input.endDate);- // MCP sends a bare `YYYY-MM-DD`. The local `clix.datetime` helper this- // replaces flattened that to midnight before the query builder could widen- // it, so the whole last day was dropped, and it read an explicit datetime in- // the server's local zone on the way through.+ // MCP sends a bare `YYYY-MM-DD`: flattening it to midnight would drop the whole last+ // day, and an explicit datetime must not be read in the server's local zone.const from = toRangeBoundaryLiteral(startDate, 'start');const to = toRangeBoundaryLiteral(endDate, 'end');@@ -487,10 +476,6 @@ export function createSessionService(deps: ServiceDeps,_services: () => Services) {- /**- * Enqueue one `session_end` job, idempotent on the closed session's id,- * through the ctx.queues-based producer.- */async function enqueueSessionEnd(input: EnqueueSessionEndInput): Promise<void> {@@ -500,9 +485,7 @@ export function createSessionService();}- /** `event.service.ts` reaches this through the composition root's thunk- * `session-end.ts` statically imports the event module, so the two are a real- * cycle and an import back would be the wrong answer. */+ /** Reached through the composition root's thunk: `session-end.ts` imports the event module, so a direct import is a cycle. */function getById(sessionId: string,projectId: stringdiff --git a/packages/core/src/modules/session/src/dates.ts b/packages/core/src/modules/session/src/dates.tsindex d6f734889..f9d165b33 100644--- a/packages/core/src/modules/session/src/dates.ts+++ b/packages/core/src/modules/session/src/dates.ts@@ -1,7 +1,6 @@-// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs-// a client and a pino logger at import time (see insight.service.ts's header),-// and the fragment builders here must stay pure and synchronous. Same choice-// cohort.service.ts made for its table map.+// @openpanel/db's clickhouse/client.ts owns these, but importing it constructs a+// client and a pino logger at import time, and the fragment builders here must stay+// pure and synchronous.const CLICKHOUSE_DATE_SUFFIX = /(\.\d{3})?Z+$/;diff --git a/packages/core/src/modules/session/src/filter-clauses.ts b/packages/core/src/modules/session/src/filter-clauses.tsindex 6ce11b2e2..279b19080 100644--- a/packages/core/src/modules/session/src/filter-clauses.ts+++ b/packages/core/src/modules/session/src/filter-clauses.ts@@ -1,10 +1,6 @@-// The ONE place this module splices pre-compiled filter SQL.-//-// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is the-// sessions/profiles/events-table filter compiler; it returns bound-// `SqlFragment`s, same as `getEventFiltersWhereClause`-// (../../chart/src/filter-where.ts). Nothing is bridged any more — this file-// only assembles what the compiler already produced.+// The ONE place this module splices pre-compiled filter SQL: it only assembles what+// the filter compilers (chart/src/table-filter-where.ts, chart/src/filter-where.ts)+// already produced.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/session/src/keys.ts b/packages/core/src/modules/session/src/keys.tsindex a8f4067e8..9c9d9dd1f 100644--- a/packages/core/src/modules/session/src/keys.ts+++ b/packages/core/src/modules/session/src/keys.ts@@ -1,7 +1,6 @@-// The Redis index the session buffer-// (packages/core/src/buffers/session-buffer.ts) maintains and the-// reaper/vacuum walk. Redefined here — the buffer keeps its own copy and-// importing it would construct the ClickHouse client at import time.+// The Redis index the session buffer (buffers/session-buffer.ts) maintains and the+// reaper/vacuum walk. Redefined here because importing the buffer would construct+// the ClickHouse client at import time./** Idle time after which a session is over; also the reaper's deadman default.* SESSION_TIMEOUT_MS overrides it (`config.session.timeoutMs`). */diff --git a/packages/core/src/modules/session/src/runtime.ts b/packages/core/src/modules/session/src/runtime.tsindex 1938e94ce..1d457ffaf 100644--- a/packages/core/src/modules/session/src/runtime.ts+++ b/packages/core/src/modules/session/src/runtime.ts@@ -54,10 +54,9 @@ export interface SessionRuntime {}/**- * The two boot singletons the lifecycle needs, read off the work scope rather- * than constructed here: `ctx.redis` and `ctx.buffers` are the same objects- * main.ts built once, so a job handler no longer opens a connection of its own- * and its writes stay inside the request's scope.+ * The two boot singletons the lifecycle needs, read off the work scope: `ctx.redis`+ * and `ctx.buffers` are the objects main.ts built once, so writes stay inside the+ * request's scope.*/export function sessionRuntimeFrom(ctx: Pick<Ctx, 'redis' | 'buffers' | 'config'>diff --git a/packages/core/src/modules/session/src/session-end.ts b/packages/core/src/modules/session/src/session-end.tsindex 88e92776f..13d9facfc 100644--- a/packages/core/src/modules/session/src/session-end.ts+++ b/packages/core/src/modules/session/src/session-end.ts@@ -1,7 +1,6 @@-// Everything that touches Redis, ClickHouse, a buffer or a queue is INJECTED-// (`SessionEndDeps`), bound in `session.jobs.ts` from the job's own `ctx`, so-// the requestId that opened the session still labels the rows this close-// writes.+// Everything touching Redis, ClickHouse, a buffer or a queue is injected+// (`SessionEndDeps`), bound in `session.jobs.ts` from the job's own `ctx`, so the+// requestId that opened the session still labels the rows this close writes.import type { CoreConfig } from '../../../config';import type { EnqueueOptions } from '../../../jobs/define';@@ -58,7 +57,7 @@ export interface EnqueueSessionEndInput {closedSession: IClickhouseSession;}-/** What rides on the `sessions` queue (legacyCompat.sessions: `{ event, snapshot }`). */+/** What rides on the `sessions` queue. */export interface SessionEndJobData {event: IServiceCreateEventPayload;snapshot: IClickhouseSession;@@ -92,10 +91,7 @@ export function sessionEndJobPayload({};}-/**- * What the emission needs beyond the shared runtime. `session.jobs.ts` binds- * it from the job's own ctx; the tests hand in stubs.- */+/** What the emission needs beyond the shared runtime; tests hand in stubs. */export interface SessionEndDeps extends SessionRuntime {logger: Logger;createEvent(@@ -116,8 +112,7 @@ export interface SessionEndDeps extends SessionRuntime {notifications: {getRules(projectId: string): Promise<INotificationRuleCached[]>;hasFunnelRules(rules: INotificationRuleCached[]): boolean;- /** notification/src/notification-dispatch.ts — it enqueues through the- * notification queue. */+ /** Enqueues through the notification queue. */checkFunnelRules(events: IServiceEvent[]): Promise<unknown>;};}diff --git a/packages/core/src/modules/session/src/session.metrics.ts b/packages/core/src/modules/session/src/session.metrics.tsindex 2253a2b40..e24563dae 100644--- a/packages/core/src/modules/session/src/session.metrics.ts+++ b/packages/core/src/modules/session/src/session.metrics.ts@@ -1,7 +1,5 @@-// The session lifecycle collectors, on core's one registry. The ingest-side-// `sessions_started_total` lives with the ingest path-// (modules/ingest/src/ingest.metrics.ts); the three at-scrape gauges are-// registered by `registerSessionScrapeMetrics` at the bottom of this file.+// The ingest-side `sessions_started_total` lives in modules/ingest/src/ingest.metrics.ts;+// the three at-scrape gauges are registered by `registerSessionScrapeMetrics` below.import client from 'prom-client';import { registry } from '../../../metrics';@@ -93,14 +91,11 @@ export const sessionsVacuumed = new client.Counter({});/**- * The three scrape-time session gauges.+ * The three scrape-time session gauges. Registered only where the role consumes+ * queues: each scrape costs one `ZCARD` and one `GET` per project, and ten api+ * replicas would multiply that Redis load for no new information.*- * Registered by main.ts and ONLY where the role consumes queues: each scrape- * costs one `ZCARD` and one `GET` per project, and ten api replicas exposing- * them would multiply that Redis load for no new information.- *- * The client is injected rather than imported so core does not open a Redis- * connection at import time — `main.ts` hands in `getRedisCache`.+ * The client is injected so core does not open a Redis connection at import time.*/export function registerSessionScrapeMetrics(getRedis: () => SessionMetricsRedis,diff --git a/packages/core/src/modules/session/src/sql.test.ts b/packages/core/src/modules/session/src/sql.test.tsindex 88bad76d6..ea82fd36e 100644--- a/packages/core/src/modules/session/src/sql.test.ts+++ b/packages/core/src/modules/session/src/sql.test.ts@@ -1,8 +1,6 @@// Shape tests for the session module's fragments: every user value binds as a-// `{pN:Type}` parameter (nothing is interpolated), the optional clauses toggle-// correctly, and `sql.id` rejects a column outside the whitelist. Result-set-// equivalence was proven per query against the local prod-copy separately —-// not here; these tests run offline.+// `{pN:Type}` parameter, the optional clauses toggle correctly, and `sql.id` rejects a+// column outside the whitelist. These run offline.import { describe, expect, test } from 'bun:test';import { sql } from '@openpanel/db/src/clickhouse/sql';@@ -230,9 +228,8 @@ describe('querySessionsQuery', () => {});});- // `query_sessions` labels its rows `created_at desc`, so the cut has to- // happen after the sort rather than wherever the scan starts. Without this- // the seeded August window returned the five OLDEST sessions (ISSUES.md H8b).+ // `query_sessions` labels its rows `created_at desc`, so the cut has to happen after+ // the sort; otherwise a bare LIMIT returns the OLDEST sessions in the window.test('takes the newest sessions, not an arbitrary slice', () => {const { query } = querySessionsQuery({projectId: PROJECT_ID,@@ -245,9 +242,8 @@ describe('querySessionsQuery', () => {expect(query.indexOf('ORDER BY')).toBeLessThan(query.indexOf('LIMIT'));});- // `query_sessions` is reached from MCP with bare `YYYY-MM-DD`, which bound- // straight through as midnight and dropped the whole last day — 7,245- // sessions on the seeded 31 Aug (ISSUES.md H8a, missed in 908bf0d1).+ // `query_sessions` is reached from MCP with bare `YYYY-MM-DD`, which bound straight+ // through as midnight and dropped the whole last day.test('widens a bare end date to the end of that day', () => {const { query_params } = querySessionsQuery({projectId: PROJECT_ID,diff --git a/packages/core/src/modules/session/src/sql.ts b/packages/core/src/modules/session/src/sql.tsindex d5fb95cd8..7542144ef 100644--- a/packages/core/src/modules/session/src/sql.ts+++ b/packages/core/src/modules/session/src/sql.ts@@ -1,15 +1,11 @@-// Every ClickHouse query the session module runs, as pure `sql` fragments,-// with every value bound as a `{pN:Type}` parameter instead of an escaped-// literal.+// Dates bind as `YYYY-MM-DD HH:mm:ss` strings on purpose: a String param in a+// DateTime64 position is parsed exactly like the literal it replaces, so result+// sets cannot drift by a millisecond truncation.//-// Dates bind as `YYYY-MM-DD HH:mm:ss` strings on purpose: a String param in-// a DateTime64 position is parsed exactly like the literal it replaces, so-// the result sets cannot drift by a millisecond truncation.-//-// Cluster note: `sessions` and `session_replay_chunks` are Distributed on-// Cloud. The has_replay LEFT JOIN subquery and any `IN (SELECT...)` a filter-// compiles to run under the client's `distributed_product_mode: 'allow'` —-// changing that shape changes the query's cluster semantics.+// `sessions` and `session_replay_chunks` are Distributed on Cloud. The has_replay+// LEFT JOIN subquery and any `IN (SELECT...)` a filter compiles to run under the+// client's `distributed_product_mode: 'allow'`; changing that shape changes the+// query's cluster semantics.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';@@ -286,7 +282,7 @@ type QuerySessionsEqualityKey =export interface QuerySessionsQueryextends Partial<Record<QuerySessionsEqualityKey, string>> {projectId: string;- /** `YYYY-MM-DD HH:mm:ss`, inclusive on both ends — what clix.datetime sent. */+ /** `YYYY-MM-DD HH:mm:ss`, inclusive on both ends. */startDate: string;endDate: string;limit: number;diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.tsindex 47a04dc52..7299e7d20 100644--- a/packages/core/src/modules/session/src/usage.ts+++ b/packages/core/src/modules/session/src/usage.ts@@ -24,8 +24,8 @@ function nextExceededAt(count: number,selfHosted: boolean): Date | null {- // Self-hosting has no billing limits: never flag, and clear any stale flag- // set before this guard existed (default limit 0 trips on the first event).+ // Self-hosting has no billing limits: never flag, and clear any stale flag (default+ // limit 0 trips on the first event).if (selfHosted) {return null;}diff --git a/packages/core/src/modules/share/share.rpc.test.ts b/packages/core/src/modules/share/share.rpc.test.tsindex cd0e71fee..596bfcf92 100644--- a/packages/core/src/modules/share/share.rpc.test.ts+++ b/packages/core/src/modules/share/share.rpc.test.ts@@ -1,8 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The query/mutation bodies ride on @openpanel/db (lazy-loaded, see-// share.service.ts's header); wiring this router end-to-end against a real-// Postgres is P6's (protectedProcedure) job, not this one's — see-// share.rpc.ts's header.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, mock, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -19,7 +15,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.tsindex 1953d980c..1300e279c 100644--- a/packages/core/src/modules/share/share.rpc.ts+++ b/packages/core/src/modules/share/share.rpc.ts@@ -2,12 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// The handler bodies reach the module through `ctx.services.share`, so the-// requestId minted at the edge reaches the Postgres call.-//-// The permission ladder itself is bound once, in auth.service.ts; every-// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import {diff --git a/packages/core/src/modules/share/share.service.ts b/packages/core/src/modules/share/share.service.tsindex 3d7b95767..7d09424eb 100644--- a/packages/core/src/modules/share/share.service.ts+++ b/packages/core/src/modules/share/share.service.ts@@ -14,8 +14,7 @@ import {const SHARE_ID_LENGTH = 6;const uid = new ShortUniqueId({ length: SHARE_ID_LENGTH });-/** `HttpCtx.cookies`'s shape, named locally so this file has no import from- * the rpc/http layer that calls it — same as auth.service.ts's CookieReader. */+/** `HttpCtx.cookies`'s shape, named locally so this file does not import the rpc/http layer. */interface CookieReader {get(name: string): string | undefined;}@@ -68,10 +67,7 @@ export async function getShareReportByReportId(return db.shareReport.findUnique({ where: { reportId } });}-/**- * @deprecated Zero call sites (ADR-015 register entry #14, graded DEAD). Ported- * as-is — removal is a separate P6/P7 task, not this one's.- */+/** @deprecated Zero call sites. */export async function validateReportAccess(deps: ServiceDeps,reportId: string,@@ -482,8 +478,7 @@ export async function getShareDashboardSettings(return { id: share.id, public: share.public, hasPassword: !!share.password };}-/** The caller must already have write access to `input.projectId` — the RPC- * layer's job (each transport still owns its own access-check plumbing). */+/** The caller must already have write access to `input.projectId`. */export interface CreateShareDashboardInput {organizationId: string;projectId: string;@@ -605,8 +600,7 @@ export async function getShareReportSettings(return { id: share.id, public: share.public, hasPassword: !!share.password };}-/** The caller must already have write access to `input.projectId` — the RPC- * layer's job (each transport still owns its own access-check plumbing). */+/** The caller must already have write access to `input.projectId`. */export interface CreateShareReportInput {organizationId: string;projectId: string;@@ -644,8 +638,6 @@ export async function createShareReport(return { id: share.id, public: share.public, hasPassword: !!share.password };}-// --- service -------------------------------------------------------------/** What the RPC layer passes to the two share validators. */export interface ShareAccessContext {cookies: CookieReader;diff --git a/packages/core/src/modules/subscription/subscription.routes.ts b/packages/core/src/modules/subscription/subscription.routes.tsindex c83ccf103..4a1470094 100644--- a/packages/core/src/modules/subscription/subscription.routes.ts+++ b/packages/core/src/modules/subscription/subscription.routes.ts@@ -1,6 +1,3 @@-// The Polar webhook, `POST /webhook/polar`. This route is the only caller of-// subscription.service.ts's `handlePolarWebhookEvent`.-//// RAW BYTES, deliberately: `validatePolarEvent` verifies Polar's signature over// the exact request body, so this handler reads `await request.text` and// declares no `body` schema — any parsing (JSON or otherwise) before thediff --git a/packages/core/src/modules/subscription/subscription.rpc.ts b/packages/core/src/modules/subscription/subscription.rpc.tsindex b933d7a0a..02b9d7d90 100644--- a/packages/core/src/modules/subscription/subscription.rpc.ts+++ b/packages/core/src/modules/subscription/subscription.rpc.ts@@ -2,10 +2,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// `requireOrganizationAdmin` lives in subscription.service.ts, not here — see-// that file's header. `ctx.services.subscription` carries this module's factory-// the same as every other module now.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.tsindex b00ae6ca1..20a1823ec 100644--- a/packages/core/src/modules/subscription/subscription.service.ts+++ b/packages/core/src/modules/subscription/subscription.service.ts@@ -1,11 +1,3 @@-// `requireOrganizationAdmin` travels with the business logic here rather than-// living in subscription.rpc.ts the way project.rpc.ts's simple ladder checks-// do: every mutating procedure in this module gates on it first, before-// touching Polar.-//-// `Prisma.DbNull` (the JSON-column null sentinel) arrives as `deps.prisma`-// rather than an import, keeping this module's only dependency `ServiceDeps`.-import {applySubscriptionDiscount,cancelSubscription as cancelPolarSubscription,@@ -44,7 +36,6 @@ const POLAR_PRODUCTS_CACHE_KEY = 'polar:products';const POLAR_PRODUCTS_CACHE_TTL_SECONDS = 60 * 60 * 24;const DEFAULT_USAGE_WINDOW_DAYS = 30;-// Every mutating export below gates on this before touching Polar.async function requireOrgAdmin(userId: string,organizationId: string@@ -356,11 +347,8 @@ export async function portal(return { url: created.customerPortalUrl };}-// - Polar webhook ---------------------------------------------------------// This module's own `/webhook/polar` route (subscription.routes.ts) is the-// only caller. `validatePolarEvent` verifies the signature over the RAW body-// bytes; any body parsing before this call breaks that verification, which is-// why the route reads `await request.text()` rather than a parsed JSON body.+// `validatePolarEvent` verifies the signature over the RAW body bytes, so the route+// must read `request.text()`, not parsed JSON.type PolarEvent = ReturnType<typeof validatePolarEvent>;type PolarSubscriptionData = Extract<diff --git a/packages/core/src/modules/tools/src/ip-lookup.test.ts b/packages/core/src/modules/tools/src/ip-lookup.test.tsindex 35ea8ad28..9d453ab12 100644--- a/packages/core/src/modules/tools/src/ip-lookup.test.ts+++ b/packages/core/src/modules/tools/src/ip-lookup.test.ts@@ -1,7 +1,5 @@-// Route-handler coverage for runIpLookup — the smell docs/review/tools.md-// flagged as "zero test coverage of the two route handlers." getGeoLocation is-// mocked; everything else (validation, rate limiting, private-range-// classification) runs for real.+// getGeoLocation is mocked; validation, rate limiting and private-range+// classification run for real.import { beforeAll, describe, expect, it, mock } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/tools/src/ip-lookup.ts b/packages/core/src/modules/tools/src/ip-lookup.tsindex 312f0d511..8d8459b86 100644--- a/packages/core/src/modules/tools/src/ip-lookup.ts+++ b/packages/core/src/modules/tools/src/ip-lookup.ts@@ -1,6 +1,3 @@-// Ported verbatim from apps/api/src/controllers/tools.controller.ts's-// `ipLookup`.-import { getGeoLocation } from '../../../clients/geo';import type { CoreConfig } from '../../../config';import type { Logger } from '../../../logger';diff --git a/packages/core/src/modules/tools/src/rate-limit.ts b/packages/core/src/modules/tools/src/rate-limit.tsindex b168e7147..b09cb6950 100644--- a/packages/core/src/modules/tools/src/rate-limit.ts+++ b/packages/core/src/modules/tools/src/rate-limit.ts@@ -1,5 +1,4 @@-// Shared in-memory rate limiter for the two public tools endpoints. Ported-// verbatim from apps/api/src/controllers/tools.controller.ts: one process-local+// Shared in-memory rate limiter for the two public tools endpoints: one process-local// map, keyed per endpoint by the caller.// Both endpoints are public and unauthenticated, so a key (one per distinctdiff --git a/packages/core/src/modules/tools/src/site-checker.test.ts b/packages/core/src/modules/tools/src/site-checker.test.tsindex ac754d91b..ff54cbcb5 100644--- a/packages/core/src/modules/tools/src/site-checker.test.ts+++ b/packages/core/src/modules/tools/src/site-checker.test.ts@@ -1,10 +1,6 @@-// Route-handler coverage for runSiteCheck — the smell docs/review/tools.md-// flagged as "zero test coverage of the two route handlers." Only the pre-fetch-// guards (missing/invalid URL, SSRF rejection, rate limit) are covered here:-// they run with no outbound I/O. The full probe (fetch, TLS, robots.txt,-// hosting lookup) is 700 lines of live network calls and is left uncovered —-// exercising it would mean mocking most of the file's behaviour, which risks-// diverging from what it actually does more than it protects.+// Only the pre-fetch guards (missing/invalid URL, SSRF rejection, rate limit) are+// covered: they run with no outbound I/O. The full probe is live network calls, and+// mocking most of it would diverge from what it does more than it protects.import { describe, expect, it } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/tools/src/site-checker.ts b/packages/core/src/modules/tools/src/site-checker.tsindex faa458653..4b3cb8319 100644--- a/packages/core/src/modules/tools/src/site-checker.ts+++ b/packages/core/src/modules/tools/src/site-checker.ts@@ -1,6 +1,3 @@-// Ported verbatim from apps/api/src/controllers/tools.controller.ts's-// `siteChecker`.-import * as dns from 'node:dns/promises';import * as net from 'node:net';import * as tls from 'node:tls';diff --git a/packages/core/src/modules/tools/tools.routes.test.ts b/packages/core/src/modules/tools/tools.routes.test.tsindex 7744d80bb..fc078bd2d 100644--- a/packages/core/src/modules/tools/tools.routes.test.ts+++ b/packages/core/src/modules/tools/tools.routes.test.ts@@ -1,8 +1,5 @@-// The `/tools` prefix came from a wrapper that mounted the router under-// `/tools`, over a router whose own urls were bare. `defineRoutes` has no-// prefix mechanism, so the port dropped the segment and both routes answered-// at the root — apps/public's own pages call `${API_URL}/tools/ip-lookup`-// and were 404ing. Nothing covered the path, which is why it slipped.+// `defineRoutes` has no prefix mechanism, so each route spells out `/tools/...`;+// apps/public calls `${API_URL}/tools/ip-lookup`, which 404s if the segment is dropped.import { describe, expect, test } from 'bun:test';import { readFileSync } from 'node:fs';diff --git a/packages/core/src/modules/tools/tools.routes.ts b/packages/core/src/modules/tools/tools.routes.tsindex ac36c0ea5..d92e7f86d 100644--- a/packages/core/src/modules/tools/tools.routes.ts+++ b/packages/core/src/modules/tools/tools.routes.ts@@ -1,9 +1,5 @@// Both routes stay unauthenticated and hidden from the OpenAPI document,// deliberately.-//-// The `/tools` prefix is spelled out on each path since `defineRoutes` has no-// prefix mechanism; apps/public calls these URLs with the full-// `/tools/ip-lookup` and `/tools/site-checker` paths.import { z } from 'zod';import { defineRoutes } from '../../http/define';diff --git a/packages/core/src/modules/user/user.rpc.test.ts b/packages/core/src/modules/user/user.rpc.test.tsindex c843c3e87..8be68009b 100644--- a/packages/core/src/modules/user/user.rpc.test.ts+++ b/packages/core/src/modules/user/user.rpc.test.ts@@ -1,7 +1,4 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// Wiring this router end-to-end against a real Postgres is a separate-// concern from `protectedProcedure`'s auth guard, which is what these-// tests cover.+// Only the "is anyone logged in" boundary is exercised here; no database.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';@@ -17,7 +14,6 @@ const COOKIE_OPTIONS: CookieOptions = {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 };diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.tsindex e06c2f5ea..235742481 100644--- a/packages/core/src/modules/user/user.rpc.ts+++ b/packages/core/src/modules/user/user.rpc.ts@@ -4,9 +4,6 @@// input parser. The explicit checks in the handlers below stay: `enforceAccess`// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved// from another id needs its own.-//-// `ctx.services.user` carries this module's factory; it has no queue/cron of-// its own, same as `conversation`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/user/user.service.test.ts b/packages/core/src/modules/user/user.service.test.tsindex 12c3434ec..c97c4f1f9 100644--- a/packages/core/src/modules/user/user.service.test.ts+++ b/packages/core/src/modules/user/user.service.test.ts@@ -1,7 +1,3 @@-// The subject is built by its factory over a fake `ServiceDeps`, so Postgres-// needs no module mock at all — `deps.db` IS the fake below, same idiom as-// reference.service.test.ts.-import { beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';import type { ServiceDeps } from '../../services';diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.tsindex 7ba8b21c6..17b1953fe 100644--- a/packages/core/src/modules/user/user.service.ts+++ b/packages/core/src/modules/user/user.service.ts@@ -1,7 +1,3 @@-// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the-// `loadDb` lazy loader is gone. Every caller — including-// `onboarding.service.ts` and `auth.service.ts` — passes the `deps` it holds.-import type { User } from '@openpanel/db/src/prisma-client';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';diff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.tsindex 438e7e757..6f9e63e42 100644--- a/packages/core/src/modules/widget/widget.rpc.ts+++ b/packages/core/src/modules/widget/widget.rpc.ts@@ -1,9 +1,3 @@-// Widgets are read-only chart embeds. Their zod schemas (`zWidgetType` /-// `zWidgetOptions`) are chart/report vocabulary and live in-// ./report/report.constants.ts, so this module carries no constants file of-// its own, and there is no widget.service.ts — the queries are small enough to-// stay in the procedures.-//// `get`/`toggle`/`updateOptions` require a login; `counter`/`badge`/// `realtimeData` are deliberately open, because a widget is embedded on a// public page.