OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M15-009): R22: shared/ stops being a drawer - the seven misfiled files go where they belong and the layer rules flip from warn to error at 0
ralphcf61e634b332
diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjsindex 72224f277..b31faa158 100644--- a/.dependency-cruiser.cjs+++ b/.dependency-cruiser.cjs@@ -1,3 +1,4 @@+'use strict';/*** ADR-008 (constants isomorphism) and ADR-022 R22 (layers only import downward)* enforcement. See decisions/ADR-008-constants.md and@@ -125,16 +126,20 @@ const R22_COMMENT ='infrastructure (rpc/, http/, jobs/) < modules < services.ts < registries < ' +'index.ts. By LAYER, not by path depth: a module importing ../../jobs/define ' +'is going down and is not a violation, and rpc/ http/ jobs/ are one layer so ' +- 'edges among them are sideways. Infrastructure reaches a module\'s behaviour ' ++ "edges among them are sideways. Infrastructure reaches a module's behaviour " +'through deps/ctx, never by deep-importing modules/<name>/src/*. Two upward ' +'edges are legal, both type-only and both exempted on ' +'core-layers-modules-below-composition: a module importing ServiceDeps / ' +'Services from services.ts (R3 requires it — all 36 factories do it), and a ' +- 'module importing another module\'s <name>.constants.ts (R8 blesses that ' +- 'file). Landed at `warn` by M14-002 with 23 violations, exactly as ' +- 'core-uses-ctx-not-db-internals did in M10-001; the fix wave flips it to ' +- '`error` at 0. Baseline, measured 2026-09-08: 7 from shared/, 6 from ' +- 'clients/, 10 from rpc/ + http/ + jobs/, 0 from modules/ and above.';+ "module importing another module's <name>.constants.ts (R8 blesses that " ++ 'file). Landed at `warn` by M14-002 with 23 violations (7 from shared/, 6 ' ++ 'from clients/, 10 from rpc/ + http/ + jobs/, 0 from modules/ and above), ' ++ 'exactly as core-uses-ctx-not-db-internals did in M10-001. M15-008 cleared ' ++ 'clients/, and M15-009 cleared the rest and flipped all six rules to ' ++ '`error` at 0: shared/ stopped being a drawer (the seven misfiled files went ' ++ 'to the layer that owns them), the ingest tier is handed to the clientAuth ' ++ 'macro instead of imported by it, and the two registry reads moved into the ' ++ 'registry. A rule that fires is the only durable fix.';// The composition root and everything above it.const COMPOSITION_AND_ABOVE =@@ -169,7 +174,7 @@ module.exports = {"seam (ADR-007; that file's own header). It is where the boot scope registers the " +'deps it already built, and the only thing behind it is the lazy fallback for a ' +"caller with no Ctx to thread through — MCP's tool handlers have a fixed " +- "@modelcontextprotocol/sdk signature (modules/mcp/src/auth.ts lazy-imports it; the gsc " ++ '@modelcontextprotocol/sdk signature (modules/mcp/src/auth.ts lazy-imports it; the gsc ' +'tools reach getGsc* through it), and the assistant tool runtime is the same shape. ' +'Nothing holding a Ctx comes through it. M11-004 corrects an earlier claim here: this ' +'file is NOT deleted with packages/trpc — it stays as that seam. ' +@@ -234,7 +239,7 @@ module.exports = {},{name: 'core-layers-shared-is-the-bottom',- severity: 'warn',+ severity: 'error',comment: R22_COMMENT,from: {path: '^packages/core/src/shared/',@@ -244,7 +249,7 @@ module.exports = {},{name: 'core-layers-clients-below-transport',- severity: 'warn',+ severity: 'error',comment: R22_COMMENT,from: {path: '^packages/core/src/clients/',@@ -254,7 +259,7 @@ module.exports = {},{name: 'core-layers-transport-below-modules',- severity: 'warn',+ severity: 'error',comment: R22_COMMENT,from: {// One layer, three directories: rpc/base.ts, http/define.ts and@@ -266,7 +271,7 @@ module.exports = {},{name: 'core-layers-modules-below-composition',- severity: 'warn',+ severity: 'error',comment: R22_COMMENT,from: {path: '^packages/core/src/modules/',@@ -287,14 +292,14 @@ module.exports = {},{name: 'core-layers-composition-below-registries',- severity: 'warn',+ severity: 'error',comment: R22_COMMENT,from: { path: '^packages/core/src/services\\.ts$' },to: { path: REGISTRIES_AND_INDEX, dependencyTypesNot: ['type-only'] },},{name: 'core-layers-registries-below-index',- severity: 'warn',+ severity: 'error',comment: R22_COMMENT,from: {path: '^packages/core/src/(rpc\\.router|rest\\.routes|jobs\\.registry)\\.ts$',diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex 4207ad84d..07b89d20f 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -40,6 +40,7 @@ import {BULL_BOARD_BASE_PATH,type BufferDeps,bullBoardRoutes,+ CRON_SCHEDULES,checkNotificationRulesForEvent,cookieOptions,corsDelegator,@@ -485,6 +486,7 @@ async function main() {production: config.core.isProduction,},logger,+ schedulers: CRON_SCHEDULES,});warnOnUnhandledSchedulers((await cron.getJobSchedulers()).map((scheduler) => scheduler.key)diff --git a/packages/core/src/buffers/base-buffer.ts b/packages/core/src/buffers/base-buffer.tsindex 0f55ece4c..d665801aa 100644--- a/packages/core/src/buffers/base-buffer.ts+++ b/packages/core/src/buffers/base-buffer.ts@@ -1,10 +1,10 @@import { Readable } from 'node:stream';import type { ClickHouseSettings } from '@clickhouse/client';import { getRedisCache } from '@openpanel/redis';+import { type ChQueryInput, type ChScope, chQuery } from '../ch-query';import type { CoreConfig } from '../config';import type { Logger } from '../logger';import type { ServiceDeps } from '../services';-import { type ChQueryInput, type ChScope, chQuery } from '../shared/ch-query';import { generateSecureId } from '../shared/id';/**diff --git a/packages/core/src/buffers/event-buffer.test.ts b/packages/core/src/buffers/event-buffer.test.tsindex 6acbb5955..14a36874f 100644--- a/packages/core/src/buffers/event-buffer.test.ts+++ b/packages/core/src/buffers/event-buffer.test.ts@@ -4,17 +4,17 @@ import { getRedisCache } from '@openpanel/redis';import { bufferDepsWithCh } from '../../test/buffer-fixtures';import { testCoreConfig } from '../../test/config-fixture';-const realChQuery = { ...(await import('../shared/ch-query')) };+const realChQuery = { ...(await import('../ch-query')) };const chInsert = mock(async (_options: unknown): Promise<unknown> => undefined);const chQuery = mock(async (_sql: string): Promise<unknown[]> => []);// M10-009: the client comes in as `BufferDeps.ch` and reads go through core's-// own `chQuery` (shared/ch-query.ts) — so the insert path needs no module mock+// own `chQuery` (ch-query.ts) — so the insert path needs no module mock// at all, and the read path mocks one core module instead of// `@openpanel/db/src/clickhouse/client` (whose import builds a real client and// a pino transport worker thread per test file).-mock.module('../shared/ch-query', () => ({+mock.module('../ch-query', () => ({...realChQuery,chQuery: (_scope: unknown, sql: string) => chQuery(sql),}));@@ -49,7 +49,7 @@ beforeEach(async () => {// every file in one process, and closing the singleton takes it away from the// files that run next (V1's vitest isolated per file, so it could).afterAll(() => {- mock.module('../shared/ch-query', () => realChQuery);+ mock.module('../ch-query', () => realChQuery);});describe('EventBuffer', () => {diff --git a/packages/core/src/buffers/profile-buffer.test.ts b/packages/core/src/buffers/profile-buffer.test.tsindex 74677d057..f9e9a3d68 100644--- a/packages/core/src/buffers/profile-buffer.test.ts+++ b/packages/core/src/buffers/profile-buffer.test.ts@@ -5,12 +5,12 @@ import type { IClickhouseProfile } from '../modules/profile/profile.service';// M10-009: the client comes in as `BufferDeps.ch` and reads go through core's// own `chQuery` — see event-buffer.test.ts's header.-const realChQuery = { ...(await import('../shared/ch-query')) };+const realChQuery = { ...(await import('../ch-query')) };const chInsert = mock(async (_options: unknown): Promise<unknown> => undefined);const chQuery = mock(async (_sql: string): Promise<IClickhouseProfile[]> => []);-mock.module('../shared/ch-query', () => ({+mock.module('../ch-query', () => ({...realChQuery,chQuery: (_scope: unknown, sql: string) => chQuery(sql),}));@@ -57,7 +57,7 @@ beforeEach(async () => {// every file in one process, and closing the singleton takes it away from the// files that run next (V1's vitest isolated per file, so it could).afterAll(() => {- mock.module('../shared/ch-query', () => realChQuery);+ mock.module('../ch-query', () => realChQuery);});describe('ProfileBuffer', () => {diff --git a/packages/core/src/shared/cacheable-per-deps.ts b/packages/core/src/cacheable-per-deps.tssimilarity index 99%rename from packages/core/src/shared/cacheable-per-deps.tsrename to packages/core/src/cacheable-per-deps.tsindex 0ef11538c..0ee757cac 100644--- a/packages/core/src/shared/cacheable-per-deps.ts+++ b/packages/core/src/cacheable-per-deps.ts@@ -23,7 +23,7 @@// takes `cacheablePerDb` below instead.import { type CacheableOptions, cacheable } from '@openpanel/redis';-import type { ServiceDeps } from '../services';+import type { ServiceDeps } from './services';type Cacheable<A extends unknown[], R> = ((...args: A) => Promise<R>) & {getKey: (...args: A) => string;diff --git a/packages/core/src/shared/ch-query.ts b/packages/core/src/ch-query.tssimilarity index 98%rename from packages/core/src/shared/ch-query.tsrename to packages/core/src/ch-query.tsindex c5fb0a422..5d1ce1e08 100644--- a/packages/core/src/shared/ch-query.ts+++ b/packages/core/src/ch-query.ts@@ -25,7 +25,7 @@ import {type SqlFragment,toStatement,} from '@openpanel/db/src/clickhouse/sql';-import type { ServiceDeps } from '../services';+import type { ServiceDeps } from './services';/** All these two need is the scope's client and its logger — narrowed so the* buffers, whose `BufferDeps` is not a `ServiceDeps`, can call them too. */diff --git a/packages/core/src/http/auth.ts b/packages/core/src/http/auth.tsindex d467eb2dd..5e0dfdf3d 100644--- a/packages/core/src/http/auth.ts+++ b/packages/core/src/http/auth.ts@@ -40,7 +40,7 @@import { Elysia } from 'elysia';import type { AppDeps } from '../context';-import { toIngestHeaders } from '../modules/ingest/src/headers';+import { toIngestHeaders } from '../shared/headers';import { authenticateClient, type ClientAuthOptions } from './client-auth';import { requestContext } from './context';diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.tsindex ce9d97deb..7453ee2e8 100644--- a/packages/core/src/http/client-auth.ts+++ b/packages/core/src/http/client-auth.ts@@ -7,7 +7,11 @@//// M8-002 filled in the INGEST branch — `modules/ingest/src/client-auth.ts`// holds V1's `validateSdkRequest` verbatim, and this file adapts it onto the-// principal. M9-004 filled in the `allow`-list tier, which is the one V1+// principal. M15-009 inverted how it gets there: transport may not deep-import+// a module (ADR-022 R22), so the route that wants the ingest tier hands its own+// validator down as `clientAuth: { ingest: validateIngestRequest }`.+//+// M9-004 filled in the `allow`-list tier, which is the one V1// spells three times (`validateExportRequest`, `validateImportRequest`,// `validateManageRequest`): identical bodies differing only by the accepted// `ClientType` set and by the prefix on their error strings. `allow` carries@@ -15,13 +19,10 @@// below. MCP is NOT here — it authenticates its own `token` form inside// `modules/mcp/src/auth.ts`, exactly as V1's mcp router did.+import type { DbScope } from '../cacheable-per-deps';import type { HttpCtx } from '../context';-import {- type IngestHeaders,- validateIngestRequest,-} from '../modules/ingest/src/client-auth';-import { headerValue } from '../modules/ingest/src/headers';import { verifyPassword } from '../shared/crypto';+import { headerValue, type IngestHeaders } from '../shared/headers';/** V1 refuses a client id that is not a UUID before it ever queries* (utils/auth.ts's three validators). Same regex, same order. */@@ -57,13 +58,39 @@ export interface AuthenticatedClient {*/export type ClientAuthLabel = 'Export' | 'Import' | 'Manage';+/**+ * What the ingest tier answers, as transport reads it.+ * `modules/ingest/src/client-auth.ts` owns the rules and returns a wider+ * outcome; only these fields cross the layer boundary.+ */+export type IngestTierOutcome =+ | {+ ok: true;+ client: {+ id: string;+ projectId: string | null;+ organizationId: string;+ type: ClientType;+ };+ secretPresented: boolean;+ }+ | { ok: false; message: string; secretPresented: boolean };++/** The ingest tier itself, passed in by the route that wants it. */+export type ValidateIngestRequest = (args: {+ deps: DbScope;+ headers: IngestHeaders;+ clientIp: string | undefined;+ body: unknown;+}) => Promise<IngestTierOutcome>;+export interface ClientAuthOptions {/** Which client types may pass. Omitted means any, as `validateSdkRequest`. */allow?: ClientType[];/** Which of V1's three validators this route was served by. */label?: ClientAuthLabel;- /** The ingest extension described above. */- ingest?: boolean;+ /** The ingest extension described above, supplied by the ingest module. */+ ingest?: ValidateIngestRequest;/** MCP presents `base64(clientId:clientSecret)` instead of the two headers. */token?: 'basic';}@@ -102,7 +129,7 @@ export async function authenticateClient(return await authenticateAllowedClient(ctx, headers, options);}- const outcome = await validateIngestRequest({+ const outcome = await options.ingest({deps: ctx,headers,clientIp: request?.ip,diff --git a/packages/core/src/http/debug.routes.ts b/packages/core/src/http/debug.routes.tsindex 686c4907d..f9eed37aa 100644--- a/packages/core/src/http/debug.routes.ts+++ b/packages/core/src/http/debug.routes.ts@@ -7,9 +7,11 @@//// Three things changed on the way over, all deliberate://-// * The job list is `queues.cron.jobs`, not a hand-written array of the 20-// `CronQueueType` strings. The array could drift from the registry; the-// registry cannot drift from itself.+// * The job list is the `cron` queue's own `jobs`, not a hand-written array of+// the 20 `CronQueueType` strings. The array could drift from the registry;+// the registry cannot drift from itself. The queue arrives as an argument —+// `rest.routes.ts` binds it — because transport may not import a registry+// (ADR-022 R22).// * A trigger runs through `runJob` with V1's `{ type }` data — the same// entry point the real worker uses, compat hook included — so what this// exercises is the production path and not a second dispatcher.@@ -19,16 +21,17 @@// services, not through a Prisma client of its own.import { z } from 'zod';+import type { AnyJob, QueueDefinition } from '../jobs/define';import { runJob } from '../jobs/workers';-import { queues } from '../jobs.registry';import { defineRoutes } from './define';+/** The `cron` queue, as this surface reads it. */+export type CronQueue = QueueDefinition<Record<string, AnyJob>>;+const BAD_REQUEST = 400;const INTERNAL_ERROR = 500;const DIGEST_INSIGHT_LIMIT = 15;-const cronTypes = Object.keys(queues.cron.jobs);-const HTML_ESCAPES: Record<string, string> = {'&': '&','<': '<',@@ -48,7 +51,7 @@ function wantsHtml(headers: Headers): boolean {return (headers.get('accept') ?? '').includes('text/html');}-function buildJobs(request: Request) {+function buildJobs(request: Request, cronTypes: string[]) {const base = new URL(request.url).origin;return cronTypes.map((type) => ({type,@@ -83,147 +86,157 @@ const errorMessage = (error: unknown): string =>const projectIdParams = z.object({ projectId: z.string() });const HIDDEN = { hide: true } as const;-export const debugRoutes = defineRoutes((app, deps) =>- app- .get(- '/debug/cron',- ({ request, set }) => {- const jobs = buildJobs(request);- if (wantsHtml(request.headers)) {- set.headers['content-type'] = 'text/html; charset=utf-8';- return renderHtml(jobs);- }- return {- message: 'Run a cron job now with GET or POST /debug/cron/:type',- jobs,- };- },- // Hidden from the OpenAPI document, like every other ops-surface route:- // in V1 these lived on the worker's own server and were never in it.- { detail: HIDDEN }- )- .all(- '/debug/cron/:type',- async ({ params, request, set, ctx }) => {- const { type } = params as { type: string };- const jobs = buildJobs(request);- const html = wantsHtml(request.headers);-- if (!cronTypes.includes(type)) {- set.status = BAD_REQUEST;- const message = `Unknown cron type "${type}"`;- if (html) {+export const createDebugRoutes = (cronQueue: CronQueue) => {+ const cronTypes = Object.keys(cronQueue.jobs);++ return defineRoutes((app, deps) =>+ app+ .get(+ '/debug/cron',+ ({ request, set }) => {+ const jobs = buildJobs(request, cronTypes);+ if (wantsHtml(request.headers)) {set.headers['content-type'] = 'text/html; charset=utf-8';- return renderHtml(jobs, message);+ return renderHtml(jobs);}- return { ok: false, error: message, jobs };- }-- ctx.logger.info({ type }, 'Manually triggering cron job');-- try {- // V1's wire data, so this goes through the `cron` compat hook.- await runJob(- queues.cron,- { name: type, data: { type }, attemptsMade: 0 },- deps- );- } catch (error) {- ctx.logger.error({ err: error, type }, 'Manual cron trigger failed');- set.status = INTERNAL_ERROR;+ return {+ message: 'Run a cron job now with GET or POST /debug/cron/:type',+ jobs,+ };+ },+ // Hidden from the OpenAPI document, like every other ops-surface route:+ // in V1 these lived on the worker's own server and were never in it.+ { detail: HIDDEN }+ )+ .all(+ '/debug/cron/:type',+ async ({ params, request, set, ctx }) => {+ const { type } = params as { type: string };+ const jobs = buildJobs(request, cronTypes);+ const html = wantsHtml(request.headers);++ if (!cronTypes.includes(type)) {+ set.status = BAD_REQUEST;+ const message = `Unknown cron type "${type}"`;+ if (html) {+ set.headers['content-type'] = 'text/html; charset=utf-8';+ return renderHtml(jobs, message);+ }+ return { ok: false, error: message, jobs };+ }++ ctx.logger.info({ type }, 'Manually triggering cron job');++ try {+ // V1's wire data, so this goes through the `cron` compat hook.+ await runJob(+ cronQueue,+ { name: type, data: { type }, attemptsMade: 0 },+ deps+ );+ } catch (error) {+ ctx.logger.error(+ { err: error, type },+ 'Manual cron trigger failed'+ );+ set.status = INTERNAL_ERROR;+ if (html) {+ set.headers['content-type'] = 'text/html; charset=utf-8';+ return renderHtml(+ jobs,+ `Error running ${type}: ${errorMessage(error)}`+ );+ }+ return { ok: false, type, error: errorMessage(error) };+ }+if (html) {set.headers['content-type'] = 'text/html; charset=utf-8';- return renderHtml(- jobs,- `Error running ${type}: ${errorMessage(error)}`- );+ return renderHtml(jobs, `${type} ran. Check the logs for details.`);}- return { ok: false, type, error: errorMessage(error) };- }-- if (html) {- set.headers['content-type'] = 'text/html; charset=utf-8';- return renderHtml(jobs, `${type} ran. Check the logs for details.`);- }- return { ok: true, type };- },- { detail: HIDDEN }- )- // The insights pipeline for ONE project, bypassing the daily cron's- // eligibility filter. Default enqueues a real job so it shows up in- // bull-board; `?inline=1` runs it here and returns a summary.- .get(- '/debug/insights/:projectId',- async ({ params, query, set, ctx }) => {- const { projectId } = params;- const inline = query.inline === '1' || query.inline === 'true';- const date = new Date().toISOString().slice(0, 10);-- try {- if (inline) {- ctx.logger.info({ projectId }, 'Manual insights run (inline)');- await ctx.services.insight.runProjectInsights({- projectId,- date,- });+ return { ok: true, type };+ },+ { detail: HIDDEN }+ )+ // The insights pipeline for ONE project, bypassing the daily cron's+ // eligibility filter. Default enqueues a real job so it shows up in+ // bull-board; `?inline=1` runs it here and returns a summary.+ .get(+ '/debug/insights/:projectId',+ async ({ params, query, set, ctx }) => {+ const { projectId } = params;+ const inline = query.inline === '1' || query.inline === 'true';+ const date = new Date().toISOString().slice(0, 10);++ try {+ if (inline) {+ ctx.logger.info({ projectId }, 'Manual insights run (inline)');+ await ctx.services.insight.runProjectInsights({+ projectId,+ date,+ });+ return {+ ok: true,+ projectId,+ date,+ insights: await ctx.services.insight.listAllInsights({+ projectId,+ limit: DIGEST_INSIGHT_LIMIT,+ }),+ };+ }++ const jobId = await ctx.queues.insights.insightsProject.add(+ { projectId, date },+ // Unique id so repeated runs are not deduped by BullMQ.+ { jobId: `debug:${projectId}:${Date.now()}` }+ );+ ctx.logger.info({ projectId, jobId }, 'Enqueued insights job');return {ok: true,projectId,- date,- insights: await ctx.services.insight.listAllInsights({- projectId,- limit: DIGEST_INSIGHT_LIMIT,- }),+ jobId,+ message:+ 'Enqueued on the "insights" queue — watch it in bull-board. Add ?inline=1 to run synchronously.',};+ } catch (error) {+ ctx.logger.error(+ { err: error, projectId },+ 'Manual insights failed'+ );+ set.status = INTERNAL_ERROR;+ return { ok: false, projectId, error: errorMessage(error) };}-- const jobId = await ctx.queues.insights.insightsProject.add(- { projectId, date },- // Unique id so repeated runs are not deduped by BullMQ.- { jobId: `debug:${projectId}:${Date.now()}` }- );- ctx.logger.info({ projectId, jobId }, 'Enqueued insights job');- return {- ok: true,- projectId,- jobId,- message:- 'Enqueued on the "insights" queue — watch it in bull-board. Add ?inline=1 to run synchronously.',- };- } catch (error) {- ctx.logger.error({ err: error, projectId }, 'Manual insights failed');- set.status = INTERNAL_ERROR;- return { ok: false, projectId, error: errorMessage(error) };- }- },- { params: projectIdParams, detail: HIDDEN }- )- // Weekly digest for ONE project, bypassing eligibility.- // [email protected] → send only to that address- // (no ?to) → return the assembled payload without sending- // ?force=1 → build even with 0 visitors this week- .get(- '/debug/weekly-digest/:projectId',- async ({ params, query, set, ctx }) => {- const { projectId } = params;- const to = typeof query.to === 'string' ? query.to : undefined;- const force = query.force === '1' || query.force === 'true';- ctx.logger.info({ projectId, to, force }, 'Manual weekly digest');-- try {- return {- ok: true,- ...(await ctx.services.insight.previewWeeklyDigest(projectId, {- to,- force,- })),- };- } catch (error) {- ctx.logger.error({ err: error, projectId }, 'Manual digest failed');- set.status = INTERNAL_ERROR;- return { ok: false, projectId, error: errorMessage(error) };- }- },- { params: projectIdParams, detail: HIDDEN }- )-);+ },+ { params: projectIdParams, detail: HIDDEN }+ )+ // Weekly digest for ONE project, bypassing eligibility.+ // [email protected] → send only to that address+ // (no ?to) → return the assembled payload without sending+ // ?force=1 → build even with 0 visitors this week+ .get(+ '/debug/weekly-digest/:projectId',+ async ({ params, query, set, ctx }) => {+ const { projectId } = params;+ const to = typeof query.to === 'string' ? query.to : undefined;+ const force = query.force === '1' || query.force === 'true';+ ctx.logger.info({ projectId, to, force }, 'Manual weekly digest');++ try {+ return {+ ok: true,+ ...(await ctx.services.insight.previewWeeklyDigest(projectId, {+ to,+ force,+ })),+ };+ } catch (error) {+ ctx.logger.error({ err: error, projectId }, 'Manual digest failed');+ set.status = INTERNAL_ERROR;+ return { ok: false, projectId, error: errorMessage(error) };+ }+ },+ { params: projectIdParams, detail: HIDDEN }+ )+ );+};diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.tsindex 9856fdf0b..c110622f4 100644--- a/packages/core/src/http/session.ts+++ b/packages/core/src/http/session.ts@@ -23,7 +23,7 @@// `EMPTY_SESSION` there.import type { Ctx, Session } from '../context';-import { runWithAlsSession } from '../modules/session/src/session-context';+import { runWithAlsSession } from '../shared/als-session';import type { CookieJar } from '../shared/cookie';export const SESSION_COOKIE_NAME = 'session';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 0877a3e74..4cab7208f 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -64,7 +64,6 @@ export { requestContext, requestLogging } from './http/context';// deployment-derived values as arguments — core reads no environment.export type { CorsOptions } from './http/cors';export { CORS_PRIVATE_PATHS, corsDelegator } from './http/cors';-export { debugRoutes } from './http/debug.routes';export type { ErrorHandlerOptions } from './http/errors';export { errorHandler } from './http/errors';// The two runtime seams over the registry (ADR-005). `main.ts` builds@@ -87,7 +86,6 @@ export type {SchedulerFlags,} from './jobs/schedulers';export {- CRON_SCHEDULES,PING_SCHEDULE,schedulersFromRegistry,startSchedulers,@@ -103,7 +101,7 @@ export type {QueueProducers,Queues,} from './jobs.registry';-export { queues } from './jobs.registry';+export { CRON_SCHEDULES, queues } from './jobs.registry';export type { LogFn, Logger, LogLevel } from './logger';export {REQUEST_ID_HEADER,@@ -182,6 +180,13 @@ export {verifyPasswordHash,verifyTotpCode,} from './modules/auth/auth.service';+export type {+ AccessChecks,+ AccessLookups,+ OrganizationAccessLike,+ ProjectAccessLike,+} from './modules/auth/src/access';+export { createAccessChecks } from './modules/auth/src/access';// Moved from packages/db/src/services/auth-session.service.ts (M8-005) —// the Postgres-backed login session CRUD. packages/db keeps a re-export// shim (existing `@openpanel/db` importers, apps/api's app.ts).@@ -342,6 +347,17 @@ export { createDashboardService } from './modules/dashboard/dashboard.service';// module map: email owns "C"); packages/constants keeps a re-export shim.export type { EmailCategory } from './modules/email/email.constants';export { emailCategories } from './modules/email/email.constants';+// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003) — shared by+// the onboarding module and, since M9-003, the organization module's+// wind-down track.+export type {+ RunSequenceOptions,+ SequenceResult,+ SequenceStep,+ SequenceSubject,+ StepResult,+} from './modules/email/src/sequence';+export { runSequence, step } from './modules/email/src/sequence';// Dissolved from @openpanel/db's services/event.service.ts, profile.service.ts// and group.service.ts, plus the query/mutation bodies packages/trpc's// event/profile/group routers held inline and apps/api's profile controller@@ -760,6 +776,10 @@ export {transformReport,transformReportEventItem,} from './modules/report/report.service';+export {+ getChartStartEndDate,+ getDatesFromRange,+} from './modules/report/src/chart-dates';export type { ReportEventItem } from './modules/report/src/series';export {mergeGlobalFilters,@@ -776,7 +796,8 @@ export {createSaltService,} from './modules/salt/salt.service';// Dissolved from @openpanel/db's services/session.service.ts and-// session-context.ts, plus apps/worker's session-end job, reaper and vacuum+// session-context.ts (now shared/als-session.ts), plus apps/worker's+// session-end job, reaper and vacuum// (M7-001, ADR-008's module map: session owns "R,S,J") — packages/trpc's// session router, the assistant/mcp tools and apps/worker's thin delegates// call these directly, the same way V1 reaches every other dissolved service@@ -802,11 +823,6 @@ export {// service here.export type { SessionMetricsRedis } from './modules/session/src/session.metrics';export { registerSessionScrapeMetrics } from './modules/session/src/session.metrics';-export {- als,- getAlsSessionId,- runWithAlsSession,-} from './modules/session/src/session-context';export type {EnqueueSessionEndInput,SessionEndJobData,@@ -869,7 +885,12 @@ export {rawStderrWrite,rawStdoutWrite,} from './pino-logger';-export { dashboardRoutes, opsRoutes, publicApiRoutes } from './rest.routes';+export {+ dashboardRoutes,+ debugRoutes,+ opsRoutes,+ publicApiRoutes,+} from './rest.routes';// The RPC base is on the barrel because it is the seam every module's own// `<name>.rpc.ts` builds its router on: ONE tRPC instance (ADR-009), mounted// by V2's `createTrpcFetchHandler`. V1's now-deleted `@openpanel/trpc`@@ -908,13 +929,6 @@ export {} from './rpc/handler';export type { AppRouter } from './rpc.router';export { appRouter } from './rpc.router';-export type {- AccessChecks,- AccessLookups,- OrganizationAccessLike,- ProjectAccessLike,-} from './shared/access';-export { createAccessChecks } from './shared/access';export type { IProjectAccess } from './shared/access-lookups';export {canWriteProject,@@ -922,6 +936,11 @@ export {getOrganizationAccess,getProjectAccess,} from './shared/access-lookups';+export {+ als,+ getAlsSessionId,+ runWithAlsSession,+} from './shared/als-session';// Dissolved from packages/common/server (M4-003) — a still-live V1 package// (db, queue, apps/worker) reaches these the same way apps/api and core// itself do, until its own module lands. mcp reaches it as an internal@@ -932,23 +951,7 @@ export {hashPassword,verifyPassword,} from './shared/crypto';-export {- getChartPrevStartEndDate,- getChartStartEndDate,- getDatesFromRange,- resolveDateRange,-} from './shared/date';-// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003) — shared by-// the onboarding module and, since M9-003, the organization module's-// wind-down track.-export type {- RunSequenceOptions,- SequenceResult,- SequenceStep,- SequenceSubject,- StepResult,-} from './shared/email-sequence';-export { runSequence, step } from './shared/email-sequence';+export { getChartPrevStartEndDate, resolveDateRange } from './shared/date';export {decrypt,decryptCredential,diff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.tsindex ee5fa43e2..ebf524e2a 100644--- a/packages/core/src/jobs.registry.ts+++ b/packages/core/src/jobs.registry.ts@@ -14,6 +14,10 @@ import { legacyCompat } from './jobs/compat';import type { Producers } from './jobs/define';import { defineQueue } from './jobs/define';import type { ProducerHandle } from './jobs/producers';+import {+ type SchedulerDefinition,+ schedulersFromRegistry,+} from './jobs/schedulers';import { cohortCronJobs, cohortQueueJobs } from './modules/cohort/cohort.jobs';import { eventCronJobs } from './modules/event/event.jobs';import { groupCronJobs } from './modules/group/group.jobs';@@ -149,6 +153,15 @@ export const queues = {export type Queues = typeof queues;+// V1's exact 19 always-on scheduler ids and cadences+// (apps/worker/src/boot-cron.ts), derived from the `cron` queue's own jobs so a+// job and its schedule cannot drift apart (ADR-021). It is computed HERE, in+// the registry, and not in `jobs/schedulers.ts`: that file is transport+// infrastructure and may not import a registry (ADR-022 R22). `ping` is the+// 20th and is conditional — see `PING_SCHEDULE` and `startSchedulers`.+export const CRON_SCHEDULES: readonly SchedulerDefinition[] =+ schedulersFromRegistry(cron);+/** What `ctx.queues` is: `ctx.queues.import.run.add({ importId })`. */export type QueueProducers = Producers<Queues>;diff --git a/packages/core/src/jobs/schedulers.test.ts b/packages/core/src/jobs/schedulers.test.tsindex c276c2922..420c3eb37 100644--- a/packages/core/src/jobs/schedulers.test.ts+++ b/packages/core/src/jobs/schedulers.test.ts@@ -1,7 +1,7 @@import { expect, test } from 'bun:test';+import { CRON_SCHEDULES } from '../jobs.registry';import type { Logger } from '../logger';import {- CRON_SCHEDULES,PING_SCHEDULE,type SchedulerQueue,startSchedulers,@@ -121,6 +121,7 @@ test('ping is excluded by default — neither self-hosted nor production', asyncqueue,flags: { selfHosted: false, production: false },logger: stubLogger(),+ schedulers: CRON_SCHEDULES,});const upsertedIds = queue.calls.upserted.map((u) => u.id).sort();@@ -135,6 +136,7 @@ test('ping is excluded when self-hosted but not production', async () => {queue,flags: { selfHosted: true, production: false },logger: stubLogger(),+ schedulers: CRON_SCHEDULES,});expect(queue.calls.upserted.map((u) => u.id)).not.toContain('ping');@@ -147,6 +149,7 @@ test('ping is excluded when production but not self-hosted', async () => {queue,flags: { selfHosted: false, production: true },logger: stubLogger(),+ schedulers: CRON_SCHEDULES,});expect(queue.calls.upserted.map((u) => u.id)).not.toContain('ping');@@ -159,6 +162,7 @@ test('ping is included only when self-hosted AND production', async () => {queue,flags: { selfHosted: true, production: true },logger: stubLogger(),+ schedulers: CRON_SCHEDULES,});const upsertedIds = queue.calls.upserted.map((u) => u.id).sort();diff --git a/packages/core/src/jobs/schedulers.ts b/packages/core/src/jobs/schedulers.tsindex c3cf1a1de..42170d5e2 100644--- a/packages/core/src/jobs/schedulers.ts+++ b/packages/core/src/jobs/schedulers.ts@@ -6,10 +6,10 @@//// ADR-021: the scheduler list is no longer a second, hand-maintained registry// — it is derived from the `cron` queue's own jobs, so a job and its schedule-// cannot drift apart. This file imports no module; `schedulersFromRegistry`-// takes the registry's `cron` queue as data.+// cannot drift apart. `schedulersFromRegistry` takes the registry's `cron`+// queue as data; the registry itself calls it and exports the result as+// `CRON_SCHEDULES`, so this file imports nothing above it (ADR-022 R22).-import { queues } from '../jobs.registry';import type { Logger } from '../logger';import type { AnyJob, QueueDefinition, RepeatSchedule } from './define';import { wrap } from './envelope';@@ -84,12 +84,6 @@ export function schedulersFromRegistry(return schedulers.sort((a, b) => a.id.localeCompare(b.id));}-// V1's exact 19 always-on scheduler ids and cadences-// (apps/worker/src/boot-cron.ts). `ping` is the 20th and is conditional —-// see `PING_SCHEDULE` and `startSchedulers`.-export const CRON_SCHEDULES: readonly SchedulerDefinition[] =- schedulersFromRegistry(queues.cron);-// V1 gated this on `SELF_HOSTED && NODE_ENV === 'production'`// (apps/worker/src/boot-cron.ts:133). `misc.jobs.ts`'s `ping` job declares// `cron: null` for exactly this reason — it is never in `CRON_SCHEDULES`.@@ -102,8 +96,9 @@ export interface StartSchedulersOptions {queue: SchedulerQueue;flags: SchedulerFlags;logger: Logger;- /** Defaults to the V1 cron set; overridable so a test can use a small fixture. */- schedulers?: readonly SchedulerDefinition[];+ /** The derived cron set — `jobs.registry.ts`'s `CRON_SCHEDULES` in the app,+ * a small fixture in a test. */+ schedulers: readonly SchedulerDefinition[];}/**@@ -119,7 +114,7 @@ export async function startSchedulers({queue,flags,logger,- schedulers = CRON_SCHEDULES,+ schedulers,}: StartSchedulersOptions): Promise<void> {const desired =flags.selfHosted && flags.productiondiff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex 759535322..f2ff258cd 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -13,7 +13,7 @@// 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 `shared/cacheable-per-deps.ts`+// while two requests do not — the same trade `cacheable-per-deps.ts`// records for the cross-module caches.import type { ServiceDeps, Services } from '../../services';diff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.tsindex c10a6d0f6..2530269a0 100644--- a/packages/core/src/modules/assistant/src/filter-command.ts+++ b/packages/core/src/modules/assistant/src/filter-command.ts@@ -16,10 +16,7 @@ import {import { z } from 'zod';import type { CoreConfig } from '../../../config';import type { ServiceDeps } from '../../../services';-import {- getDatesFromRange,- resolveDateRange as resolveDateRangeCore,-} from '../../../shared/date';+import { resolveDateRange as resolveDateRangeCore } from '../../../shared/date';import { listEventNamesCore } from '../../event/event.service';import { getTrafficBreakdownCore } from '../../overview/overview.service';import { getTopPagesCore } from '../../overview/pages.service';@@ -31,6 +28,7 @@ import {timeWindows,zRange,} from '../../report/report.constants';+import { getDatesFromRange } from '../../report/src/chart-dates';import {CHAT_MODELS,type ChatModelEntry,diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.tsindex 3b97a2554..32d93520e 100644--- a/packages/core/src/modules/assistant/src/report-runner.ts+++ b/packages/core/src/modules/assistant/src/report-runner.ts@@ -14,11 +14,11 @@import type { CoreConfig } from '../../../config';import type { ServiceDeps } from '../../../services';-import { getChartStartEndDate } from '../../../shared/date';import { executeAggregateChart, executeChart } from '../../chart/chart.service';import { getFunnel } from '../../chart/funnel.service';import { getSettingsForProject } from '../../organization/organization.service';import { getReportById } from '../../report/report.service';+import { getChartStartEndDate } from '../../report/src/chart-dates';const DEFAULT_DASHBOARD_URL = 'https://dashboard.openpanel.dev';const TRAILING_SLASH = /\/$/;diff --git a/packages/core/src/modules/assistant/src/tools/dashboard.ts b/packages/core/src/modules/assistant/src/tools/dashboard.tsindex 1a01688ea..41e1080d8 100644--- a/packages/core/src/modules/assistant/src/tools/dashboard.ts+++ b/packages/core/src/modules/assistant/src/tools/dashboard.ts@@ -1,6 +1,5 @@import { z } from 'zod';import type { ServiceDeps } from '../../../../services';-import { getChartStartEndDate } from '../../../../shared/date';import {executeAggregateChart,executeChart,@@ -10,6 +9,7 @@ import { getDashboardById } from '../../../dashboard/dashboard.service';import { getSettingsForProject } from '../../../organization/organization.service';import type { IChartRange, IInterval } from '../../../report/report.constants';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,diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.tsindex 8b901794b..3baa24152 100644--- a/packages/core/src/modules/assistant/src/tools/helpers.ts+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts@@ -5,14 +5,12 @@ import {} from '@better-agent/core';import type { z } from 'zod';import type { CoreConfig } from '../../../../config';-import {- getDatesFromRange,- resolveDateRange as resolveDateRangeCore,-} from '../../../../shared/date';+import { resolveDateRange as resolveDateRangeCore } from '../../../../shared/date';import type {IChartEventFilter,IChartRange,} from '../../../report/report.constants';+import { getDatesFromRange } from '../../../report/src/chart-dates';import type { ChatAgentContext, PageContext } from '../context';import { chatRunContext } from '../run-context';diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.tsindex b95f04a12..207ea2dbf 100644--- a/packages/core/src/modules/auth/auth.service.access.test.ts+++ b/packages/core/src/modules/auth/auth.service.access.test.ts@@ -1,5 +1,5 @@// M10-002 (docs/TECH_DEBT.md §5b): auth.service.ts is now the ONLY place-// `shared/access.ts`'s ladder is bound to real lookups, via the lazy,+// 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 alldiff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 1c8a194d0..e7610c913 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -3,7 +3,7 @@// Prisma-touching half — creating, validating and invalidating a `sessions`// row — moved here too (M8-005, `./src/login-session.ts`).//-// M10-002 (docs/TECH_DEBT.md §5b): the permission ladder (`shared/access.ts`)+// M10-002 (docs/TECH_DEBT.md §5b): 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.@@ -18,13 +18,13 @@import { z } from 'zod';import type { CoreConfig } from '../../config';import type { ServiceDeps, Services } from '../../services';-import { type AccessChecks, createAccessChecks } from '../../shared/access';import type {getClientAccess as GetClientAccessFn,getOrganizationAccess as GetOrganizationAccessFn,IProjectAccess,} from '../../shared/access-lookups';import type { ISetCookie } from '../../shared/cookie';+import { type AccessChecks, createAccessChecks } from './src/access';import {deleteSessionTokenCookie,setLastAuthProviderCookie,@@ -94,7 +94,7 @@ type ProjectAccessChecks = AccessChecks<IProjectAccess>;let accessChecksPromise: Promise<ProjectAccessChecks> | undefined;/**- * The single binding of `shared/access.ts`'s ladder to real lookups+ * The single binding of the ladder to real lookups* (M10-002, docs/TECH_DEBT.md §5b) — lazy AND memoized: `createAccessChecks`* itself runs exactly once per process, on however many requests, no matter* how many of this function's callers invoke it. Nothing here runs atdiff --git a/packages/core/src/shared/access.ts b/packages/core/src/modules/auth/src/access.tssimilarity index 94%rename from packages/core/src/shared/access.tsrename to packages/core/src/modules/auth/src/access.tsindex 9fc37d7b0..0e7301fd4 100644--- a/packages/core/src/shared/access.ts+++ b/packages/core/src/modules/auth/src/access.ts@@ -1,4 +1,7 @@-// The permission ladder (ADR-007 layout: `shared/access`).+// The permission ladder. M15-009 (ADR-022 R10/R22): it lives in the auth+// module, not in `shared/` — it threw a transport error (`TRPCForbiddenError`)+// from the bottom layer, and R10 puts every access check in the auth service+// and the procedure builders.//// Ported verbatim from packages/trpc/src/access.ts — the rules, the fail-closed// ordering and the messages are unchanged, and ADR-011 invariants 5 and 6 bind@@ -13,7 +16,7 @@// now-deleted `@openpanel/trpc` used to bind it the same way; a test binds// it to two functions.-import { TRPCForbiddenError } from '../rpc/errors';+import { TRPCForbiddenError } from '../../../rpc/errors';/** What a project access row has to expose for the ladder to read it. */export interface ProjectAccessLike {diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex 12818dfa8..edc79b384 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -20,10 +20,7 @@import { flatten, map, pipe, prop, sort, uniq } from 'ramda';import type { ServiceDeps, Services } from '../../services';-import {- getChartPrevStartEndDate,- getChartStartEndDate,-} from '../../shared/date';+import { getChartPrevStartEndDate } from '../../shared/date';import { getEventMetasCached } from '../event/event.service';import { getSettingsForProject } from '../organization/organization.service';import {@@ -41,6 +38,7 @@ import type {IReportInput,} from '../report/report.constants';import type { IServiceReport } from '../report/report.service';+import { getChartStartEndDate } from '../report/src/chart-dates';import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';import { createConversionService, getConversion } from './conversion.service';import {diff --git a/packages/core/src/modules/chart/src/engine/format.ts b/packages/core/src/modules/chart/src/engine/format.tsindex 9c687e599..3f5d909ca 100644--- a/packages/core/src/modules/chart/src/engine/format.ts+++ b/packages/core/src/modules/chart/src/engine/format.ts@@ -1,14 +1,8 @@-import {- average,- getPreviousMetric,- max,- min,- round,- sum,-} from '../../../../shared/math';+import { average, max, min, round, sum } from '../../../../shared/math';import { slug } from '../../../../shared/slug';import type { FinalChart } from '../../../report/report.constants';import { alphabetIds } from '../../../report/report.constants';+import { getPreviousMetric } from '../../../report/src/previous-metric';import type { ConcreteSeries } from './types';/**diff --git a/packages/core/src/modules/chart/src/engine/normalize.ts b/packages/core/src/modules/chart/src/engine/normalize.tsindex 98908f888..babc51e5b 100644--- a/packages/core/src/modules/chart/src/engine/normalize.ts+++ b/packages/core/src/modules/chart/src/engine/normalize.ts@@ -1,5 +1,4 @@import type { ServiceDeps } from '../../../../services';-import { getChartStartEndDate } from '../../../../shared/date';import { getSettingsForProject } from '../../../organization/organization.service';import type {IChartEvent,@@ -7,6 +6,7 @@ import type {IReportInputWithDates,} from '../../../report/report.constants';import { alphabetIds } from '../../../report/report.constants';+import { getChartStartEndDate } from '../../../report/src/chart-dates';import { mergeGlobalFilters } from '../../../report/src/series';import type { SeriesDefinition } from './types';diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.tsindex 456e27b46..5430a1ea8 100644--- a/packages/core/src/modules/client/client.service.ts+++ b/packages/core/src/modules/client/client.service.ts@@ -25,8 +25,8 @@import crypto from 'node:crypto';import type { Client, Prisma } from '@openpanel/db/src/prisma-client';+import { cacheablePerDb, type DbScope } from '../../cacheable-per-deps';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDb, type DbScope } from '../../shared/cacheable-per-deps';import { hashPassword } from '../auth/auth.service';export type IServiceClient = Client;diff --git a/packages/core/src/modules/cohort/cohort.service.test.ts b/packages/core/src/modules/cohort/cohort.service.test.tsindex 61dcdd59c..bb2cac16d 100644--- a/packages/core/src/modules/cohort/cohort.service.test.ts+++ b/packages/core/src/modules/cohort/cohort.service.test.ts@@ -2,7 +2,7 @@// `deps.ch` ARE the fakes below — the two `@openpanel/db` module mocks this// file used to install (and had to carefully restore, because `mock.module`// has no per-file scope without `--isolate`) are gone. The one module still-// mocked is core's own `shared/ch-query`, which is what the subject now calls.+// mocked is core's own `ch-query`, which is what the subject now calls.//// The pure SQL-shape builders (buildEventCriteriaQuery,// buildPropertyBasedCohortQuery, deriveCohortQuerySettings) have their own@@ -59,19 +59,19 @@ const chInsert = mock(async (_args: { table: string }) => undefined);const chCommand = mock(async (_args: { query: string }) => undefined);// The subject reaches ClickHouse through core's own `chQuery(deps, ...)`-// (shared/ch-query.ts) — mocking that one module keeps this file off+// (ch-query.ts) — mocking that one module keeps this file off// @openpanel/db's live-bound client singleton entirely. `mock.module` still// 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 just re-apply the mock.-const realChQuery = { ...(await import('../../shared/ch-query')) };-mock.module('../../shared/ch-query', () => ({+const realChQuery = { ...(await import('../../ch-query')) };+mock.module('../../ch-query', () => ({...realChQuery,chQuery: (_deps: unknown, ...args: unknown[]) => chQuery(...(args as [])),}));afterAll(() => {- mock.module('../../shared/ch-query', () => realChQuery);+ mock.module('../../ch-query', () => realChQuery);});const deps = {diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.tsindex a92c87af7..edf95cfa4 100644--- a/packages/core/src/modules/cohort/cohort.service.ts+++ b/packages/core/src/modules/cohort/cohort.service.ts@@ -38,9 +38,9 @@import type { ClickHouseSettings } from '@clickhouse/client';import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import { chQuery } from '../../ch-query';import type { CoreConfig } from '../../config';import type { ServiceDeps, Services } from '../../services';-import { chQuery } from '../../shared/ch-query';import type { IServiceProfile } from '../profile/profile.service';import type { IChartEventFilter } from '../report/report.constants';import type {diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.tsindex 7160153a7..a3164e65f 100644--- a/packages/core/src/modules/dashboard/dashboard.service.ts+++ b/packages/core/src/modules/dashboard/dashboard.service.ts@@ -12,7 +12,7 @@ import type { Dashboard, Prisma } from '@openpanel/db/src/prisma-client';import { PrismaError } from 'prisma-error-enum';import { TRPCNotFoundError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';-import { getId } from '../../shared/slug-id';+import { getId } from '../../slug-id';import { getProjectById } from '../project/project.service';export type IServiceDashboard = Dashboard;diff --git a/packages/core/src/shared/email-sequence.test.ts b/packages/core/src/modules/email/src/sequence.test.tssimilarity index 95%rename from packages/core/src/shared/email-sequence.test.tsrename to packages/core/src/modules/email/src/sequence.test.tsindex fc327e865..6da599b1b 100644--- a/packages/core/src/shared/email-sequence.test.ts+++ b/packages/core/src/modules/email/src/sequence.test.ts@@ -13,15 +13,15 @@ const sendEmail = mock(_options: unknown): Promise<Record<string, unknown> | null> => ({}));-mock.module('../clients/email', () => ({ sendEmail }));+mock.module('../../../clients/email', () => ({ sendEmail }));-let runSequence: typeof import('./email-sequence').runSequence;-let step: typeof import('./email-sequence').step;-type SequenceStep<TCtx> = import('./email-sequence').SequenceStep<TCtx>;-type SequenceSubject<TCtx> = import('./email-sequence').SequenceSubject<TCtx>;+let runSequence: typeof import('./sequence').runSequence;+let step: typeof import('./sequence').step;+type SequenceStep<TCtx> = import('./sequence').SequenceStep<TCtx>;+type SequenceSubject<TCtx> = import('./sequence').SequenceSubject<TCtx>;beforeAll(async () => {- ({ runSequence, step } = await import('./email-sequence'));+ ({ runSequence, step } = await import('./sequence'));});interface Ctx {diff --git a/packages/core/src/shared/email-sequence.ts b/packages/core/src/modules/email/src/sequence.tssimilarity index 96%rename from packages/core/src/shared/email-sequence.tsrename to packages/core/src/modules/email/src/sequence.tsindex 6bc6dceb7..45d45a964 100644--- a/packages/core/src/shared/email-sequence.ts+++ b/packages/core/src/modules/email/src/sequence.ts@@ -1,8 +1,9 @@-// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003). Shared by+// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003), and out of+// `shared/` at M15-009 (ADR-022 R22): 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, which joined it at M9-003 when-// apps/worker was deleted). `shared/`, not a module, because two modules need-// it (ADR-007 layout: "shared/ when several backend modules need it").+// (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@@ -28,8 +29,8 @@ import {type EmailData,type EmailTemplate,sendEmail,-} from '../clients/email';-import type { Logger } from '../logger';+} from '../../../clients/email';+import type { Logger } from '../../../logger';/*** - `true` send it nowdiff --git a/packages/core/src/modules/event/event.rpc.ts b/packages/core/src/modules/event/event.rpc.tsindex df9b664f3..01aa0cf3e 100644--- a/packages/core/src/modules/event/event.rpc.ts+++ b/packages/core/src/modules/event/event.rpc.ts@@ -18,13 +18,13 @@import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';import { TRPCNotFoundError } from '../../rpc/errors';-import { getChartStartEndDate } from '../../shared/date';import { getSettingsForProject } from '../organization/organization.service';import {zChartEventFilter,zRange,zTimeInterval,} from '../report/report.constants';+import { getChartStartEndDate } from '../report/src/chart-dates';import {getBotEventsPage,getConversionEventNames,diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.tsindex be468d697..93c1e9934 100644--- a/packages/core/src/modules/event/event.service.ts+++ b/packages/core/src/modules/event/event.service.ts@@ -19,7 +19,7 @@//// M10-005: every function that touches a database takes `ServiceDeps` and// reaches Postgres as `deps.db`, ClickHouse as `deps.ch` (through-// shared/ch-query.ts) and the event/bot buffers as `deps.buffers.*`. The+// ch-query.ts) and the event/bot buffers as `deps.buffers.*`. The// `loadDb` / `loadChClient` / `loadDbBuffers` lazy loaders are gone, and so// are the two `import('@openpanel/core')` self-barrel hops this file made for// `resolveDateRange` — imported straight from `shared/`@@ -29,9 +29,9 @@import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import type { EventMeta, Prisma } from '@openpanel/db/src/prisma-client';import { clone, mergeDeepRight, uniq } from 'ramda';+import { cacheablePerDeps } from '../../cacheable-per-deps';+import { chQuery } from '../../ch-query';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDeps } from '../../shared/cacheable-per-deps';-import { chQuery } from '../../shared/ch-query';import { DateTime, resolveDateRange } from '../../shared/date';import { toDots } from '../../shared/object';import { getEventFiltersWhereClause } from '../chart/src/filter-where';diff --git a/packages/core/src/modules/export/export.routes.ts b/packages/core/src/modules/export/export.routes.tsindex 572bfdddf..d148cbb75 100644--- a/packages/core/src/modules/export/export.routes.ts+++ b/packages/core/src/modules/export/export.routes.ts@@ -31,7 +31,7 @@ import type { Ctx } from '../../context';import type { ClientType } from '../../http/client-auth';import { defineRoutes } from '../../http/define';import { parseQueryStringTransform } from '../../http/query';-import { DateTime, getChartStartEndDate } from '../../shared/date';+import { DateTime } from '../../shared/date';import { HttpError } from '../../shared/errors';import type { GetEventListOptions } from '../event/event.service';import {@@ -83,6 +83,7 @@ import {zRange,zReport,} from '../report/report.constants';+import { getChartStartEndDate } from '../report/src/chart-dates';import { querySessionsCore } from '../session/session.service';import {resolveExportProjectId,diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.tsindex c1b805488..d5ef42424 100644--- a/packages/core/src/modules/export/export.service.ts+++ b/packages/core/src/modules/export/export.service.ts@@ -15,10 +15,11 @@import type { AuthenticatedClient } from '../../http/client-auth';import type { ServiceDeps, Services } from '../../services';-import { getChartStartEndDate, resolveDateRange } from '../../shared/date';+import { resolveDateRange } from '../../shared/date';import { getSettingsForProject } from '../organization/organization.service';import { resolveClientProjectId } from '../project/project.service';import type { IChartRange } from '../report/report.constants';+import { getChartStartEndDate } from '../report/src/chart-dates';export type ProjectIdResolution =| { ok: true; projectId: string }diff --git a/packages/core/src/modules/group/group.service.ts b/packages/core/src/modules/group/group.service.tsindex 640d646b8..38851d2b5 100644--- a/packages/core/src/modules/group/group.service.ts+++ b/packages/core/src/modules/group/group.service.ts@@ -8,12 +8,12 @@// with a result-set proof each, per ADR-013.//// M10-005: every function takes `ServiceDeps` and reaches ClickHouse as-// `deps.ch` — reads through shared/ch-query.ts, the one write (`writeGroupToCh`)+// `deps.ch` — reads through ch-query.ts, the one write (`writeGroupToCh`)// through `deps.ch.insert`. The `loadChClient` lazy loader is gone// (docs/TECH_DEBT.md §2, §4).+import { chQuery } from '../../ch-query';import type { ServiceDeps, Services } from '../../services';-import { chQuery } from '../../shared/ch-query';import { toDots } from '../../shared/object';import { getProfiles, type IServiceProfile } from '../profile/profile.service';import { formatClickhouseDate, toNullIfDefaultMinDate } from './src/dates';diff --git a/packages/core/src/modules/gsc/gsc.service.test.ts b/packages/core/src/modules/gsc/gsc.service.test.tsindex 13b95dc88..6897f8e1c 100644--- a/packages/core/src/modules/gsc/gsc.service.test.ts+++ b/packages/core/src/modules/gsc/gsc.service.test.ts@@ -101,13 +101,13 @@ const ch = {// M10-009: 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 `shared/ch-query`, which is what+// 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.-const realChQuery = { ...(await import('../../shared/ch-query')) };-mock.module('../../shared/ch-query', () => ({+const realChQuery = { ...(await import('../../ch-query')) };+mock.module('../../ch-query', () => ({...realChQuery,chQuery: (_deps: unknown, ...args: unknown[]) => chQuery(...(args as [])),}));@@ -138,12 +138,12 @@ mock.module('@openpanel/redis', () => ({// file runs next sees real behavior again.afterAll(() => {mock.module('@openpanel/redis', () => realRedis);- mock.module('../../shared/ch-query', () => realChQuery);+ mock.module('../../ch-query', () => realChQuery);mock.module('../organization/organization.service',() => realOrganizationService);- mock.module('../../shared/date', () => realSharedDate);+ mock.module('../report/src/chart-dates', () => realSharedDate);});const validateAuthorizationCode = mock(async () => ({@@ -184,8 +184,8 @@ mock.module('../organization/organization.service', () => ({...realOrganizationService,getSettingsForProject,}));-const realSharedDate = { ...(await import('../../shared/date')) };-mock.module('../../shared/date', () => ({+const realSharedDate = { ...(await import('../report/src/chart-dates')) };+mock.module('../report/src/chart-dates', () => ({...realSharedDate,getChartStartEndDate,}));diff --git a/packages/core/src/modules/gsc/gsc.service.ts b/packages/core/src/modules/gsc/gsc.service.tsindex 149eba746..4a80e3616 100644--- a/packages/core/src/modules/gsc/gsc.service.ts+++ b/packages/core/src/modules/gsc/gsc.service.ts@@ -24,12 +24,12 @@// tag: ADR-013 converts the analytics read path one query per P7 task, and// this module's queries haven't been converted yet.+import { cacheablePerDeps } from '../../cacheable-per-deps';+import { chQuery } from '../../ch-query';import type { CoreConfig } from '../../config';import type { Logger } from '../../logger';import { TRPCNotFoundError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDeps } from '../../shared/cacheable-per-deps';-import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import { decrypt, encrypt } from '../../shared/encryption';import { googleGscClient } from '../auth/auth.service';@@ -794,7 +794,7 @@ export async function resolveGscDateRange(const { getSettingsForProject } = await import('../organization/organization.service');- const { getChartStartEndDate } = await import('../../shared/date');+ const { getChartStartEndDate } = await import('../report/src/chart-dates');const { timezone } = await getSettingsForProject(deps, projectId);const { startDate, endDate } = getChartStartEndDate({diff --git a/packages/core/src/modules/health/health.routes.ts b/packages/core/src/modules/health/health.routes.tsindex 0866ee338..99ae3834b 100644--- a/packages/core/src/modules/health/health.routes.ts+++ b/packages/core/src/modules/health/health.routes.ts@@ -14,8 +14,8 @@// and self-hosters use it as a "is this thing on" check.import { z } from 'zod';+import { chQuery } from '../../ch-query';import { defineRoutes } from '../../http/define';-import { chQuery } from '../../shared/ch-query';import { tryCatch } from '../../shared/try-catch';import { currentReadiness } from './src/readiness';@@ -74,7 +74,7 @@ export const healthRoutes = defineRoutes((app) =>async ({ ctx, set }) => {// core's own `chQuery` over `ctx.ch` — the same round-robin + retry// proxy every real read takes (M10-009; `ctx.ch.query` IS- // `withRetry(client => client.query(...))`, see shared/ch-query.ts).+ // `withRetry(client => client.query(...))`, see ch-query.ts).const [redisResult, dbResult, chResult] = await Promise.all([tryCatch(async () => (await ctx.redis.ping()) === 'PONG'),tryCatch(async () => Boolean(await ctx.db.$executeRaw`SELECT 1`)),diff --git a/packages/core/src/modules/ingest/ingest.routes.ts b/packages/core/src/modules/ingest/ingest.routes.tsindex 2feba5e54..ad913f4d8 100644--- a/packages/core/src/modules/ingest/ingest.routes.ts+++ b/packages/core/src/modules/ingest/ingest.routes.ts@@ -30,6 +30,7 @@import type { AppDeps, HttpCtx } from '../../context';import { defineRoutes } from '../../http/define';+import { toIngestHeaders } from '../../shared/headers';import type { DeprecatedPostEventPayload } from './ingest.constants';import { zTrackHandlerPayload } from './ingest.constants';import {@@ -41,7 +42,7 @@ import {isIngestionWoundDown,type TrackOutcome,} from './ingest.service';-import { toIngestHeaders } from './src/headers';+import { validateIngestRequest } from './src/client-auth';import { recordLegacyEventRequest } from './src/ingest.metrics';// The Kafka producer is a sibling now (M11-003), not an `AppDeps` field:// kafka.ts moved into this module, so there is nothing left for main.ts to@@ -187,7 +188,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>return respondToOutcome(outcome, status);},{- clientAuth: { ingest: true },+ clientAuth: { ingest: validateIngestRequest },body: zTrackHandlerPayload,beforeHandle: [botGuard, windDownGuard(deps)],detail: {@@ -227,7 +228,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>}},{- clientAuth: { ingest: true },+ clientAuth: { ingest: validateIngestRequest },beforeHandle: [botGuard, windDownGuard(deps)],detail: {tags: TAGS,@@ -263,7 +264,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>return status(ACCEPTED_STATUS, 'ok');},{- clientAuth: { ingest: true },+ clientAuth: { ingest: validateIngestRequest },// V1's own order: the usage metric is a `preHandler` registered// after `clientHook` and before `isBotHook`/`subscriptionHook`.beforeHandle: [diff --git a/packages/core/src/modules/ingest/ingest.service.ts b/packages/core/src/modules/ingest/ingest.service.tsindex 325eab43d..81a39446b 100644--- a/packages/core/src/modules/ingest/ingest.service.ts+++ b/packages/core/src/modules/ingest/ingest.service.ts@@ -17,6 +17,7 @@ import { assocPath, pathOr, pick } from 'ramda';import { v4 as uuid } from 'uuid';import type { Buffers } from '../../buffers/create-buffers';import { resolveSessionTimeoutMs } from '../../buffers/session-buffer';+import type { DbScope } from '../../cacheable-per-deps';import {type AsnInfo,type GeoLocation,@@ -25,7 +26,7 @@ import {} from '../../clients/geo';import type { Logger } from '../../logger';import type { ServiceDeps, Services } from '../../services';-import type { DbScope } from '../../shared/cacheable-per-deps';+import { headerValue, type IngestHeaders } from '../../shared/headers';import { generateId } from '../../shared/id';import { parseUserAgent } from '../../shared/parser-user-agent';import { generateDeviceId } from '../../shared/profileId';@@ -53,12 +54,12 @@ import { isBot } from './src/bots/detect';import { applyBotSuspicion, stripBotProperties } from './src/bots/suspicion';import { isDuplicatedEvent } from './src/deduplicate';import { getDeviceId } from './src/device-id';-import { headerValue, type IngestHeaders } from './src/headers';import type {IncomingEventPayload,IncomingEventProducer,} from './src/incoming-event';+export type { IngestHeaders } from '../../shared/headers';export type { BotMatch } from './src/bots/detect';export { detectBot, isBot } from './src/bots/detect';export {@@ -75,7 +76,6 @@ export {} from './src/client-auth';export { isDuplicatedEvent } from './src/deduplicate';export { getDeviceId } from './src/device-id';-export type { IngestHeaders } from './src/headers';export type {IncomingEventPayload,IncomingEventProducer,diff --git a/packages/core/src/modules/ingest/src/client-auth.ts b/packages/core/src/modules/ingest/src/client-auth.tsindex fa0fabffb..778472142 100644--- a/packages/core/src/modules/ingest/src/client-auth.ts+++ b/packages/core/src/modules/ingest/src/client-auth.ts@@ -1,8 +1,9 @@// The ingest tier of caller authentication (ADR-011 A-i's "ingest extension",// ported verbatim from apps/api/src/utils/auth.ts's `validateSdkRequest`).// apps/api's `clientHook` is a thin delegate over this; core's `clientAuth`-// macro reaches it through http/client-auth.ts when a route asks for-// `{ ingest: true }`.+// macro reaches it through http/client-auth.ts, which a route hands this+// function to as `clientAuth: { ingest: validateIngestRequest }` (ADR-022 R22:+// transport never deep-imports a module).//// Everything here is behaviour V1 relies on and none of it is decoration: the// `ignoreCorsAndSecret` short-circuit, the unanchored wildcard origin regex,@@ -14,8 +15,9 @@import { getCache } from '@openpanel/redis';import { path } from 'ramda';-import type { DbScope } from '../../../shared/cacheable-per-deps';+import type { DbScope } from '../../../cacheable-per-deps';import { verifyPassword } from '../../../shared/crypto';+import { headerValue, type IngestHeaders } from '../../../shared/headers';import {getClientByIdCached,type IServiceClientWithProject,@@ -24,9 +26,8 @@ import type {IProjectFilterIp,IProjectFilterProfileId,} from '../../project/project.constants';-import { headerValue, type IngestHeaders } from './headers';-export type { IngestHeaders } from './headers';+export type { IngestHeaders } from '../../../shared/headers';const CLIENT_ID_UUID_REGEX =/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;diff --git a/packages/core/src/modules/insight/src/cached-query.test.ts b/packages/core/src/modules/insight/src/cached-query.test.tsindex 5b3698212..4a9fa2580 100644--- a/packages/core/src/modules/insight/src/cached-query.test.ts+++ b/packages/core/src/modules/insight/src/cached-query.test.ts@@ -11,7 +11,7 @@import { expect, test } from 'bun:test';import { sql } from '@openpanel/db/src/clickhouse/sql';-import type { ChScope } from '../../../shared/ch-query';+import type { ChScope } from '../../../ch-query';import { createStatementCache } from './cached-query';function fakeDeps(diff --git a/packages/core/src/modules/insight/src/cached-query.ts b/packages/core/src/modules/insight/src/cached-query.tsindex d267a9776..690d30f70 100644--- a/packages/core/src/modules/insight/src/cached-query.ts+++ b/packages/core/src/modules/insight/src/cached-query.ts@@ -17,7 +17,7 @@import crypto from 'node:crypto';import type { ClickHouseSettings } from '@clickhouse/client';import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';-import { type ChScope, chQuery } from '../../../shared/ch-query';+import { type ChScope, chQuery } from '../../../ch-query';/** clix's own default when a call site passed no timezone. */const DEFAULT_SESSION_TIMEZONE = 'UTC';diff --git a/packages/core/src/modules/insight/src/engine.ts b/packages/core/src/modules/insight/src/engine.tsindex 7222d76dc..f38250006 100644--- a/packages/core/src/modules/insight/src/engine.ts+++ b/packages/core/src/modules/insight/src/engine.ts@@ -1,4 +1,4 @@-import type { ChScope } from '../../../shared/ch-query';+import type { ChScope } from '../../../ch-query';import { createStatementCache } from './cached-query';import { materialDecision } from './material';import { defaultImpactScore, severityBand } from './scoring';diff --git a/packages/core/src/modules/insight/src/legacy-scan.ts b/packages/core/src/modules/insight/src/legacy-scan.tsindex 28e89e9aa..ce5ff57e0 100644--- a/packages/core/src/modules/insight/src/legacy-scan.ts+++ b/packages/core/src/modules/insight/src/legacy-scan.ts@@ -21,8 +21,8 @@ import {type SqlParam,sql,} from '@openpanel/db/src/clickhouse/sql';+import { type ChScope, chQuery } from '../../../ch-query';import { formatClickhouseDate } from '../../../shared/ch-dates';-import { type ChScope, chQuery } from '../../../shared/ch-query';/** clix sent `session_timezone` on every `execute()`, defaulting to `'UTC'`. */const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;diff --git a/packages/core/src/modules/insight/src/referrer-spikes.ts b/packages/core/src/modules/insight/src/referrer-spikes.tsindex d88b22fa1..7e7d12658 100644--- a/packages/core/src/modules/insight/src/referrer-spikes.ts+++ b/packages/core/src/modules/insight/src/referrer-spikes.ts@@ -8,9 +8,9 @@// no `query_params` slot to carry them through. clix always sent// `session_timezone` (query-builder.ts:562) — `chQuery` gets the same value.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import { chQuery } from '../../../ch-query';import type { ServiceDeps } from '../../../services';import { convertClickhouseDateToJs } from '../../../shared/ch-dates';-import { chQuery } from '../../../shared/ch-query';import { TABLE_NAMES } from '../../../shared/ch-tables';import { getRawWhereClause } from '../../overview/overview.service';import type {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 617f259c1..0f4916764 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@@ -2,7 +2,7 @@ import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';import type { ServiceDeps } from '../../../../../services';// M10-005: `findProfilesCore` takes `ServiceDeps` and reaches ClickHouse as-// `deps.ch` (through shared/ch-query.ts), so the client is HANDED IN rather+// `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.const chQuery = mock(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 56062ee76..813b2c48b 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@@ -1,7 +1,7 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { sql } from '@openpanel/db/src/clickhouse/sql';import { z } from 'zod';-import { chQuery } from '../../../../../shared/ch-query';+import { chQuery } from '../../../../../ch-query';import { TABLE_NAMES } from '../../../../../shared/ch-tables';import { EVENT_COLUMNS } from '../../../../event/event.service';import {diff --git a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.tsindex 35e93cb79..0157a14e8 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts@@ -2,7 +2,6 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import type { CoreConfig } from '../../../../../config';import type { ServiceDeps } from '../../../../../services';-import { getChartStartEndDate } from '../../../../../shared/date';import {executeAggregateChart,executeChart,@@ -13,6 +12,7 @@ import {getReportById,getReportsByDashboardId,} from '../../../../report/report.service';+import { getChartStartEndDate } from '../../../../report/src/chart-dates';import { dashboardBaseUrl } from '../dashboard-links';import {type McpToolDeps,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 7c0fb7c8f..f072cdd95 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@@ -94,9 +94,9 @@ mock.module('../../../project/project.service', () => ({),}));-const actualSlugId = await import('../../../../shared/slug-id');+const actualSlugId = await import('../../../../slug-id');const realSlugId = { ...actualSlugId };-mock.module('../../../../shared/slug-id', () => ({+mock.module('../../../../slug-id', () => ({...realSlugId,getId: mockGetId,}));@@ -115,7 +115,7 @@ afterAll(() => {() => realDashboardService);mock.module('../../../project/project.service', () => realProjectService);- mock.module('../../../../shared/slug-id', () => realSlugId);+ mock.module('../../../../slug-id', () => realSlugId);});import { testCoreConfig } from '../../../../../test/config-fixture';diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.tsindex 5a7efc63e..99e219191 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts@@ -2,7 +2,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import type { CoreConfig } from '../../../../config';import type { ServiceDeps } from '../../../../services';-import { getId } from '../../../../shared/slug-id';+import { getId } from '../../../../slug-id';import { getDashboardById } from '../../../dashboard/dashboard.service';import { getProjectById } from '../../../project/project.service';import { zReport } from '../../../report/report.constants';diff --git a/packages/core/src/modules/misc/misc.service.ts b/packages/core/src/modules/misc/misc.service.tsindex d30007bf7..fcb9b1c18 100644--- a/packages/core/src/modules/misc/misc.service.ts+++ b/packages/core/src/modules/misc/misc.service.ts@@ -8,7 +8,7 @@// depends on them), so this wave is where V1 drops them too.//// M10-005: the ClickHouse CLIENT is `deps.ch` — reads through-// shared/ch-query.ts, the one write through `deps.ch.insert` — so the+// ch-query.ts, the one write through `deps.ch.insert` — so the// `loadCh()` lazy import of `@openpanel/db` is gone. M15-005 dropped the last// hop too: these three statements are raw strings, not `sql` fragments, so// they still need `TABLE_NAMES` / `formatClickhouseDate`, and core owns its@@ -24,12 +24,12 @@import crypto from 'node:crypto';import { getRedisCache } from '@openpanel/redis';+import { chQuery } from '../../ch-query';import { type GeoLocation, getGeoLocation } from '../../clients/geo';import type { CoreConfig } from '../../config';import type { Logger } from '../../logger';import type { ServiceDeps, Services } from '../../services';import { formatClickhouseDate } from '../../shared/ch-dates';-import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import {DEFAULT_IP_HEADER_ORDER,diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.tsindex 98f4bb154..c0811b606 100644--- a/packages/core/src/modules/notification/notification.service.ts+++ b/packages/core/src/modules/notification/notification.service.ts@@ -18,10 +18,10 @@import type { Integration, Prisma } from '@openpanel/db/src/prisma-client';import { pathOr } from 'ramda';+import { cacheablePerDeps } from '../../cacheable-per-deps';import { sendEmail } from '../../clients/email';import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDeps } from '../../shared/cacheable-per-deps';import { stripLeadingAndTrailingSlashes } from '../../shared/string';import type {IServiceCreateEventPayload,diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsindex e41977ad0..3b45a8a6d 100644--- a/packages/core/src/modules/onboarding/onboarding.service.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -15,14 +15,14 @@ import { getRecommendedPlan } from '@openpanel/payments';import { format } from 'date-fns';import type { Logger } from '../../logger';import type { ServiceDeps, Services } from '../../services';+import { stripTrailingSlash } from '../../shared/string';+import { hashPassword } from '../auth/auth.service';import {runSequence,type SequenceStep,type SequenceSubject,step,-} from '../../shared/email-sequence';-import { stripTrailingSlash } from '../../shared/string';-import { hashPassword } from '../auth/auth.service';+} from '../email/src/sequence';import {getOrganizationById,getOrganizationEventsCount,@@ -36,7 +36,7 @@ const TRIAL_DURATION_IN_DAYS = 30;const TRIAL_EVENTS_LIMIT = 10_000_000;function loadIdService() {- return import('../../shared/slug-id');+ return import('../../slug-id');}export async function canSkipOnboarding(diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex 6b6c6aa93..2dbbbc237 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -29,7 +29,7 @@// in full instead of assembled by `createSqlBuilder`'s record-of-strings.// `sqlstring` and `createSqlBuilder` are both gone from this module. The// `sql` tag is a value import of `@openpanel/db` and stays one: it is a-// compile-time template tag holding no client (see shared/ch-query.ts). The+// compile-time template tag holding no client (see ch-query.ts). The// V1-vs-V2 result-set proof is `organization.sql.proof.md` beside this file.import { sql } from '@openpanel/db/src/clickhouse/sql';@@ -39,6 +39,8 @@ import type {ProjectAccess,User,} from '@openpanel/db/src/prisma-client';+import { cacheablePerDeps } from '../../cacheable-per-deps';+import { chQuery } from '../../ch-query';import { sendEmail } from '../../clients/email';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';@@ -46,9 +48,7 @@ import {getOrganizationAccess,getProjectAccess,} from '../../shared/access-lookups';-import { cacheablePerDeps } from '../../shared/cacheable-per-deps';import { formatClickhouseDate } from '../../shared/ch-dates';-import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import { DateTime } from '../../shared/date';import { generateSecureId } from '../../shared/id';diff --git a/packages/core/src/modules/organization/src/wind-down.ts b/packages/core/src/modules/organization/src/wind-down.tsindex 2f0a813ab..0093091da 100644--- a/packages/core/src/modules/organization/src/wind-down.ts+++ b/packages/core/src/modules/organization/src/wind-down.ts@@ -17,7 +17,7 @@ import {type SequenceStep,type SequenceSubject,step,-} from '../../../shared/email-sequence';+} from '../../email/src/sequence';import type { HighlightProject } from './win-back-highlight';/**diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.tsindex a29d05f81..ff616b953 100644--- a/packages/core/src/modules/overview/overview.rpc.ts+++ b/packages/core/src/modules/overview/overview.rpc.ts@@ -22,10 +22,7 @@ import {} from '../../rpc/base';import { TRPCForbiddenError } from '../../rpc/errors';import type { ServiceDeps } from '../../services';-import {- getChartPrevStartEndDate,- getChartStartEndDate,-} from '../../shared/date';+import { getChartPrevStartEndDate } from '../../shared/date';import { pageContextSchema } from '../assistant/assistant.constants';import { getConversionEventNames } from '../event/event.service';import { getReferrerSpikes } from '../insight/insight.service';@@ -34,6 +31,7 @@ import {getSettingsForProject,} from '../organization/organization.service';import { type IChartRange, zRange } from '../report/report.constants';+import { getChartStartEndDate } from '../report/src/chart-dates';import {zGetMapDataInput,zGetMetricsInput,diff --git a/packages/core/src/modules/overview/src/run-query.ts b/packages/core/src/modules/overview/src/run-query.tsindex 4408d159c..0cff8d01c 100644--- a/packages/core/src/modules/overview/src/run-query.ts+++ b/packages/core/src/modules/overview/src/run-query.ts@@ -12,8 +12,8 @@// wrapper is worth keeping over calling `chQuery` directly.import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';+import { chQuery } from '../../../ch-query';import type { ServiceDeps } from '../../../services';-import { chQuery } from '../../../shared/ch-query';export function runQuery<T extends object>(deps: ServiceDeps,diff --git a/packages/core/src/modules/profile/profile.routes.test.ts b/packages/core/src/modules/profile/profile.routes.test.tsindex 3f6d4f6fc..dafa3f07c 100644--- a/packages/core/src/modules/profile/profile.routes.test.ts+++ b/packages/core/src/modules/profile/profile.routes.test.ts@@ -12,6 +12,7 @@ import type {ClientAuthOptions,ClientAuthResult,} from '../../http/client-auth';+import { validateIngestRequest } from '../ingest/src/client-auth';import type {AdjustProfilePropertyResult,IdentifyProfileInput,@@ -161,7 +162,9 @@ test('every /profile route requires client credentials', async () => {expect(response.status).toBe(401);}expect(authenticateClient).toHaveBeenCalledTimes(3);- expect(authenticateClient.mock.calls[0]?.[2]).toEqual({ ingest: true });+ expect(authenticateClient.mock.calls[0]?.[2]).toEqual({+ ingest: validateIngestRequest,+ });expect(identifyProfile).not.toHaveBeenCalled();expect(adjustProfileProperty).not.toHaveBeenCalled();});diff --git a/packages/core/src/modules/profile/profile.routes.ts b/packages/core/src/modules/profile/profile.routes.tsindex f25145a7f..9b9941567 100644--- a/packages/core/src/modules/profile/profile.routes.ts+++ b/packages/core/src/modules/profile/profile.routes.ts@@ -9,7 +9,7 @@// NAMED GAP, same as import.routes.ts: not yet reachable. `authenticateClient`// (http/client-auth.ts) is a P8 stub that always returns null, so `clientAuth`// 401s every request until it is filled in, and main.ts does not mount-// `publicApiRoutes` until a real `AppDeps` exists. `ingest: true` is V1's+// `publicApiRoutes` until a real `AppDeps` exists. `ingest` is V1's// `clientHook` (the SDK credential rules); V1's `isBotHook` and// `subscriptionHook` on this router are P8's too — the ingest module owns// them, not this one.@@ -21,6 +21,7 @@import { getGeoLocation } from '../../clients/geo';import { defineRoutes } from '../../http/define';import { parseUserAgent } from '../../shared/parser-user-agent';+import { validateIngestRequest } from '../ingest/src/client-auth';import {type AdjustProfilePropertyResult,adjustProfileProperty,@@ -75,7 +76,7 @@ export const profileRoutes = defineRoutes((app) =>return payload.profileId;},{- clientAuth: { ingest: true },+ clientAuth: { ingest: validateIngestRequest },detail: {tags: TAGS,description: 'Identify or update a user profile.',@@ -97,7 +98,7 @@ export const profileRoutes = defineRoutes((app) =>return respondAdjusted(result, status, set);},{- clientAuth: { ingest: true },+ clientAuth: { ingest: validateIngestRequest },detail: {tags: TAGS,description: 'Increment a numeric property on a user profile.',@@ -119,7 +120,7 @@ export const profileRoutes = defineRoutes((app) =>return respondAdjusted(result, status, set);},{- clientAuth: { ingest: true },+ clientAuth: { ingest: validateIngestRequest },detail: {tags: TAGS,description: 'Decrement a numeric property on a user profile.',diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.tsindex d5b4d5c0f..70c969bd3 100644--- a/packages/core/src/modules/profile/profile.service.ts+++ b/packages/core/src/modules/profile/profile.service.ts@@ -11,15 +11,15 @@// src/filter-clauses.ts is the one bridge.//// M10-005: every function that touches ClickHouse or the profile buffer takes-// `ServiceDeps` and reaches them as `deps.ch` (through shared/ch-query.ts) and+// `ServiceDeps` and reaches them as `deps.ch` (through ch-query.ts) and// `deps.buffers.profile`. The `loadChClient` / `loadProfileBuffer` lazy// loaders are gone (docs/TECH_DEBT.md §2, §4); `loadFilterCompiler` stays and// reaches a core sibling, not @openpanel/db.import { assocPath, flatten, map, pathOr, pipe, prop, sort, uniq } from 'ramda';+import { cacheablePerDeps } from '../../cacheable-per-deps';+import { chQuery } from '../../ch-query';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDeps } from '../../shared/cacheable-per-deps';-import { chQuery } from '../../shared/ch-query';import { strip, toObject } from '../../shared/object';import type { IClickhouseEvent } from '../event/event.service';import type { IChartEventFilter } from '../report/report.constants';diff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.tsindex 718ea0031..c097920d3 100644--- a/packages/core/src/modules/project/project.service.test.ts+++ b/packages/core/src/modules/project/project.service.test.ts@@ -178,15 +178,15 @@ mock.module('@openpanel/redis', () => ({}),}));-const realSlugId = { ...(await import('../../shared/slug-id')) };-mock.module('../../shared/slug-id', () => ({+const realSlugId = { ...(await import('../../slug-id')) };+mock.module('../../slug-id', () => ({...realSlugId,getId: async (_deps: unknown, _table: string, name: string) => `${name}-slug`,}));afterAll(() => {mock.module('@openpanel/redis', () => realRedis);- mock.module('../../shared/slug-id', () => realSlugId);+ mock.module('../../slug-id', () => realSlugId);});let subject: ReturnType<diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.tsindex 6cc7a7a14..9f6ee27f6 100644--- a/packages/core/src/modules/project/project.service.ts+++ b/packages/core/src/modules/project/project.service.ts@@ -16,7 +16,7 @@// (`getProjectEventsCount` / `getLastEventPerProject`) onto the ADR-013 `sql`// tag: every value binds as a `{pN:Type}` param, so `sqlstring` and `clix` are// both gone. The CLIENT is `deps.ch` either way, through core's own `chQuery`-// (shared/ch-query.ts) — M10-009 dropped the `compatChHelpers()` hop these two+// (ch-query.ts) — M10-009 dropped the `compatChHelpers()` hop these two// used to make. The V1-vs-V2 result-set proof is `project.sql.proof.md` beside// this file.@@ -27,19 +27,19 @@ import type {Project,ProjectType,} from '@openpanel/db/src/prisma-client';+import { cacheablePerDb, type DbScope } from '../../cacheable-per-deps';+import { chQuery } from '../../ch-query';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDb, type DbScope } from '../../shared/cacheable-per-deps';import { convertClickhouseDateToJs } from '../../shared/ch-dates';-import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';-import { getId } from '../../shared/slug-id';import { stripTrailingSlash } from '../../shared/string';+import { getId } from '../../slug-id';import { hashPassword } from '../auth/auth.service';import { getClientByIdCached } from '../client/client.service';// The `sql` tag is a value import of `@openpanel/db` and stays one: it is a-// compile-time template tag holding no client (see shared/ch-query.ts).+// 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).//diff --git a/packages/core/src/modules/realtime/realtime.service.test.ts b/packages/core/src/modules/realtime/realtime.service.test.tsindex 02dc5bc0e..7f582ec79 100644--- a/packages/core/src/modules/realtime/realtime.service.test.ts+++ b/packages/core/src/modules/realtime/realtime.service.test.ts@@ -56,7 +56,7 @@ afterAll(() => {mock.module('@openpanel/redis', () => realRedis);});-// `deps.ch.query` is what shared/ch-query.ts calls; it returns the raw+// `deps.ch.query` is what ch-query.ts calls; it returns the raw// ClickHouse response envelope, so the stub speaks that shape.let nextRows: unknown[] = [];const chQuery = mock(diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsindex 8fda935b2..4542b8778 100644--- a/packages/core/src/modules/realtime/realtime.service.ts+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -21,7 +21,7 @@// same Redis subscription underneath.//// M10-005: every query function takes `ServiceDeps`. The ClickHouse CLIENT is-// `deps.ch` — reads through shared/ch-query.ts — and the event buffer is+// `deps.ch` — reads through ch-query.ts — and the event buffer is// `deps.buffers.event`, so the `loadChClient` / `loadEventBuffer` lazy imports// of @openpanel/db are gone and the requestId reaches the query (ADR-018 R1,// docs/TECH_DEBT.md §2, §4).@@ -39,12 +39,12 @@import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IPublishChannels } from '@openpanel/redis';import { subMinutes } from 'date-fns';+import { chQuery } from '../../ch-query';import type { ServiceDeps, Services } from '../../services';import {convertClickhouseDateToJs,formatClickhouseDate,} from '../../shared/ch-dates';-import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import { type IClickhouseEvent, transformEvent } from '../event/event.service';import { getProfiles } from '../profile/profile.service';diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsindex 885ef292a..bac7c1077 100644--- a/packages/core/src/modules/reference/reference.service.test.ts+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -116,16 +116,16 @@ mock.module('../organization/organization.service', () => ({...realOrganization,getSettingsForProject,}));-const actualDate = await import('../../shared/date');+const actualDate = await import('../report/src/chart-dates');const realDate = { ...actualDate };-mock.module('../../shared/date', () => ({+mock.module('../report/src/chart-dates', () => ({...realDate,getChartStartEndDate,}));afterAll(() => {mock.module('../organization/organization.service', () => realOrganization);- mock.module('../../shared/date', () => realDate);+ mock.module('../report/src/chart-dates', () => realDate);});let subject: ReturnType<diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsindex f74c19d87..86d628740 100644--- a/packages/core/src/modules/reference/reference.service.ts+++ b/packages/core/src/modules/reference/reference.service.ts@@ -13,9 +13,9 @@import type { Reference } from '@openpanel/db/src/prisma-client';import type { ServiceDeps, Services } from '../../services';-import { getChartStartEndDate } from '../../shared/date';import { getSettingsForProject } from '../organization/organization.service';import type { IChartRange } from '../report/report.constants';+import { getChartStartEndDate } from '../report/src/chart-dates';export type IServiceReference = Reference;diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.tsindex 0f9baeef6..505355d4a 100644--- a/packages/core/src/modules/report/report.service.ts+++ b/packages/core/src/modules/report/report.service.ts@@ -15,7 +15,6 @@ import type {} from '@openpanel/db/src/prisma-client';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';-import { getChartStartEndDate } from '../../shared/date';import { getFunnel } from '../chart/funnel.service';import {executeAggregateChart,@@ -33,6 +32,7 @@ import type {IReportOptions,} from './report.constants';import { alphabetIds, lineTypes } from './report.constants';+import { getChartStartEndDate } from './src/chart-dates';import { mergeGlobalFilters, onlyReportEvents } from './src/series';export type IServiceReport = Awaited<ReturnType<typeof getReportById>>;diff --git a/packages/core/src/modules/report/src/chart-dates.ts b/packages/core/src/modules/report/src/chart-dates.tsnew file mode 100644index 000000000..9b01557bb--- /dev/null+++ b/packages/core/src/modules/report/src/chart-dates.ts@@ -0,0 +1,264 @@+// The two date helpers that read the report vocabulary. Split out of+// `shared/date.ts` at M15-009 (ADR-022 R22): they take `IChartRange` /+// `IReportInput`, which are this module's own constants, so a file in the+// bottom layer could not hold them. The generic Date/Luxon math they build on+// stays in `shared/date.ts`.++import { DateTime } from '../../../shared/date';+import type { IChartRange, IReportInput } from '../report.constants';++export function getDatesFromRange(range: IChartRange, timezone: string) {+ if (range === '30min' || range === 'lastHour') {+ const minutes = range === '30min' ? 30 : 60;+ const startDate = DateTime.now()+ .minus({ minute: minutes })+ .startOf('minute')+ .setZone(timezone)+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('minute')+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'last24h') {+ const startDate = DateTime.now()+ .minus({ hour: 24 })+ .startOf('minute')+ .setZone(timezone)+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('minute')+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'today') {+ const startDate = DateTime.now()+ .setZone(timezone)+ .startOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'yesterday') {+ const startDate = DateTime.now()+ .minus({ day: 1 })+ .setZone(timezone)+ .startOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .minus({ day: 1 })+ .setZone(timezone)+ .endOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ return {+ startDate,+ endDate,+ };+ }++ if (range === '7d') {+ const startDate = DateTime.now()+ .minus({ day: 7 })+ .setZone(timezone)+ .startOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === '3m') {+ const startDate = DateTime.now()+ .minus({ month: 3 })+ .setZone(timezone)+ .startOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === '6m') {+ const startDate = DateTime.now()+ .minus({ month: 6 })+ .setZone(timezone)+ .startOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === '12m') {+ const startDate = DateTime.now()+ .minus({ month: 12 })+ .setZone(timezone)+ .startOf('month')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('month')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'monthToDate') {+ const startDate = DateTime.now()+ .setZone(timezone)+ .startOf('month')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'lastMonth') {+ const month = DateTime.now()+ .minus({ month: 1 })+ .setZone(timezone)+ .startOf('month');++ const startDate = month.toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = month+ .endOf('month')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'yearToDate') {+ const startDate = DateTime.now()+ .setZone(timezone)+ .startOf('year')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ if (range === 'lastYear') {+ const year = DateTime.now().minus({ year: 1 }).setZone(timezone);+ const startDate = year.startOf('year').toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = year.endOf('year').toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+ }++ // range === '30d'+ const startDate = DateTime.now()+ .minus({ day: 30 })+ .setZone(timezone)+ .startOf('day')+ .toFormat('yyyy-MM-dd HH:mm:ss');+ const endDate = DateTime.now()+ .setZone(timezone)+ .endOf('day')+ .plus({ millisecond: 1 })+ .toFormat('yyyy-MM-dd HH:mm:ss');++ return {+ startDate,+ endDate,+ };+}++const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/;++function normalizeBoundary(value: string, boundary: 'start' | 'end'): string {+ if (DATE_ONLY_REGEX.test(value)) {+ return boundary === 'start' ? `${value} 00:00:00` : `${value} 23:59:59`;+ }+ return value;+}++export function getChartStartEndDate(+ {+ startDate,+ endDate,+ range,+ }: Pick<IReportInput, 'endDate' | 'startDate' | 'range'>,+ timezone: string+) {+ const normalizedStart = startDate+ ? normalizeBoundary(startDate, 'start')+ : startDate;+ const normalizedEnd = endDate ? normalizeBoundary(endDate, 'end') : endDate;++ if (normalizedStart && normalizedEnd) {+ return { startDate: normalizedStart, endDate: normalizedEnd };+ }++ const ranges = getDatesFromRange(range, timezone);+ if (!normalizedStart && normalizedEnd) {+ return { startDate: ranges.startDate, endDate: normalizedEnd };+ }++ return ranges;+}diff --git a/packages/core/src/modules/report/src/previous-metric.ts b/packages/core/src/modules/report/src/previous-metric.tsnew file mode 100644index 000000000..7913a8236--- /dev/null+++ b/packages/core/src/modules/report/src/previous-metric.ts@@ -0,0 +1,46 @@+// The previous-period comparison a report card renders. Split out of+// `shared/math.ts` at M15-009 (ADR-022 R22): it returns `PreviousValue`, this+// module's own vocabulary, so it belongs to the report module rather than to+// the layer below every transport. The generic aggregates it is built on stay+// in `shared/math.ts`.++import { isNil } from 'ramda';+import { round } from '../../../shared/math';+import type { PreviousValue } from '../report.constants';++const PERCENT = 100;+const DIFF_DECIMALS = 1;++export function getPreviousMetric(+ current: number,+ previous: number | null | undefined+): PreviousValue {+ if (isNil(previous)) {+ return undefined;+ }++ const diff = round(+ ((current > previous+ ? current / previous+ : current < previous+ ? previous / current+ : 0) -+ 1) *+ PERCENT,+ DIFF_DECIMALS+ );++ return {+ diff:+ Number.isNaN(diff) || !Number.isFinite(diff) || current === previous+ ? null+ : diff,+ state:+ current > previous+ ? 'positive'+ : current < previous+ ? 'negative'+ : 'neutral',+ value: previous,+ };+}diff --git a/packages/core/src/modules/salt/salt.service.ts b/packages/core/src/modules/salt/salt.service.tsindex f66e9a9c3..89227cd5c 100644--- a/packages/core/src/modules/salt/salt.service.ts+++ b/packages/core/src/modules/salt/salt.service.ts@@ -14,8 +14,8 @@// passes the scope it holds instead of reading a boot-scoped singleton through// the deleted compat seam. `generateNewSalt` clears the same instance.+import { cacheablePerDb } from '../../cacheable-per-deps';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDb } from '../../shared/cacheable-per-deps';import { generateSalt } from '../../shared/crypto';const SALT_CACHE_NAME = 'op:salt';diff --git a/packages/core/src/modules/session/session.jobs.ts b/packages/core/src/modules/session/session.jobs.tsindex 06e7642b4..7005dc00e 100644--- a/packages/core/src/modules/session/session.jobs.ts+++ b/packages/core/src/modules/session/session.jobs.ts@@ -16,10 +16,10 @@// requestId is bound to (M10-006, docs/TECH_DEBT.md §2).import { z } from 'zod';+import { chQuery } from '../../ch-query';import type { Ctx } from '../../context';import { defineJob } from '../../jobs/define';import type { Logger } from '../../logger';-import { chQuery } from '../../shared/ch-query';import {createEvent,type IClickhouseEvent,diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 537758a21..8ccc6884a 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -9,7 +9,7 @@// compiler, out of this task's scope; src/filter-clauses.ts is the one bridge.//// M10-009: the ClickHouse client is `deps.ch`, reached through core's own-// `chQuery` (shared/ch-query.ts), so the requestId minted at the edge reaches+// `chQuery` (ch-query.ts), so the requestId minted at the edge reaches// every query here (ADR-018, docs/TECH_DEBT.md §4). `getSessionsCountCached`// is `cacheablePerDeps` (M15-004): `cacheable` keys on the call's ARGUMENTS// (packages/redis/cachable.ts), so the caller's deps travel beside the key@@ -17,9 +17,9 @@// `load*` functions are intra-package lazy imports, kept lazy for a cycle, not// for a client.+import { cacheablePerDeps } from '../../cacheable-per-deps';+import { chQuery } from '../../ch-query';import type { ServiceDeps, Services } from '../../services';-import { cacheablePerDeps } from '../../shared/cacheable-per-deps';-import { chQuery } from '../../shared/ch-query';import { getSafeJson } from '../../shared/json';import type { IServiceProfile } from '../profile/profile.service';import type { IChartEventFilter } from '../report/report.constants';diff --git a/packages/core/src/modules/session/src/session-context.ts b/packages/core/src/modules/session/src/session-context.tsdeleted file mode 100644index 2141e87eb..000000000--- a/packages/core/src/modules/session/src/session-context.ts+++ /dev/null@@ -1,20 +0,0 @@-// Moved from packages/db/src/session-context.ts (M7-001; module map: session-// owns session-context). The ALS scopes a request's dashboard session id so-// anything downstream — today only the Prisma read-replica consistency-// extension ADR-012 retires — can read it without threading a parameter.-// packages/db keeps a re-export shim for its V1 callers.--import { AsyncLocalStorage } from 'node:async_hooks';--interface SessionScope {- sessionId: string | null;-}--export const als = new AsyncLocalStorage<SessionScope>();--export const runWithAlsSession = <T>(- sessionId: string | null | undefined,- fn: () => Promise<T>-) => als.run({ sessionId: sessionId || null }, fn);--export const getAlsSessionId = () => als.getStore()?.sessionId ?? null;diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.tsindex c4f2f01f2..bef1aa3a4 100644--- a/packages/core/src/modules/session/src/usage.ts+++ b/packages/core/src/modules/session/src/usage.ts@@ -4,9 +4,9 @@// at 80% / 100% of the billing limit.import type { Organization } from '@openpanel/db/src/prisma-client';+import { cacheablePerDeps } from '../../../cacheable-per-deps';import { sendEmail } from '../../../clients/email';import type { ServiceDeps } from '../../../services';-import { cacheablePerDeps } from '../../../shared/cacheable-per-deps';// The two project counters stay a DYNAMIC import: jobs.registry.ts reaches// this file (session.jobs.ts -> session-end -> usage), and a static edge todiff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.tsindex ead0dc617..440e59019 100644--- a/packages/core/src/modules/widget/widget.rpc.ts+++ b/packages/core/src/modules/widget/widget.rpc.ts@@ -31,11 +31,12 @@// `widget.sql.proof.md` beside this file.//// `sql` is a value import and stays one: it is a compile-time template tag-// holding no client and no request scope (see shared/ch-query.ts).+// holding no client and no request scope (see ch-query.ts).import { sql } from '@openpanel/db/src/clickhouse/sql';import ShortUniqueId from 'short-unique-id';import { z } from 'zod';+import { chQuery } from '../../ch-query';import type { Ctx } from '../../context';import {createTRPCRouter,@@ -43,7 +44,6 @@ import {publicProcedure,} from '../../rpc/base';import { TRPCNotFoundError } from '../../rpc/errors';-import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import { getSettingsForProject } from '../organization/organization.service';import { zWidgetOptions, zWidgetType } from '../report/report.constants';diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.tsindex e6496dba3..6d3610bf9 100644--- a/packages/core/src/rest.routes.ts+++ b/packages/core/src/rest.routes.ts@@ -7,7 +7,9 @@import { openapi } from '@elysiajs/openapi';import { Elysia } from 'elysia';import type { AppDeps } from './context';+import { createDebugRoutes } from './http/debug.routes';import { httpMetrics } from './http/http.metrics';+import { queues } from './jobs.registry';import { registry } from './metrics';import { assistantRoutes } from './modules/assistant/assistant.routes';import { authRoutes } from './modules/auth/auth.routes';@@ -50,7 +52,7 @@ const OPENAPI_EXCLUDED_PATHS = ['/metrics'];// does not mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8).// tools' `/site-checker` + `/ip-lookup` (M7-008) joined it too — unauthenticated// like V1's, per the module map. ingest's `/track` + `/track/device-id`-// (M8-002) lead the list: the hot path, `clientAuth: { ingest: true }`, and+// (M8-002) lead the list: the hot path, the ingest `clientAuth` tier, and// the one route surface whose hook ORDER is part of the contract.export const publicApiRoutes = (deps: AppDeps) =>new Elysia({ name: 'core/public-api-routes' })@@ -115,3 +117,9 @@ export const opsRoutes = (deps: AppDeps) =>set.headers['content-type'] = registry.contentType;return await registry.metrics();});++// The local-only ops surface. It is bound HERE rather than in+// `http/debug.routes.ts` because that file needs the `cron` queue's job list+// and transport may not import a registry (ADR-022 R22); a registry binding a+// transport to a queue is the edge pointing the right way.+export const debugRoutes = createDebugRoutes(queues.cron);diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.tsindex 51ceb71b1..c7f738b1a 100644--- a/packages/core/src/rpc/base.ts+++ b/packages/core/src/rpc/base.ts@@ -14,7 +14,7 @@ import superjson from 'superjson';import { ZodError, z } from 'zod';import type { HttpCtx, Session } from '../context';import type { Logger } from '../logger';-import { runWithAlsSession } from '../modules/session/src/session-context';+import { runWithAlsSession } from '../shared/als-session';import { type CookieOptions, serializeCookie } from '../shared/cookie';import { EMPTY_SESSION } from '../shared/session';import { TRPCForbiddenError } from './errors';diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.tsindex ff2318a1b..02e4a8c03 100644--- a/packages/core/src/shared/access-lookups.ts+++ b/packages/core/src/shared/access-lookups.ts@@ -1,6 +1,6 @@// The concrete, Prisma-backed access lookups (M8-005, moved from// packages/db/src/services/access.service.ts). Deliberately a sibling of-// shared/access.ts rather than living inside it: the ladder in access.ts must+// modules/auth/src/access.ts rather than living inside it: the ladder must// stay importable with no database (see its own header), while this file is// the real `@openpanel/db` binding ~28 modules' `src/access.ts` files supply// to it. Same shape as packages/trpc/src/access.ts's binding.@@ -30,7 +30,7 @@ function unscopedDb() {}/**- * The project row the ladder reads (`shared/access.ts`'s `AccessLookups`).+ * The project row the ladder reads (`modules/auth/src/access.ts`'s `AccessLookups`).* Same query as `project.service.ts`'s `getProjectById`, without the scope* that file's callers have and this one does not.*/diff --git a/packages/core/src/shared/als-session.ts b/packages/core/src/shared/als-session.tsnew file mode 100644index 000000000..dadaf8959--- /dev/null+++ b/packages/core/src/shared/als-session.ts@@ -0,0 +1,24 @@+// Moved from packages/db/src/session-context.ts (M7-001), and out of+// `modules/session/src/` at M15-009 (ADR-022 R22): both transports open the+// scope and nothing in the session module reads it, so it is request scoping,+// not session domain logic. Dependency-free — `node:async_hooks` and nothing+// else — so it sits at the bottom, where a transport may reach it.+//+// The ALS scopes a request's dashboard session id so anything downstream —+// today only the Prisma read-replica consistency extension ADR-012 retires —+// can read it without threading a parameter.++import { AsyncLocalStorage } from 'node:async_hooks';++interface SessionScope {+ sessionId: string | null;+}++export const als = new AsyncLocalStorage<SessionScope>();++export const runWithAlsSession = <T>(+ sessionId: string | null | undefined,+ fn: () => Promise<T>+) => als.run({ sessionId: sessionId || null }, fn);++export const getAlsSessionId = () => als.getStore()?.sessionId ?? null;diff --git a/packages/core/src/shared/date.ts b/packages/core/src/shared/date.tsindex 40b6050d1..0f3f0a3d3 100644--- a/packages/core/src/shared/date.ts+++ b/packages/core/src/shared/date.ts@@ -1,15 +1,16 @@-// Chart date-range resolution (ADR-007 shared/ layout: "date"). Moved from+// Generic date helpers (ADR-007 shared/ layout: "date"). Moved from// packages/db/src/services/date.service.ts (M8-005) — pure Date/Luxon math,// no ClickHouse or Postgres access.//// M11-006: `DateTime` and `getTime` moved here from packages/common/src/date.ts,// which was the workspace's only luxon declaration. This file is now the one// place core re-exports luxon's DateTime from.+//+// M15-009: `getDatesFromRange` and `getChartStartEndDate` left with the report+// vocabulary they read (`IChartRange`, `IReportInput`) — they are+// `modules/report/src/chart-dates.ts` now. What stays here knows nothing above+// it (ADR-022 R22).import { DateTime } from 'luxon';-import type {- IChartRange,- IReportInput,-} from '../modules/report/report.constants';export { DateTime } from 'luxon';@@ -28,262 +29,6 @@ export function resolveDateRange(return { startDate: start, endDate: end };}-export function getDatesFromRange(range: IChartRange, timezone: string) {- if (range === '30min' || range === 'lastHour') {- const minutes = range === '30min' ? 30 : 60;- const startDate = DateTime.now()- .minus({ minute: minutes })- .startOf('minute')- .setZone(timezone)- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('minute')- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'last24h') {- const startDate = DateTime.now()- .minus({ hour: 24 })- .startOf('minute')- .setZone(timezone)- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('minute')- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'today') {- const startDate = DateTime.now()- .setZone(timezone)- .startOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'yesterday') {- const startDate = DateTime.now()- .minus({ day: 1 })- .setZone(timezone)- .startOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .minus({ day: 1 })- .setZone(timezone)- .endOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- return {- startDate,- endDate,- };- }-- if (range === '7d') {- const startDate = DateTime.now()- .minus({ day: 7 })- .setZone(timezone)- .startOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === '3m') {- const startDate = DateTime.now()- .minus({ month: 3 })- .setZone(timezone)- .startOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === '6m') {- const startDate = DateTime.now()- .minus({ month: 6 })- .setZone(timezone)- .startOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === '12m') {- const startDate = DateTime.now()- .minus({ month: 12 })- .setZone(timezone)- .startOf('month')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('month')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'monthToDate') {- const startDate = DateTime.now()- .setZone(timezone)- .startOf('month')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'lastMonth') {- const month = DateTime.now()- .minus({ month: 1 })- .setZone(timezone)- .startOf('month');-- const startDate = month.toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = month- .endOf('month')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'yearToDate') {- const startDate = DateTime.now()- .setZone(timezone)- .startOf('year')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- if (range === 'lastYear') {- const year = DateTime.now().minus({ year: 1 }).setZone(timezone);- const startDate = year.startOf('year').toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = year.endOf('year').toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };- }-- // range === '30d'- const startDate = DateTime.now()- .minus({ day: 30 })- .setZone(timezone)- .startOf('day')- .toFormat('yyyy-MM-dd HH:mm:ss');- const endDate = DateTime.now()- .setZone(timezone)- .endOf('day')- .plus({ millisecond: 1 })- .toFormat('yyyy-MM-dd HH:mm:ss');-- return {- startDate,- endDate,- };-}--const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/;--function normalizeBoundary(value: string, boundary: 'start' | 'end'): string {- if (DATE_ONLY_REGEX.test(value)) {- return boundary === 'start' ? `${value} 00:00:00` : `${value} 23:59:59`;- }- return value;-}--export function getChartStartEndDate(- {- startDate,- endDate,- range,- }: Pick<IReportInput, 'endDate' | 'startDate' | 'range'>,- timezone: string-) {- const normalizedStart = startDate- ? normalizeBoundary(startDate, 'start')- : startDate;- const normalizedEnd = endDate ? normalizeBoundary(endDate, 'end') : endDate;-- if (normalizedStart && normalizedEnd) {- return { startDate: normalizedStart, endDate: normalizedEnd };- }-- const ranges = getDatesFromRange(range, timezone);- if (!normalizedStart && normalizedEnd) {- return { startDate: ranges.startDate, endDate: normalizedEnd };- }-- return ranges;-}-export function getChartPrevStartEndDate({startDate,endDate,diff --git a/packages/core/src/modules/ingest/src/headers.ts b/packages/core/src/shared/headers.tssimilarity index 70%rename from packages/core/src/modules/ingest/src/headers.tsrename to packages/core/src/shared/headers.tsindex 6a5231b46..3e7a0e5b0 100644--- a/packages/core/src/modules/ingest/src/headers.ts+++ b/packages/core/src/shared/headers.ts@@ -2,6 +2,12 @@// flattened with `Object.fromEntries`. The ingest path reads headers exactly// as V1 read them, so no transport has to build a `Headers` from a raw record// (which throws on a malformed name V1 simply ignored).+//+// M15-009: moved down out of `modules/ingest/src/` (ADR-022 R22). Both auth+// macros in `http/` convert Elysia's `Headers` here before anything else runs,+// and a transport may not deep-import a module's `src/`. The names keep the+// `Ingest` prefix because the record shape is the ingest wire contract; the+// three declarations are dependency-free and belong below every layer.export type IngestHeaders = Record<string, string | string[] | undefined>;diff --git a/packages/core/src/shared/math.ts b/packages/core/src/shared/math.tsindex 5c3fc63b8..1150dfa84 100644--- a/packages/core/src/shared/math.ts+++ b/packages/core/src/shared/math.ts@@ -2,11 +2,13 @@// packages/common/src/get-previous-metric.ts (M11-006, ADR-007 shared/ layout).// `isFloat` does NOT come along: no importer, anywhere.//+// M15-009: `getPreviousMetric` left with the report vocabulary it returns —+// it is `modules/report/src/previous-metric.ts` now. What stays here is the+// generic arithmetic, which knows nothing above it (ADR-022 R22).+//// `isNumber` is mathjs's, not `typeof n === 'number'` — it is the filter// predicate for every chart aggregate below, so it stays exactly as it was.import { isNumber } from 'mathjs';-import { isNil } from 'ramda';-import type { PreviousValue } from '../modules/report/report.constants';export const round = (num: number, decimals = 2) => {const factor = 10 ** decimals;@@ -48,37 +50,3 @@ export const ifNaN = <T extends number>(n: number | null | undefined,defaultValue: T): T => (Number.isNaN(n) ? defaultValue : (n as T));--export function getPreviousMetric(- current: number,- previous: number | null | undefined-): PreviousValue {- if (isNil(previous)) {- return undefined;- }-- const diff = round(- ((current > previous- ? current / previous- : current < previous- ? previous / current- : 0) -- 1) *- 100,- 1- );-- return {- diff:- Number.isNaN(diff) || !Number.isFinite(diff) || current === previous- ? null- : diff,- state:- current > previous- ? 'positive'- : current < previous- ? 'negative'- : 'neutral',- value: previous,- };-}diff --git a/packages/core/src/shared/slug-id.ts b/packages/core/src/slug-id.tssimilarity index 94%rename from packages/core/src/shared/slug-id.tsrename to packages/core/src/slug-id.tsindex 282dd8a4b..eb49449cd 100644--- a/packages/core/src/shared/slug-id.ts+++ b/packages/core/src/slug-id.ts@@ -10,8 +10,8 @@// `@modelcontextprotocol/sdk` signature and only ever hold the db the route// closed over.-import type { ServiceDeps } from '../services';-import { slug } from './slug';+import type { ServiceDeps } from './services';+import { slug } from './shared/slug';export async function getId(deps: Pick<ServiceDeps, 'db'>,