OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M15-001): R3: services.ts gains the services() accessor and all 36 factories become (deps, services) - one commit, alone, every behavioural gate after it
ralphea859c1173fe
diff --git a/.dev-stack-supervisor.sh b/.dev-stack-supervisor.shnew file mode 100755index 000000000..6f91003c9--- /dev/null+++ b/.dev-stack-supervisor.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Operator-run: keeps the api/worker dev stack up for the M15 wave's e2e gates.+# The stack currently exits on an unhandled rejection when http.metrics.ts+# observes a NaN duration (a 404 can trigger it), so a bare `bun run dev` dies+# and every task with an e2e gate then fails at preflight.+cd /home/deploy/openpanel/apps/api || exit 1+while true; do+ API_PORT=3333 bun run dev >> /tmp/api-dev.log 2>&1+ echo "[$(date -u +%FT%TZ)] dev stack exited, restarting in 3s" >> /tmp/api-dev.log+ sleep 3+donediff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex c7fa0ec96..f7e1d1e15 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -28,6 +28,7 @@// them through the v1-compat singleton (see that file's header), the same// way every other bare, no-`Ctx` caller in this wave does.+import type { ServiceDeps, Services } from '../../services';import type { PageContext } from './assistant.constants';let _app: Promise<typeof import('./src/app')> | undefined;@@ -87,12 +88,16 @@ export interface AssistantService {}/**- * Takes NO `ServiceDeps`: the three members are `@better-agent/core` entry- * points with a fixed signature, and each reaches the database through the- * v1-compat seam its own tools already use — there is nothing here to hand a- * client to.+ * Ignores BOTH arguments, and takes them only because ADR-022 R3 keeps the+ * composition root a flat list: the three members are `@better-agent/core`+ * entry points with a fixed signature, and each reaches the database through+ * the v1-compat seam its own tools already use — there is nothing here to+ * hand a client to.*/-export function createAssistantService(): AssistantService {+export function createAssistantService(+ _deps: ServiceDeps,+ _services: () => Services+): AssistantService {return {getChatApp,getChatRunContext,diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.tsindex 48d9aa04b..7bcd00c51 100644--- a/packages/core/src/modules/auth/auth.service.access.test.ts+++ b/packages/core/src/modules/auth/auth.service.access.test.ts@@ -8,6 +8,7 @@// gate are unchanged.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeProjectAccess {level: 'read' | 'write' | 'admin';@@ -62,7 +63,13 @@ afterAll(() => {});function authService() {- return createAuthService();+ // Both arguments are ignored by `createAuthService` — it takes them so the+ // composition root stays a flat list (ADR-022 R3). Every member reaches the+ // mocked lookups above.+ return createAuthService(+ {} as import('../../services').ServiceDeps,+ testServices()+ );}test('requireProjectAccess is fail-closed: no access throws before the write-level check', async () => {diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 01b5beca6..2f89c0edf 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -19,7 +19,7 @@// carries a `Ctx` and passes it straight through.import { z } from 'zod';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { type AccessChecks, createAccessChecks } from '../../shared/access';import type {getClientAccess as GetClientAccessFn,@@ -180,15 +180,18 @@ export function resetAccessChecksForTests(): void {}/**- * Registered in `services.ts`. Takes NO `ServiceDeps`, and says so on the- * signature rather than ignoring an argument: every member here is either- * pure, reads its own env, or — for the access checks — reaches the shared,- * memoized `getAccessChecks()` above, whose lookups are `cacheable` (their- * key is derived from the call's arguments, so they cannot take a leading- * `deps`; see shared/access-lookups.ts). A member that later needs `db` /- * `logger` adds the parameter back, and the one call site follows.+ * Registered in `services.ts`. Ignores BOTH arguments, and takes them only+ * because ADR-022 R3 keeps the composition root a flat list: every member+ * here is either pure, reads its own env, or — for the access checks —+ * reaches the shared, memoized `getAccessChecks()` above, whose lookups are+ * `cacheable` (their key is derived from the call's arguments, so they cannot+ * take a leading `deps`; see shared/access-lookups.ts). A member that later+ * needs `db` / `logger` drops the underscore and reads the parameter.*/-export function createAuthService(): AuthService {+export function createAuthService(+ _deps: ServiceDeps,+ _services: () => Services+): AuthService {return {async requireProjectAccess(args) {return (await getAccessChecks()).requireProjectAccess(args);diff --git a/packages/core/src/modules/chart/chart.service.test.ts b/packages/core/src/modules/chart/chart.service.test.tsindex d0d7ef6da..8b8099ec1 100644--- a/packages/core/src/modules/chart/chart.service.test.ts+++ b/packages/core/src/modules/chart/chart.service.test.ts@@ -62,9 +62,11 @@ beforeAll(async () => {const fixtures = await import('../../../../../test/fixtures');FIXTURE = fixtures.FIXTURE;({ ch } = await import('@openpanel/db/src/clickhouse/client'));- const { testServiceDeps } = await import('../../../test/service-deps');+ const { testServiceDeps, testServices } = await import(+ '../../../test/service-deps'+ );const { createChartService } = await import('./chart.service');- service = createChartService(await testServiceDeps());+ service = createChartService(await testServiceDeps(), testServices());const { bootstrapTestDatabases } = await import('../../../../../test/bootstrap-databases'diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex 168321540..776fc481a 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -20,7 +20,7 @@import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import { flatten, map, pipe, prop, sort, uniq } from 'ramda';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import {getChartPrevStartEndDate,getChartStartEndDate,@@ -849,15 +849,18 @@ export interface ChartService {getEngagementCore(projectId: string): ReturnType<typeof getEngagementCore>;}-export function createChartService(deps: ServiceDeps): ChartService {+export function createChartService(+ deps: ServiceDeps,+ services: () => Services+): ChartService {// The four chart sub-modules each expose their own `create*Service(deps)`// (ADR-007). `services.ts` binds each under its own key; `chart` composes// them as well, so the callers that reach a funnel/retention method through// the chart facade keep working. Both bind the same stateless closures.- const funnel = createFunnelService(deps);- const conversion = createConversionService(deps);- const sankey = createSankeyService(deps);- const retention = createRetentionService(deps);+ const funnel = createFunnelService(deps, services);+ const conversion = createConversionService(deps, services);+ const sankey = createSankeyService(deps, services);+ const retention = createRetentionService(deps, services);return {execute: (input) => executeChart(deps, input),diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.tsindex adc12e7dc..e63de2f07 100644--- a/packages/core/src/modules/chart/conversion.service.ts+++ b/packages/core/src/modules/chart/conversion.service.ts@@ -5,7 +5,7 @@import { sql } from '@openpanel/db/src/clickhouse/sql';import { omit } from 'ramda';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import type { IReportInput } from '../report/report.constants';import { NOT_SET_VALUE } from '../report/report.constants';import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';@@ -273,7 +273,10 @@ export interface ConversionService {): ReturnType<typeof getConversion>;}-export function createConversionService(deps: ServiceDeps): ConversionService {+export function createConversionService(+ deps: ServiceDeps,+ _services: () => Services+): ConversionService {return {getConversion: (input) => getConversion(deps, input),};diff --git a/packages/core/src/modules/chart/funnel.service.ts b/packages/core/src/modules/chart/funnel.service.tsindex 82e80713e..f46aca296 100644--- a/packages/core/src/modules/chart/funnel.service.ts+++ b/packages/core/src/modules/chart/funnel.service.ts@@ -4,7 +4,7 @@// re-export shim onto this module (DELEGATE PATTERN).import { last, reverse } from 'ramda';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { ifNaN } from '../../shared/math';import { getSettingsForProject } from '../organization/organization.service';import type {@@ -456,7 +456,10 @@ export interface FunnelService {): ReturnType<typeof getFunnelProfileIds>;}-export function createFunnelService(deps: ServiceDeps): FunnelService {+export function createFunnelService(+ deps: ServiceDeps,+ _services: () => Services+): FunnelService {return {getFunnelGroup,toSeries,diff --git a/packages/core/src/modules/chart/retention.service.ts b/packages/core/src/modules/chart/retention.service.tsindex f3f20b14c..56232bf23 100644--- a/packages/core/src/modules/chart/retention.service.ts+++ b/packages/core/src/modules/chart/retention.service.ts@@ -8,7 +8,7 @@// well as the MCP / agent / REST retention endpoints.import { range } from 'ramda';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { DateTime } from '../../shared/date';import { round } from '../../shared/math';import type { IChartEventFilter } from '../report/report.constants';@@ -419,7 +419,10 @@ export interface RetentionService {getEngagementCore(projectId: string): ReturnType<typeof getEngagementCore>;}-export function createRetentionService(deps: ServiceDeps): RetentionService {+export function createRetentionService(+ deps: ServiceDeps,+ _services: () => Services+): RetentionService {return {processCohortData,getRetentionCohort: (input) => getRetentionCohort(deps, input),diff --git a/packages/core/src/modules/chart/sankey.service.ts b/packages/core/src/modules/chart/sankey.service.tsindex 68f8657ae..107fae23e 100644--- a/packages/core/src/modules/chart/sankey.service.ts+++ b/packages/core/src/modules/chart/sankey.service.ts@@ -5,7 +5,7 @@import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import { z } from 'zod';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getSettingsForProject } from '../organization/organization.service';import {chartColors,@@ -531,7 +531,10 @@ export interface SankeyService {): ReturnType<typeof getUserFlowCore>;}-export function createSankeyService(deps: ServiceDeps): SankeyService {+export function createSankeyService(+ deps: ServiceDeps,+ _services: () => Services+): SankeyService {return {getRawWhereClause,getSankey: (input) => getSankey(deps, input),diff --git a/packages/core/src/modules/client/client.service.test.ts b/packages/core/src/modules/client/client.service.test.tsindex 0fac4e62a..2ca7ddc9d 100644--- a/packages/core/src/modules/client/client.service.test.ts+++ b/packages/core/src/modules/client/client.service.test.ts@@ -7,6 +7,7 @@// land before that import — hence the `await import` in `beforeAll`.import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeProject {id: string;@@ -140,9 +141,12 @@ mock.module('@openpanel/redis', () => ({let subject: import('./client.service').ClientService;beforeAll(async () => {const { createClientService } = await import('./client.service');- subject = createClientService({- db: { project, client },- } as unknown as import('../../services').ServiceDeps);+ subject = createClientService(+ {+ db: { project, client },+ } as unknown as import('../../services').ServiceDeps,+ testServices()+ );});beforeEach(() => {diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.tsindex 4b7a751cb..8768c8e68 100644--- a/packages/core/src/modules/client/client.service.ts+++ b/packages/core/src/modules/client/client.service.ts@@ -29,7 +29,7 @@import crypto from 'node:crypto';import type { Client, Prisma } from '@openpanel/db/src/prisma-client';import { cacheable } from '@openpanel/redis';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { hashPassword } from '../auth/auth.service';export type IServiceClient = Client;@@ -168,7 +168,10 @@ export interface ClientService {): Promise<boolean>;}-export function createClientService(deps: ServiceDeps): ClientService {+export function createClientService(+ deps: ServiceDeps,+ _services: () => Services+): ClientService {/** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */const getClientByIdCached = cacheable((id: string) => getClientById(deps, id),diff --git a/packages/core/src/modules/cohort/cohort.service.test.ts b/packages/core/src/modules/cohort/cohort.service.test.tsindex 4950835a2..3340d6e67 100644--- a/packages/core/src/modules/cohort/cohort.service.test.ts+++ b/packages/core/src/modules/cohort/cohort.service.test.ts@@ -10,6 +10,7 @@// ClickHouse connection.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeCohort {id: string;@@ -196,7 +197,9 @@ test('createCohortService().enqueueCompute enqueues with the cohort-<id> dedupli},} as unknown as Parameters<typeof subject.createCohortService>[0];- await subject.createCohortService(deps).enqueueCompute('cohort_1');+ await subject+ .createCohortService(deps, testServices())+ .enqueueCompute('cohort_1');expect(addCalls).toEqual([{@@ -210,7 +213,7 @@ test('createCohortService() delegates updateMembership and listRefreshableCohortcohortStore.clear();seedCohort({ id: 'c1', isStatic: false });seedCohort({ id: 'c2', isStatic: true });- const service = subject.createCohortService(deps);+ const service = subject.createCohortService(deps, testServices());// M10-009: the container's members are closures over `deps`, not the bare// functions, so identity is no longer the observable — delegation is.diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.tsindex 1066ec614..1796d9689 100644--- a/packages/core/src/modules/cohort/cohort.service.ts+++ b/packages/core/src/modules/cohort/cohort.service.ts@@ -38,7 +38,7 @@import type { ClickHouseSettings } from '@clickhouse/client';import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { chQuery } from '../../shared/ch-query';import { isClickhouseClustered } from '../../shared/ch-tables';import type { IServiceProfile } from '../profile/profile.service';@@ -1038,7 +1038,10 @@ export interface CohortService {enqueueCompute(cohortId: string): Promise<void>;}-export function createCohortService(deps: ServiceDeps): CohortService {+export function createCohortService(+ deps: ServiceDeps,+ _services: () => Services+): CohortService {return {updateMembership: (cohortId) => updateCohortMembership(deps, cohortId),listRefreshableCohortIds: () => listRefreshableCohortIds(deps),diff --git a/packages/core/src/modules/conversation/conversation.service.test.ts b/packages/core/src/modules/conversation/conversation.service.test.tsindex b16d0062e..cbf9d82cc 100644--- a/packages/core/src/modules/conversation/conversation.service.test.ts+++ b/packages/core/src/modules/conversation/conversation.service.test.ts@@ -3,6 +3,7 @@// idiom as reference.service.test.ts.import { beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';import type { ServiceDeps } from '../../services';import { createConversationService } from './conversation.service';@@ -101,9 +102,12 @@ const conversation = {}),};-const subject = createConversationService({- db: { conversation },-} as unknown as ServiceDeps);+const subject = createConversationService(+ {+ db: { conversation },+ } as unknown as ServiceDeps,+ testServices()+);beforeEach(() => {conversationStore.clear();diff --git a/packages/core/src/modules/conversation/conversation.service.ts b/packages/core/src/modules/conversation/conversation.service.tsindex 2d481e521..9989ceb79 100644--- a/packages/core/src/modules/conversation/conversation.service.ts+++ b/packages/core/src/modules/conversation/conversation.service.ts@@ -11,7 +11,7 @@ import type {Conversation,Prisma,} from '@openpanel/db/src/prisma-client';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';export type IServiceConversation = Conversation;export type IServiceChatMessage = ChatMessage;@@ -108,7 +108,8 @@ export interface ConversationService {}export function createConversationService(- deps: ServiceDeps+ deps: ServiceDeps,+ _services: () => Services): ConversationService {return {getConversationById: (id, options) =>diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.tsindex e20753f73..570c58fbe 100644--- a/packages/core/src/modules/dashboard/dashboard.service.ts+++ b/packages/core/src/modules/dashboard/dashboard.service.ts@@ -11,7 +11,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 } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getId } from '../../shared/slug-id';import { getProjectById } from '../project/project.service';@@ -179,7 +179,10 @@ export interface DashboardService {deleteDashboard(input: { id: string; forceDelete?: boolean }): Promise<void>;}-export function createDashboardService(deps: ServiceDeps): DashboardService {+export function createDashboardService(+ deps: ServiceDeps,+ _services: () => Services+): DashboardService {return {getDashboardById: (id, projectId) => getDashboardById(deps, id, projectId),getDashboardByIdOrThrow: (id) => getDashboardByIdOrThrow(deps, id),diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.tsindex 696b7e28a..be265e21d 100644--- a/packages/core/src/modules/event/event.service.ts+++ b/packages/core/src/modules/event/event.service.ts@@ -29,7 +29,7 @@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 type { ServiceDeps } from '../../services';+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';@@ -1333,7 +1333,10 @@ export interface EventService {): Promise<{ document: IClickhouseEvent }>;}-export function createEventService(deps: ServiceDeps): EventService {+export function createEventService(+ deps: ServiceDeps,+ _services: () => Services+): EventService {return {getById: (input) => getEventById(deps, input),create: (payload) => createEvent(deps, payload),diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.tsindex 6a8f6531c..d325f13b4 100644--- a/packages/core/src/modules/export/export.service.ts+++ b/packages/core/src/modules/export/export.service.ts@@ -14,7 +14,7 @@// relative import cannot do (docs/TECH_DEBT.md §4).import type { AuthenticatedClient } from '../../http/client-auth';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getChartStartEndDate, resolveDateRange } from '../../shared/date';import { getSettingsForProject } from '../organization/organization.service';import type { IChartRange } from '../report/report.constants';@@ -133,7 +133,10 @@ export interface ExportService {): Promise<{ startDate: string; endDate: string }>;}-export function createExportService(deps: ServiceDeps): ExportService {+export function createExportService(+ deps: ServiceDeps,+ _services: () => Services+): ExportService {return {resolveExportProjectId: (client, query) =>resolveExportProjectId(deps, client, query),diff --git a/packages/core/src/modules/group/group.service.ts b/packages/core/src/modules/group/group.service.tsindex 3b07907b4..31a906f73 100644--- a/packages/core/src/modules/group/group.service.ts+++ b/packages/core/src/modules/group/group.service.ts@@ -12,7 +12,7 @@// through `deps.ch.insert`. The `loadChClient` lazy loader is gone// (docs/TECH_DEBT.md §2, §4).-import type { ServiceDeps } from '../../services';+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';@@ -521,7 +521,10 @@ export interface GroupService {upsert(input: IServiceUpsertGroup): Promise<void>;}-export function createGroupService(deps: ServiceDeps): GroupService {+export function createGroupService(+ deps: ServiceDeps,+ _services: () => Services+): GroupService {return {byId: (id, projectId) => getGroupById(deps, id, projectId),upsert: (input) => upsertGroup(deps, input),diff --git a/packages/core/src/modules/gsc/gsc.service.ts b/packages/core/src/modules/gsc/gsc.service.tsindex e81fe95e3..7caa0612c 100644--- a/packages/core/src/modules/gsc/gsc.service.ts+++ b/packages/core/src/modules/gsc/gsc.service.ts@@ -28,7 +28,7 @@ import { cacheable } from '@openpanel/redis';import { createLogger, type ILogger } from '../../clients/logger';import type { Logger } from '../../logger';import { TRPCNotFoundError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import { decrypt, encrypt } from '../../shared/encryption';@@ -1500,7 +1500,10 @@ export interface GscService {}/** `ctx.services.gsc` — a thin binding of the functions above to a Ctx's logger/queues. */-export function createGscService(deps: ServiceDeps): GscService {+export function createGscService(+ deps: ServiceDeps,+ _services: () => Services+): GscService {const logger = deps.logger.child({ module: 'gsc' });return {diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.tsindex 327c6bae8..cb0603991 100644--- a/packages/core/src/modules/import/import.service.test.ts+++ b/packages/core/src/modules/import/import.service.test.ts@@ -6,6 +6,7 @@// the v1-compat seam memoizes whatever it resolved while one was installed.import { beforeAll, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';import type { AppDeps, Buffers } from '../../context';import { createRecordingProducers } from '../../jobs/testing';import { queues } from '../../jobs.registry';@@ -144,15 +145,18 @@ test('updateImportStatus marks a failed step with its error message', async () =test('ImportService.enqueue adds the import job onto the import queue', async () => {const producers = createRecordingProducers(queues);- const service = createImportService({- db: {} as AppDeps['db'],- ch: {} as AppDeps['ch'],- redis: {} as AppDeps['redis'],- clients: {} as AppDeps['clients'],- buffers: {} as Buffers,- logger: stubLogger(),- queues: producers.queues,- });+ const service = createImportService(+ {+ db: {} as AppDeps['db'],+ ch: {} as AppDeps['ch'],+ redis: {} as AppDeps['redis'],+ clients: {} as AppDeps['clients'],+ buffers: {} as Buffers,+ logger: stubLogger(),+ queues: producers.queues,+ },+ testServices()+ );const jobId = await service.enqueue('imp_1');diff --git a/packages/core/src/modules/import/import.service.ts b/packages/core/src/modules/import/import.service.tsindex 6cd83545f..175b040c3 100644--- a/packages/core/src/modules/import/import.service.ts+++ b/packages/core/src/modules/import/import.service.ts@@ -22,7 +22,7 @@ import { createHash } from 'node:crypto';import type { Prisma } from '@openpanel/db/src/prisma-client';import { createLogger, type ILogger } from '../../clients/logger';import type { Logger } from '../../logger';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import {convertClickhouseDateToJs,formatClickhouseDate,@@ -1242,7 +1242,10 @@ export interface ImportService {}/** `ctx.services.import` — a thin binding of the job body above to a Ctx's queues. */-export function createImportService(deps: ServiceDeps): ImportService {+export function createImportService(+ deps: ServiceDeps,+ _services: () => Services+): ImportService {const logger = deps.logger.child({ module: 'import' });return {diff --git a/packages/core/src/modules/ingest/ingest.service.ts b/packages/core/src/modules/ingest/ingest.service.tsindex acae09837..acee2ca53 100644--- a/packages/core/src/modules/ingest/ingest.service.ts+++ b/packages/core/src/modules/ingest/ingest.service.ts@@ -24,7 +24,7 @@ import {getGeoLocation,} from '../../clients/geo';import type { Logger } from '../../logger';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { generateId } from '../../shared/id';import { parseUserAgent } from '../../shared/parser-user-agent';import { generateDeviceId } from '../../shared/profileId';@@ -912,7 +912,10 @@ export interface IngestService {isDuplicate: typeof isDuplicateIngestRequest;}-export function createIngestService(deps: ServiceDeps): IngestService {+export function createIngestService(+ deps: ServiceDeps,+ _services: () => Services+): IngestService {return {track: (request, produceIncomingEvent) =>ingestTrack(request, {diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.tsindex a5ee7fca0..0b45f6c52 100644--- a/packages/core/src/modules/insight/insight.service.test.ts+++ b/packages/core/src/modules/insight/insight.service.test.ts@@ -5,6 +5,7 @@// registered before the subject's first call, not before its import.import { beforeAll, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';import type { AppDeps, Buffers } from '../../context';const listProjectIdsForCadence = mock(async () => ['p1', 'p2']);@@ -164,16 +165,19 @@ test('createInsightService binds every InsightService method', () => {trace: noop,child: () => logger,};- const service = subject.createInsightService({- db: undefined as unknown as AppDeps['db'],- ch: undefined as unknown as AppDeps['ch'],- redis: undefined as unknown as AppDeps['redis'],- clients: undefined as unknown as AppDeps['clients'],- buffers: undefined as unknown as Buffers,- logger,- queues:- undefined as unknown as import('../../jobs.registry').QueueProducers,- });+ const service = subject.createInsightService(+ {+ db: undefined as unknown as AppDeps['db'],+ ch: undefined as unknown as AppDeps['ch'],+ redis: undefined as unknown as AppDeps['redis'],+ clients: undefined as unknown as AppDeps['clients'],+ buffers: undefined as unknown as Buffers,+ logger,+ queues:+ undefined as unknown as import('../../jobs.registry').QueueProducers,+ },+ testServices()+ );for (const method of ['listDailyInsightCandidates',diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.tsindex 6b500bb2e..2822a813d 100644--- a/packages/core/src/modules/insight/insight.service.ts+++ b/packages/core/src/modules/insight/insight.service.ts@@ -34,7 +34,7 @@ import {import { generateWeeklyNarrative } from '../../clients/ai/narrative';import { sendEmail } from '../../clients/email';import type { Logger } from '../../logger';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import type { EngineConfig } from './src/engine';import type { Insight as LegacyInsight } from './src/legacy-scan';import type {@@ -730,7 +730,10 @@ export interface InsightService {}/** `ctx.services.insight` — a thin binding of the functions above to a Ctx's logger. */-export function createInsightService(deps: ServiceDeps): InsightService {+export function createInsightService(+ deps: ServiceDeps,+ _services: () => Services+): InsightService {const logger = deps.logger.child({ module: 'insight' });return {diff --git a/packages/core/src/modules/integration/integration.service.ts b/packages/core/src/modules/integration/integration.service.tsindex 77e76d578..eb7bbfc82 100644--- a/packages/core/src/modules/integration/integration.service.ts+++ b/packages/core/src/modules/integration/integration.service.ts@@ -38,7 +38,7 @@ import {slackInstaller,} from '../../clients/integrations/slack';import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getOrganizationAccess } from '../../shared/access-lookups';import { getAccessChecks } from '../auth/auth.service';import { BASE_INTEGRATIONS } from '../notification/notification.service';@@ -496,7 +496,8 @@ export interface IntegrationService {/** M10-009: this module had no factory at all — the one `*.service.ts` file* `services.ts` did not register (docs/TECH_DEBT.md §5a). */export function createIntegrationService(- deps: ServiceDeps+ deps: ServiceDeps,+ _services: () => Services): IntegrationService {return {getById: (...args) => getIntegrationById(deps, ...args),diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.tsindex 2098e3acc..1c1155f22 100644--- a/packages/core/src/modules/mcp/mcp.service.ts+++ b/packages/core/src/modules/mcp/mcp.service.ts@@ -29,6 +29,7 @@import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';import { createLogger } from '../../clients/logger';+import type { ServiceDeps, Services } from '../../services';import {authenticateToken,extractToken,@@ -207,13 +208,17 @@ export interface McpService {}/**- * Takes NO `ServiceDeps`: `extractToken` is pure and+ * Ignores BOTH arguments, and takes them only because ADR-022 R3 keeps the+ * composition root a flat list: `extractToken` is pure and* `handleStatelessMcpRequest` hands the request to the* `@modelcontextprotocol/sdk` server, whose tool handlers have a fixed* signature with no room for a `deps` argument (docs/TECH_DEBT.md's* "loaders still standing" table).*/-export function createMcpService(): McpService {+export function createMcpService(+ _deps: ServiceDeps,+ _services: () => Services+): McpService {return {extractToken,handleStatelessMcpRequest,diff --git a/packages/core/src/modules/misc/misc.service.ts b/packages/core/src/modules/misc/misc.service.tsindex cd16edf01..4b6aefb63 100644--- a/packages/core/src/modules/misc/misc.service.ts+++ b/packages/core/src/modules/misc/misc.service.ts@@ -25,7 +25,7 @@ import crypto from 'node:crypto';import { getRedisCache } from '@openpanel/redis';import { type GeoLocation, getGeoLocation } from '../../clients/geo';import type { Logger } from '../../logger';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { chQuery } from '../../shared/ch-query';import {DEFAULT_IP_HEADER_ORDER,@@ -497,6 +497,9 @@ export interface MiscService {runPingCron(): Promise<unknown>;}-export function createMiscService(deps: ServiceDeps): MiscService {+export function createMiscService(+ deps: ServiceDeps,+ _services: () => Services+): MiscService {return { runPingCron: () => runPingCron(deps) };}diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.tsindex 958510d20..1227aa7c4 100644--- a/packages/core/src/modules/notification/notification.service.ts+++ b/packages/core/src/modules/notification/notification.service.ts@@ -22,7 +22,7 @@ import { pathOr } from 'ramda';import { sendEmail } from '../../clients/email';import { getServerIntegration } from '../../clients/integrations/registry';import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { stripLeadingAndTrailingSlashes } from '../../shared/string';import type {IServiceCreateEventPayload,@@ -525,7 +525,8 @@ export interface NotificationService {}export function createNotificationService(- deps: ServiceDeps+ deps: ServiceDeps,+ _services: () => Services): NotificationService {return {dispatch: (notification) => deliverNotification(deps, notification),diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsindex c382a7b69..c72f5668b 100644--- a/packages/core/src/modules/onboarding/onboarding.service.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -16,7 +16,7 @@ import crypto from 'node:crypto';import { getRecommendedPlan } from '@openpanel/payments';import { format } from 'date-fns';import type { Logger } from '../../logger';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import {runSequence,type SequenceStep,@@ -423,7 +423,10 @@ export interface OnboardingService {* `ctx.logger` is, so `ctx.services.onboarding.runOnboardingCron()` takes no* arguments — same shape as organization's `runDeleteCron`, which needs no* logger of its own at all. */-export function createOnboardingService(deps: ServiceDeps): OnboardingService {+export function createOnboardingService(+ deps: ServiceDeps,+ _services: () => Services+): OnboardingService {return {runOnboardingCron: () => runOnboardingCron(deps, deps.logger),};diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex 31a715bd1..e69e0f281 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -43,7 +43,7 @@ import type {import { cacheable } from '@openpanel/redis';import { sendEmail } from '../../clients/email';import { TRPCBadRequestError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import {getOrganizationAccess,getProjectAccess,@@ -967,7 +967,8 @@ export interface OrganizationService {}export function createOrganizationService(- deps: ServiceDeps+ deps: ServiceDeps,+ _services: () => Services): OrganizationService {return {get: (organizationId) => getOrganizationById(deps, organizationId),diff --git a/packages/core/src/modules/overview/overview.service.ts b/packages/core/src/modules/overview/overview.service.tsindex 502b5aef8..dd4e6cfe0 100644--- a/packages/core/src/modules/overview/overview.service.ts+++ b/packages/core/src/modules/overview/overview.service.ts@@ -12,7 +12,7 @@import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import { z } from 'zod';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { average, sum } from '../../shared/math';import { convertClickhouseDateToJs } from '../chart/src/dates';import {@@ -1408,7 +1408,10 @@ export interface OverviewService {): ReturnType<typeof getAnalyticsOverviewCore>;}-export function createOverviewService(deps: ServiceDeps): OverviewService {+export function createOverviewService(+ deps: ServiceDeps,+ _services: () => Services+): OverviewService {return {isPageFilter,getRawWhereClause,diff --git a/packages/core/src/modules/overview/pages.service.ts b/packages/core/src/modules/overview/pages.service.tsindex a776962ab..202698d25 100644--- a/packages/core/src/modules/overview/pages.service.ts+++ b/packages/core/src/modules/overview/pages.service.ts@@ -12,7 +12,7 @@// dodge a module-singleton mocking hazard, and there is no singleton left to// dodge.-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getSettingsForProject } from '../organization/organization.service';import type { IChartEventFilter, IInterval } from '../report/report.constants';import {@@ -242,7 +242,10 @@ export interface PagesService {): Promise<IPageConversionRow[]>;}-export function createPagesService(deps: ServiceDeps): PagesService {+export function createPagesService(+ deps: ServiceDeps,+ _services: () => Services+): PagesService {return {getTopPages: (input) => getTopPages(deps, input),getPageTimeseries: (input) => getPageTimeseries(deps, input),diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.tsindex 971565fe8..498a4d90b 100644--- a/packages/core/src/modules/profile/profile.service.ts+++ b/packages/core/src/modules/profile/profile.service.ts@@ -17,7 +17,7 @@// reaches a core sibling, not @openpanel/db.import { assocPath, flatten, map, pathOr, pipe, prop, sort, uniq } from 'ramda';-import type { ServiceDeps } from '../../services';+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';@@ -716,7 +716,10 @@ export interface ProfileService {upsert(input: IServiceUpsertProfile, isFromEvent?: boolean): Promise<void>;}-export function createProfileService(deps: ServiceDeps): ProfileService {+export function createProfileService(+ deps: ServiceDeps,+ _services: () => Services+): ProfileService {return {byId: (id, projectId) => getProfileById(deps, id, projectId),upsert: (input, isFromEvent) => upsertProfile(deps, input, isFromEvent),diff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.tsindex 667d8ac3c..82e2ec98c 100644--- a/packages/core/src/modules/project/project.service.test.ts+++ b/packages/core/src/modules/project/project.service.test.ts@@ -11,6 +11,7 @@// has no real `AppDeps` to build.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeProject {id: string;@@ -201,9 +202,12 @@ afterAll(() => {let subject: import('./project.service').ProjectService;beforeAll(async () => {const { createProjectService } = await import('./project.service');- subject = createProjectService({- db: { project, report, member },- } as unknown as import('../../services').ServiceDeps);+ subject = createProjectService(+ {+ db: { project, report, member },+ } as unknown as import('../../services').ServiceDeps,+ testServices()+ );});beforeEach(() => {diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.tsindex 15f29a05b..1f789ff94 100644--- a/packages/core/src/modules/project/project.service.ts+++ b/packages/core/src/modules/project/project.service.ts@@ -30,7 +30,7 @@ import type {} from '@openpanel/db/src/prisma-client';import { cacheable } from '@openpanel/redis';import { TRPCBadRequestError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { convertClickhouseDateToJs } from '../../shared/ch-dates';import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';@@ -447,7 +447,10 @@ export interface ProjectService {cancelProjectDeletion(id: string): Promise<void>;}-export function createProjectService(deps: ServiceDeps): ProjectService {+export function createProjectService(+ deps: ServiceDeps,+ _services: () => Services+): ProjectService {/** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */const getProjectByIdCached = cacheable((id: string) => getProjectById(deps, id),diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsindex f4c28900f..d0024dc06 100644--- a/packages/core/src/modules/realtime/realtime.service.ts+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -39,7 +39,7 @@import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IPublishChannels } from '@openpanel/redis';import { subMinutes } from 'date-fns';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import {convertClickhouseDateToJs,formatClickhouseDate,@@ -563,7 +563,10 @@ export interface RealtimeService {getActiveVisitorCount(projectId: string): Promise<number>;}-export function createRealtimeService(deps: ServiceDeps): RealtimeService {+export function createRealtimeService(+ deps: ServiceDeps,+ _services: () => Services+): RealtimeService {return {getCoordinates: (projectId) => getRealtimeCoordinates(deps, projectId),getMapBadgeDetails: (input) => getRealtimeMapBadgeDetails(deps, input),diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsindex d6359e46e..9433ec94b 100644--- a/packages/core/src/modules/reference/reference.service.test.ts+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -4,6 +4,7 @@// at the specifier the source resolves through.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeReference {id: string;@@ -130,9 +131,12 @@ afterAll(() => {let subject: import('./reference.service').ReferenceService;beforeAll(async () => {const { createReferenceService } = await import('./reference.service');- subject = createReferenceService({- db: { reference },- } as unknown as import('../../services').ServiceDeps);+ subject = createReferenceService(+ {+ db: { reference },+ } as unknown as import('../../services').ServiceDeps,+ testServices()+ );});beforeEach(() => {diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsindex b9317a036..1fe442152 100644--- a/packages/core/src/modules/reference/reference.service.ts+++ b/packages/core/src/modules/reference/reference.service.ts@@ -12,7 +12,7 @@// worker per test file — left to defer (docs/TECH_DEBT.md §4).import type { Reference } from '@openpanel/db/src/prisma-client';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getChartStartEndDate } from '../../shared/date';import { getSettingsForProject } from '../organization/organization.service';import type { IChartRange } from '../report/report.constants';@@ -145,7 +145,10 @@ export interface ReferenceService {getChartReferences(input: ChartReferencesInput): Promise<Reference[]>;}-export function createReferenceService(deps: ServiceDeps): ReferenceService {+export function createReferenceService(+ deps: ServiceDeps,+ _services: () => Services+): ReferenceService {return {getReferenceById: (id) => getReferenceById(deps, id),getReferenceByIdOrThrow: (id) => getReferenceByIdOrThrow(deps, id),diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.tsindex 38fc08762..47b25500f 100644--- a/packages/core/src/modules/report/report.service.ts+++ b/packages/core/src/modules/report/report.service.ts@@ -14,7 +14,7 @@ import type {ReportLayout,} from '@openpanel/db/src/prisma-client';import { TRPCBadRequestError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getChartStartEndDate } from '../../shared/date';import { getFunnel } from '../chart/funnel.service';import {@@ -512,7 +512,10 @@ export interface ReportService {): ReturnType<typeof resetReportLayouts>;}-export function createReportService(deps: ServiceDeps): ReportService {+export function createReportService(+ deps: ServiceDeps,+ _services: () => Services+): ReportService {return {transformFilter,transformReportEventItem,diff --git a/packages/core/src/modules/salt/salt.service.test.ts b/packages/core/src/modules/salt/salt.service.test.tsindex 1873943d8..4f2cc6aea 100644--- a/packages/core/src/modules/salt/salt.service.test.ts+++ b/packages/core/src/modules/salt/salt.service.test.ts@@ -13,6 +13,7 @@// exercised directly instead.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeSalt {salt: string;@@ -99,7 +100,7 @@ beforeAll(async () => {const deps = {db: { salt: saltDelegate, $transaction },} as unknown as import('../../services').ServiceDeps;- subject = mod.createSaltService(deps);+ subject = mod.createSaltService(deps, testServices());});beforeEach(() => {diff --git a/packages/core/src/modules/salt/salt.service.ts b/packages/core/src/modules/salt/salt.service.tsindex 3b55126a1..dce0caf7f 100644--- a/packages/core/src/modules/salt/salt.service.ts+++ b/packages/core/src/modules/salt/salt.service.ts@@ -18,7 +18,7 @@// closure's cache, which is why it lives inside the factory too.import { cacheable } from '@openpanel/redis';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { generateSalt } from '../../shared/crypto';const SALT_CACHE_NAME = 'op:salt';@@ -94,7 +94,10 @@ export interface SaltService {rotateSalt(): Promise<{ salt: string; createdAt: Date }>;}-export function createSaltService(deps: ServiceDeps): SaltService {+export function createSaltService(+ deps: ServiceDeps,+ _services: () => Services+): SaltService {const getSalts = cacheable(SALT_CACHE_NAME,() => fetchSalts(deps),diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 6f078c4d0..942153683 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -18,7 +18,7 @@// imports, kept lazy for a cycle, not for a client.import { cacheable } from '@openpanel/redis';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { chQuery } from '../../shared/ch-query';import { getSafeJson } from '../../shared/json';import type { IServiceProfile } from '../profile/profile.service';@@ -511,7 +511,10 @@ export interface SessionService {enqueueSessionEnd(input: EnqueueSessionEndInput): Promise<void>;}-export function createSessionService(deps: ServiceDeps): SessionService {+export function createSessionService(+ deps: ServiceDeps,+ _services: () => Services+): SessionService {return {byId: (sessionId, projectId) => getSessionById(deps, sessionId, projectId),enqueueSessionEnd: async (input) => {diff --git a/packages/core/src/modules/share/share.service.test.ts b/packages/core/src/modules/share/share.service.test.tsindex 8302bdf7e..be23d98a2 100644--- a/packages/core/src/modules/share/share.service.test.ts+++ b/packages/core/src/modules/share/share.service.test.ts@@ -5,6 +5,7 @@// `afterAll` restores the real module instead of re-applying the mock.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';interface FakeShare {id: string;@@ -220,9 +221,12 @@ afterAll(() => {let subject: import('./share.service').ShareService;beforeAll(async () => {const { createShareService } = await import('./share.service');- subject = createShareService({- db: { shareOverview, shareDashboard, shareReport },- } as unknown as import('../../services').ServiceDeps);+ subject = createShareService(+ {+ db: { shareOverview, shareDashboard, shareReport },+ } as unknown as import('../../services').ServiceDeps,+ testServices()+ );});beforeEach(() => {diff --git a/packages/core/src/modules/share/share.service.ts b/packages/core/src/modules/share/share.service.tsindex 10067cae0..003a03868 100644--- a/packages/core/src/modules/share/share.service.ts+++ b/packages/core/src/modules/share/share.service.ts@@ -14,7 +14,7 @@import ShortUniqueId from 'short-unique-id';import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';import { getProjectAccess } from '../../shared/access-lookups';import { hashPassword } from '../auth/auth.service';import { getDashboardById } from '../dashboard/dashboard.service';@@ -659,7 +659,10 @@ export interface ShareService {): ReturnType<typeof createShareReport>;}-export function createShareService(deps: ServiceDeps): ShareService {+export function createShareService(+ deps: ServiceDeps,+ _services: () => Services+): ShareService {return {getShareOverviewById: (id) => getShareOverviewById(deps, id),getShareByProjectId: (projectId) => getShareByProjectId(deps, projectId),diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.tsindex 68daeb8d4..b8f733956 100644--- a/packages/core/src/modules/subscription/subscription.service.ts+++ b/packages/core/src/modules/subscription/subscription.service.ts@@ -41,7 +41,7 @@ import { addMonths, subDays } from 'date-fns';import { z } from 'zod';import type { Logger } from '../../logger';import { TRPCBadRequestError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';// `getOrganizationById` takes `ServiceDeps` since M10-009 and these four// functions carry none (V1's still-live subscription router calls them with a// bare userId) — reached through the v1-compat seam, same as the rest of this@@ -838,7 +838,8 @@ export interface SubscriptionService {}export function createSubscriptionService(- deps: ServiceDeps+ deps: ServiceDeps,+ _services: () => Services): SubscriptionService {return {getCurrentSubscriptionProduct,diff --git a/packages/core/src/modules/user/user.service.test.ts b/packages/core/src/modules/user/user.service.test.tsindex 4404815b6..fe1eea6d5 100644--- a/packages/core/src/modules/user/user.service.test.ts+++ b/packages/core/src/modules/user/user.service.test.ts@@ -3,6 +3,7 @@// idiom as reference.service.test.ts.import { beforeEach, expect, mock, test } from 'bun:test';+import { testServices } from '../../../test/service-deps';import type { ServiceDeps } from '../../services';import { createUserService } from './user.service';@@ -90,9 +91,12 @@ const organization = {),};-const subject = createUserService({- db: { user, organization },-} as unknown as ServiceDeps);+const subject = createUserService(+ {+ db: { user, organization },+ } as unknown as ServiceDeps,+ testServices()+);beforeEach(() => {userStore.clear();diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.tsindex ef7867652..0252c399a 100644--- a/packages/core/src/modules/user/user.service.ts+++ b/packages/core/src/modules/user/user.service.ts@@ -12,7 +12,7 @@import type { User } from '@openpanel/db/src/prisma-client';import { TRPCBadRequestError } from '../../rpc/errors';-import type { ServiceDeps } from '../../services';+import type { ServiceDeps, Services } from '../../services';export type IServiceUser = Awaited<ReturnType<typeof getUserById>>;@@ -152,7 +152,10 @@ export interface UserService {): ReturnType<typeof updateUserProfile>;}-export function createUserService(deps: ServiceDeps): UserService {+export function createUserService(+ deps: ServiceDeps,+ _services: () => Services+): UserService {return {getUserById: (id) => getUserById(deps, id),getUserAccount: (args) => getUserAccount(deps, args),diff --git a/packages/core/src/services.test.ts b/packages/core/src/services.test.tsnew file mode 100644index 000000000..944d57855--- /dev/null+++ b/packages/core/src/services.test.ts@@ -0,0 +1,73 @@+// The composition root's two runtime invariants (ADR-022 R3). Neither is+// visible to `tooling/gates/conformance.sh`, which reads signatures only.+//+// Deliberately mock-free: this suite exists to run the REAL 36 factories, so+// a `mock.module` here would test the stub instead of the composition root.++import { expect, test } from 'bun:test';+import type { Logger } from './logger';+import { createServices, type ServiceDeps } from './services';++const SERVICE_COUNT = 36;++function stubLogger(): Logger {+ const noop = () => undefined;+ const logger: Logger = {+ fatal: noop,+ error: noop,+ warn: noop,+ info: noop,+ debug: noop,+ trace: noop,+ child: () => logger,+ };+ return logger;+}++/** Everything a factory must NOT touch while the container is being built:+ * the `services()` thunk is deferred, and so is every connection-backed+ * handle. Reaching one during construction names itself here. */+function constructionOnlyDeps(): ServiceDeps {+ const unavailable = (name: string): never => {+ throw new Error(`${name} was read while the container was being built`);+ };+ return {+ logger: stubLogger(),+ get db(): never {+ return unavailable('ServiceDeps.db');+ },+ get ch(): never {+ return unavailable('ServiceDeps.ch');+ },+ get redis(): never {+ return unavailable('ServiceDeps.redis');+ },+ get clients(): never {+ return unavailable('ServiceDeps.clients');+ },+ get buffers(): never {+ return unavailable('ServiceDeps.buffers');+ },+ get queues(): never {+ return unavailable('ServiceDeps.queues');+ },+ } as unknown as ServiceDeps;+}++test('every factory builds without reaching a sibling or a connection', () => {+ const services = createServices(constructionOnlyDeps());++ const missing = Object.entries(services)+ .filter(([, member]) => member === undefined)+ .map(([key]) => key);+ expect(missing).toEqual([]);+ expect(Object.keys(services)).toHaveLength(SERVICE_COUNT);+});++test('each call returns its own container — the graph is per unit of work', () => {+ const first = createServices(constructionOnlyDeps());+ const second = createServices(constructionOnlyDeps());++ expect(second).not.toBe(first);+ expect(second.session).not.toBe(first.session);+});diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex 8691575f3..eade1024b 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -201,46 +201,53 @@ export interface Services {mcp: McpService;}+// MUST stay a hoisted `function` declaration, not a `const` arrow: one static+// ESM cycle runs through it (subscription.service.ts -> v1-compat.ts ->+// services.ts -> subscription.service.ts) and hoisting is the only reason it+// evaluates. A `const` would put it in a temporal dead zone that no typecheck+// reports and that fails at process boot.export function createServices(deps: ServiceDeps): Services {- // When a second module needs to call this one, each factory takes `deps`- // and a `() => container` thunk: captured, not copied, so two services may- // call each other without a cycle.- return {- auth: createAuthService(),- insight: createInsightService(deps),- gsc: createGscService(deps),- cohort: createCohortService(deps),- import: createImportService(deps),- ingest: createIngestService(deps),- organization: createOrganizationService(deps),- integration: createIntegrationService(deps),- onboarding: createOnboardingService(deps),- notification: createNotificationService(deps),- session: createSessionService(deps),- event: createEventService(deps),- profile: createProfileService(deps),- group: createGroupService(deps),- chart: createChartService(deps),- funnel: createFunnelService(deps),- conversion: createConversionService(deps),- sankey: createSankeyService(deps),- retention: createRetentionService(deps),- overview: createOverviewService(deps),- pages: createPagesService(deps),- realtime: createRealtimeService(deps),- misc: createMiscService(deps),- report: createReportService(deps),- dashboard: createDashboardService(deps),- export: createExportService(deps),- share: createShareService(deps),- reference: createReferenceService(deps),- client: createClientService(deps),- project: createProjectService(deps),- user: createUserService(deps),- subscription: createSubscriptionService(deps),- salt: createSaltService(deps),- conversation: createConversationService(deps),- assistant: createAssistantService(),- mcp: createMcpService(),+ // The thunk is captured, not copied, so two services may call each other+ // without a cycle: `container` is assigned before any thunk body can run,+ // because every sibling reach lives inside a method body.+ const services = (): Services => container;+ const container: Services = {+ auth: createAuthService(deps, services),+ insight: createInsightService(deps, services),+ gsc: createGscService(deps, services),+ cohort: createCohortService(deps, services),+ import: createImportService(deps, services),+ ingest: createIngestService(deps, services),+ organization: createOrganizationService(deps, services),+ integration: createIntegrationService(deps, services),+ onboarding: createOnboardingService(deps, services),+ notification: createNotificationService(deps, services),+ session: createSessionService(deps, services),+ event: createEventService(deps, services),+ profile: createProfileService(deps, services),+ group: createGroupService(deps, services),+ chart: createChartService(deps, services),+ funnel: createFunnelService(deps, services),+ conversion: createConversionService(deps, services),+ sankey: createSankeyService(deps, services),+ retention: createRetentionService(deps, services),+ overview: createOverviewService(deps, services),+ pages: createPagesService(deps, services),+ realtime: createRealtimeService(deps, services),+ misc: createMiscService(deps, services),+ report: createReportService(deps, services),+ dashboard: createDashboardService(deps, services),+ export: createExportService(deps, services),+ share: createShareService(deps, services),+ reference: createReferenceService(deps, services),+ client: createClientService(deps, services),+ project: createProjectService(deps, services),+ user: createUserService(deps, services),+ subscription: createSubscriptionService(deps, services),+ salt: createSaltService(deps, services),+ conversation: createConversationService(deps, services),+ assistant: createAssistantService(deps, services),+ mcp: createMcpService(deps, services),};+ return container;}diff --git a/packages/core/test/service-deps.ts b/packages/core/test/service-deps.tsindex 660115cb7..f202bc2db 100644--- a/packages/core/test/service-deps.ts+++ b/packages/core/test/service-deps.ts@@ -6,7 +6,7 @@// container.import type { Logger } from '../src/logger';-import type { ServiceDeps } from '../src/services';+import type { ServiceDeps, Services } from '../src/services';/** Records what the ClickHouse/Postgres call was logged with — the requestId* chain's observation point. */@@ -36,7 +36,14 @@ export function recordingLogger(}function unavailable(name: string): never {- throw new Error(`ServiceDeps.${name} is not built in this test`);+ throw new Error(`${name} is not built in this test`);+}++/** The `services()` thunk every factory takes (ADR-022 R3). No suite here+ * reaches a sibling, so calling it is a named error rather than a silently+ * half-built container; a suite that needs one passes its own thunk. */+export function testServices(): () => Services {+ return () => unavailable('services()');}export async function testServiceDeps(@@ -53,13 +60,13 @@ export async function testServiceDeps(redis,logger: recordingLogger(),get clients(): never {- return unavailable('clients');+ return unavailable('ServiceDeps.clients');},get buffers(): never {- return unavailable('buffers');+ return unavailable('ServiceDeps.buffers');},get queues(): never {- return unavailable('queues');+ return unavailable('ServiceDeps.queues');},...overrides,};