OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
comments: drop citations to documents this repo does not contain
Carl-Gerhard Lindesvärd7ad4e4672f21
diff --git a/apps/api/e2e/legacy-job-proof.ts b/apps/api/e2e/legacy-job-proof.tsindex 4fc557cbc..8ad972ef0 100644--- a/apps/api/e2e/legacy-job-proof.ts+++ b/apps/api/e2e/legacy-job-proof.ts@@ -1,9 +1,8 @@/**- * M9-001 acceptance proof: a LEGACY-shaped job already sitting in Redis is- * still picked up and run by the V2 worker, with no drain and no rename- * (ADR-005). Plus the other direction — a job the V2 producer enqueues- * carries the `{payload, meta}` envelope and its `requestId` reaches the- * handler's logger (ADR-018 R1).+ * Acceptance proof: a LEGACY-shaped job already sitting in Redis is still+ * picked up and run by the V2 worker, with no drain and no rename. Plus the+ * other direction — a job the V2 producer enqueues carries the `{payload,+ * meta}` envelope and its `requestId` reaches the handler's logger.** What is real here: the registry (`queues`), every `compat` hook, every job* payload schema, `resolveJob`, BullMQ, and Redis. The legacy jobs are put in@@ -13,16 +12,15 @@** Two deliberate narrowings, both stated in the output:*- * 1. It runs on a `-m9001proof` queue-key namespace, not on the shared dev- * Redis's live `cron`/`sessions`/… keys, so it can neither consume nor be- * confused by whatever the golden harness left there. Only the key string- * differs; the un-namespaced keys' byte-identity is pinned separately by- * `packages/core/src/jobs/naming.test.ts`.- * 2. `cron` runs its REAL handlers over the REAL boot buffers. The other six- * queues' handlers reach `ctx.services`, which needs the db/ch clients- * `AppDeps` does not carry until M9-002/M9-003, so for those six the- * handler body is a recorder — everything up to and including the handler- * lookup is the real thing.+ * 1. It runs on a `-m9001proof` queue-key namespace, not on the shared dev+ * Redis's live `cron`/`sessions`/… keys, so it can neither consume nor be+ * confused by whatever the golden harness left there. Only the key string+ * differs; the un-namespaced keys' byte-identity is pinned separately by+ * `packages/core/src/jobs/naming.test.ts`. 2. `cron` runs its REAL handlers+ * over the REAL boot buffers. The other six queues' handlers reach+ * `ctx.services`, which needs the db/ch clients `AppDeps` does not carry until+ * M9-002/M9-003, so for those six the handler body is a recorder — everything+ * up to and including the handler lookup is the real thing.** Run: `bash apps/api/e2e/legacy-job-proof.sh`*/diff --git a/apps/api/e2e/redis-command-cost.ts b/apps/api/e2e/redis-command-cost.tsindex b40395555..a0c1c32de 100644--- a/apps/api/e2e/redis-command-cost.ts+++ b/apps/api/e2e/redis-command-cost.ts@@ -1,23 +1,22 @@/**- * M18-003 — what does a LEGITIMATE Redis command on the cache client cost?+ * What does a LEGITIMATE Redis command on the cache client cost?** `commandTimeout` on the cache client is a deadline every command on the* ingest path now runs under, including the event buffer's writes and reads.- * Picking it needs the cost of the heaviest honest command, not a guess: if- * the deadline is anywhere near a busy flush, a healthy server starts looking- * like a down one and M18-001's shutdown path starts refusing to commit- * offsets it should have committed.+ * Picking it needs the cost of the heaviest honest command, not a guess: if the+ * deadline is anywhere near a busy flush, a healthy server starts looking like+ * a down one and M18-001's shutdown path starts refusing to commit offsets it+ * should have committed.*- * Measures the four shapes the cache client actually issues, worst first:- * - `MULTI` of `EVENT_BUFFER_BATCH_SIZE` rpush — the shutdown flush of a- * full local buffer (`event-buffer.ts:writeToRedis`).- * - `MULTI` of the micro-batch size — the steady-state ingest write.- * - `LRANGE 0..batchSize-1` — the cron flush read (`processBuffer`).- * - `GET` — every cache/auth lookup.+ * Measures the four shapes the cache client actually issues, worst first: -+ * `MULTI` of `EVENT_BUFFER_BATCH_SIZE` rpush — the shutdown flush of a full+ * local buffer (`event-buffer.ts:writeToRedis`). - `MULTI` of the micro-batch+ * size — the steady-state ingest write. - `LRANGE 0..batchSize-1` — the cron+ * flush read (`processBuffer`). - `GET` — every cache/auth lookup.** Runs against the local server in its own database with its own key prefix.*- * dotenv -e ../../.env -- bun e2e/redis-command-cost.ts+ * Dotenv -e../../.env -- bun e2e/redis-command-cost.ts*/import { Redis } from '@openpanel/redis';diff --git a/apps/api/e2e/redis-fail-fast.ts b/apps/api/e2e/redis-fail-fast.tsindex 53d0e52fe..048fe0e18 100644--- a/apps/api/e2e/redis-fail-fast.ts+++ b/apps/api/e2e/redis-fail-fast.ts@@ -1,5 +1,5 @@/**- * M18-003 — how long does `/track` take when the Redis CACHE is unreachable?+ * How long does `/track` take when the Redis CACHE is unreachable?** Drill 02 measured 9,427 / 12,039 / 41,978 ms and 10-of-20 no-answer. This* harness reproduces that measurement in-repo so the fix can be justified with@@ -7,10 +7,10 @@** It never touches the shared Redis server: the API under test is pointed at a* local TCP proxy which is then stopped (`refuse`, docker-stop shaped) or- * frozen (`blackhole`, docker-pause shaped). The operator's stack keeps its- * own connection to :6379 throughout.+ * frozen (`blackhole`, docker-pause shaped). The operator's stack keeps its own+ * connection to:6379 throughout.*- * dotenv -e ../../.env -- bun e2e/redis-fail-fast.ts+ * Dotenv -e../../.env -- bun e2e/redis-fail-fast.ts*/import { spawn } from 'node:child_process';diff --git a/apps/api/e2e/saturation-sweep.ts b/apps/api/e2e/saturation-sweep.tsindex 8bf5af922..55d84023e 100644--- a/apps/api/e2e/saturation-sweep.ts+++ b/apps/api/e2e/saturation-sweep.ts@@ -1,5 +1,5 @@/**- * Saturation sweep — the ramp driver on top of `session-stress.ts` (M16-001).+ * Saturation sweep — the ramp driver on top of `session-stress.ts`.** GOAL: find the MAX SUSTAINABLE INGEST THROUGHPUT, defined as the highest* offered load at which the pipeline still drains. It runs `session-stress.ts`@@ -7,18 +7,16 @@* connection, cached pid or latency sink leaks between rungs), parses each* rung's machine-readable result line, and applies the knee definition below.*- * THE KNEE, exactly as implemented in `classifyRung()`. A rung DID NOT DRAIN if- * any of these is true:- * 1. `lag.secondsToZeroAfterEmitEnd` is null — the Kafka consumer group was- * still behind when sampling stopped.- * 2. That figure grew rung-over-rung rather than staying flat: more than- * SWEEP_DRAIN_GROWTH_FACTOR x the best drain time seen so far, AND more- * than SWEEP_DRAIN_GROWTH_MIN_S seconds worse in absolute terms (the- * absolute floor keeps 0.4s → 0.9s from reading as a knee).- * 3. A queue depth or a buffer pending count failed to return to zero.- * The first such rung is the knee. The last rung BEFORE it is the max- * sustainable throughput, reported in events/second with that rung's api and- * worker CPU and RSS.+ * THE KNEE, exactly as implemented in `classifyRung`. A rung DID NOT DRAIN if+ * any of these is true: 1. `lag.secondsToZeroAfterEmitEnd` is null — the Kafka+ * consumer group was still behind when sampling stopped. 2. That figure grew+ * rung-over-rung rather than staying flat: more than SWEEP_DRAIN_GROWTH_FACTOR+ * x the best drain time seen so far, AND more than SWEEP_DRAIN_GROWTH_MIN_S+ * seconds worse in absolute terms (the absolute floor keeps 0.4s → 0.9s from+ * reading as a knee). 3. A queue depth or a buffer pending count failed to+ * return to zero. The first such rung is the knee. The last rung BEFORE it is+ * the max sustainable throughput, reported in events/second with that rung's+ * api and worker CPU and RSS.** A rung that fails to drain is a DATA POINT, not a harness error: it is* recorded, the ladder stops climbing, and the sweep still exits 0. The sweep@@ -26,9 +24,9 @@* result).** AUTH: defaults to E2E_AUTH_MODE=secret — the pessimistic, server-side-SDK- * path through the cached scrypt verify. The two other paths are reachable- * with SWEEP_AUTH_MODE=cors (browser traffic) and SWEEP_AUTH_MODE=bypass- * (diagnostic baseline, no real traffic takes it).+ * path through the cached scrypt verify. The two other paths are reachable with+ * SWEEP_AUTH_MODE=cors (browser traffic) and SWEEP_AUTH_MODE=bypass (diagnostic+ * baseline, no real traffic takes it).** Full knob list and how to read the output: docs/BENCHMARK_HARNESS.md.*/diff --git a/apps/api/e2e/session-stress.ts b/apps/api/e2e/session-stress.tsindex 258fbd497..9776c90ae 100644--- a/apps/api/e2e/session-stress.ts+++ b/apps/api/e2e/session-stress.ts@@ -2,42 +2,41 @@* Session stress + drain-to-completion.** Ramps out many short sessions (default 500, not all at once), then drives the- * reaper + buffer flushes until EVERYTHING has fully drained — every session_end- * emitted, Redis cleaned, the session buffer empty — and reconciles the- * ClickHouse counts. Exits 0 only when nothing is left open.+ * reaper + buffer flushes until EVERYTHING has fully drained — every+ * session_end emitted, Redis cleaned, the session buffer empty — and reconciles+ * the ClickHouse counts. Exits 0 only when nothing is left open.** Also instruments the run (BENCH-001): per-request /track latency- * (P50/P95/P99, emit phase only), RSS/CPU of the api + worker processes- * (>=1Hz, peak + steady-state), Kafka consumer-group lag on the events- * topic (>=1Hz; peak, lag at emit-end, seconds-to-zero after emit stops),- * and every BullMQ queue depth + buffer pending count scraped off /metrics- * (>=1Hz; peak, depth at emit-end, whether it returned to zero — M16-001).- * None of it changes what the run asserts — see `check()` calls below,- * unchanged from the un-instrumented version.+ * (P50/P95/P99, emit phase only), RSS/CPU of the api + worker processes (>=1Hz,+ * peak + steady-state), Kafka consumer-group lag on the events topic (>=1Hz;+ * peak, lag at emit-end, seconds-to-zero after emit stops), and every BullMQ+ * queue depth + buffer pending count scraped off /metrics (>=1Hz; peak, depth+ * at emit-end, whether it returned to zero — M16-001). None of it changes what+ * the run asserts — see `check` calls below, unchanged from the un-instrumented+ * version.** `saturation-sweep.ts` drives this script across a ladder of offered loads;* see docs/BENCHMARK_HARNESS.md.** Run (shrink the idle window; start the stack with the SAME value):- * SESSION_TIMEOUT_MS=4000 pnpm dev- * SESSION_TIMEOUT_MS=4000 pnpm --filter @openpanel/api e2e:sessions:stress+ * SESSION_TIMEOUT_MS=4000 pnpm dev SESSION_TIMEOUT_MS=4000 pnpm --filter+ * @openpanel/api e2e:sessions:stress** Tunables (env): E2E_SESSIONS (500), E2E_CONCURRENCY (25),- * E2E_EVENTS_PER_SESSION (3), E2E_DRAIN_TIMEOUT_MS (120000),- * E2E_RECONCILE_TIMEOUT_MS (30000), E2E_RUNS (1) — run the whole harness- * E2E_RUNS times (as separate processes, so no state leaks between them)- * and print a median summary across runs at the end. E2E_NO_SAMPLING (0) —- * skip starting the process/lag monitors entirely (per-request latency- * still records; it's inherent to what's measured, not background- * polling). Control lever for isolating whether the >=1Hz sampling itself- * is dragging on throughput, e.g. `E2E_RUNS=3 E2E_NO_SAMPLING=1`.- * E2E_AUTH_MODE (bypass) — which ingest auth path every request takes:- * `bypass` | `cors` | `secret`; see AUTH_PATH_DESCRIPTION in lib.ts. The- * default keeps this script on the path the pre-existing suites were- * written against; `saturation-sweep.ts` defaults to `secret`.- * E2E_AUTH_WARM_REQUESTS (3) — authenticated requests sent and discarded- * before recording starts, so the scrypt verify behind VERIFY_CACHE_SECONDS- * is paid outside the measured window.+ * E2E_EVENTS_PER_SESSION (3), E2E_DRAIN_TIMEOUT_MS (120000),+ * E2E_RECONCILE_TIMEOUT_MS (30000), E2E_RUNS (1) — run the whole harness+ * E2E_RUNS times (as separate processes, so no state leaks between them) and+ * print a median summary across runs at the end. E2E_NO_SAMPLING (0) — skip+ * starting the process/lag monitors entirely (per-request latency still+ * records; it's inherent to what's measured, not background polling). Control+ * lever for isolating whether the >=1Hz sampling itself is dragging on+ * throughput, e.g. `E2E_RUNS=3 E2E_NO_SAMPLING=1`. E2E_AUTH_MODE (bypass) —+ * which ingest auth path every request takes: `bypass` | `cors` | `secret`; see+ * AUTH_PATH_DESCRIPTION in lib.ts. The default keeps this script on the path+ * the pre-existing suites were written against; `saturation-sweep.ts` defaults+ * to `secret`. E2E_AUTH_WARM_REQUESTS (3) — authenticated requests sent and+ * discarded before recording starts, so the scrypt verify behind+ * VERIFY_CACHE_SECONDS is paid outside the measured window.*/import { spawn } from 'node:child_process';@@ -597,12 +596,12 @@ function runChild(index: number, total: number): Promise<RunResult> {);return new Promise<RunResult>((resolve, reject) => {// Re-run the same package.json script rather than replaying argv: argv[1]- // here is a bare .ts path that only resolves because the *current*- // process already has jiti's loader hook registered in-process — a fresh- // node/bun invocation needs the same wrapper the user ran ("pnpm run- // <script>") to get that hook again. This also means the repeat mode- // keeps working unchanged once the toolchain moves to Bun (ADR-001):- // whatever `e2e:sessions:stress` runs then is what gets re-exec'd.+ // here is a bare.ts path that only resolves because the *current* process+ // already has jiti's loader hook registered in-process — a fresh node/bun+ // invocation needs the same wrapper the user ran ("pnpm run <script>") to+ // get that hook again. This also means the repeat mode keeps working+ // unchanged once the toolchain moves to Bun: whatever `e2e:sessions:stress`+ // runs then is what gets re-exec'd.const child = spawn('pnpm', ['run', 'e2e:sessions:stress'], {cwd: process.cwd(),env: { ...process.env, E2E_RUNS: '1', E2E_STRESS_CHILD: '1' },diff --git a/apps/api/e2e/trpc-routing-golden.ts b/apps/api/e2e/trpc-routing-golden.tsindex 7de486148..a98eec31a 100644--- a/apps/api/e2e/trpc-routing-golden.ts+++ b/apps/api/e2e/trpc-routing-golden.ts@@ -1,23 +1,22 @@#!/usr/bin/env bun/**- * tRPC routing golden — proves every procedure the mounted router declares is+ * TRPC routing golden — proves every procedure the mounted router declares is* reachable through the real HTTP lifecycle, and that the auth layer answers* identically before and after the M11-001 mount swap.** Only 11 of 217 procedures have any end-to-end coverage and 22 of the 29- * routers have none (docs/RPC_PROCEDURE_SET_EQUIVALENCE.md), so swapping- * `apps/api/src/main.ts`'s `appRouter` import needs a proof of its own. This- * is it: with the harness up, run it against the OLD mount, swap, run it- * against the NEW mount, and diff the two maps.+ * routers have none, so swapping `apps/api/src/main.ts`'s `appRouter` import+ * needs a proof of its own. This is it: with the harness up, run it against the+ * OLD mount, swap, run it against the NEW mount, and diff the two maps.*- * It asserts REACHABILITY, not behaviour. Every request is unauthenticated- * with an empty input, so 401/403/400 are the expected answers — they prove- * the procedure was resolved and its auth/validation middleware ran. Only a- * 404 or a tRPC `NOT_FOUND` means the router did not resolve the path, and- * that is the single failure this script exists to catch.+ * It asserts REACHABILITY, not behaviour. Every request is unauthenticated with+ * an empty input, so 401/403/400 are the expected answers — they prove the+ * procedure was resolved and its auth/validation middleware ran. Only a 404 or+ * a tRPC `NOT_FOUND` means the router did not resolve the path, and that is the+ * single failure this script exists to catch.*- * Usage (needs `verification/harness start`):- * cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json+ * Usage (needs `verification/harness start`): cd apps/api && bun run+ * e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json** The router is imported from whatever specifier `main.ts` mounts, read out of* main.ts itself, so the same committed script measures both sides of the swapdiff --git a/apps/api/src/config/bun-version.test.ts b/apps/api/src/config/bun-version.test.tsindex fc531c861..3527fff01 100644--- a/apps/api/src/config/bun-version.test.ts+++ b/apps/api/src/config/bun-version.test.ts@@ -2,10 +2,10 @@ import { describe, expect, it } from 'bun:test';import { readFileSync } from 'node:fs';import { join } from 'node:path';-// ADR-016 rule 5 wants the Bun pin asserted in three places: .bun-version,-// scripts/doctor.sh, and a boot log line — and all three must agree with-// each other and with the Dockerfile's ARG BUN_VERSION. A test proving that-// is worth more than the three edits it checks.+// Rule 5 wants the Bun pin asserted in three places:.bun-version,+// scripts/doctor.sh, and a boot log line — and all three must agree with each+// other and with the Dockerfile's ARG BUN_VERSION. A test proving that is worth+// more than the three edits it checks.const REPO_ROOT = join(import.meta.dir, '../../../..');function readBunVersionFile(): string {diff --git a/apps/api/src/config/env.test.ts b/apps/api/src/config/env.test.tsindex 7cce932a6..5fdc6f16c 100644--- a/apps/api/src/config/env.test.ts+++ b/apps/api/src/config/env.test.ts@@ -127,7 +127,7 @@ describe('the boot flags main.ts branches on', () => {});});-// --- M15-006: the parsing core used to do for itself -------------------------+// -- M15-006: the parsing core used to do for itself -------------------------describe('blank KEY= is absent, not empty', () => {it('falls through to the default on every field, not just the preprocessed ones', () => {@@ -337,8 +337,8 @@ describe('derived values, computed once in the transform', () => {});it('the dead-letter list cap defaults to 1000 and takes a positive integer', () => {- // The Kafka DLQ topic above is no longer the dead-letter destination- // (M20-001) — it is kept only so the seam can be swapped back.+ // The Kafka DLQ topic above is no longer the dead-letter destination — it+ // is kept only so the seam can be swapped back.expect(loadConfig(base).INGEST_DEAD_LETTER_MAX_ENTRIES).toBe(1000);expect(loadConfig({ ...base, INGEST_DEAD_LETTER_MAX_ENTRIES: '25' })diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.tsindex bf0f3fa7f..76b442e24 100644--- a/apps/api/src/config/env.ts+++ b/apps/api/src/config/env.ts@@ -1,31 +1,30 @@// The sole `process.env` READER on the V2 boot path, and since M15-006 that is-// true rather than aspirational: `packages/core` reads none (ADR-022 R7), so-// every variable core used to read itself is parsed here and travels down as-// `AppDeps.config` (`CoreConfig`). The one other `process.env` touch on the-// path is `main.ts`'s `process.env.TZ = 'UTC'` write, which sets the process's-// timezone rather than reading configuration. `packages/db` and-// `packages/redis` keep reading their own connection env until they grow-// factories — an accepted pragmatic deviation (ADR-007 §7).+// true rather than aspirational: `packages/core` reads none, so every variable+// core used to read itself is parsed here and travels down as `AppDeps.config`+// (`CoreConfig`). The one other `process.env` touch on the path is `main.ts`'s+// `process.env.TZ = 'UTC'` write, which sets the process's timezone rather than+// reading configuration. `packages/db` and `packages/redis` keep reading their+// own connection env until they grow factories — an accepted pragmatic+// deviation (ADR-007 §7).//-// The shape is ADR-022 R17's, in this order:-// 1. one zod object over the raw environment;-// 2. every cross-field invariant as a `.superRefine` BEFORE the transform,-// so a contradiction is named at boot rather than discovered at runtime;-// 3. one `.transform` that computes every derived value — URLs, namespaces,-// IS_PRODUCTION, the listen address, the concurrency map — so nothing-// downstream re-derives one;-// 4. `loadConfig(source = process.env)`, so a test hands in a minimal object.+// The shape is ADR-022 R17's, in this order: 1. one zod object over the raw+// environment; 2. every cross-field invariant as a `.superRefine` BEFORE the+// transform, so a contradiction is named at boot rather than discovered at+// runtime; 3. one `.transform` that computes every derived value — URLs,+// namespaces, IS_PRODUCTION, the listen address, the concurrency map — so+// nothing downstream re-derives one; 4. `loadConfig(source = process.env)`, so+// a test hands in a minimal object.//// A blank `KEY=` is absent everywhere: `blankToUndefined` runs in front of-// every field, so `.default()` fires on an empty value exactly as it does on-// an unset one.+// every field, so `.default` fires on an empty value exactly as it does on an+// unset one.//-// Invalid config fails boot loudly, with every issue reported at once — never-// a fail-fast on the first bad var. Two classes, deliberately different:-// - boot-critical values (roles, queues, Kafka wiring) FAIL;-// - tuning knobs (batch sizes, limits, TTLs) fall back to the module's own-// documented default on a malformed value, which is what the modules did-// when they parsed these themselves.+// Invalid config fails boot loudly, with every issue reported at once — never a+// fail-fast on the first bad var. Two classes, deliberately different: -+// boot-critical values (roles, queues, Kafka wiring) FAIL; - tuning knobs+// (batch sizes, limits, TTLs) fall back to the module's own documented default+// on a malformed value, which is what the modules did when they parsed these+// themselves.import type { CoreConfig, KafkaSaslMechanism } from '@openpanel/core';import { KAFKA_SASL_MECHANISMS, queues } from '@openpanel/core';@@ -71,14 +70,14 @@ const DEFAULT_KAFKA_PRODUCER_MAX_IN_FLIGHT = 1;const DEFAULT_KAFKA_PRODUCER_BATCH_SIZE = 25;/*** A partial batch's maximum wait. The linger is added to the request's own- * response time, so ADR-023 takes 5 ms (82% of the available gain) over the- * 25 ms that would roughly double a quiet install's ingest latency.+ * response time, so ADR-023 takes 5 ms (82% of the available gain) over the 25+ * ms that would roughly double a quiet install's ingest latency.*/const DEFAULT_KAFKA_PRODUCER_BATCH_LINGER_MS = 5;const DEFAULT_KAFKA_HANDLER_MAX_ATTEMPTS = 3;/**- * How many dead-lettered events the capped Redis list keeps (M20-001). A- * debugging sample, not a recovery mechanism — the volume is in+ * How many dead-lettered events the capped Redis list keeps. A debugging+ * sample, not a recovery mechanism — the volume is in* `kafka_events_dead_lettered_total`. Carl's "only keep the last N events".*/const DEFAULT_INGEST_DEAD_LETTER_MAX_ENTRIES = 1000;@@ -87,26 +86,26 @@ const DEFAULT_KAFKA_HANDLER_RETRY_MAX_MS = 1000;const DEFAULT_KAFKA_SASL_MECHANISM: KafkaSaslMechanism = 'scram-sha-512';/**- * How long a duplicate marker outlives its event (M21-001). It only has to- * outlive the REPLAY window, not the data: drill 08's eviction rejoin — the- * one reassignment that costs duplicate rows — was 3,094 ms, and drill 06's- * lost-ACK replay landed ~30 s after the produce. Two minutes is ~40x the- * first and 4x the second, and covers a process restart resuming from its last+ * How long a duplicate marker outlives its event. It only has to outlive the+ * REPLAY window, not the data: drill 08's eviction rejoin — the one+ * reassignment that costs duplicate rows — was 3,094 ms, and drill 06's+ * lost-ACK replay landed ~30 s after the produce. Two minutes is ~40x the first+ * and 4x the second, and covers a process restart resuming from its last* committed offset.** It is the knob that decides the key count, which is `events/s x TTL`: at the* 5,000 events/s the scaling requirement targets that is 600,000 live markers.- * Measured on this box's Redis 2026-09-14 — 200,000 real markers cost- * 137.6 bytes each including the expires dict — so ~79 MB. Longer is only- * worth buying if a redelivery window longer than this is ever observed.+ * Measured on this box's Redis 2026-09-14 — 200,000 real markers cost 137.6+ * bytes each including the expires dict — so ~79 MB. Longer is only worth+ * buying if a redelivery window longer than this is ever observed.*/const DEFAULT_INGEST_DUPLICATE_MARKER_TTL_MS = 120_000;/**- * The Kafka events consumer's token. Renamed from `events_kafka` — there is- * one events transport now, so there is one token for it (ADR-004 rec 5/6,- * docs/ANSWERS.md §1.3). Carl updates the cloud env at cutover, which is why- * the old spelling gets its own message below rather than being aliased.+ * The Kafka events consumer's token. Renamed from `events_kafka` — there is one+ * events transport now, so there is one token for it (ADR-004 rec 5/6). Carl+ * updates the cloud env at cutover, which is why the old spelling gets its own+ * message below rather than being aliased.*/export const KAFKA_QUEUE_TOKEN = 'events';@@ -124,7 +123,7 @@ const RENAMED_QUEUE_TOKENS: Record<string, string> = {};/** V1's `getConcurrencyFor` key derivation, verbatim — `cohortCompute` keeps- * reading `COHORTCOMPUTE_CONCURRENCY` (ADR-005 acceptance note: no rename). */+ * Reading `COHORTCOMPUTE_CONCURRENCY` (ADR-005 acceptance note: no rename). */const NON_ENV_KEY_CHARS = /[^A-Z0-9]/g;export function concurrencyEnvKey(queueName: string): string {@@ -306,15 +305,15 @@ const roleSchema = z.preprocess(});}})- // Refine before transform (ADR-022 R17): the cast is only ever observed- // once the refinement above has already accepted the value.+ // Refine before transform: the cast is only ever observed once the+ // refinement above has already accepted the value..transform((value) => value as Role));/**- * Same doctrine as ROLE: an unknown token fails boot loudly rather than- * leaving a worker silently idle (V1 ignored it — boot-workers.ts:78-87 —- * which docs/ANSWERS.md §1.3 rules must change). Unset means all of them.+ * Same doctrine as ROLE: an unknown token fails boot loudly rather than leaving+ * a worker silently idle (V1 ignored it — boot-workers.ts:78-87 — which+ * docs/ANSWERS.md §1.3 rules must change). Unset means all of them.*/const enabledQueuesSchema = z.preprocess(blankToUndefined,@@ -377,10 +376,10 @@ const rawSchema = z.object({*/API_HOST: optionalString,/**- * One truthiness rule for the whole tree (M15-006). Core used to read this- * three different ways — `=== 'true'`, `'true' || '1'`, and any truthy- * string — so a `SELF_HOSTED=1` deployment got the SSRF guard dropped but- * kept the cloud-only cron jobs. `true` or `1`, everywhere.+ * One truthiness rule for the whole tree. Core used to read this three+ * different ways — `=== 'true'`, `'true' || '1'`, and any truthy string — so+ * a `SELF_HOSTED=1` deployment got the SSRF guard dropped but kept the+ * cloud-only cron jobs. `true` or `1`, everywhere.*/SELF_HOSTED: trueOrOneSchema,SHUTDOWN_FORCE_EXIT_MS: z.preprocess(@@ -420,8 +419,8 @@ const rawSchema = z.object({DASHBOARD_URL: optionalString,API_CORS_ORIGINS: optionalString,/**- * Signs the three GSC OAuth cookies. Always set in a real deployment- * (docs/ANSWERS.md §1.5); an unset value degrades to V1's `?? ''`.+ * Signs the three GSC OAuth cookies. Always set in a real deployment; an+ * unset value degrades to V1's `?? ''`.*/COOKIE_SECRET: z.preprocess(blankToUndefined,@@ -987,10 +986,10 @@ export interface Config {COOKIE_SECRET: string;SHUTDOWN_FORCE_EXIT_MS: number;/**- * The dead-letter list's cap (M20-001). It sits here rather than in- * `core.kafka` because the destination is no longer Kafka: `apps/api`- * chooses the dead-letter sink, and `packages/core` only knows the- * `sendToDeadLetter` seam it is handed.+ * The dead-letter list's cap. It sits here rather than in `core.kafka`+ * because the destination is no longer Kafka: `apps/api` chooses the+ * dead-letter sink, and `packages/core` only knows the `sendToDeadLetter`+ * seam it is handed.*/INGEST_DEAD_LETTER_MAX_ENTRIES: number;/**@@ -1016,8 +1015,8 @@ export interface Config {}const envSchema = rawSchema- // Every cross-field invariant runs BEFORE the transform (ADR-022 R17), so- // the derivations below can assume a coherent environment.+ // Every cross-field invariant runs BEFORE the transform, so the derivations+ // below can assume a coherent environment..superRefine((raw, ctx) => {checkRoleConsumesSomething(raw, ctx);checkOtlpHasKey(raw, ctx);diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex 9da18c66e..574f497cc 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -5,28 +5,23 @@//// THE ROLE TABLE (TARGET_ARCHITECTURE §7). One process, three shapes://-// | | api | worker | all |-// | ops HTTP + /metrics | x | x | x |-// | producers | x | x | x |-// | BullMQ workers | | x | x |-// | schedulers (cron) | | x | x |-// | Kafka ingest | | x | x |-// | initial salts | | x | x |-// | bull-board | | x | x |-// | queue/buffer/session scrape gauges | | x | x |-// | redis keyspace-notify | x | | x |+// | | api | worker | all | | ops HTTP + /metrics | x | x | x | | producers | x+// | x | x | | BullMQ workers | | x | x | | schedulers (cron) | | x | x | |+// Kafka ingest | | x | x | | initial salts | | x | x | | bull-board | | x | x |+// | queue/buffer/session scrape gauges | | x | x | | redis keyspace-notify | x+// | | x |//-// An unknown ROLE fails boot loudly, naming the value — `config/env.ts`.-// Inside a consuming role, ENABLED_QUEUES narrows *which* of the eight-// consumers start (cloud runs 4 replicas on `events` and 6 on the rest,-// docs/ANSWERS.md §1.3), and an unknown token there fails boot the same way.+// An unknown ROLE fails boot loudly, naming the value — `config/env.ts`. Inside+// a consuming role, ENABLED_QUEUES narrows *which* of the eight consumers start+// (cloud runs 4 replicas on `events` and 6 on the rest), and an unknown token+// there fails boot the same way.//-// THE MOUNTED SURFACE (M9-004). `AppDeps` now carries the real db, ClickHouse,-// Redis and outbound clients, and `buildHttpApp` hangs all four V1 scopes on-// one Bun.serve: the root chain (CORS -> requestId -> timestamp -> ip -> the-// error handler, in V1's order), the ops surface, the public API, the-// dashboard surface and `/trpc`. A role that only consumes serves none of the-// last three — V1's worker never did either.+// THE MOUNTED SURFACE. `AppDeps` now carries the real db, ClickHouse, Redis and+// outbound clients, and `buildHttpApp` hangs all four V1 scopes on one+// Bun.serve: the root chain (CORS -> requestId -> timestamp -> ip -> the error+// handler, in V1's order), the ops surface, the public API, the dashboard+// surface and `/trpc`. A role that only consumes serves none of the last three+// — V1's worker never did either.// The only `process.env` touch outside config/env.ts, and a WRITE: it sets the// process timezone. Every value the app READS comes from `loadConfig` below.@@ -108,10 +103,10 @@ const CRON_DRAIN_POLL_MS = 500;const FATAL_EXIT_DELAY_MS = 1000;const MS_PER_SECOND = 1000;// Set here because Elysia's Bun adapter otherwise injects `idleTimeout: 30`,-// which severed slow dashboard calls without a response (M36-001). It must-// outlast the tRPC deadline so the deadline's error is delivered first; the-// margin covers the ~1.6 s event-loop stall measured at the end of a large-// drill-down plus Bun's up-to-1 s timer granularity.+// which severed slow dashboard calls without a response. It must outlast the+// tRPC deadline so the deadline's error is delivered first; the margin covers+// the ~1.6 s event-loop stall measured at the end of a large drill-down plus+// Bun's up-to-1 s timer granularity.const HTTP_IDLE_TIMEOUT_MARGIN_SECONDS = 10;const HTTP_IDLE_TIMEOUT_SECONDS =RPC_DEADLINE_MS / MS_PER_SECOND + HTTP_IDLE_TIMEOUT_MARGIN_SECONDS;@@ -145,14 +140,14 @@ const workersEnabled = roleConsumes && !config.DISABLE_WORKERS;/*** All seven queues, envelope on, on the Redis keys V1 already uses — so a job- * V1 enqueued before the cutover is read back by V2's `resolveJob` through- * that queue's compat hook, with no drain and no rename (ADR-005).+ * V1 enqueued before the cutover is read back by V2's `resolveJob` through that+ * queue's compat hook, with no drain and no rename.** The connection is `packages/redis`'s dedicated queue client: a separate* client from cache/pub/sub with `maxRetriesPerRequest: null`, which is what* BullMQ requires and exactly what V1's `packages/queue` producers connect* through. It stays that package's singleton to close (ADR-007 §7's accepted- * pragmatic deviation); `producers.close()` closes the queues over it.+ * pragmatic deviation); `producers.close` closes the queues over it.*/function buildProducerHandle(): QueueProducerHandle {return createProducers(queues, {@@ -165,9 +160,9 @@ function buildProducerHandle(): QueueProducerHandle {/*** A named child of the boot logger per buffer, plus the buffers' one direct- * BullMQ read — ADR-005's `bullQueues` escape hatch.- * Pausing `cron` from bull-board halts ALL buffer flushing, preserved- * deliberately (docs/ANSWERS.md §3: "known!").+ * BullMQ read — ADR-005's `bullQueues` escape hatch. Pausing `cron` from+ * bull-board halts ALL buffer flushing, preserved deliberately (docs/ANSWERS.md+ * §3: "known!").*/function bufferDeps(producers: QueueProducerHandle): BufferDeps {const cron = findBullQueue(producers, CRON_QUEUE_NAME);@@ -176,9 +171,9 @@ function bufferDeps(producers: QueueProducerHandle): BufferDeps {createLogger: (name) => logger.child({ name }),isCronPaused: async () => (cron ? await cron.isPaused() : false),config: config.core,- // M10-009: the boot scope's ClickHouse client, so a buffer flush logs- // under the same client every service reaches as `deps.ch` instead of- // constructing its own (docs/TECH_DEBT.md §4).+ // The boot scope's ClickHouse client, so a buffer flush logs under the same+ // client every service reaches as `deps.ch` instead of constructing its+ // own.ch,};}@@ -195,16 +190,15 @@ function findBullQueue(producers: QueueProducerHandle, name: string) {function buildDeps(): AppDeps {const producers = buildProducerHandle();return {- // The four boot handles. `packages/db` and `packages/redis` still own- // their own singletons and read their own env (ADR-007 §7's accepted- // pragmatic deviation), so these are references to those, not new- // connections: one Prisma client, one round-robin ClickHouse client and- // the cache Redis, handed down so a service reaches them through its- // request-scoped `Ctx` instead of importing them (TECH_DEBT §4).+ // The four boot handles. `packages/db` and `packages/redis` still own their+ // own singletons and read their own env (ADR-007 §7's accepted pragmatic+ // deviation), so these are references to those, not new connections: one+ // Prisma client, one round-robin ClickHouse client and the cache Redis,+ // handed down so a service reaches them through its request-scoped `Ctx`+ // instead of importing them (TECH_DEBT §4).db,// Prisma's two JSON sentinels, so the four modules that write a nullable- // `Json?` column read them off the scope instead of importing the client- // (ADR-022 R6).+ // `Json?` column read them off the scope instead of importing the client.prisma: { DbNull: Prisma.DbNull, JsonNull: Prisma.JsonNull },ch,redis: getRedisCache(),@@ -258,9 +252,9 @@ function warnOnUnhandledSchedulers(schedulerIds: string[]): void {}/**- * The Kafka events consumer. The kafkajs client, the topic, the consumer- * group, the DLQ producer and the retry bounds all come from core's own- * `modules/ingest/src/kafka.ts` (M11-003) — still passed in as arguments, so+ * The Kafka events consumer. The kafkajs client, the topic, the consumer group,+ * the DLQ producer and the retry bounds all come from core's own+ * `modules/ingest/src/kafka.ts` — still passed in as arguments, so* `consumer.ts` spells none of those names itself.*/async function startIngestConsumer(@@ -277,29 +271,27 @@ async function startIngestConsumer(topic: config.core.kafka.eventsTopic,partitionsConsumedConcurrently: config.core.kafka.partitionsConcurrent,batch: {- // One Ctx per message, scoped to the requestId the producer stamped- // into the envelope (M10-006). The one binding a work scope cannot- // supply is resolved here, once: the notification dispatch has no Ctx- // slot in its signature.+ // One Ctx per message, scoped to the requestId the producer stamped into+ // the envelope. The one binding a work scope cannot supply is resolved+ // here, once: the notification dispatch has no Ctx slot in its signature.handleEvent: createIncomingEventHandler(deps, {checkNotificationRulesForEvent,- // M21-001: MARKS a redelivery, never drops one — the event is- // inserted either way. The CACHE client, again, and for the same- // reason: a handler that blocks on Redis is what got drill 02's- // consumer evicted past its session timeout, and an eviction is the- // one reassignment M19 measured costing duplicate rows.+ // MARKS a redelivery, never drops one — the event is inserted either+ // way. The CACHE client, again, and for the same reason: a handler that+ // blocks on Redis is what got drill 02's consumer evicted past its+ // session timeout, and an eviction is the one reassignment M19 measured+ // costing duplicate rows.markDuplicateEvent: createDuplicateEventMarker({client: deps.redis,ttlMs: config.INGEST_DUPLICATE_MARKER_TTL_MS,}),}),- // M20-001: a capped Redis list, and the event is DROPPED whether or not- // the record lands. The Kafka DLQ it replaced- // (`produceDeadLetterEvent`, still exported from core) produced to a- // topic nothing creates — 1,592 failures, 0 successes in drill 08 — and- // every failure held the offset back, which was the redelivery loop.- // The CACHE client, not the queue client: only that one fails fast, and- // failing fast is the point here.+ // A capped Redis list, and the event is DROPPED whether or not the record+ // lands. The Kafka DLQ it replaced (`produceDeadLetterEvent`, still+ // exported from core) produced to a topic nothing creates — 1,592+ // failures, 0 successes in drill 08 — and every failure held the offset+ // back, which was the redelivery loop. The CACHE client, not the queue+ // client: only that one fails fast, and failing fast is the point here.sendToDeadLetter: createDeadLetterRecorder({client: deps.redis,maxEntries: config.INGEST_DEAD_LETTER_MAX_ENTRIES,@@ -321,8 +313,8 @@ async function startIngestConsumer(/*** V1's shutdown drain (apps/worker/src/boot-workers.ts): let the cron queue- * finish what it started before closing the workers, because a cron job cut- * in half comes back as a stalled retry. One of ADR-005's four sanctioned+ * finish what it started before closing the workers, because a cron job cut in+ * half comes back as a stalled retry. One of ADR-005's four sanctioned* `bullQueues` call sites.*/async function waitForCronToDrain(producers: QueueProducerHandle) {@@ -361,11 +353,11 @@ function registerConsumerMetrics(deps: AppDeps): void {}/**- * The three cookies the GSC OAuth flow signs (gsc.rpc.ts's `signed: true`).- * V1 signed them through `@fastify/cookie`'s `secret`; Elysia takes the same- * list, and `signCookie` below produces the identical `value.<b64 hmac>` form- * on the tRPC side, which writes cookies through the fetch adapter's- * `resHeaders` rather than through Elysia (ADR-009 constraint 1).+ * The three cookies the GSC OAuth flow signs (gsc.rpc.ts's `signed: true`). V1+ * signed them through `@fastify/cookie`'s `secret`; Elysia takes the same list,+ * and `signCookie` below produces the identical `value.<b64 hmac>` form on the+ * tRPC side, which writes cookies through the fetch adapter's `resHeaders`+ * rather than through Elysia (ADR-009 constraint 1).*/const SIGNED_COOKIE_NAMES = ['gsc_oauth_state',@@ -386,8 +378,8 @@ function signCookie(value: string): string {}/**- * V1's `app.ts`, merged into the one entrypoint: the four Fastify scopes- * become one Elysia tree.+ * V1's `app.ts`, merged into the one entrypoint: the four Fastify scopes become+ * one Elysia tree.** THE ROOT CHAIN ORDER IS THE CONTRACT (ADR-002 "behaviour that must be* preserved explicitly" 2): cors -> requestId -> timestamp -> ip, before every@@ -430,12 +422,11 @@ async function buildHttpApp(deps: AppDeps) {.use(dashboardRoutes(deps))// `.all('/trpc/*')`, never `/trpc/:path`: the fetch adapter derives the// procedure by `pathname.slice(endpoint.length)` and a batched request- // puts commas in that segment (ADR-009).+ // puts commas in that segment.//// `parse: 'none'` is load-bearing: the adapter reads the body off the- // `Request` itself, and Elysia's own body parsing would have consumed- // the stream first — every tRPC mutation then fails with- // "Body already used".+ // `Request` itself, and Elysia's own body parsing would have consumed the+ // stream first — every tRPC mutation then fails with "Body already used"..all(`${TRPC_ENDPOINT}/*`,({ request, ctx }: { request: Request; ctx: HttpCtx }) =>@@ -617,9 +608,9 @@ async function main() {role,port: config.API_PORT,hostname: config.listen.hostname ?? '0.0.0.0',- // ADR-016 rule 5: the running Bun version, asserted against- // .bun-version by scripts/doctor.sh — logged so a wrong-runtime- // incident is one log line away rather than an inference.+ // Rule 5: the running Bun version, asserted against.bun-version by+ // scripts/doctor.sh — logged so a wrong-runtime incident is one log+ // line away rather than an inference.bunVersion: Bun.version,},'API listening'diff --git a/apps/api/src/shutdown.test.ts b/apps/api/src/shutdown.test.tsindex 7cce9463f..9d0b3bf5d 100644--- a/apps/api/src/shutdown.test.ts+++ b/apps/api/src/shutdown.test.ts@@ -1,5 +1,5 @@/**- * The regression test for drill 03's loss (M18-001).+ * The regression test for drill 03's loss.** Both halves matter and the happy path alone would not have caught the bug:* (a) the event buffer is flushed to Redis BEFORE the Kafka consumer isdiff --git a/apps/api/src/shutdown.ts b/apps/api/src/shutdown.tsindex f02a9816e..59a5e0c5d 100644--- a/apps/api/src/shutdown.ts+++ b/apps/api/src/shutdown.ts@@ -1,6 +1,6 @@// The graceful-shutdown sequence, lifted out of `main.ts` so its ORDER is a// thing a test can assert rather than a property of how a `Promise.all` was-// typed (M18-001).+// typed.//// Drill 03 (`verification/drills/03-restart-in-flight.md`) measured a SIGTERM// restart permanently losing 2 of 44,075 accepted events while both SIGKILL@@ -10,12 +10,11 @@// redelivered. A crash commits nothing, so Kafka replays the same window.//// The commit itself is NOT here: kafkajs auto-commits the offsets a batch-// resolved as soon as `eachBatch` returns, so the events a Kafka batch-// buffered are made durable inside the batch handler, before it resolves-// anything (`consumer.ts`'s `flushBufferedEvents`). What is left for this-// sequence is everything buffered OUTSIDE a Kafka batch — a session-end job's-// event, an import — which no offset covers and which a `process.exit` would-// simply drop.+// resolved as soon as `eachBatch` returns, so the events a Kafka batch buffered+// are made durable inside the batch handler, before it resolves anything+// (`consumer.ts`'s `flushBufferedEvents`). What is left for this sequence is+// everything buffered OUTSIDE a Kafka batch — a session-end job's event, an+// import — which no offset covers and which a `process.exit` would simply drop.//// Either way it is one rpush of at most `microBatchMaxSize` events —// milliseconds, well inside `SHUTDOWN_FORCE_EXIT_MS`. It is NOT a Redis ->diff --git a/apps/public/src/app/(content)/compare/[slug]/_components/related-links.tsx b/apps/public/src/app/(content)/compare/[slug]/_components/related-links.tsxindex c793fecc9..97f1e5539 100644--- a/apps/public/src/app/(content)/compare/[slug]/_components/related-links.tsx+++ b/apps/public/src/app/(content)/compare/[slug]/_components/related-links.tsx@@ -9,11 +9,11 @@ interface RelatedLinksProps {export function RelatedLinksSection({ relatedLinks }: RelatedLinksProps) {if (- !relatedLinks ||!(- relatedLinks.guides?.length ||- relatedLinks.articles?.length ||- relatedLinks.alternatives?.length+ relatedLinks &&+ (relatedLinks.guides?.length ||+ relatedLinks.articles?.length ||+ relatedLinks.alternatives?.length))) {return null;diff --git a/apps/start/src/agents/client.ts b/apps/start/src/agents/client.tsindex f96b37933..8d716a1a0 100644--- a/apps/start/src/agents/client.ts+++ b/apps/start/src/agents/client.ts@@ -2,27 +2,24 @@ import { createClient } from '@better-agent/client';import type { ChatApp } from '@openpanel/core';/**- * Typed Better Agent client. The `ChatApp` import surfaces every- * agent name, every context schema, and every typed tool input — so- * `useAgent(client, { agent: 'gpt-4-1' })` is autocompleted and- * validated end-to-end.+ * Typed Better Agent client. The `ChatApp` import surfaces every agent name,+ * every context schema, and every typed tool input — so `useAgent(client, {+ * agent: 'gpt-4-1' })` is autocompleted and validated end-to-end.** About the import: `ChatApp = typeof chatApp` is the full Better- * Agent-inferred application type, which inherently binds to the- * server-side agent definition (models, tools, context). It can't be- * moved into `@openpanel/core`'s assistant.constants without dragging the- * entire agent definition (DB services, providers, etc.) along with it. It is- * type-only, erased at build time — no runtime coupling, which is what- * keeps it inside ADR-008's rule that only `*.constants.ts` may be- * VALUE-imported here. The barrel is the only door: `@openpanel/core`'s- * exports map publishes `.` and `./modules/*.constants`, and `ChatApp`- * cannot live in a constants file. The shared schemas (context, client- * tool inputs, model whitelist) do live in- * `@openpanel/core`'s assistant.constants, so this is the one type import- * that crosses the app boundary — a second one past `AppRouter`, which- * ADR-022 R12 says should be the only one. Recorded as an open R12- * finding (M14-101 / M15-101): widening R12 to `AppRouter` + `ChatApp`- * is an ADR amendment, not a code change.+ * Agent-inferred application type, which inherently binds to the server-side+ * agent definition (models, tools, context). It can't be moved into+ * `@openpanel/core`'s assistant.constants without dragging the entire agent+ * definition (DB services, providers, etc.) along with it. It is type-only,+ * erased at build time — no runtime coupling, which is what keeps it inside+ * ADR-008's rule that only `*.constants.ts` may be VALUE-imported here. The+ * barrel is the only door: `@openpanel/core`'s exports map publishes `.` and+ * `./modules/*.constants`, and `ChatApp` cannot live in a constants file. The+ * shared schemas (context, client tool inputs, model whitelist) do live in+ * `@openpanel/core`'s assistant.constants, so this is the one type import that+ * crosses the app boundary — a second one past `AppRouter`, which ADR-022 R12+ * says should be the only one. Recorded as an open R12 finding: widening R12 to+ * `AppRouter` + `ChatApp` is an ADR amendment, not a code change.*/export type AppClient = ReturnType<typeof createClient<ChatApp>>;diff --git a/apps/start/src/utils/object-to-zod-enums.ts b/apps/start/src/utils/object-to-zod-enums.tsindex 36ee6f4e6..6f3153986 100644--- a/apps/start/src/utils/object-to-zod-enums.ts+++ b/apps/start/src/utils/object-to-zod-enums.ts@@ -1,6 +1,6 @@-// Helper, not vocabulary — ADR-008's ruling: `objectToZodEnums` has no-// owning module, so it is copied here rather than value-imported from-// @openpanel/core (same treatment ADR-007 gives the `common` math helpers).+// Helper, not vocabulary — ADR-008's ruling: `objectToZodEnums` has no owning+// module, so it is copied here rather than value-imported from @openpanel/core+// (same treatment ADR-007 gives the `common` math helpers).export function objectToZodEnums<K extends string>(obj: Record<K, unknown>): [K, ...K[]] {diff --git a/apps/start/src/utils/previous-metric.test.ts b/apps/start/src/utils/previous-metric.test.tsindex dab7bf051..76a37f716 100644--- a/apps/start/src/utils/previous-metric.test.ts+++ b/apps/start/src/utils/previous-metric.test.ts@@ -1,8 +1,7 @@// Replaces utils/math.test.ts: the `shortId` it covered moved to-// @openpanel/shared (M15-010) and is tested there-// (packages/core/src/shared/id.test.ts). What is left in this file is the one-// helper that stays duplicated between the dashboard and core, so it is the-// one worth a test here.+// @openpanel/shared and is tested there (packages/core/src/shared/id.test.ts).+// What is left in this file is the one helper that stays duplicated between the+// dashboard and core, so it is the one worth a test here.import { describe, expect, test } from 'vitest';import { getPreviousMetric } from './previous-metric';diff --git a/apps/start/src/utils/previous-metric.ts b/apps/start/src/utils/previous-metric.tsindex 9f49188ce..e85892c52 100644--- a/apps/start/src/utils/previous-metric.ts+++ b/apps/start/src/utils/previous-metric.ts@@ -1,11 +1,12 @@-// The dashboard's copy of packages/core/src/modules/report/src/previous-metric.ts.+// The dashboard's copy of+// packages/core/src/modules/report/src/previous-metric.ts.//-// M15-010 moved the six generic aggregates and `shortId` that used to sit-// beside it into @openpanel/shared, which the dashboard now imports directly.-// This one function stays duplicated: it returns `PreviousValue`, report-// vocabulary, and ADR-022 R21 keeps domain constants out of @openpanel/shared-// while R12 keeps apps/start from value-importing core outside a-// `*.constants.ts` path. The type is safe to import — it is erased.+// Moved the six generic aggregates and `shortId` that used to sit beside it+// into @openpanel/shared, which the dashboard now imports directly. This one+// function stays duplicated: it returns `PreviousValue`, report vocabulary, and+// ADR-022 R21 keeps domain constants out of @openpanel/shared while R12 keeps+// apps/start from value-importing core outside a `*.constants.ts` path. The+// type is safe to import — it is erased.import type { PreviousValue } from '@openpanel/core/modules/report/report.constants';import { round } from '@openpanel/shared';import { isNil } from 'ramda';diff --git a/apps/start/src/utils/union-omit.ts b/apps/start/src/utils/union-omit.tsindex 29c2221d2..322dd5098 100644--- a/apps/start/src/utils/union-omit.ts+++ b/apps/start/src/utils/union-omit.ts@@ -1,4 +1,4 @@-// No owning module (ADR-008) — copied rather than value-imported from core.+// No owning module — copied rather than value-imported from core.export type UnionOmit<T, K extends keyof any> = T extends any? Omit<T, K>: never;diff --git a/apps/start/vitest.config.ts b/apps/start/vitest.config.tsindex 372818e5d..b541436d4 100644--- a/apps/start/vitest.config.ts+++ b/apps/start/vitest.config.ts@@ -3,8 +3,8 @@ import { defineConfig } from 'vitest/config';/*** `apps/start` keeps vitest (ADR-010: "vitest stays for apps/start") and its- * own `vitest ^3.0.5` devDependency. This file exists so it keeps it on its- * own terms: without a vitest config, vitest loads `vite.config.ts`, whose+ * own `vitest ^3.0.5` devDependency. This file exists so it keeps it on its own+ * terms: without a vitest config, vitest loads `vite.config.ts`, whose* Cloudflare / TanStack Start / Sentry plugin chain is a dev-server and build* pipeline that a unit test has no use for.*/diff --git a/packages/core/scripts/migrate-code.ts b/packages/core/scripts/migrate-code.tsindex ddf9a900b..fb438a107 100644--- a/packages/core/scripts/migrate-code.ts+++ b/packages/core/scripts/migrate-code.ts@@ -1,11 +1,11 @@-// Compatibility entrypoint. `code-migrations` moved to @openpanel/db in-// M15-204 (ADR-022, Carl's rulings), but the shipped compose files and the-// Coolify template still run `cd /app/packages/core && bun-// scripts/migrate-code.ts`, and those files are outside that task's scope.-// This forwards so a self-hoster pulling the new image keeps migrating.+// Compatibility entrypoint. `code-migrations` moved to @openpanel/db in M15-204+// (Carl's rulings), but the shipped compose files and the Coolify template+// still run `cd /app/packages/core && bun scripts/migrate-code.ts`, and those+// files are outside that task's scope. This forwards so a self-hoster pulling+// the new image keeps migrating.//// Delete this the moment self-hosting/docker-compose.template.yml,-// self-hosting/coolify.yml and .github/smoke/docker-compose.yml name+// self-hosting/coolify.yml and.github/smoke/docker-compose.yml name// `packages/db` instead.import '@openpanel/db/scripts/migrate-code';diff --git a/packages/core/src/buffers/base-buffer.ts b/packages/core/src/buffers/base-buffer.tsindex 5289ef48c..50eff7f99 100644--- a/packages/core/src/buffers/base-buffer.ts+++ b/packages/core/src/buffers/base-buffer.ts@@ -10,7 +10,7 @@ import type { ServiceDeps } from '../services';/*** What a buffer needs from the boot scope. Buffers are built once by* `createBuffers(deps)` and hung on `AppDeps` — never module singletons, so a- * test constructs its own and closes nothing shared (ADR-007).+ * test constructs its own and closes nothing shared.*/export interface BufferDeps {/**@@ -20,11 +20,11 @@ export interface BufferDeps {*/createLogger(name: string): Logger;/**- * The boot scope's ClickHouse client — the same round-robin/retry proxy- * every service reaches as `deps.ch`. M10-009: the buffers used to lazily- * `import('@openpanel/db/src/clickhouse/client')` for it, which constructed- * a second client (and a second pino transport) outside any scope. M15-004- * made it required: the one caller that had none+ * The boot scope's ClickHouse client — the same round-robin/retry proxy every+ * service reaches as `deps.ch`. M10-009: the buffers used to lazily+ * `import('@openpanel/db/src/clickhouse/client')` for it, which constructed a+ * second client (and a second pino transport) outside any scope. M15-004 made+ * it required: the one caller that had none* (`apps/api/e2e/legacy-job-proof.ts`, a BullMQ-keys-only proof that never* flushes to ClickHouse) already passes the field, so the unscoped fallback* behind it had no live path left.@@ -39,9 +39,9 @@ export interface BufferDeps {isCronPaused(): Promise<boolean>;/*** The parsed environment. Every buffer's batch/chunk/TTL knob used to be a- * module-scope `process.env` read; they arrive here instead (ADR-022 R7),- * which is also what lets a test build a buffer with a different sizing- * without touching the process environment.+ * module-scope `process.env` read; they arrive here instead, which is also+ * what lets a test build a buffer with a different sizing without touching+ * the process environment.*/config: CoreConfig;}diff --git a/packages/core/src/buffers/clickhouse-failover.test.ts b/packages/core/src/buffers/clickhouse-failover.test.tsindex 65db77f6e..ea74bc8e7 100644--- a/packages/core/src/buffers/clickhouse-failover.test.ts+++ b/packages/core/src/buffers/clickhouse-failover.test.ts@@ -1,28 +1,28 @@import { afterAll, describe, expect, it } from 'bun:test';-// M10-009: the buffers take the boot scope's client as `BufferDeps.ch` now, so-// the `loadClickHouse()` seam this file used to call through is gone. What it-// proves is unchanged — the round-robin/retry client the buffers are handed-// (`ch` / `chQuery`, `@openpanel/db`'s exports) must survive a dead node — so-// the subject is imported directly here. This is a test file, which+// The buffers take the boot scope's client as `BufferDeps.ch` now, so the+// `loadClickHouse` seam this file used to call through is gone. What it proves+// is unchanged — the round-robin/retry client the buffers are handed (`ch` /+// `chQuery`, `@openpanel/db`'s exports) must survive a dead node — so the+// subject is imported directly here. This is a test file, which// `core-uses-ctx-not-db-internals` exempts.function loadClickHouse() {return import('@openpanel/db/src/clickhouse/client');}/**- * ADR-013 R1 / M8-006: the deliberate ECONNREFUSED to a dead ClickHouse node- * must be caught and retried (sin-binning) on the client the buffers are- * handed as `BufferDeps.ch`, exactly as packages/db's+ * / M8-006: the deliberate ECONNREFUSED to a dead ClickHouse node must be+ * caught and retried (sin-binning) on the client the buffers are handed as+ * `BufferDeps.ch`, exactly as packages/db's* `sql.round-robin.clickhouse.test.ts` proves for `chQuery`/`chQueryWithMeta`- * directly. That file is NOT touched here; this extends the same proof onto- * the path M8-001 moved: `ch.insert` reached via the core buffer seam.+ * directly. That file is NOT touched here; this extends the same proof onto the+ * path M8-001 moved: `ch.insert` reached via the core buffer seam.*- * Setup mirrors that file exactly: a two-node `CLICKHOUSE_URL` whose first- * node (port 1, privileged and unbindable without root) is reliably refused.- * The picker starts at index 0, so every call here fails over to node 1 — if- * the seam let the rejection escape instead of retrying, this file would- * throw or hang rather than pass.+ * Setup mirrors that file exactly: a two-node `CLICKHOUSE_URL` whose first node+ * (port 1, privileged and unbindable without root) is reliably refused. The+ * picker starts at index 0, so every call here fails over to node 1 — if the+ * seam let the rejection escape instead of retrying, this file would throw or+ * hang rather than pass.*/const CLICKHOUSE_TEST_DATABASE = 'openpanel_test';diff --git a/packages/core/src/buffers/event-buffer.test.ts b/packages/core/src/buffers/event-buffer.test.tsindex 2abb7ec7b..18d4b7670 100644--- a/packages/core/src/buffers/event-buffer.test.ts+++ b/packages/core/src/buffers/event-buffer.test.ts@@ -20,9 +20,9 @@ const chQuery = mock(async (_query: string | SqlFragment): Promise<unknown[]> => []);-// M10-009: the client comes in as `BufferDeps.ch` and reads go through core's-// 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+// The client comes in as `BufferDeps.ch` and reads go through core's 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('../ch-query', () => ({@@ -335,10 +335,10 @@ describe('EventBuffer', () => {expect(await eventBuffer.getBufferSize()).toBe(5);});- // M18-001 / drill 03: the shutdown path has to be able to SEE a failed- // rpush, because it decides whether to commit the Kafka offsets on the- // answer. `flush()` deliberately swallows one (the micro-batch timer retries- // while the process lives); `flushPendingOrThrow()` does not.+ // / drill 03: the shutdown path has to be able to SEE a failed rpush, because+ // it decides whether to commit the Kafka offsets on the answer. `flush`+ // deliberately swallows one (the micro-batch timer retries while the process+ // lives); `flushPendingOrThrow` does not.describe('flushPendingOrThrow', () => {// A failed flush re-queues its events AND arms the micro-batch timer, so// without this the retry lands in whichever test runs next.@@ -428,11 +428,11 @@ describe('EventBuffer', () => {});});- // M18-005 / drill 03 re-run: the gate has to answer "are my events in- // Redis?", not "did I start the write?". Answering the second question made- // 221 durability failures in 5.5 minutes on a HEALTHY stack and turned 16.9%- // of accepted events into duplicates, because a caller that lost the race to- // start a write was told its already-durable events were not durable.+ // / drill 03 re-run: the gate has to answer "are my events in Redis?", not+ // "did I start the write?". Answering the second question made 221 durability+ // failures in 5.5 minutes on a HEALTHY stack and turned 16.9% of accepted+ // events into duplicates, because a caller that lost the race to start a+ // write was told its already-durable events were not durable.describe('flushPendingOrThrow under concurrency', () => {// 24 partitions is what drill 03 ran; the callers are its `eachBatch`// handlers, and the background producer stands in for the HTTP path and@@ -539,10 +539,10 @@ describe('EventBuffer', () => {});});- // M18-007 / drill 02 re-run: a failed flush leaves the batch's Kafka offsets- // unresolved (M18-001) and the fail-fast cache client (M18-003) brings the- // redelivery back in ~90ms. Re-queueing the failed events then holds one- // copy per lap — 4,759 ClickHouse rows for 230 events, measured.+ // / drill 02 re-run: a failed flush leaves the batch's Kafka offsets+ // unresolved and the fail-fast cache client brings the redelivery back in+ // ~90ms. Re-queueing the failed events then holds one copy per lap — 4,759+ // ClickHouse rows for 230 events, measured.describe('events a redelivery will produce again', () => {const REDELIVERY_LAPS = 5;diff --git a/packages/core/src/buffers/event-buffer.ts b/packages/core/src/buffers/event-buffer.tsindex 6bc29589f..131690e5f 100644--- a/packages/core/src/buffers/event-buffer.ts+++ b/packages/core/src/buffers/event-buffer.ts@@ -75,12 +75,12 @@ export class EventBuffer extends BaseBuffer {/*** The durability watermark. Every event gets a monotonically increasing- * sequence number in `add()`; `lastDurableSeq` is the highest sequence a+ * sequence number in `add`; `lastDurableSeq` is the highest sequence a* COMPLETED rpush covered. A caller's events are in Redis once* `lastDurableSeq` reaches the sequence of its last event — whoever wrote* them. That is the question the Kafka batch handler and shutdown need* answered ("are my events in Redis?"), and it is not the same question as- * "did I start the write?" (M18-005, drill 03 re-run).+ * "did I start the write?" (drill 03 re-run).*/private lastQueuedSeq = 0;private lastDurableSeq = 0;@@ -182,12 +182,12 @@ export class EventBuffer extends BaseBuffer {* The same flush, but it THROWS when the rpush did not land, and it does not* resolve until every event accepted before the call is in Redis.*- * `flush()` swallows a Redis failure on purpose. The two callers here have no+ * `flush` swallows a Redis failure on purpose. The two callers here have no* next attempt: the Kafka batch handler is about to resolve offsets that* kafkajs commits as soon as it returns, and shutdown is about to exit. Both* must be able to SEE the failure and decline to commit — a redelivered- * duplicate is recoverable, a dropped `pendingEvents` array is not- * (M18-001, drill 03).+ * duplicate is recoverable, a dropped `pendingEvents` array is not (drill+ * 03).*/public async flushPendingOrThrow(sinceSeq: number = this.droppedThroughSeq@@ -198,7 +198,7 @@ export class EventBuffer extends BaseBuffer {// running or starts the one write still missing, and a write covers// everything pending when it starts. So a concurrent write that happens to// carry our events resolves us — losing the race to start a write is a- // SUCCESS, which is the whole correctness point (M18-005).+ // SUCCESS, which is the whole correctness point.while (this.lastDurableSeq < target) {const inFlight = this.inFlightWrite;@@ -226,27 +226,26 @@ export class EventBuffer extends BaseBuffer {// alone cannot say so: it moves on with the NEXT write, which carries none// of them. Without this a batch whose events were dropped by a micro-batch// timer it never awaited would be told they are safe, commit its offsets,- // and lose them for good (M18-007).+ // and lose them for good.if (this.droppedThroughSeq > sinceSeq) {this.throwIfFailed(this.lastDropFailure);}}/**- * Buffer an event whose producer produces it AGAIN when this buffer reports- * a failed flush — today the Kafka consumer, whose batch is left- * uncommitted and redelivered (`modules/ingest/src/consumer.ts`).+ * Buffer an event whose producer produces it AGAIN when this buffer reports a+ * failed flush — today the Kafka consumer, whose batch is left uncommitted+ * and redelivered (`modules/ingest/src/consumer.ts`).*- * Such an event is not re-queued by a failed write. Re-queueing it was- * right while the buffer owned the retry, and became harmful the moment- * Kafka took that ownership over (M18-001): the redelivery buffers a fresh- * copy, so the old one is a SECOND copy of one event, and every further- * redelivery adds another. Drill 02's re-run measured 4,759 ClickHouse rows- * for 230 events that way (M18-007).+ * Such an event is not re-queued by a failed write. Re-queueing it was right+ * while the buffer owned the retry, and became harmful the moment Kafka took+ * that ownership over: the redelivery buffers a fresh copy, so the old one is+ * a SECOND copy of one event, and every further redelivery adds another.+ * Drill 02's re-run measured 4,759 ClickHouse rows for 230 events that way.*- * Producers Kafka does not redeliver — the session-end job, whose Redis- * `SET NX` claim makes a job retry a no-op — keep the safety net by using- * plain `add()`.+ * Producers Kafka does not redeliver — the session-end job, whose Redis `SET+ * NX` claim makes a job retry a no-op — keep the safety net by using plain+ * `add`.*/public addRedeliverable(event: IClickhouseEvent): void {this.redeliverableEvents.add(event);@@ -282,7 +281,7 @@ export class EventBuffer extends BaseBuffer {* Redis?" cannot tell its own dropped events from another producer's, and a* failed write can drop events the caller never awaited. Opening the window* before the first event is buffered is what makes the answer that caller's- * own (M18-007).+ * own.*/public openDurabilityWindow(): () => Promise<void> {const sinceSeq = this.lastQueuedSeq;@@ -346,11 +345,11 @@ export class EventBuffer extends BaseBuffer {}const results = await multi.exec();- // ioredis RESOLVES a MULTI whose individual commands failed, handing the+ // Ioredis RESOLVES a MULTI whose individual commands failed, handing the// error back per entry — so a WRONGTYPE or an out-of-memory rpush would// otherwise read as a successful flush and the events would be dropped- // silently. The batch handler decides whether to resolve Kafka offsets- // on this answer, so it has to be the truth (M18-001).+ // silently. The batch handler decides whether to resolve Kafka offsets on+ // this answer, so it has to be the truth.if (results === null) {throw new Error('event buffer rpush transaction was aborted');}diff --git a/packages/core/src/buffers/profile-buffer.test.ts b/packages/core/src/buffers/profile-buffer.test.tsindex f9e9a3d68..a45bb493b 100644--- a/packages/core/src/buffers/profile-buffer.test.ts+++ b/packages/core/src/buffers/profile-buffer.test.ts@@ -3,8 +3,8 @@ import { getRedisCache } from '@openpanel/redis';import { bufferDepsWithCh } from '../../test/buffer-fixtures';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.+// 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('../ch-query')) };const chInsert = mock(async (_options: unknown): Promise<unknown> => undefined);diff --git a/packages/core/src/buffers/session-buffer.test.ts b/packages/core/src/buffers/session-buffer.test.tsindex 17e8a41c0..f3c52cded 100644--- a/packages/core/src/buffers/session-buffer.test.ts+++ b/packages/core/src/buffers/session-buffer.test.ts@@ -4,8 +4,8 @@ import { bufferDepsWithCh } from '../../test/buffer-fixtures';import type { IServiceCreateEventPayload } from '../modules/event/event.service';import type { IClickhouseSession } from '../modules/session/session.service';-// M10-009: the client comes in as `BufferDeps.ch` — no module mock needed for-// the flush path at all. See event-buffer.test.ts's header.+// The client comes in as `BufferDeps.ch` — no module mock needed for the flush+// path at all. See event-buffer.test.ts's header.const chInsert = mock(async (_options: {table: string;diff --git a/packages/core/src/cacheable-per-deps.ts b/packages/core/src/cacheable-per-deps.tsindex 0ee757cac..f3bb8e0a8 100644--- a/packages/core/src/cacheable-per-deps.ts+++ b/packages/core/src/cacheable-per-deps.ts@@ -1,24 +1,24 @@// `cacheable` for a function that needs the caller's `ServiceDeps`.//-// M10-005: the three cross-module caches on the runtime path-// (`getEventMetasCached`, `getProfilesCached`, `getProfilePropertyKeysCached`)-// wrap a function that now reaches Postgres/ClickHouse through `deps`. Passing-// `deps` to `cacheable` directly is not an option: it keys on EVERY argument-// through `stringify`, which walks an object's entries recursively — it would-// serialize the whole Prisma client into the Redis key.+// The three cross-module caches on the runtime path (`getEventMetasCached`,+// `getProfilesCached`, `getProfilePropertyKeysCached`) wrap a function that now+// reaches Postgres/ClickHouse through `deps`. Passing `deps` to `cacheable`+// directly is not an option: it keys on EVERY argument through `stringify`,+// which walks an object's entries recursively — it would serialize the whole+// Prisma client into the Redis key.//// `deps` is not cache identity anyway. It is the scope a call runs in (the// process's clients plus this request's logger); two calls with the same// arguments are the same call whichever scope makes them. So the cacheable is// built once per `deps` and remembered in a WeakMap, and the Redis key stays// byte-identical to what the module-scope `cacheable(fn, ttl)` this replaces-// produced — hence the EXPLICIT `name`, which is what `fn.name` used to-// supply and what an inline arrow would silently drop.+// produced — hence the EXPLICIT `name`, which is what `fn.name` used to supply+// and what an inline arrow would silently drop.//// Consequence, stated: `createCtx` builds a fresh deps object per request-// (context.ts's `installLazyServices`), so the L1 LRU inside `cacheable` is-// per scope rather than per process. The L2 Redis cache — the shared one, the-// one that actually saves the query — is unchanged, so a repeat call costs one+// (context.ts's `installLazyServices`), so the L1 LRU inside `cacheable` is per+// scope rather than per process. The L2 Redis cache — the shared one, the one+// that actually saves the query — is unchanged, so a repeat call costs one// Redis GET where it used to cost none. A cache that must be process-lived// takes `cacheablePerDb` below instead.diff --git a/packages/core/src/ch-abortable.ts b/packages/core/src/ch-abortable.tsindex 53b8f6f95..699a8d1d9 100644--- a/packages/core/src/ch-abortable.ts+++ b/packages/core/src/ch-abortable.ts@@ -1,6 +1,6 @@-// A work scope's ClickHouse reads, bound to that scope's AbortSignal (M36-001),-// so a read whose answer nobody can receive stops on the server instead of-// running to completion.+// A work scope's ClickHouse reads, bound to that scope's AbortSignal, so a read+// whose answer nobody can receive stops on the server instead of running to+// completion.//// Aborting the HTTP call alone does not stop the query: ClickHouse only cancels// on client close for a READ-ONLY query withdiff --git a/packages/core/src/ch-query.ts b/packages/core/src/ch-query.tsindex 5d1ce1e08..198d44198 100644--- a/packages/core/src/ch-query.ts+++ b/packages/core/src/ch-query.ts@@ -1,24 +1,24 @@-// core's ClickHouse read path, bound to the scope's client.+// Core's ClickHouse read path, bound to the scope's client.//-// M10-005: the six modules on the runtime path used to reach ClickHouse-// through `await import('@openpanel/db/src/clickhouse/client')` and call that-// package's `chQuery`. That client has no request scope, so the requestId-// minted at the edge stopped there (ADR-018 R1, docs/TECH_DEBT.md §2). These-// two functions are `chQuery` / `chQueryWithMeta` over `deps.ch` — the same-// round-robin/retry proxy `main.ts` builds and hands to every scope — and-// `deps.logger`, so the `query info` line carries the request's id.+// The six modules on the runtime path used to reach ClickHouse through `await+// import('@openpanel/db/src/clickhouse/client')` and call that package's+// `chQuery`. That client has no request scope, so the requestId minted at the+// edge stopped there. These two functions are `chQuery` / `chQueryWithMeta`+// over `deps.ch` — the same round-robin/retry proxy `main.ts` builds and hands+// to every scope — and `deps.logger`, so the `query info` line carries the+// request's id.//// Behaviour is @openpanel/db's, unchanged: `deps.ch.query` IS `withRetry-// (client => client.query(...))`, the same transport, and the Int-meta-// coercion below is the same one — ClickHouse's JSON format returns every-// Int*/UInt* column as a string, so a caller's `count: number` only holds if-// it is parsed back out here. The one field that cannot survive the move is-// `host`: the retry proxy does not report which replica served the query.-// chart/src/run-query.ts (M10-003) made the same trade.+// (client => client.query(...))`, the same transport, and the Int-meta coercion+// below is the same one — ClickHouse's JSON format returns every Int*/UInt*+// column as a string, so a caller's `count: number` only holds if it is parsed+// back out here. The one field that cannot survive the move is `host`: the+// retry proxy does not report which replica served the query.+// chart/src/run-query.ts made the same trade.//// `@openpanel/db/src/clickhouse/sql` is a value import and stays one: ADR-013-// puts the `sql` tag in packages/db by name, and it is a compile-time-// template tag with no client and no request scope.+// puts the `sql` tag in packages/db by name, and it is a compile-time template+// tag with no client and no request scope.import type { ClickHouseSettings, ResponseJSON } from '@clickhouse/client';import {diff --git a/packages/core/src/clients/create-clients.ts b/packages/core/src/clients/create-clients.tsindex be69f51d2..77a6ea494 100644--- a/packages/core/src/clients/create-clients.ts+++ b/packages/core/src/clients/create-clients.ts@@ -5,14 +5,14 @@// It is a NAMING of what already exists under `src/clients/`, not a new// abstraction: every member below is the exact function this package already// exports, gathered so a service can reach an outbound client through its-// scoped `Ctx` instead of importing the module directly. Nothing is-// constructed here — the geo readers open their mmdb lazily and the email /-// Discord transports read their own credentials — so building it costs one-// object literal per process.+// scoped `Ctx` instead of importing the module directly. Nothing is constructed+// here — the geo readers open their mmdb lazily and the email / Discord+// transports read their own credentials — so building it costs one object+// literal per process.//-// M15-008 removed the `slack` and `ai` members: those transports moved into-// the single module that calls each (ADR-022 A2), and a client handle cannot-// reach up into a module. Nothing read either member.+// Removed the `slack` and `ai` members: those transports moved into the single+// module that calls each (ADR-022 A2), and a client handle cannot reach up into+// a module. Nothing read either member.import { sendEmail } from './email';import { getAsnInfo, getGeoLocation } from './geo';diff --git a/packages/core/src/clients/email.ts b/packages/core/src/clients/email.tsindex ccb549f25..0d0c51058 100644--- a/packages/core/src/clients/email.ts+++ b/packages/core/src/clients/email.ts@@ -1,20 +1,19 @@// @openpanel/email stays its own package — the react-email JSX toolchain-// doesn't belong in core (TARGET_ARCHITECTURE §7: "email (react-email JSX-// stays out of core; core wraps it as clients/email)").+// doesn't belong in core (TARGET_ARCHITECTURE §7: "email (react-email JSX stays+// out of core; core wraps it as clients/email)").//-// Loaded lazily, deliberately: @openpanel/email depends on @openpanel/db-// (to check email-unsubscribe rows before sending), and @openpanel/db still-// depends on @openpanel/core for shared crypto/logging utilities that-// haven't moved yet (mid-P4 state). A static top-level import here would-// make core's own barrel eagerly load @openpanel/db while core is still-// mid-evaluation — the cycle resolves core's own exports as undefined partway-// through. Deferring the import to call time sidesteps it: by the time-// anything actually sends an email, core has finished loading.+// Loaded lazily, deliberately: @openpanel/email depends on @openpanel/db (to+// check email-unsubscribe rows before sending), and @openpanel/db still depends+// on @openpanel/core for shared crypto/logging utilities that haven't moved yet+// (mid-P4 state). A static top-level import here would make core's own barrel+// eagerly load @openpanel/db while core is still mid-evaluation — the cycle+// resolves core's own exports as undefined partway through. Deferring the+// import to call time sidesteps it: by the time anything actually sends an+// email, core has finished loading.//-// No `ProviderError` (ADR-022 R19): `@openpanel/email` swallows every Resend-// and SMTP failure itself and returns `null`, so nothing reaches this wrapper-// to classify. Classifying it means changing that package, which is outside-// this seam.+// No `ProviderError`: `@openpanel/email` swallows every Resend and SMTP failure+// itself and returns `null`, so nothing reaches this wrapper to classify.+// Classifying it means changing that package, which is outside this seam.import type { EmailData, EmailTemplate } from '@openpanel/email';diff --git a/packages/core/src/clients/geo.ts b/packages/core/src/clients/geo.tsindex 6744f78db..7394dac9f 100644--- a/packages/core/src/clients/geo.ts+++ b/packages/core/src/clients/geo.ts@@ -1,11 +1,11 @@// Ported from @openpanel/geo (dissolved into core — M4-004).//-// The one client with no `ProviderError` (ADR-022 R19): there is no third-// party on the other end. Both lookups read a bundled MaxMind `.mmdb`, so an-// IP the database does not carry is a missing thing and comes back as the-// default value (R9), and a database that will not load fails identically on-// every retry. `ingest.service.ts` therefore has no failure to classify —-// it reads a value, never a throw.+// The one client with no `ProviderError`: there is no third party on the other+// end. Both lookups read a bundled MaxMind `.mmdb`, so an IP the database does+// not carry is a missing thing and comes back as the default value (R9), and a+// database that will not load fails identically on every retry.+// `ingest.service.ts` therefore has no failure to classify — it reads a value,+// never a throw.import { readFile } from 'node:fs/promises';import path, { dirname } from 'node:path';diff --git a/packages/core/src/clients/integrations/discord.ts b/packages/core/src/clients/integrations/discord.tsindex 59708add0..f1371727e 100644--- a/packages/core/src/clients/integrations/discord.ts+++ b/packages/core/src/clients/integrations/discord.ts@@ -1,5 +1,6 @@-// Ported from @openpanel/integrations (dissolved into core — M4-005).-// Cred to (@OpenStatusHQ) https://github.com/openstatusHQ/openstatus/blob/main/packages/notifications/discord/src/index.ts+// Ported from @openpanel/integrations (dissolved into core — M4-005). Cred to+// (@OpenStatusHQ)+// https://github.com/openstatusHQ/openstatus/blob/main/packages/notifications/discord/src/index.tsimport {browserFetcher,diff --git a/packages/core/src/clients/integrations/fetcher.ts b/packages/core/src/clients/integrations/fetcher.tsindex b26c7e662..c5977af34 100644--- a/packages/core/src/clients/integrations/fetcher.ts+++ b/packages/core/src/clients/integrations/fetcher.ts@@ -31,11 +31,10 @@ export interface WebhookResult {ok: boolean;status: number;/**- * ADR-022 R19, classified once here so no caller re-derives it: 429 and 5xx- * are worth another delivery attempt, every other 4xx is the destination- * refusing this exact request. A transport failure that produced no response- * (DNS, connect, TLS, timeout) is retryable — nothing about the request was- * rejected.+ * R19, classified once here so no caller re-derives it: 429 and 5xx are worth+ * another delivery attempt, every other 4xx is the destination refusing this+ * exact request. A transport failure that produced no response (DNS, connect,+ * TLS, timeout) is retryable — nothing about the request was rejected.*/retryable: boolean;}diff --git a/packages/core/src/clients/provider-error.test.ts b/packages/core/src/clients/provider-error.test.tsindex 9c4f52dbf..f005e896e 100644--- a/packages/core/src/clients/provider-error.test.ts+++ b/packages/core/src/clients/provider-error.test.ts@@ -1,6 +1,6 @@-// ADR-022 R19: the classification is the whole point of the type, so the-// boundaries (429 retryable, 4xx not, no status at all) are pinned here rather-// than re-derived by every handler that reads the flag.+// The classification is the whole point of the type, so the boundaries (429+// retryable, 4xx not, no status at all) are pinned here rather than re-derived+// by every handler that reads the flag.import { describe, expect, it } from 'bun:test';import {diff --git a/packages/core/src/clients/provider-error.ts b/packages/core/src/clients/provider-error.tsindex 6f3eff24d..fb609406b 100644--- a/packages/core/src/clients/provider-error.ts+++ b/packages/core/src/clients/provider-error.ts@@ -1,10 +1,10 @@-// ADR-022 R19 / A4: the one failure type every outbound client raises.+// / A4: the one failure type every outbound client raises.//-// A client classifies ONCE, at the edge where it still holds the provider's-// own status code; a handler then reads `retryable` instead of re-deriving it-// from a message string. The rule the flag encodes: a retryable failure is-// rethrown so the queue runs the unit of work again, a permanent refusal is-// logged and swallowed, because a retry cannot change it.+// A client classifies ONCE, at the edge where it still holds the provider's own+// status code; a handler then reads `retryable` instead of re-deriving it from+// a message string. The rule the flag encodes: a retryable failure is rethrown+// so the queue runs the unit of work again, a permanent refusal is logged and+// swallowed, because a retry cannot change it./** Too Many Requests — the provider is asking for the same call, later. */export const RATE_LIMITED_STATUS = 429;diff --git a/packages/core/src/config.ts b/packages/core/src/config.tsindex e2c1c1605..d381aa22a 100644--- a/packages/core/src/config.ts+++ b/packages/core/src/config.ts@@ -1,15 +1,14 @@-// The shape of everything core needs from the environment (ADR-022 R7: only-// the config loader reads `process.env`). `apps/api/src/config/env.ts` is that+// The shape of everything core needs from the environment (ADR-022 R7: only the+// config loader reads `process.env`). `apps/api/src/config/env.ts` is that// loader; it parses, validates and derives, and hands the result down as// `AppDeps.config` / `Ctx.config`, so nothing below this file re-derives a// value or reaches for `process.env` again.//-// Two conventions hold throughout:-// - `undefined` means "not set", never "blank". A blank `KEY=` is absent.-// - a field that only ever had one spelling of a default keeps that default-// next to the code that documents WHY (e.g. the buffers' batch sizes), so-// the loader parses and the module decides. Anything DERIVED from more-// than one variable is resolved here and arrives finished.+// Two conventions hold throughout: - `undefined` means "not set", never+// "blank". A blank `KEY=` is absent. - a field that only ever had one spelling+// of a default keeps that default next to the code that documents WHY (e.g. the+// buffers' batch sizes), so the loader parses and the module decides. Anything+// DERIVED from more than one variable is resolved here and arrives finished./** Which pino transport ships the logs, and how the service name is built. */export interface LoggingConfig {diff --git a/packages/core/src/context.ts b/packages/core/src/context.tsindex de127c0c6..56d8d3fab 100644--- a/packages/core/src/context.ts+++ b/packages/core/src/context.ts@@ -1,8 +1,8 @@// One boot scope, one work scope, one builder. HTTP routes, tRPC procedures,// job handlers and the Kafka consumer all extend the same `Ctx`, so a service-// written once works under every transport and the requestId minted at the-// edge reaches the query, the enqueue and the job that enqueue causes-// (ADR-007 decision 18, ADR-018 R1).+// written once works under every transport and the requestId minted at the edge+// reaches the query, the enqueue and the job that enqueue causes (ADR-007+// decision 18).import type { Buffers } from './buffers/create-buffers';import { bindReadsToSignal } from './ch-abortable';@@ -14,11 +14,10 @@ import { createServices, type Services } from './services';import type { CookieJar, CookieOptions } from './shared/cookie';// The four boot handles, landed at M9-004 when main.ts became the only-// entrypoint and had to build a real `AppDeps` for the mounted route-// surfaces. Each is a TYPE QUERY over the module that constructs the client,-// so the alias cannot drift from what `main.ts` actually passes; all four are-// type-only, so core still imports no database at runtime and `bun test`-// still runs offline.+// entrypoint and had to build a real `AppDeps` for the mounted route surfaces.+// Each is a TYPE QUERY over the module that constructs the client, so the alias+// cannot drift from what `main.ts` actually passes; all four are type-only, so+// core still imports no database at runtime and `bun test` still runs offline.export type Db = typeof import('@openpanel/db/src/prisma-client').db;export type ClickHouseClient =typeof import('@openpanel/db/src/clickhouse/client').ch;@@ -43,13 +42,13 @@ export type PrismaNamespace =* Prisma's JSON sentinels (`DbNull`, `JsonNull`): frozen constants that write* an explicit SQL NULL — or a JSON `null` — onto a nullable `Json?` column.* They are values on the namespace, not a client, so nothing about them is- * per-request — but they are still `@openpanel/db` VALUES, and the four- * modules that write a `Json?` column each reached them through a lazy- * `load*` back into this file. ADR-022 R6 has one answer for that: the scope- * carries it. `main.ts` reads the two off the namespace once and puts them on- * `AppDeps`; every writer reads `deps.prisma.DbNull`. Two named fields, not- * the namespace itself — nothing else on it belongs in a request scope, and- * `Prisma` is a very large type for every consumer's `tsc` to walk.+ * per-request — but they are still `@openpanel/db` VALUES, and the four modules+ * that write a `Json?` column each reached them through a lazy `load*` back+ * into this file. ADR-022 R6 has one answer for that: the scope carries it.+ * `main.ts` reads the two off the namespace once and puts them on `AppDeps`;+ * every writer reads `deps.prisma.DbNull`. Two named fields, not the namespace+ * itself — nothing else on it belongs in a request scope, and `Prisma` is a+ * very large type for every consumer's `tsc` to walk.*/export interface PrismaSentinels {DbNull: PrismaNamespace['DbNull'];@@ -74,18 +73,18 @@ export function unscopedDb(): Promise<Db> {// module singleton.export type { Buffers } from './buffers/create-buffers';-// The resolved session. `SessionValidationResult` is Prisma-shaped-// (Session + User) but the import above is type-only, so nothing of-// `@openpanel/db` is loaded at runtime — core stays importable with no-// database, which is what lets `bun test` run offline. It stays defined next-// to the Prisma-touching session CRUD in `./modules/auth/src/login-session.ts`-// (M8-005) rather than here, which is the same file that CRUD lazily reaches-// `@openpanel/db`'s Prisma client from.+// The resolved session. `SessionValidationResult` is Prisma-shaped (Session ++// User) but the import above is type-only, so nothing of `@openpanel/db` is+// loaded at runtime — core stays importable with no database, which is what+// lets `bun test` run offline. It stays defined next to the Prisma-touching+// session CRUD in `./modules/auth/src/login-session.ts` rather than here, which+// is the same file that CRUD lazily reaches `@openpanel/db`'s Prisma client+// from.export type Session = SessionValidationResult;// The parsed environment. `apps/api`'s config/env.ts is the sole reader of-// process.env and core reads none (ADR-022 R7, made true at M15-006), so the-// shape of what core needs is declared in `./config.ts` and arrives here.+// process.env and core reads none (made true at M15-006), so the shape of what+// core needs is declared in `./config.ts` and arrives here.export type { CoreConfig } from './config';/** Boot scope. Built once in apps/api's main.ts, closed once in shutdown. */diff --git a/packages/core/src/http/auth.test.ts b/packages/core/src/http/auth.test.tsindex ad7486012..7a1891b6c 100644--- a/packages/core/src/http/auth.test.ts+++ b/packages/core/src/http/auth.test.ts@@ -152,8 +152,8 @@ test('session answers 401 when the cookie resolves to nothing', async () => {expect(response.status).toBe(401);});-// ADR-002 problem 2: a route is unauthenticated because it did not ask for a-// tier, not because of which `.use()` it was nested under.+// Problem 2: a route is unauthenticated because it did not ask for a tier, not+// because of which `.use` it was nested under.test('a route that requests no tier authenticates nobody', async () => {const response = await buildApp().handle(new Request('http://localhost/open')diff --git a/packages/core/src/http/auth.ts b/packages/core/src/http/auth.tsindex 5e0dfdf3d..12d06e183 100644--- a/packages/core/src/http/auth.ts+++ b/packages/core/src/http/auth.ts@@ -5,38 +5,37 @@// missing authorization check is silent: a broken chart throws, a dropped// access check returns 200 with somebody else's data.//-// ADR-011 A-iii invariants, binding:-// 1. Macros authenticate the caller only. A route or procedure holding a-// reportId/dashboardId/cohortId/importId/referenceId/ruleId/insightId/-// integrationId/conversationId/clientId does its own check in the handler.-// Porting a router NEVER deletes an in-handler check.-// 2. `enforceAccess` triggers on the RAW pre-zod input, top-level keys only,-// so `{projectId: null}` still reaches the project lookup and fails closed.-// 3. `needsWrite = mutation && !meta.readOnlyMutation`; the opt-out stays on-// exactly `conversation.rename` and `overview.runFilterCommand`.-// 4. The organizationId check is membership only, never admin. The 12-// `org:admin` gates stay hand-written.-// 5. `getProjectAccess`: zero ProjectAccess rows in the org => write; one row-// anywhere in the org => every unlisted project is null; all exceptions-// swallowed => null (fail-closed).-// 6. `canWriteProject` = level in {write, admin}; admin stays a superset.-// 7. 5-minute Redis cache + 60s in-process LRU on both access lookups;-// removeMember/updateMemberAccess do not clear them. Sessions survive-// revocation (docs/ANSWERS.md §3: acceptable).-// 8. The nine cross-object binding checks in DISC-011 §4.4.-// 9. chartProcedure's share branch overwrites the caller's projectId with the-// report's — explicit in the builder, not an accident of spread order.-// 10. `/live/visitors/:projectId` stays unauthenticated; the other three /live-// routes keep session + access, and all four keep reject-after-upgrade.-// 11. Invites stay bearer tokens: no invite.email vs user.email comparison.-// 12. `resolveClientProjectId` is the single client->project resolution point.-// 13. Public-API routes never see a session cookie, however the scopes compose.+// A-iii invariants, binding: 1. Macros authenticate the caller only. A route or+// procedure holding a+// reportId/dashboardId/cohortId/importId/referenceId/ruleId/insightId/+// integrationId/conversationId/clientId does its own check in the handler.+// Porting a router NEVER deletes an in-handler check. 2. `enforceAccess`+// triggers on the RAW pre-zod input, top-level keys only, so `{projectId:+// null}` still reaches the project lookup and fails closed. 3. `needsWrite =+// mutation && !meta.readOnlyMutation`; the opt-out stays on exactly+// `conversation.rename` and `overview.runFilterCommand`. 4. The organizationId+// check is membership only, never admin. The 12 `org:admin` gates stay+// hand-written. 5. `getProjectAccess`: zero ProjectAccess rows in the org =>+// write; one row anywhere in the org => every unlisted project is null; all+// exceptions swallowed => null (fail-closed). 6. `canWriteProject` = level in+// {write, admin}; admin stays a superset. 7. 5-minute Redis cache + 60s+// in-process LRU on both access lookups; removeMember/updateMemberAccess do not+// clear them. Sessions survive revocation (docs/ANSWERS.md §3: acceptable). 8.+// The nine cross-object binding checks in DISC-011 §4.4. 9. chartProcedure's+// share branch overwrites the caller's projectId with the report's — explicit+// in the builder, not an accident of spread order. 10.+// `/live/visitors/:projectId` stays unauthenticated; the other three /live+// routes keep session + access, and all four keep reject-after-upgrade. 11.+// Invites stay bearer tokens: no invite.email vs user.email comparison. 12.+// `resolveClientProjectId` is the single client->project resolution point. 13.+// Public-API routes never see a session cookie, however the scopes compose.//// Elysia 1.4.30 carries the option-bearing macro shape, so ADR-011's-// `requireClient(ctx, opts)` fallback is NOT taken: `clientAuth: { allow: [...] }`-// types the resolved client onto the handler, and a route that does not request-// the macro has no `client` binding at all — "did this route authenticate?" is-// a type question. Verified by http/auth.test.ts and by `tsc --noEmit`.+// `requireClient(ctx, opts)` fallback is NOT taken: `clientAuth: { allow: [...]+// }` types the resolved client onto the handler, and a route that does not+// request the macro has no `client` binding at all — "did this route+// authenticate?" is a type question. Verified by http/auth.test.ts and by `tsc+// --noEmit`.import { Elysia } from 'elysia';import type { AppDeps } from '../context';diff --git a/packages/core/src/http/bull-board.ts b/packages/core/src/http/bull-board.tsindex 956e8da13..3fade7bd4 100644--- a/packages/core/src/http/bull-board.ts+++ b/packages/core/src/http/bull-board.ts@@ -1,18 +1,18 @@-// Bull-board, on the main port, behind the dashboard session guard-// (ADR-005 recommendation 6). What dies with it is `@bull-board/express` and-// the worker's second express server — nothing named `@bull-board/fastify`-// ever existed. `@bull-board/api` + `@bull-board/elysia` are both pinned-// exact 9.6.0 (ADR-016; ADR-017 register row 4 grants the bump+swap at P9).+// Bull-board, on the main port, behind the dashboard session guard (ADR-005+// recommendation 6). What dies with it is `@bull-board/express` and the+// worker's second express server — nothing named `@bull-board/fastify` ever+// existed. `@bull-board/api` + `@bull-board/elysia` are both pinned exact 9.6.0+// (ADR-017 register row 4 grants the bump+swap at P9).//// TWO things a reader must not mistake for accidents://-// 1. **The base path moved.** V1 served bull-board at `/` on the worker's own-// express server (apps/worker/src/index.ts, `setBasePath('/')`). V2 has-// one port for everything, so `/` would shadow every other route. It is-// `/bullboard`; that is a deploy-note, written up in-// `packages/core/docs/OPS_GRAFANA_MIGRATION.md`.-// 2. **Pausing `cron` from this UI halts ALL buffer flushing.** Preserved-// deliberately — docs/ANSWERS.md §3: "known!".+// 1. **The base path moved.** V1 served bull-board at `/` on the worker's own+// express server (apps/worker/src/index.ts, `setBasePath('/')`). V2 has one+// port for everything, so `/` would shadow every other route. It is+// `/bullboard`; that is a deploy-note, written up in+// `packages/core/docs/OPS_GRAFANA_MIGRATION.md`. 2. **Pausing `cron` from this+// UI halts ALL buffer flushing.** Preserved deliberately — docs/ANSWERS.md §3:+// "known!".import type { Queue as BullQueue } from 'bullmq';import { Elysia } from 'elysia';diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.tsindex 905bac04f..32730c25d 100644--- a/packages/core/src/http/client-auth.ts+++ b/packages/core/src/http/client-auth.ts@@ -1,23 +1,23 @@// Where API/SDK credentials become a client principal.//// V1 has five near-identical validators — `validateSdkRequest`,-// `validateExportRequest`, `validateImportRequest`, `validateManageRequest`-// and the MCP copy — that differ only by the accepted `ClientType` set and by-// the ingest extension. They collapse into this one function (ADR-011 A-i).+// `validateExportRequest`, `validateImportRequest`, `validateManageRequest` and+// the MCP copy — that differ only by the accepted `ClientType` set and by the+// ingest extension. They collapse into this one function (ADR-011 A-i).//-// 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. 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 }`.+// Filled in the INGEST branch — `modules/ingest/src/client-auth.ts` holds V1's+// `validateSdkRequest` verbatim, and this file adapts it onto the principal.+// M15-009 inverted how it gets there: transport may not deep-import a module,+// 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-// that difference and the three collapse into `authenticateAllowedClient`-// below. MCP is NOT here — it authenticates its own `token` form inside-// `modules/mcp/src/auth.ts`, exactly as V1's mcp router did.+// 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 that difference and the three+// collapse into `authenticateAllowedClient` 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';@@ -44,9 +44,8 @@ export interface AuthenticatedClient {/*** Whether the supplied client secret VERIFIED against the stored hash.* `isBotHook` reads it as "this is a server-side SDK, never a bot", so it- * follows the verification result, not the presence of a secret string- * (main #481). The side-channel survives as a field on the principal- * (ADR-011 A-i).+ * follows the verification result, not the presence of a secret string (main+ * #481). The side-channel survives as a field on the principal (ADR-011 A-i).*/secretVerified: boolean;}@@ -114,11 +113,11 @@ export interface ClientAuthRequest {}/**- * M15-005: takes the request's own `Ctx`, not the boot scope. The ingest tier- * reads only `ctx.db` — `getClientByIdCached`'s L1 is keyed on the Postgres- * client, so `/track` reaches the one process-lived cache without forcing- * `ctx.services`. The allow-list tier is not a hot path and goes through- * `ctx.services.client` like every other handler.+ * Takes the request's own `Ctx`, not the boot scope. The ingest tier reads only+ * `ctx.db` — `getClientByIdCached`'s L1 is keyed on the Postgres client, so+ * `/track` reaches the one process-lived cache without forcing `ctx.services`.+ * The allow-list tier is not a hot path and goes through `ctx.services.client`+ * like every other handler.*/export async function authenticateClient(ctx: HttpCtx,diff --git a/packages/core/src/http/context.ts b/packages/core/src/http/context.tsindex 468840c7f..f124bafce 100644--- a/packages/core/src/http/context.ts+++ b/packages/core/src/http/context.ts@@ -57,9 +57,9 @@ export function requestContext(deps: AppDeps) {? cancelOnDisconnect(request.signal): undefined;- // `resolveSession` reads `ctx.services.auth` (ADR-022 R22), so the- // resolver closes over the ctx it is installed on. Safe because it is- // lazy: nothing calls it during the derive.+ // `resolveSession` reads `ctx.services.auth`, so the resolver closes+ // over the ctx it is installed on. Safe because it is lazy: nothing+ // calls it during the derive.const ctx: HttpCtx = extendCtx(createCtx(deps, { requestId, logger, signal: cancellation?.signal }),{@@ -90,7 +90,7 @@ export interface RequestLoggingOptions {/*** V1's `onResponse` requestLoggingHook. One `info` line per request, named* `request done` — the `requestId` field rides in from the child logger,- * replacing V1's `reqId` (ADR-018 R1).+ * replacing V1's `reqId`.*/export function requestLogging(deps: AppDeps,@@ -140,8 +140,8 @@ export function requestLogging(method: request.method,elapsed,headers: pickHeaders(request.headers, LOGGED_INGEST_HEADERS),- // V1 logs the whole /track body here; ADR-018 R6's budget for it- // is P9's call, not this port's.+ // V1 logs the whole /track body here; ADR-018 R6's budget for it is+ // P9's call, not this port's.body: path.startsWith('/track') ? body : undefined,clientIp: verbose ? ctx.ip : '',clientIpHeader: verbose ? clientIpHeader : '',diff --git a/packages/core/src/http/cors.ts b/packages/core/src/http/cors.tsindex 7e6b82179..c4fcf324d 100644--- a/packages/core/src/http/cors.ts+++ b/packages/core/src/http/cors.ts@@ -3,21 +3,21 @@//// Two halves, and BOTH are the contract://-// 1. `CORS_PRIVATE_PATHS` is V1's `corsPaths` allowlist verbatim. A request-// under one of those prefixes is only allowed from a configured dashboard-// origin; everything else — `/track`, `/export`, `/insights`, `/import`,-// `/manage`, `/profile`, `/event`, `/tools` — is open to any origin.-// 2. The quirk that `/gsc` and `/mcp` are dashboard-scope routes ABSENT from-// the list, and therefore open. Ported, not fixed.+// 1. `CORS_PRIVATE_PATHS` is V1's `corsPaths` allowlist verbatim. A request+// under one of those prefixes is only allowed from a configured dashboard+// origin; everything else — `/track`, `/export`, `/insights`, `/import`,+// `/manage`, `/profile`, `/event`, `/tools` — is open to any origin. 2. The+// quirk that `/gsc` and `/mcp` are dashboard-scope routes ABSENT from the list,+// and therefore open. Ported, not fixed.//-// The origins come from `apps/api`'s config, not from `process.env`: core-// reads no environment.+// The origins come from `apps/api`'s config, not from `process.env`: core reads+// no environment.//// ONE deliberate delta from V1, forced by the plugin substitution ADR-002// mandates (`@fastify/cors`'s per-request delegate -> `@elysiajs/cors`, whose-// `credentials` and `maxAge` are static while only `origin` is per-request):-// on an open path that DOES send an `Origin` header, V2 echoes that origin-// with `vary: Origin` where V1 answered `*`, and carries+// `credentials` and `maxAge` are static while only `origin` is per-request): on+// an open path that DOES send an `Origin` header, V2 echoes that origin with+// `vary: Origin` where V1 answered `*`, and carries// `access-control-allow-credentials: true`. Both forms permit exactly the same// set of cross-origin requests; a browser treats an echoed origin plus `Vary`// as it treats `*`. A request with no `Origin` header — every server-side SDK,diff --git a/packages/core/src/http/debug.routes.ts b/packages/core/src/http/debug.routes.tsindex f9eed37aa..2c37a92d7 100644--- a/packages/core/src/http/debug.routes.ts+++ b/packages/core/src/http/debug.routes.ts@@ -1,24 +1,23 @@// V1's `apps/worker/src/boot-debug.ts`, ported onto Elysia and onto the ONE// port. Local-only: `main.ts` mounts this surface only outside production AND-// only in a consuming role — the same two facts that were true of V1, where-// the routes lived in the worker behind `NODE_ENV !== 'production'`. They are-// what keeps an unauthenticated "run any cron job now" endpoint off a-// production box.+// only in a consuming role — the same two facts that were true of V1, where the+// routes lived in the worker behind `NODE_ENV !== 'production'`. They are what+// keeps an unauthenticated "run any cron job now" endpoint off a production+// box.//// Three things changed on the way over, all deliberate://-// * 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.-// * `/debug/insights/:projectId?inline=1` summarises with the insight-// service's own `listAllInsights` instead of V1's ad-hoc-// `projectInsight.groupBy`, because core reaches Postgres through its-// services, not through a Prisma client of its own.+// * 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. * 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. *+// `/debug/insights/:projectId?inline=1` summarises with the insight service's+// own `listAllInsights` instead of V1's ad-hoc `projectInsight.groupBy`,+// because core reaches Postgres through its services, not through a Prisma+// client of its own.import { z } from 'zod';import type { AnyJob, QueueDefinition } from '../jobs/define';diff --git a/packages/core/src/http/hooks.test.ts b/packages/core/src/http/hooks.test.tsindex b975974f3..5cac04a2c 100644--- a/packages/core/src/http/hooks.test.ts+++ b/packages/core/src/http/hooks.test.ts@@ -68,9 +68,9 @@ describe('clientIpHook', () => {});});-// ADR-002 "behaviour that must be preserved explicitly" 2. V1's order held by-// avvio's registration order; here it holds by `.use()` order plus the fact-// that cors runs at `onRequest`, an earlier phase than any `derive`.+// "behaviour that must be preserved explicitly" 2. V1's order held by avvio's+// registration order; here it holds by `.use` order plus the fact that cors+// runs at `onRequest`, an earlier phase than any `derive`.test('root chain runs cors -> requestId -> timestamp -> ip', async () => {const ran: string[] = [];diff --git a/packages/core/src/http/hooks.ts b/packages/core/src/http/hooks.tsindex 2b96ad4ab..04c02031c 100644--- a/packages/core/src/http/hooks.ts+++ b/packages/core/src/http/hooks.ts@@ -2,15 +2,14 @@//// V1's order is cors -> requestId -> timestamp -> ip, and it precedes every// route-level hook including the rate limiters (apps/api/src/app.ts:130-133;-// ADR-002 "behaviour that must be preserved explicitly" 2). Here it is `.use()`+// ADR-002 "behaviour that must be preserved explicitly" 2). Here it is `.use`// order: `requestContext` composes these three in that order and `app.ts`// mounts `@elysiajs/cors` ahead of it. The cors position is structural rather// than conventional — it runs at `onRequest`, a strictly earlier lifecycle// phase than `derive`, so it cannot be reordered by accident.//-// The request-logging hook lives with `requestContext` in ./context.ts: it-// reads the request logger off `ctx` and would otherwise import this file's-// consumer.+// The request-logging hook lives with `requestContext` in./context.ts: it reads+// the request logger off `ctx` and would otherwise import this file's consumer.import { generateId } from '@openpanel/shared';import { Elysia } from 'elysia';@@ -20,9 +19,9 @@ import { getClientIpFromHeaders } from '../shared/get-client-ip';import { sanitizeRequestId } from '../shared/request-id';/**- * First of the three. `requestIdFromCaller` is not decoration: ADR-018 R6- * keeps a caller-supplied id out of per-event log sampling, so the support- * case that supplied one still resolves.+ * First of the three. `requestIdFromCaller` is not decoration: ADR-018 R6 keeps+ * a caller-supplied id out of per-event log sampling, so the support case that+ * supplied one still resolves.*/export function requestIdHook() {return new Elysia({ name: 'core/http/request-id' }).derive(@@ -52,8 +51,8 @@ export function timestampHook() {** This is the *attribution* ip: it prefers client-forwarded headers, which is* right for analytics and fatal for a rate-limit bucket. The limiter keys on- * `openpanel-client-id` and then `getTrustedIpFromHeaders`, and must never- * read this (ADR-002 "behaviour that must be preserved explicitly" 2).+ * `openpanel-client-id` and then `getTrustedIpFromHeaders`, and must never read+ * this (ADR-002 "behaviour that must be preserved explicitly" 2).*/export function clientIpHook(ipHeaders: IpHeaderConfig) {return new Elysia({ name: 'core/http/client-ip' }).derive(diff --git a/packages/core/src/http/http.metrics.ts b/packages/core/src/http/http.metrics.tsindex 2bd0f2cd6..cd673bbae 100644--- a/packages/core/src/http/http.metrics.ts+++ b/packages/core/src/http/http.metrics.ts@@ -1,22 +1,20 @@// `fastify-metrics`'s two route series, re-created on Elysia-// (TARGET_ARCHITECTURE §18 / ADR-018's metrics-continuity register: "kept,-// name and labels reproduced exactly"). The plugin itself dies with Fastify+// (TARGET_ARCHITECTURE §18 / ADR-018's metrics-continuity register: "kept, name+// and labels reproduced exactly"). The plugin itself dies with Fastify// (ADR-002's deleted-plugin list), so these are ours now.//// What "reproduced exactly" pins, from fastify-metrics 12.1.0's own source// (dist/fastify-metrics.js:181-210, 258-290)://-// * names `http_request_duration_seconds` (histogram) and-// `http_request_summary_seconds` (summary)-// * help "request duration in seconds" / "... summary"-// * labels `method`, `route`, `status_code`, in that order-// * unit SECONDS. prom-client's `startTimer()` observes seconds; a-// milliseconds observation on the same series silently multiplies-// every existing percentile by 1000.-// * scope HEAD and OPTIONS are excluded (fastify-metrics' default-// `methodBlacklist`), and only a MATCHED route is observed-// (`registeredRoutesOnly` defaults true) — so a 404 produces no-// series, exactly as today.+// * names `http_request_duration_seconds` (histogram) and+// `http_request_summary_seconds` (summary) * help "request duration in seconds"+// / "... summary" * labels `method`, `route`, `status_code`, in that order *+// unit SECONDS. prom-client's `startTimer` observes seconds; a milliseconds+// observation on the same series silently multiplies every existing percentile+// by 1000. * scope HEAD and OPTIONS are excluded (fastify-metrics' default+// `methodBlacklist`), and only a MATCHED route is observed+// (`registeredRoutesOnly` defaults true) — so a 404 produces no series, exactly+// as today.//// The `route` label VALUE moves, because it is the framework's own route// pattern and the framework changed. That is the one thing a dashboard ownerdiff --git a/packages/core/src/http/query.ts b/packages/core/src/http/query.tsindex f9e586512..91f113fd0 100644--- a/packages/core/src/http/query.ts+++ b/packages/core/src/http/query.ts@@ -1,18 +1,18 @@// The querystring pre-pass, ported from-// apps/api/src/utils/parse-zod-query-string.ts (ADR-003, "behaviour that must-// be re-implemented deliberately": the `parseQueryString` pre-pass as an-// Elysia lifecycle hook running BEFORE schema validation on `/export` and+// apps/api/src/utils/parse-zod-query-string.ts ("behaviour that must be+// re-implemented deliberately": the `parseQueryString` pre-pass as an Elysia+// lifecycle hook running BEFORE schema validation on `/export` and// `/insights`).//-// It exists because ~31 query schemas on those two surfaces are written-// against already-coerced values — `z.number()`, `z.boolean()`,-// `z.array(...)` — while a querystring only ever carries strings. V1 coerced-// in a Fastify `preValidation` hook; rewriting those schemas with `z.coerce`-// instead would change the contract, which is why the ADR names the hook.+// It exists because ~31 query schemas on those two surfaces are written against+// already-coerced values — `z.number`, `z.boolean`, `z.array(...)` — while a+// querystring only ever carries strings. V1 coerced in a Fastify+// `preValidation` hook; rewriting those schemas with `z.coerce` instead would+// change the contract, which is why the ADR names the hook.//-// `transform` is Elysia's pre-validation phase, and the hook MUTATES `query`-// in place: reassigning the destructured binding would not reach the object-// the validator then reads.+// `transform` is Elysia's pre-validation phase, and the hook MUTATES `query` in+// place: reassigning the destructured binding would not reach the object the+// validator then reads.import { getSafeJson } from '@openpanel/shared';diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.tsindex c110622f4..d5eaf2c11 100644--- a/packages/core/src/http/session.ts+++ b/packages/core/src/http/session.ts@@ -1,25 +1,25 @@// Where the session cookie becomes a session.//-// `HttpCtx.session()` memoizes this call, so a request that asks twice pays-// once, and the cookie is read through `HttpCtx` rather than through a plugin-// whose registration order could put it after the guard that needs it-// (ADR-002 "behaviour that must be preserved explicitly" 1).+// `HttpCtx.session` memoizes this call, so a request that asks twice pays once,+// and the cookie is read through `HttpCtx` rather than through a plugin whose+// registration order could put it after the guard that needs it (ADR-002+// "behaviour that must be preserved explicitly" 1).//-// M9-004 filled the body in, porting apps/api/src/app.ts's dashboard-scope-// `onRequest` hook: decode, `runWithAlsSession`, validate, and V1's-// DEMO_USER_ID branch — which lives inside `validateSessionToken` itself, so-// the no-cookie path still goes through it rather than short-circuiting here.+// Filled the body in, porting apps/api/src/app.ts's dashboard-scope `onRequest`+// hook: decode, `runWithAlsSession`, validate, and V1's DEMO_USER_ID branch —+// which lives inside `validateSessionToken` itself, so the no-cookie path still+// goes through it rather than short-circuiting here.//-// M15-007: both halves arrive as `ctx.services.auth`, not as a deep import of-// `modules/auth/src/*` (ADR-022 R22). The derive in `http/context.ts` builds-// the `Ctx` before it installs this resolver and the resolver is lazy, so the-// services graph is there by the time a guard asks for a session — a request-// that never asks (every `/track`) still builds none.+// Both halves arrive as `ctx.services.auth`, not as a deep import of+// `modules/auth/src/*`. The derive in `http/context.ts` builds the `Ctx` before+// it installs this resolver and the resolver is lazy, so the services graph is+// there by the time a guard asks for a session — a request that never asks+// (every `/track`) still builds none.//-// `null` means "nobody is signed in", NOT `EMPTY_SESSION`: the `session`-// macro, the bull-board guard and the four `/live` handlers all treat the-// resolved value as truthy-means-authenticated. tRPC is the one caller that-// wants V1's empty shape instead, and `makeTrpcContext` maps `null` back to+// `null` means "nobody is signed in", NOT `EMPTY_SESSION`: the `session` macro,+// the bull-board guard and the four `/live` handlers all treat the resolved+// value as truthy-means-authenticated. tRPC is the one caller that wants V1's+// empty shape instead, and `makeTrpcContext` maps `null` back to// `EMPTY_SESSION` there.import type { Ctx, Session } from '../context';diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.tsindex bc73fffb1..9b2bc4af1 100644--- a/packages/core/src/index.test.ts+++ b/packages/core/src/index.test.ts@@ -3,8 +3,8 @@ import * as core from './index';// The curated barrel is the package's real public API (ADR-008 acceptance// note): what apps/api needs to build AppDeps once and mount the three route-// surfaces plus the tRPC router. A name missing here is a name apps/api-// cannot reach — there is no `./*` wildcard to fall back on.+// surfaces plus the tRPC router. A name missing here is a name apps/api cannot+// reach — there is no `./*` wildcard to fall back on.test('the mount surface is curated', () => {expect(core.appRouter).toBeDefined();expect(core.publicApiRoutes).toBeTypeOf('function');@@ -18,11 +18,10 @@ test('the mount surface is curated', () => {expect(core.queues).toBeDefined();});-// ONE tRPC instance (ADR-009): `initTRPC` is called in rpc/base.ts and-// nowhere else. All 28 routers now build on this barrel's builder, router-// factory and the two injected middleware factories (M11-001); V1's-// `@openpanel/trpc` used to reach them the same way before it was deleted-// (M11-004).+// ONE tRPC instance: `initTRPC` is called in rpc/base.ts and nowhere else. All+// 28 routers now build on this barrel's builder, router factory and the two+// injected middleware factories; V1's `@openpanel/trpc` used to reach them the+// same way before it was deleted.test('the rpc base is on the barrel, so there is one tRPC instance', () => {expect(core.procedure).toBeDefined();expect(core.middleware).toBeTypeOf('function');@@ -37,9 +36,9 @@ test('a service, a client or a buffer is not on the barrel', () => {expect(Object.keys(core)).not.toContain('createServices');});-// The buffers are boot singletons on AppDeps (ADR-007), so main.ts needs the-// FACTORY and nothing else. A named instance here would be the module-// singleton the design refuses.+// The buffers are boot singletons on AppDeps, so main.ts needs the FACTORY and+// nothing else. A named instance here would be the module singleton the design+// refuses.test('buffers reach the barrel as a factory, never as instances', () => {expect(core.createBuffers).toBeTypeOf('function');expect(core.registerBufferMetrics).toBeTypeOf('function');diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 218794ef8..be1ccc733 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -24,10 +24,10 @@ export type {UserAgentInfo,UserAgentResult,} from '@openpanel/shared/server';-// 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-// relative import now that it lives inside core (M5-007).+// Dissolved from packages/common/server — 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 relative import now that+// it lives inside core.export {assertPublicHostname,assertPublicUrl,@@ -50,11 +50,10 @@ export {safeFetchStream,verifyPassword,} from '@openpanel/shared/server';-// The seven buffers (moved from packages/db/src/buffers, M8-001). Only the-// FACTORY is on the barrel: they are boot singletons on `AppDeps`, built once-// by `main.ts`, never module singletons (ADR-007). V1's-// packages/db/src/buffers/index.ts calls this once and re-exports the-// instances, so both boots share one set.+// The seven buffers (moved from packages/db/src/buffers). Only the FACTORY is+// on the barrel: they are boot singletons on `AppDeps`, built once by+// `main.ts`, never module singletons. V1's packages/db/src/buffers/index.ts+// calls this once and re-exports the instances, so both boots share one set.export type {AddObservation,AddObserver,@@ -72,15 +71,14 @@ export type { ProfileBackfillEntry } from './buffers/profile-backfill-buffer';export type { IClickhouseSessionReplayChunk } from './buffers/replay-buffer';export type { SessionIngestResult } from './buffers/session-buffer';export { resolveSessionTimeoutMs } from './buffers/session-buffer';-// ADR-022 R13, M15-008: of the ~35 `clients/` symbols this barrel used to-// re-export, `main.ts` imported one (`createClients`) and `apps/start` none.-// The rest — every AI call, the Slack/Discord senders, the geo lookups, the-// object-store adapters, the integration registry — are reached by relative-// import inside this package and are no longer on the public surface.-// `pino-logger` is the concrete implementation of `./logger`'s structural-// interface; main.ts builds its own named logger from it and mirrors a fatal-// to the real stderr with the write captured before `interceptProcessOutput`-// wrapped the stream.+// R13, M15-008: of the ~35 `clients/` symbols this barrel used to re-export,+// `main.ts` imported one (`createClients`) and `apps/start` none. The rest —+// every AI call, the Slack/Discord senders, the geo lookups, the object-store+// adapters, the integration registry — are reached by relative import inside+// this package and are no longer on the public surface. `pino-logger` is the+// concrete implementation of `./logger`'s structural interface; main.ts builds+// its own named logger from it and mirrors a fatal to the real stderr with the+// write captured before `interceptProcessOutput` wrapped the stream.export type { ServiceClients } from './clients/create-clients';export { createClients } from './clients/create-clients';export {@@ -103,20 +101,20 @@ export type {} from './context';export { createCtx, extendCtx } from './context';// The role-conditional HTTP surfaces main.ts mounts over the three in-// rest.routes.ts (M9-002). `bullBoardRoutes` is async because the adapter-// reads its own UI assets off disk before it can register.+// rest.routes.ts. `bullBoardRoutes` is async because the adapter reads its own+// UI assets off disk before it can register.export { BULL_BOARD_BASE_PATH, bullBoardRoutes } from './http/bull-board';export { requestContext, requestLogging } from './http/context';-// The root chain `main.ts` hangs every surface on (M9-004): V1's CORS-// delegator and V1's error handler, both ported and both taking their-// deployment-derived values as arguments — core reads no environment.+// The root chain `main.ts` hangs every surface on: V1's CORS delegator and V1's+// error handler, both ported and both taking their deployment-derived values as+// arguments — core reads no environment.export type { CorsOptions } from './http/cors';export { CORS_PRIVATE_PATHS, corsDelegator } from './http/cors';export type { ErrorHandlerOptions } from './http/errors';export { errorHandler } from './http/errors';-// The two runtime seams over the registry (ADR-005). `main.ts` builds-// producers in every role and workers only where the role consumes; both take-// the registry as data, so neither opens a connection until it is called.+// The two runtime seams over the registry. `main.ts` builds producers in every+// role and workers only where the role consumes; both take the registry as+// data, so neither opens a connection until it is called.export type {AnyJob,EnqueueOptions,@@ -160,13 +158,14 @@ export {// exported: a caller that can reach it can start a second collector graph// somewhere other than a module, which is the thing §18 forbids.export { registerDefaultMetrics } from './metrics';-// Moved from apps/api/src/agents/* + packages/trpc/src/agents/filter-command.ts-// (M5-005). M15-003: the chat app, the run context and the filter command all-// take the API's `deps` now, so the barrel carries the factory and the types-// only — `assistant.routes.ts` and `overview.rpc.ts` reach them through-// `ctx.services.assistant`. `ChatApp` is the one type past `AppRouter` that-// crosses into apps/start (`src/agents/client.ts`); it stays a TYPE, so no-// value of this module reaches a browser bundle.+// Moved from apps/api/src/agents/* ++// packages/trpc/src/agents/filter-command.ts. M15-003: the chat app, the run+// context and the filter command all take the API's `deps` now, so the barrel+// carries the factory and the types only — `assistant.routes.ts` and+// `overview.rpc.ts` reach them through `ctx.services.assistant`. `ChatApp` is+// the one type past `AppRouter` that crosses into apps/start+// (`src/agents/client.ts`); it stays a TYPE, so no value of this module reaches+// a browser bundle.export type {ChatApp,ChatRunContext,@@ -174,17 +173,16 @@ export type {RunFilterCommandInput,} from './modules/assistant/assistant.service';export { createAssistantService } from './modules/assistant/assistant.service';-// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks call-// these directly; V1's now-deleted @openpanel/trpc auth/share/user/gsc-// routers did too, the same way they reached the other dissolved leaf-// packages here. `hashPassword` is renamed on the way out:-// `@openpanel/shared/server` already owns that name for the (unrelated) scrypt-// hash client secrets use.+// Dissolved from @openpanel/auth — apps/api's OAuth callbacks call these+// directly; V1's now-deleted @openpanel/trpc auth/share/user/gsc routers did+// too, the same way they reached the other dissolved leaf packages here.+// `hashPassword` is renamed on the way out: `@openpanel/shared/server` already+// owns that name for the (unrelated) scrypt hash client secrets use.//-// The sign-up/sign-in/TOTP/reset-password/share/OAuth-callback half (M6-003)-// joined it here — V1's now-deleted packages/trpc auth router and-// apps/api/src/controllers/oauth-callback.controller.tsx called these-// directly, the same way V1 reached every other dissolved service here.+// The sign-up/sign-in/TOTP/reset-password/share/OAuth-callback half joined it+// here — V1's now-deleted packages/trpc auth router and+// apps/api/src/controllers/oauth-callback.controller.tsx called these directly,+// the same way V1 reached every other dissolved service here.export type {AuthProvider,CompleteOAuthCallbackInput,@@ -236,9 +234,9 @@ export type {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).+// Moved from packages/db/src/services/auth-session.service.ts — the+// Postgres-backed login session CRUD. packages/db keeps a re-export shim+// (existing `@openpanel/db` importers, apps/api's app.ts).export type { SessionValidationResult } from './modules/auth/src/login-session';export {createDemoSession,@@ -247,10 +245,10 @@ export {validateSessionToken,} from './modules/auth/src/login-session';export { getIsRegistrationAllowed } from './modules/auth/src/registration';-// Dissolved from @openpanel/db's services/chart.service.ts and engine/-// (M7-003) — packages/trpc's chart router, apps/api's export controller,-// V1's funnel/conversion/sankey/retention/overview services and the-// mcp/assistant tools reach the engine and the field/filter compilers here.+// Dissolved from @openpanel/db's services/chart.service.ts and engine/ —+// packages/trpc's chart router, apps/api's export controller, V1's+// funnel/conversion/sankey/retention/overview services and the mcp/assistant+// tools reach the engine and the field/filter compilers here.// packages/db/src/services/chart.service.ts and src/engine/index.ts stay// re-export shims.export type {@@ -303,10 +301,10 @@ export {rewriteProfilePropertyRefs,transformPropertyKey,} from './modules/chart/chart.service';-// Dissolved from @openpanel/db's services/funnel.service.ts (M7-004) —-// packages/db's reports.service, apps/api's insights controller and the-// mcp/assistant tools call these. packages/db/src/services/funnel.service.ts-// stays a re-export shim.+// Dissolved from @openpanel/db's services/funnel.service.ts — packages/db's+// reports.service, apps/api's insights controller and the mcp/assistant tools+// call these. packages/db/src/services/funnel.service.ts stays a re-export+// shim.export type {BuildFunnelBaseInput,FunnelStep,@@ -317,8 +315,8 @@ export {getFunnelGroup,toSeries,} from './modules/chart/funnel.service';-// Dissolved from @openpanel/db's services/retention.service.ts (M7-004) —-// apps/api's insights controller and the mcp/assistant tools call these.+// Dissolved from @openpanel/db's services/retention.service.ts — apps/api's+// insights controller and the mcp/assistant tools call these.// packages/db/src/services/retention.service.ts stays a re-export shim.export type {IGetRetentionCohortInput,@@ -328,8 +326,8 @@ export type {IServiceRetentionRollingActiveUsers,} from './modules/chart/retention.service';export { processCohortData } from './modules/chart/retention.service';-// Dissolved from @openpanel/db's services/sankey.service.ts (M7-004) —-// apps/api's insights controller and the mcp/assistant tools call these.+// Dissolved from @openpanel/db's services/sankey.service.ts — apps/api's+// insights controller and the mcp/assistant tools call these.// packages/db/src/services/sankey.service.ts stays a re-export shim.export type {IGetSankeyInput,@@ -341,17 +339,16 @@ export {getRawWhereClause,zGetSankeyInput,} from './modules/chart/sankey.service';-// Moved from packages/db/src/services/filter-where.service.ts (M8-005) — the+// Moved from packages/db/src/services/filter-where.service.ts — the// sessions/profiles/events-table filter compiler, distinct from// `getEventFiltersWhereClause` above. packages/db/src/services/// filter-where.service.ts stays a re-export shim.export type { FilterTableContext } from './modules/chart/src/table-filter-where';export { buildFilterWhere } from './modules/chart/src/table-filter-where';-// Dissolved from @openpanel/db's services/clients.service.ts (M6-002) —-// packages/trpc's client router, apps/api's manage controller and mcp/utils-// auth call these directly, the same way V1 reaches every other dissolved-// service here. packages/db/src/services/clients.service.ts stays a-// re-export shim.+// Dissolved from @openpanel/db's services/clients.service.ts — packages/trpc's+// client router, apps/api's manage controller and mcp/utils auth call these+// directly, the same way V1 reaches every other dissolved service here.+// packages/db/src/services/clients.service.ts stays a re-export shim.export type {CreatedClient,IPublicClient,@@ -363,17 +360,16 @@ export {// apps/api's session e2e clears one client's cache between runs.getClientByIdCached,} from './modules/client/client.service';-// Dissolved from @openpanel/db's services/cohort.service.ts (M5-003) —-// packages/trpc's cohort router and apps/worker's cohort job files call-// these directly, the same way V1 reaches every other dissolved service-// here. Nothing else in the tree reached cohort.service.ts through-// @openpanel/db's barrel, so packages/db loses the file entirely rather than-// keeping a re-export shim (unlike gsc.ts/gsc.service.ts).-// Moved from @openpanel/db's services/conversation.service.ts (M5-006) —-// packages/trpc's conversation router, apps/api's live chat route and this-// package's own assistant.routes.ts stub call these directly. packages/db-// keeps a re-export shim (unlike cohort, M5-003): both non-trpc call sites-// still reach it through `@openpanel/db`'s barrel.+// Dissolved from @openpanel/db's services/cohort.service.ts — packages/trpc's+// cohort router and apps/worker's cohort job files call these directly, the+// same way V1 reaches every other dissolved service here. Nothing else in the+// tree reached cohort.service.ts through @openpanel/db's barrel, so packages/db+// loses the file entirely rather than keeping a re-export shim (unlike+// gsc.ts/gsc.service.ts). Moved from @openpanel/db's+// services/conversation.service.ts — packages/trpc's conversation router,+// apps/api's live chat route and this package's own assistant.routes.ts stub+// call these directly. packages/db keeps a re-export shim (unlike cohort): both+// non-trpc call sites still reach it through `@openpanel/db`'s barrel.export type {IServiceChatMessage,IServiceConversation,@@ -381,25 +377,24 @@ export type {} from './modules/conversation/conversation.service';export { createConversationService } from './modules/conversation/conversation.service';// Dissolved from @openpanel/db's services/dashboard.service.ts, plus V1's-// dashboard router mutation bodies (M7-006) — packages/trpc's dashboard-// router, apps/api's insights controller and the mcp/assistant tools call-// these. packages/db/src/services/dashboard.service.ts stays a re-export-// shim.+// dashboard router mutation bodies — packages/trpc's dashboard router,+// apps/api's insights controller and the mcp/assistant tools call these.+// packages/db/src/services/dashboard.service.ts stays a re-export shim.export type {IServiceDashboard,IServiceDashboards,} from './modules/dashboard/dashboard.service';export { createDashboardService } from './modules/dashboard/dashboard.service';-// R + C only (M6-004): the router's three bodies are three small-// `db.emailUnsubscribe` calls, small enough to live inline in-// `email.rpc.ts` rather than a dedicated `email.service.ts` — see that-// file's header. `emailCategories` moved from packages/constants (ADR-008's-// module map: email owns "C"); packages/constants keeps a re-export shim.+// R + C only: the router's three bodies are three small `db.emailUnsubscribe`+// calls, small enough to live inline in `email.rpc.ts` rather than a dedicated+// `email.service.ts` — see that file's header. `emailCategories` moved from+// packages/constants (ADR-008's 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.+// Moved from apps/worker/src/jobs/lib/email-sequence.ts — shared by the+// onboarding module and, since M9-003, the organization module's wind-down+// track.export type {RunSequenceOptions,SequenceResult,@@ -411,15 +406,15 @@ 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-// (M7-002, ADR-008's module map: event "R,S", profile "R,H,S", group-// "R,S,C") — packages/trpc's routers, apps/api's export controller, is-bot-// hook and profile controller, apps/worker's incoming-event job and the-// assistant/mcp tools call these directly, the same way V1 reaches every-// other dissolved service here. `packages/db`'s re-export shims for these-// three files are gone (M9-CLEANUP-001) — every caller now imports this-// barrel directly. `profileSearchSql` (cohort.service's one addition atop the-// shim) died with M12-003: its only caller now composes a `sql` fragment and-// uses `profileSearchCondition`.+// (ADR-008's module map: event "R,S", profile "R,H,S", group "R,S,C") —+// packages/trpc's routers, apps/api's export controller, is-bot hook and+// profile controller, apps/worker's incoming-event job and the assistant/mcp+// tools call these directly, the same way V1 reaches every other dissolved+// service here. `packages/db`'s re-export shims for these three files are gone+// (M9-CLEANUP-001) — every caller now imports this barrel directly.+// `profileSearchSql` (cohort.service's one addition atop the shim) died with+// M12-003: its only caller now composes a `sql` fragment and uses+// `profileSearchCondition`.export type {EventListSelect,GetEventListOptions,@@ -451,12 +446,12 @@ export type {IServiceGroupStats,IServiceUpsertGroup,} from './modules/group/group.service';-// Dissolved from @openpanel/db's src/gsc.ts + services/gsc.service.ts-// (M5-002) — apps/worker's gsc job file, apps/api's gsc OAuth callback-// controller and packages/trpc's gsc router call these directly, the same-// way V1 reaches every other dissolved service here. packages/db/src/gsc.ts-// and packages/db/src/services/gsc.service.ts re-export the subset MCP's gsc-// tools and the assistant's SEO tools still reach via `@openpanel/db`.+// Dissolved from @openpanel/db's src/gsc.ts + services/gsc.service.ts —+// apps/worker's gsc job file, apps/api's gsc OAuth callback controller and+// packages/trpc's gsc router call these directly, the same way V1 reaches every+// other dissolved service here. packages/db/src/gsc.ts and+// packages/db/src/services/gsc.service.ts re-export the subset MCP's gsc tools+// and the assistant's SEO tools still reach via `@openpanel/db`.export type {GscCannibalizedQuery,GscConnectionSummary,@@ -468,12 +463,12 @@ export type {} from './modules/gsc/gsc.service';export { getGscCannibalization } from './modules/gsc/gsc.service';export { isShuttingDown, setShuttingDown } from './modules/health/src/shutdown';-// Dissolved from @openpanel/db's services/import.service.ts +-// apps/worker's job file + apps/api's /import controller (M5-004) —-// apps/worker's import job file and apps/api's import controller call these-// directly, the same way V1 reaches every other dissolved service here.-// packages/db/src/services/import.service.ts is deleted outright: nothing-// else reached it through @openpanel/db's barrel (same as cohort, M5-003).+// Dissolved from @openpanel/db's services/import.service.ts + apps/worker's job+// file + apps/api's /import controller — apps/worker's import job file and+// apps/api's import controller call these directly, the same way V1 reaches+// every other dissolved service here.+// packages/db/src/services/import.service.ts is deleted outright: nothing else+// reached it through @openpanel/db's barrel (same as cohort).export type {ImportJobProgress,ImportStageResult,@@ -481,9 +476,9 @@ export type {InsertRawEventsResult,UpdateImportStatusOptions,} from './modules/import/import.service';-// The ingestion pipeline (M8-002). apps/api's /track controller, its three-// route hooks and the legacy /event controller are thin delegates over these-// — the same functions core's own `ingestRoutes` calls.+// The ingestion pipeline. apps/api's /track controller, its three route hooks+// and the legacy /event controller are thin delegates over these — the same+// functions core's own `ingestRoutes` calls.export type {BotMatch,BotSuspicion,@@ -516,10 +511,10 @@ export {summarizeBotSignals,validateIngestRequest,} from './modules/ingest/ingest.service';-// The Kafka consumer and its per-message handler (M8-003), which take the-// kafkajs client, the topic/group names and the retry bounds as arguments —-// the injection seam that used to cross a package boundary and now just-// crosses two files.+// The Kafka consumer and its per-message handler, which take the kafkajs+// client, the topic/group names and the retry bounds as arguments — the+// injection seam that used to cross a package boundary and now just crosses two+// files.export type {ConsumerLogger,ConsumerMetrics,@@ -535,8 +530,8 @@ export {startKafkaEventsConsumer,} from './modules/ingest/src/consumer';export { createIncomingEventHandler } from './modules/ingest/src/consumer-handler';-// The readiness probe's two inputs (M9-002). `markEventsActivity` is the-// consumer's `onActivity`; `setShuttingDown` is main.ts's signal handler.+// The readiness probe's two inputs. `markEventsActivity` is the consumer's+// `onActivity`; `setShuttingDown` is main.ts's signal handler.export {enableEventsHeartbeat,getEventsHeartbeat,@@ -555,10 +550,10 @@ export {incomingEvent,} from './modules/ingest/src/incoming-event-handler';export { ingestConsumerMetrics } from './modules/ingest/src/ingest.metrics';-// The Kafka transport itself (M11-003): producer, consumer factory, admin/lag-// sampling and every topic/group/retry constant, moved from-// @openpanel/queue's kafka.ts unchanged. It constructs no client at import-// time, so the barrel stays offline-importable.+// The Kafka transport itself: producer, consumer factory, admin/lag sampling+// and every topic/group/retry constant, moved from @openpanel/queue's kafka.ts+// unchanged. It constructs no client at import time, so the barrel stays+// offline-importable.export type {Admin,ConsumerGroupLag,@@ -585,34 +580,33 @@ export type {} from './modules/insight/insight.service';export { explainInsight } from './modules/insight/insight.service';// Moved from packages/trpc/src/routers/integration.ts, plus the Slack OAuth-// callback business logic out of-// apps/api/src/controllers/webhook.controller.ts (M6-006, ADR-008's module-// map: integration owns "S"+"C") — packages/trpc's integration router and-// apps/api's webhook controller call these directly, the same way V1 reaches-// every other dissolved service here.+// callback business logic out of apps/api/src/controllers/webhook.controller.ts+// (ADR-008's module map: integration owns "S"+"C") — packages/trpc's+// integration router and apps/api's webhook controller call these directly, the+// same way V1 reaches every other dissolved service here.export type { CompleteSlackOAuthCallbackResult } from './modules/integration/integration.service';export { SlackOAuthCallbackError } from './modules/integration/integration.service';-// Slack's OAuth token-exchange wire contract (M6-006) — not integration-// config (stays out of the `*.constants` subpath, see-// modules/integration/src/slack-contract.ts's header), but apps/api's-// webhook controller still needs it to validate Slack's `oauth.v2.access`-// response, the same way it reaches slackInstaller above.+// Slack's OAuth token-exchange wire contract — not integration config (stays+// out of the `*.constants` subpath, see+// modules/integration/src/slack-contract.ts's header), but apps/api's webhook+// controller still needs it to validate Slack's `oauth.v2.access` response, the+// same way it reaches slackInstaller above.export { zSlackAuthResponse } from './modules/integration/src/slack-contract';-// packages/mcp absorbed whole (M5-007) — ADR-015 entry 2: stateless-only, so-// there is no SessionManager to manage. M15-003: the barrel carries the-// factory and the two types only. `handleStatelessMcpRequest` needs the-// API's `deps`, so the app shell reaches MCP the one way it ever did —-// `rest.routes.ts`'s `.use(mcpRoutes(deps))` and `ctx.services.mcp`.+// Packages/mcp absorbed whole — ADR-015 entry 2: stateless-only, so there is no+// SessionManager to manage. M15-003: the barrel carries the factory and the two+// types only. `handleStatelessMcpRequest` needs the API's `deps`, so the app+// shell reaches MCP the one way it ever did — `rest.routes.ts`'s+// `.use(mcpRoutes(deps))` and `ctx.services.mcp`.export type {McpAuthContext,McpHttpResult,} from './modules/mcp/mcp.service';export { createMcpService } from './modules/mcp/mcp.service';-// Ported from apps/api's misc controller + apps/worker's cron.ping.ts (M7-008)-// — apps/api's misc controller and the worker's ping cron job call these-// directly, the same way V1 reaches every other dissolved service here.-// `GET /misc/og/clear` and `/misc/favicon/clear` are NOT ported (ADR-015-// entry #6: RULED + DEAD).+// Ported from apps/api's misc controller + apps/worker's cron.ping.ts —+// apps/api's misc controller and the worker's ping cron job call these+// directly, the same way V1 reaches every other dissolved service here. `GET+// /misc/og/clear` and `/misc/favicon/clear` are NOT ported (ADR-015 entry #6:+// RULED + DEAD).export type {GeoReport,ImageAssetResult,@@ -642,32 +636,32 @@ export {notificationTemplateEvent,notificationTemplateFunnel,} from './modules/notification/notification.service';-// Dissolved from @openpanel/db's services/notification.service.ts (M6-005,-// "rules + dispatch stay together"). `createNotification` /-// `triggerNotification` / `checkNotificationRulesForEvent` /-// `checkNotificationRulesForSessionEnd` — the BullMQ-producer orchestration-// around a rule match — came home from @openpanel/queue at M11-003 and now-// live in this module's own src/notification-dispatch.ts. Only the one the-// Kafka message handler is bound to at boot needs to leave the package.+// Dissolved from @openpanel/db's services/notification.service.ts ("rules ++// dispatch stay together"). `createNotification` / `triggerNotification` /+// `checkNotificationRulesForEvent` / `checkNotificationRulesForSessionEnd` —+// the BullMQ-producer orchestration around a rule match — came home from+// @openpanel/queue at M11-003 and now live in this module's own+// src/notification-dispatch.ts. Only the one the Kafka message handler is bound+// to at boot needs to leave the package.export { checkNotificationRulesForEvent } from './modules/notification/src/notification-dispatch';-// New module (M6-003) — the onboarding-project mutation and the onboarding-// email drip, neither of which had a packages/db/src/services/* home to move-// from. V1's now-deleted packages/trpc onboarding router and apps/worker's-// onboarding cron job called these directly, the same way V1 reached every-// other dissolved service here.+// New module — the onboarding-project mutation and the onboarding email drip,+// neither of which had a packages/db/src/services/* home to move from. V1's+// now-deleted packages/trpc onboarding router and apps/worker's onboarding cron+// job called these directly, the same way V1 reached every other dissolved+// service here.export type {CreateOnboardingProjectResult,OnboardingCronSummary,} from './modules/onboarding/onboarding.service';export { createOnboardingService } from './modules/onboarding/onboarding.service';// Dissolved from @openpanel/db's services/organization.service.ts +-// services/delete.service.ts (M6-001, folded together per the module map) —+// services/delete.service.ts (folded together per the module map) —// packages/trpc's organization router, apps/worker's delete cron job and// packages/db's own engine/analytics services (`getSettingsForProject`) call// these directly, the same way V1 reaches every other dissolved service here.// packages/db/src/services/organization.service.ts stays a re-export shim-// (unlike delete.service.ts, which packages/db loses entirely — nothing but-// the worker's cron job reached it through @openpanel/db's barrel).+// (unlike delete.service.ts, which packages/db loses entirely — nothing but the+// worker's cron job reached it through @openpanel/db's barrel).export type {DeleteCronResult,InviteUserResult,@@ -682,10 +676,10 @@ export {getOrganizationByProjectIdCached,} from './modules/organization/organization.service';// Dissolved from @openpanel/db's services/overview.service.ts +-// pages.service.ts (M7-005) — packages/trpc's overview/event routers,-// apps/api's insights controller, apps/worker's win-back job and the-// mcp/assistant tools call these directly. packages/db/src/services/-// overview.service.ts and pages.service.ts stay re-export shims.+// pages.service.ts — packages/trpc's overview/event routers, apps/api's+// insights controller, apps/worker's win-back job and the mcp/assistant tools+// call these directly. packages/db/src/services/ overview.service.ts and+// pages.service.ts stay re-export shims.export type {IGetMapDataInput,IGetMetricsInput,@@ -730,11 +724,11 @@ export type {ProfileRequestContext,} from './modules/profile/profile.service';export { transformProfile } from './modules/profile/profile.service';-// Dissolved from @openpanel/db's services/project.service.ts (M6-002) —-// packages/trpc's project router, apps/api's manage controller and several-// core modules' `src/access.ts` call these directly, the same way V1-// reaches every other dissolved service here. packages/db/src/services/-// project.service.ts stays a re-export shim.+// Dissolved from @openpanel/db's services/project.service.ts — packages/trpc's+// project router, apps/api's manage controller and several core modules'+// `src/access.ts` call these directly, the same way V1 reaches every other+// dissolved service here. packages/db/src/services/ project.service.ts stays a+// re-export shim.export { ProjectTypeNames } from './modules/project/project.constants';export type {CreatedProjectClient,@@ -743,27 +737,27 @@ export type {ProjectActivationStatus,} from './modules/project/project.service';export { createProjectService } from './modules/project/project.service';-// The six ClickHouse queries moved from packages/trpc/src/routers/realtime.ts-// (M6-007) — packages/trpc's realtime router calls these directly, the same-// way V1 reaches every other dissolved service here. The `/live` websocket-// glue in the same file stays internal to core/realtime.routes.ts; V1's own-// Fastify `/live` controller is untouched (see realtime.service.ts's header)-// so nothing else needs it from this barrel.+// The six ClickHouse queries moved from packages/trpc/src/routers/realtime.ts —+// packages/trpc's realtime router calls these directly, the same way V1 reaches+// every other dissolved service here. The `/live` websocket glue in the same+// file stays internal to core/realtime.routes.ts; V1's own Fastify `/live`+// controller is untouched (see realtime.service.ts's header) so nothing else+// needs it from this barrel.export type {RealtimeBadgeDetailScope,RealtimeLocation,} from './modules/realtime/realtime.service';// Moved from packages/db/src/services/reference.service.ts, plus the-// query/mutation bodies packages/trpc/src/routers/reference.ts held inline-// (M6-004) — packages/trpc's reference router calls these directly, the same-// way V1 reaches every other dissolved service here. packages/db keeps a-// re-export shim.+// query/mutation bodies packages/trpc/src/routers/reference.ts held inline —+// packages/trpc's reference router calls these directly, the same way V1+// reaches every other dissolved service here. packages/db keeps a re-export+// shim.export type { IServiceReference } from './modules/reference/reference.service';export { createReferenceService } from './modules/reference/reference.service';// Moved from packages/constants/index.ts and packages/validation/src/index.ts-// (M7-006, ADR-008's module map: report owns "C" for the chart/report/widget-// vocabulary) — apps/start's report builder and the assistant/mcp tools-// reach the vocabulary directly through @openpanel/core here, same shape as+// (ADR-008's module map: report owns "C" for the chart/report/widget+// vocabulary) — apps/start's report builder and the assistant/mcp tools reach+// the vocabulary directly through @openpanel/core here, same shape as// `emailCategories`/`ProjectTypeNames` below. Both origin packages stay// re-export shims.export type { IFilterValueType } from './modules/report/report.constants';@@ -815,9 +809,9 @@ export {zWidgetOptions,zWidgetType,} from './modules/report/report.constants';-// Dissolved from @openpanel/db's services/reports.service.ts, plus V1's-// report router mutation bodies (M7-006) — packages/trpc's report router,-// apps/api's insights controller and the mcp/assistant tools call these.+// Dissolved from @openpanel/db's services/reports.service.ts, plus V1's report+// router mutation bodies — packages/trpc's report router, apps/api's insights+// controller and the mcp/assistant tools call these.// packages/db/src/services/reports.service.ts stays a re-export shim.export type { IServiceReport } from './modules/report/report.service';export {@@ -836,7 +830,7 @@ export {onlyReportEvents,} from './modules/report/src/series';// Moved from packages/db/src/services/salt.service.ts +-// apps/worker/src/jobs/cron.salt.ts (M8-004) — `main.ts` calls+// apps/worker/src/jobs/cron.salt.ts — `main.ts` calls// `createInitialSalts(deps)` directly at boot; `salt.jobs.ts`'s cron handler// and everything else reach `rotateSalt`/`getSalts` through// `ctx.services.salt`.@@ -847,13 +841,13 @@ export {} from './modules/salt/salt.service';// Dissolved from @openpanel/db's services/session.service.ts and// 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-// here. `packages/db`'s re-export shims for both files are gone-// (M9-CLEANUP-001). The `sessions` queue's own job and the reaper/vacuum cron-// fragments are registered in jobs.registry.ts, not exported.+// session-end job, reaper and vacuum (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 here. `packages/db`'s re-export shims for both+// files are gone (M9-CLEANUP-001). The `sessions` queue's own job and the+// reaper/vacuum cron fragments are registered in jobs.registry.ts, not+// exported.export type {GetSessionListOptions,IClickhouseSession,@@ -867,10 +861,9 @@ export {SESSION_DISTINCT_FIELDS,transformSession,} from './modules/session/session.service';-// Dissolved from @openpanel/db's services/insights* + referrer-spikes.service-// (M5-001) — apps/worker's insight job files and packages/trpc's insight-// router call these directly, the same way V1 reaches every other dissolved-// service here.+// Dissolved from @openpanel/db's services/insights* + referrer-spikes.service —+// apps/worker's insight job files and packages/trpc's insight router call these+// directly, the same way V1 reaches every other dissolved service here.export type { SessionMetricsRedis } from './modules/session/src/session.metrics';export { registerSessionScrapeMetrics } from './modules/session/src/session.metrics';export type {@@ -886,12 +879,12 @@ export {export { reapIdleSessions } from './modules/session/src/session-reaper';export { vacuumStaleSessions } from './modules/session/src/session-vacuum';export { updateEventsCount } from './modules/session/src/usage';-// Moved from packages/db/src/services/share.service.ts, plus the-// query/mutation bodies packages/trpc/src/routers/share.ts held inline-// (M6-004, ADR-008's module map: share owns "C") — packages/trpc's share-// router calls these directly, the same way V1 reaches every other dissolved-// service here. packages/db keeps a re-export shim: auth.service.ts's-// signInToShare and packages/trpc's chart/overview routers still reach+// Moved from packages/db/src/services/share.service.ts, plus the query/mutation+// bodies packages/trpc/src/routers/share.ts held inline (ADR-008's module map:+// share owns "C") — packages/trpc's share router calls these directly, the same+// way V1 reaches every other dissolved service here. packages/db keeps a+// re-export shim: auth.service.ts's signInToShare and packages/trpc's+// chart/overview routers still reach// validateShareAccess/validateOverviewShareAccess through it.export {zShareDashboard,@@ -899,19 +892,18 @@ export {zShareReport,} from './modules/share/share.constants';export { createShareService } from './modules/share/share.service';-// Moved from packages/trpc/src/routers/subscription.ts, plus the Polar-// webhook business logic out of-// apps/api/src/controllers/webhook.controller.ts (M6-006, ADR-008's module-// map: subscription owns "S"+"C") — packages/trpc's subscription router and-// apps/api's webhook controller call these directly, the same way V1 reaches-// every other dissolved service here.+// Moved from packages/trpc/src/routers/subscription.ts, plus the Polar webhook+// business logic out of apps/api/src/controllers/webhook.controller.ts+// (ADR-008's module map: subscription owns "S"+"C") — packages/trpc's+// subscription router and apps/api's webhook controller call these directly,+// the same way V1 reaches every other dissolved service here.export {createSubscriptionService,getCurrentSubscriptionProduct,toSubscriptionDiscount,} from './modules/subscription/subscription.service';-// New module (M7-008) — apps/api's tools controller calls these directly,-// the same way V1 reaches every other dissolved service here.+// New module — apps/api's tools controller calls these directly, the same way+// V1 reaches every other dissolved service here.export type {IpLookupOutcome,IpLookupResult,@@ -922,10 +914,10 @@ export type {SiteCheckResult,} from './modules/tools/src/site-checker';export { runSiteCheck } from './modules/tools/src/site-checker';-// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —-// packages/trpc's auth/onboarding routers call `getUserById`/-// `getUserAccount` directly through @openpanel/db's re-export shim, the same-// way they reach every other dissolved service here.+// Dissolved from @openpanel/db's services/user.service.ts — packages/trpc's+// auth/onboarding routers call `getUserById`/ `getUserAccount` directly through+// @openpanel/db's re-export shim, the same way they reach every other dissolved+// service here.export { createUserService } from './modules/user/user.service';export type { ILogger } from './pino-logger';export {@@ -942,11 +934,10 @@ export {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`-// reached the same builder the same way, before all 28 routers moved into-// `modules/<name>/<name>.rpc.ts` (M11-001) and the package itself was-// deleted (M11-004).+// `<name>.rpc.ts` builds its router on: ONE tRPC instance, mounted by V2's+// `createTrpcFetchHandler`. V1's now-deleted `@openpanel/trpc` reached the same+// builder the same way, before all 28 routers moved into+// `modules/<name>/<name>.rpc.ts` and the package itself was deleted.export type {CacheMiddlewareDeps,EnforceRateLimit,@@ -1000,6 +991,6 @@ export {} from './shared/get-client-ip';export { getReferrerWithQuery, parseReferrer } from './shared/parse-referrer';export { generateDeviceId } from './shared/profileId';-// Below the transports since M15-007 (ADR-022 R22): `rpc/base.ts` needs the-// empty shape and may not deep-import a module to get it.+// Below the transports since M15-007: `rpc/base.ts` needs the empty shape and+// may not deep-import a module to get it.export { EMPTY_SESSION } from './shared/session';diff --git a/packages/core/src/jobs.registry.test.ts b/packages/core/src/jobs.registry.test.tsindex 720720284..61833861c 100644--- a/packages/core/src/jobs.registry.test.ts+++ b/packages/core/src/jobs.registry.test.ts@@ -93,9 +93,9 @@ test('every queue has a compat hook — the cutover has no drain step', () => {}});-// M5-001: the insight module's job — the BullMQ job *name* IS the registry-// key (defineQueue stamps it), and legacyCompat.insights already discriminates-// on this exact name (jobs/compat.ts), so this pins the two in agreement.+// The insight module's job — the BullMQ job *name* IS the registry key+// (defineQueue stamps it), and legacyCompat.insights already discriminates on+// this exact name (jobs/compat.ts), so this pins the two in agreement.test('the insights queue carries the insight module job', () => {expect(Object.keys(queues.insights.jobs)).toEqual(['insightsProject']);expect(queues.insights.jobs.insightsProject).toMatchObject({@@ -105,17 +105,17 @@ test('the insights queue carries the insight module job', () => {});// The insight module's cron fragment (insight.jobs.ts), spread into the ONE-// cron queue (ADR-005: "no cron module"). legacyCompat.cron maps a legacy-// job's `type` straight onto its name, so these three ids double as job names.-// `ping` (M7-008, misc.jobs.ts) is the twentieth and only conditional one —-// its scheduler is added by `startSchedulers` only when SELF_HOSTED &&-// production (jobs/schedulers.ts's `PING_SCHEDULE`), but the job HANDLER is-// always registered here so a scheduled run always has somewhere to land.-// `salt` (salt.jobs.ts) and the six `flush*` jobs (event/profile/session/+// cron queue (ADR-005: "no cron module"). legacyCompat.cron maps a legacy job's+// `type` straight onto its name, so these three ids double as job names. `ping`+// (misc.jobs.ts) is the twentieth and only conditional one — its scheduler is+// added by `startSchedulers` only when SELF_HOSTED && production+// (jobs/schedulers.ts's `PING_SCHEDULE`), but the job HANDLER is always+// registered here so a scheduled run always has somewhere to land. `salt`+// (salt.jobs.ts) and the six `flush*` jobs (event/profile/session/// group.jobs.ts) join the list at M8-004; `dataHealth` (misc.jobs.ts),-// `windDown` (organization.jobs.ts) and `flushExports` (integration.jobs.ts)-// at M9-003, which completes the set — all 20 V1 scheduler ids now have a-// handler here.+// `windDown` (organization.jobs.ts) and `flushExports` (integration.jobs.ts) at+// M9-003, which completes the set — all 20 V1 scheduler ids now have a handler+// here.test('the cron queue carries the insight module cron fragment', () => {expect(Object.keys(queues.cron.jobs).sort()).toEqual([@@ -148,7 +148,7 @@ test('the cron queue carries the insight module cron fragment', () => {}});-// M5-002: the gsc module's own queue job, plus its cron fan-out fragment.+// The gsc module's own queue job, plus its cron fan-out fragment.// legacyCompat.gsc already discriminates on these exact names (jobs/compat.ts),// so this pins the two in agreement.test('the gsc queue carries the gsc module jobs', () => {@@ -169,7 +169,7 @@ test('the cron queue carries the gsc module cron fragment', () => {});});-// M5-003: the cohort module's own queue job, plus its cron fan-out fragment.+// The cohort module's own queue job, plus its cron fan-out fragment.// legacyCompat.cohortCompute already discriminates on a bare `{cohortId}`// (jobs/compat.ts), so this pins the two in agreement.test('the cohortCompute queue carries the cohort module job', () => {@@ -187,7 +187,7 @@ test('the cron queue carries the cohort module cron fragment', () => {});});-// M6-001: the organization module's `delete` cron fragment (folded in from+// The organization module's `delete` cron fragment (folded in from// packages/db/src/services/delete.service.ts).test('the cron queue carries the organization module cron fragment', () => {expect(queues.cron.jobs.delete).toMatchObject({@@ -196,7 +196,7 @@ test('the cron queue carries the organization module cron fragment', () => {});});-// M6-003: the onboarding module's own cron fragment.+// The onboarding module's own cron fragment.test('the cron queue carries the onboarding module cron fragment', () => {expect(queues.cron.jobs.onboarding).toMatchObject({queue: 'cron',@@ -204,9 +204,9 @@ test('the cron queue carries the onboarding module cron fragment', () => {});});-// M7-001: the session module's own job (legacyCompat.sessions maps V1's-// `createSessionEnd` onto this exact name) and its reaper/vacuum cron-// fragment — the scheduler ids double as the job names.+// The session module's own job (legacyCompat.sessions maps V1's+// `createSessionEnd` onto this exact name) and its reaper/vacuum cron fragment+// — the scheduler ids double as the job names.test('the sessions queue carries the session module job', () => {expect(Object.keys(queues.sessions.jobs)).toEqual(['session']);expect(queues.sessions.jobs.session).toMatchObject({@@ -223,7 +223,7 @@ test('the cron queue carries the session module cron fragment', () => {}});-// M5-004: the import module's own job. No cron fragment — imports are always+// The import module's own job. No cron fragment — imports are always// user-triggered (import.rpc.ts's create/retry), unlike gsc/cohort/insight.// legacyCompat.import already discriminates on this exact name// (jobs/compat.ts), so this pins the two in agreement.@@ -235,8 +235,8 @@ test('the import queue carries the import module job', () => {});});-// M6-005: the notification module's own job. No cron fragment — notifications-// are always triggered by a rule match, never scheduled. legacyCompat.notification+// The notification module's own job. No cron fragment — notifications are+// always triggered by a rule match, never scheduled. legacyCompat.notification// already discriminates on this exact name (jobs/compat.ts), so this pins the// two in agreement.test('the notification queue carries the notification module job', () => {@@ -247,13 +247,13 @@ test('the notification queue carries the notification module job', () => {});});-// ADR-021 shrinks M9-001's bidirectional "every scheduler id has a handler,-// and vice versa" test to this single derivation-vs-golden comparison: the-// join between a cron job and its schedule is now enforced by the type-// system (`defineQueue`'s overload for the `cron` queue requires every job on-// it to declare `cron`, a schedule or explicit `null`), so the property that-// test policed can no longer drift — it is true by construction, not by a-// test walking both registries.+// Shrinks M9-001's bidirectional "every scheduler id has a handler, and vice+// versa" test to this single derivation-vs-golden comparison: the join between+// a cron job and its schedule is now enforced by the type system+// (`defineQueue`'s overload for the `cron` queue requires every job on it to+// declare `cron`, a schedule or explicit `null`), so the property that test+// policed can no longer drift — it is true by construction, not by a test+// walking both registries.test('the cron queue derives the golden 20 scheduler ids', () => {const derivedIds = [...schedulersFromRegistry(queues.cron).map((s) => s.id),diff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.tsindex ebf524e2a..f22a93805 100644--- a/packages/core/src/jobs.registry.ts+++ b/packages/core/src/jobs.registry.ts@@ -1,14 +1,14 @@// The seven BullMQ queues, statically composed. Adding a module's jobs is one// spread into the queue that owns them; there is no auto-discovery, because-// static composition is what keeps `QueueProducers` typed (ADR-007).+// static composition is what keeps `QueueProducers` typed.//-// Registry key === Redis name for all seven, `cohortCompute` included: ADR-005's-// acceptance note refuses the rename, so `COHORTCOMPUTE_CONCURRENCY` keeps-// working. `queueKey` decides what actually reaches Redis.+// Registry key === Redis name for all seven, `cohortCompute` included:+// ADR-005's acceptance note refuses the rename, so `COHORTCOMPUTE_CONCURRENCY`+// keeps working. `queueKey` decides what actually reaches Redis.//-// Retry and retention values are V1's, verbatim, defects included — five-// queues that never retry, four whose failed sets are unbounded. Changing them-// is a behaviour change and a separate decision (ADR-005 acceptance note).+// Retry and retention values are V1's, verbatim, defects included — five queues+// that never retry, four whose failed sets are unbounded. Changing them is a+// behaviour change and a separate decision (ADR-005 acceptance note).import { legacyCompat } from './jobs/compat';import type { Producers } from './jobs/define';@@ -66,8 +66,8 @@ const sessions = defineQueue('sessions', {});// One queue, one worker at concurrency 1, every scheduled job in the system.-// Pausing it from bull-board halts all buffer flushing — preserved-// deliberately (docs/ANSWERS.md §3: "known!").+// Pausing it from bull-board halts all buffer flushing — preserved deliberately+// (docs/ANSWERS.md §3: "known!").const cron = defineQueue('cron', {defaults: { removeOnComplete: 10 },worker: { concurrency: CONCURRENCY.cron },@@ -155,10 +155,10 @@ 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`.+// job and its schedule cannot drift apart. It is computed HERE, in the+// registry, and not in `jobs/schedulers.ts`: that file is transport+// infrastructure and may not import a registry. `ping` is the 20th and is+// conditional — see `PING_SCHEDULE` and `startSchedulers`.export const CRON_SCHEDULES: readonly SchedulerDefinition[] =schedulersFromRegistry(cron);diff --git a/packages/core/src/jobs/compat.test.ts b/packages/core/src/jobs/compat.test.tsindex a097d938c..14a1aa0b8 100644--- a/packages/core/src/jobs/compat.test.ts+++ b/packages/core/src/jobs/compat.test.ts@@ -4,9 +4,9 @@ import { resolveJob } from './compat';import { wrap } from './envelope';// One test per legacy shape, from ADR-005's table. The data is exactly what a-// V1 producer left in Redis; the assertion is the V2 (job name, payload) pair-// a worker must see. Fixtures are shape-only — nothing here validates a-// payload, and nothing in V1 did either.+// V1 producer left in Redis; the assertion is the V2 (job name, payload) pair a+// worker must see. Fixtures are shape-only — nothing here validates a payload,+// and nothing in V1 did either.describe('sessions', () => {const payload = {diff --git a/packages/core/src/jobs/compat.ts b/packages/core/src/jobs/compat.tsindex 4a7b80cc8..60c7b7734 100644--- a/packages/core/src/jobs/compat.ts+++ b/packages/core/src/jobs/compat.ts@@ -1,7 +1,7 @@// The whole of the P9 cutover. There is no dual-write window, no drain and no-// queue rename: a job enqueued by V1 is read back by V2 through these hooks-// (ADR-005). A wrong one is silent job loss, which is why the tests next to-// this file were written before it.+// queue rename: a job enqueued by V1 is read back by V2 through these hooks. A+// wrong one is silent job loss, which is why the tests next to this file were+// written before it.import type { CompatHook } from './define';import { isEnvelope, type JobMeta } from './envelope';@@ -17,8 +17,8 @@ const NO_META: JobMeta = {};/*** Envelope or legacy, one answer. Throws on anything neither path recognises:- * V1's cron `switch` had no `default` and completed an unknown type having- * done nothing, which is the failure mode this replaces (ADR-005 risk 2).+ * V1's cron `switch` had no `default` and completed an unknown type having done+ * nothing, which is the failure mode this replaces (ADR-005 risk 2).*/export function resolveJob(definition: { name: string; compat?: CompatHook },@@ -57,10 +57,9 @@ function discriminatedByType(types: readonly string[]): CompatHook {}/**- * One hook per queue, keyed by registry key. Each is deletable on its own —- * but not until no legacy-shaped job can still be replayed, and four queues- * have no `removeOnFail` at all, so their failed sets never lapse- * (ADR-005 risk 1).+ * One hook per queue, keyed by registry key. Each is deletable on its own — but+ * not until no legacy-shaped job can still be replayed, and four queues have no+ * `removeOnFail` at all, so their failed sets never lapse (ADR-005 risk 1).*/export const legacyCompat = {// Job name `'session'`, payload type `'createSessionEnd'` — the one queuediff --git a/packages/core/src/jobs/define.ts b/packages/core/src/jobs/define.tsindex 8f152a82f..05e18c821 100644--- a/packages/core/src/jobs/define.ts+++ b/packages/core/src/jobs/define.ts@@ -82,11 +82,11 @@ export interface JobDefinition<TPayload extends z.ZodType> {/** Defaults for this job alone, over the queue's. */options?: EnqueueOptions;/**- * ADR-021: a property of the job, not a parallel registry. Only meaningful- * on the `cron` queue, where `defineQueue`'s overload for that name makes- * this field required — `null` for a job the scheduler never enqueues- * (e.g. `ping`, gated elsewhere), a schedule otherwise. Leaving it absent- * is a type error there, on purpose (the three-state rule).+ * A property of the job, not a parallel registry. Only meaningful on the+ * `cron` queue, where `defineQueue`'s overload for that name makes this field+ * required — `null` for a job the scheduler never enqueues (e.g. `ping`,+ * gated elsewhere), a schedule otherwise. Leaving it absent is a type error+ * there, on purpose (the three-state rule).*/cron?: RepeatSchedule | null;}@@ -162,7 +162,7 @@ export type Producers<TQueues extends QueueMap> = {* `JobDefinition`'s optional field — that is what lets a caller's omission of* `cron` stay a genuinely absent property (rather than an optional one that* happens to be `undefined`), which `defineQueue`'s `cron`-queue overload- * relies on to reject it at the type level (ADR-021).+ * relies on to reject it at the type level.*/export function defineJob<TPayload extends z.ZodType,diff --git a/packages/core/src/jobs/jobs.metrics.test.ts b/packages/core/src/jobs/jobs.metrics.test.tsindex cc0d4f06e..7806c13fe 100644--- a/packages/core/src/jobs/jobs.metrics.test.ts+++ b/packages/core/src/jobs/jobs.metrics.test.ts@@ -31,8 +31,8 @@ test('five gauges per queue, named from the Redis key exactly as V1 named them',for (const suffix of COUNT_SUFFIXES) {expect(names).toContain(`sessions_${suffix}_count`);expect(names).toContain(`cron_${suffix}_count`);- // ADR-005 acceptance note: the registry key stays `cohortCompute`, so the- // series name does too.+ // Acceptance note: the registry key stays `cohortCompute`, so the series+ // name does too.expect(names).toContain(`cohortCompute_${suffix}_count`);}});diff --git a/packages/core/src/jobs/jobs.metrics.ts b/packages/core/src/jobs/jobs.metrics.tsindex 33906191e..4ce1d2f90 100644--- a/packages/core/src/jobs/jobs.metrics.ts+++ b/packages/core/src/jobs/jobs.metrics.ts@@ -1,21 +1,20 @@-// The queue-side collectors, moved from apps/worker/src/metrics.ts onto the-// one core registry (TARGET_ARCHITECTURE §18). Names, labels and buckets are-// V1's; the worker-side copies died with apps/worker (M9-003).+// The queue-side collectors, moved from apps/worker/src/metrics.ts onto the one+// core registry (TARGET_ARCHITECTURE §18). Names, labels and buckets are V1's;+// the worker-side copies died with apps/worker.//// Three deliberate differences from V1, all listed in// `packages/core/docs/OPS_GRAFANA_MIGRATION.md`://-// 1. V1 registered the five `<queue>_*_count` gauges for TWO queues-// (`sessionsQueue`, `cronQueue`). V2 registers them for all seven, which-// ADR-018's continuity register asks for ("kept for the 7 BullMQ-// queues"). Ten new series appear; none of the existing ten changes.-// 2. They register only where the role consumes (main.ts), because each-// gauge is one Redis round trip per scrape and ten api replicas exposing-// them would multiply that for no new information.-// 3. A gauge whose Redis read throws is skipped rather than failing the whole-// scrape. V1 let it reject `registry.metrics()`, which turns one Redis-// blip into a 500 on /metrics and a gap in every panel; core's buffer-// gauges already swallow the same way (buffers/buffer.metrics.ts).+// 1. V1 registered the five `<queue>_*_count` gauges for TWO queues+// (`sessionsQueue`, `cronQueue`). V2 registers them for all seven, which+// ADR-018's continuity register asks for ("kept for the 7 BullMQ queues"). Ten+// new series appear; none of the existing ten changes. 2. They register only+// where the role consumes (main.ts), because each gauge is one Redis round trip+// per scrape and ten api replicas exposing them would multiply that for no new+// information. 3. A gauge whose Redis read throws is skipped rather than+// failing the whole scrape. V1 let it reject `registry.metrics`, which turns+// one Redis blip into a 500 on /metrics and a gap in every panel; core's buffer+// gauges already swallow the same way (buffers/buffer.metrics.ts).import type { Queue as BullQueue } from 'bullmq';import client from 'prom-client';@@ -41,10 +40,10 @@ function metricPrefix(queueName: string): string {/*** FAILURE-ONLY, deliberately. V1 observed this exclusively in the workers'- * `failed` listener (apps/worker/src/boot-workers.ts), so every percentile- * ever computed from it is a percentile of failures. Success timings, if- * wanted, get a NEW series name — emitting them here silently rewrites every- * existing panel (ADR-018 risk 7).+ * `failed` listener (apps/worker/src/boot-workers.ts), so every percentile ever+ * computed from it is a percentile of failures. Success timings, if wanted, get+ * a NEW series name — emitting them here silently rewrites every existing panel+ * (ADR-018 risk 7).*/export const jobDurationMs = new client.Histogram({name: 'job_duration_ms',diff --git a/packages/core/src/jobs/naming.test.ts b/packages/core/src/jobs/naming.test.tsindex 59eae683b..d95a2476e 100644--- a/packages/core/src/jobs/naming.test.ts+++ b/packages/core/src/jobs/naming.test.ts@@ -2,11 +2,10 @@ import { expect, test } from 'bun:test';import { queues } from '../jobs.registry';import { queueKey } from './naming';-// Byte-identity snapshot, mirroring-// `verification/golden/queue-keys/keys.json` — which the controller's-// `check.sh` independently recomputes from V1's `getQueueName`. Both sides pin-// the same 14 strings; a one-character drift orphans every queue in Redis-// (ADR-005 risk 4).+// Byte-identity snapshot, mirroring `verification/golden/queue-keys/keys.json`+// — which the controller's `check.sh` independently recomputes from V1's+// `getQueueName`. Both sides pin the same 14 strings; a one-character drift+// orphans every queue in Redis (ADR-005 risk 4).const GOLDEN_KEYS = [{ name: 'cohortCompute', queueCluster: false, key: 'cohortCompute' },{ name: 'cohortCompute', queueCluster: true, key: '{cohortCompute}' },diff --git a/packages/core/src/jobs/naming.ts b/packages/core/src/jobs/naming.tsindex 9896f2e45..dc896ae34 100644--- a/packages/core/src/jobs/naming.ts+++ b/packages/core/src/jobs/naming.ts@@ -14,8 +14,8 @@ export interface QueueKeyOptions {* The Redis key a queue lives under.** Braces only under `QUEUE_CLUSTER`, because V1's `getQueueName` did and every- * existing queue in every deployment is named that way (ADR-005). `-` joins- * the namespace because BullMQ rejects a `:` in a queue name.+ * existing queue in every deployment is named that way. `-` joins the namespace+ * because BullMQ rejects a `:` in a queue name.*/export function queueKey(name: string, options?: QueueKeyOptions): string {const scoped = options?.namespace ? `${name}-${options.namespace}` : name;diff --git a/packages/core/src/jobs/schedulers.test.ts b/packages/core/src/jobs/schedulers.test.tsindex 420c3eb37..c76e50694 100644--- a/packages/core/src/jobs/schedulers.test.ts+++ b/packages/core/src/jobs/schedulers.test.ts@@ -8,11 +8,11 @@ import {} from './schedulers';// Byte-identity snapshot, mirroring-// `verification/golden/queue-keys/scheduler-ids.json` — which the-// controller's `check.sh` independently recomputes from V1's-// `packages/queue/src/queues.ts` (CronQueuePayload union) and-// `apps/worker/src/boot-cron.ts`. Both sides pin the same 20 ids, including-// the three ADR-005 fixed omissions (ADR-005 acceptance note).+// `verification/golden/queue-keys/scheduler-ids.json` — which the controller's+// `check.sh` independently recomputes from V1's `packages/queue/src/queues.ts`+// (CronQueuePayload union) and `apps/worker/src/boot-cron.ts`. Both sides pin+// the same 20 ids, including the three ADR-005 fixed omissions (ADR-005+// acceptance note).const GOLDEN_SCHEDULER_IDS = ['cohortRefresh','dataHealth',diff --git a/packages/core/src/jobs/schedulers.ts b/packages/core/src/jobs/schedulers.tsindex 42170d5e2..44f467493 100644--- a/packages/core/src/jobs/schedulers.ts+++ b/packages/core/src/jobs/schedulers.ts@@ -1,14 +1,13 @@-// Ports apps/worker/src/boot-cron.ts onto BullMQ's job-scheduler API-// (ADR-005). Upsert is keyed on job name — the V1 scheduler id — which is-// what makes it idempotent across replicas: two processes upserting the same-// id with the same repeat options at boot converge on one scheduler, with no-// locking of our own needed.+// Ports apps/worker/src/boot-cron.ts onto BullMQ's job-scheduler API. Upsert is+// keyed on job name — the V1 scheduler id — which is what makes it idempotent+// across replicas: two processes upserting the same id with the same repeat+// options at boot converge on one scheduler, with no locking of our own needed.//-// 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. `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).+// 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. `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.import type { Logger } from '../logger';import type { AnyJob, QueueDefinition, RepeatSchedule } from './define';@@ -57,13 +56,13 @@ const CONFLICT_JOB_STATES = [const CONFLICT_ERROR_SUBSTRING = 'job ID already exists';/**- * Derives the scheduler list from the `cron` queue's own jobs (ADR-021) — the- * join is by construction now, not by a second registry kept in sync by a- * test. A job's `cron` is `RepeatSchedule` (always-on), `null` (on-demand —- * e.g. `ping`, scheduled conditionally elsewhere), or, on the `cron` queue,- * never simply absent: `defineQueue`'s overload for that queue name makes- * omitting it a type error. This throw is the defensive fallback for the one- * hole the type system can't close — a value forced through with `as any`.+ * Derives the scheduler list from the `cron` queue's own jobs — the join is by+ * construction now, not by a second registry kept in sync by a test. A job's+ * `cron` is `RepeatSchedule` (always-on), `null` (on-demand — e.g. `ping`,+ * scheduled conditionally elsewhere), or, on the `cron` queue, never simply+ * absent: `defineQueue`'s overload for that queue name makes omitting it a type+ * error. This throw is the defensive fallback for the one hole the type system+ * can't close — a value forced through with `as any`.*/export function schedulersFromRegistry(cronQueue: QueueDefinition<Record<string, AnyJob>>@@ -195,8 +194,8 @@ function upsert(): Promise<unknown> {// Envelope-shaped for every scheduler-created job — these are freshly// enqueued, never a replay of a V1-shaped job, so there is nothing for the- // `cron` compat hook to do here (ADR-005: new data only, old shape read- // back through `resolveJob`).+ // `cron` compat hook to do here (ADR-005: new data only, old shape read back+ // through `resolveJob`).return queue.upsertJobScheduler(scheduler.id, scheduler.schedule, {data: wrap(null, {}),});diff --git a/packages/core/src/jobs/workers.test.ts b/packages/core/src/jobs/workers.test.tsindex 5875660ca..d6af36337 100644--- a/packages/core/src/jobs/workers.test.ts+++ b/packages/core/src/jobs/workers.test.ts@@ -92,7 +92,7 @@ test('a legacy job reaches the same handler through the compat hook', async () =expect(seen).toHaveLength(1);expect(seen[0]?.payload).toEqual({ importId: 'imp_1' });// No request caused it, so one is minted rather than left absent — a job's- // own logs and its follow-up enqueues still correlate (ADR-018 R2).+ // own logs and its follow-up enqueues still correlate.expect(seen[0]?.ctx.requestId).toMatch(/^[\w-]{21}$/);});diff --git a/packages/core/src/jobs/workers.ts b/packages/core/src/jobs/workers.tsindex 10bbb13c6..e0fb71b24 100644--- a/packages/core/src/jobs/workers.ts+++ b/packages/core/src/jobs/workers.ts@@ -164,8 +164,8 @@ export async function runJob(const payload = jobDefinition.payload.parse(resolved.payload);const attempt = job.attemptsMade + 1;- // A scheduled or legacy job has no originating request; minting one keeps- // its own logs and its follow-up enqueues correlated (ADR-018 R2).+ // A scheduled or legacy job has no originating request; minting one keeps its+ // own logs and its follow-up enqueues correlated.const requestId =resolved.meta.requestId ?? generateId(undefined, REQUEST_ID_LENGTH);diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.tsindex 1df55465b..303922107 100644--- a/packages/core/src/logger.ts+++ b/packages/core/src/logger.ts@@ -1,7 +1,7 @@-// Structural interface only. pino satisfies this shape once it is-// instantiated in apps/api (ADR-007 layout: "pino instantiated later in-// apps/api") — nothing here imports pino, so shared/ and modules/ can depend-// on the shape of a logger without pulling the implementation into core.+// Structural interface only. pino satisfies this shape once it is instantiated+// in apps/api (ADR-007 layout: "pino instantiated later in apps/api") — nothing+// here imports pino, so shared/ and modules/ can depend on the shape of a+// logger without pulling the implementation into core.export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';@@ -20,13 +20,13 @@ export interface Logger {child(bindings: Record<string, unknown>): Logger;}-// ADR-018 R1: one identifier, one name, one constant — the field is-// `requestId` everywhere (JobMeta.requestId, every log line, Ctx), replacing-// V1's `reqId`. Exported here to kill the four-file literal coupling.+// One identifier, one name, one constant — the field is `requestId` everywhere+// (JobMeta.requestId, every log line, Ctx), replacing V1's `reqId`. Exported+// here to kill the four-file literal coupling.export const REQUEST_ID_LOG_FIELD = 'requestId' as const;-// 126 bits of nanoid (ADR-018 R2). A correlation id, not a secret, and the-// hot path pays for it 5000x/s — hence `nanoid/non-secure` behind generateId.+// 126 bits of nanoid. A correlation id, not a secret, and the hot path pays for+// it 5000x/s — hence `nanoid/non-secure` behind generateId.export const REQUEST_ID_LENGTH = 21;// The wire header stays `request-id` byte-for-byte — it is caller-visiblediff --git a/packages/core/src/metrics.ts b/packages/core/src/metrics.tsindex e469991a3..f15f36a14 100644--- a/packages/core/src/metrics.ts+++ b/packages/core/src/metrics.ts@@ -1,11 +1,11 @@-// The one prom-client registry for the whole process (this package's-// AGENTS.md layout; TARGET_ARCHITECTURE §18: "One `prom-client` registry-// built by `core/src/metrics.ts`, served at `/metrics` from the ops scope in-// every role"). `apps/api/src/metrics.ts` and `apps/worker/src/metrics.ts`-// are V1-side registries that die with the apps they live in (ADR-007-// package fates: `worker` dies, `api` becomes a shell over this package) —-// core neither reads nor extends either one. Every collector a core module-// registers from here on registers on THIS registry, and only this one.+// The one prom-client registry for the whole process (this package's AGENTS.md+// layout; TARGET_ARCHITECTURE §18: "One `prom-client` registry built by+// `core/src/metrics.ts`, served at `/metrics` from the ops scope in every+// role"). `apps/api/src/metrics.ts` and `apps/worker/src/metrics.ts` are+// V1-side registries that die with the apps they live in (ADR-007 package+// fates: `worker` dies, `api` becomes a shell over this package) — core neither+// reads nor extends either one. Every collector a core module registers from+// here on registers on THIS registry, and only this one.import client from 'prom-client';diff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.tsindex 02e07d867..45cd1096c 100644--- a/packages/core/src/modules/assistant/assistant.constants.ts+++ b/packages/core/src/modules/assistant/assistant.constants.ts@@ -1,8 +1,8 @@import { z } from 'zod';/**- * Moved from the V1 validation package (M5-005, ADR-008's module map:- * assistant owns "C"). apps/start reaches these symbols through the+ * Moved from the V1 validation package (ADR-008's module map: assistant owns+ * "C"). apps/start reaches these symbols through the* `@openpanel/core/modules/assistant/assistant.constants` subpath —* `src/agents/models.ts`, `src/contexts/page-context.tsx` and* `src/components/chat/tool-handlers.ts`.@@ -10,10 +10,10 @@ import { z } from 'zod';* Isomorphic by the AGENTS.md rule: zod and nothing else.** The full `ChatApp` type (Better Agent's inferred app type) lives in- * `./src/app.ts` — it's `ReturnType<typeof createChatApp>` and inherently- * bound to the server-side agent definition, so it stays out of this- * constants file (a Prisma/Better-Agent type would follow it into a browser- * bundle). The frontend type-imports it from the core barrel instead+ * `./src/app.ts` — it's `ReturnType<typeof createChatApp>` and inherently bound+ * to the server-side agent definition, so it stays out of this constants file+ * (a Prisma/Better-Agent type would follow it into a browser bundle). The+ * frontend type-imports it from the core barrel instead* (`apps/start/src/agents/client.ts`); see that file for why.*/diff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.tsindex 2a35472cb..2fb6a2fa8 100644--- a/packages/core/src/modules/assistant/assistant.routes.ts+++ b/packages/core/src/modules/assistant/assistant.routes.ts@@ -1,21 +1,21 @@-// Better Agent chat, mounted under `/ai/agents/*` (M5-005) inside-// `dashboardRoutes` (rest.routes.ts), which `apps/api/src/main.ts` mounts.+// Better Agent chat, mounted under `/ai/agents/*` inside `dashboardRoutes`+// (rest.routes.ts), which `apps/api/src/main.ts` mounts.//-// Elysia has no adapter in `@better-agent/adapters` (only express/fastify),-// but `BetterAgentApp.handler` already speaks the Web `Request`/`Response`-// pair Elysia's own handlers do, so this route calls it directly instead of-// waiting on one. `parse: 'none'` is load-bearing, as on the /trpc mount in+// Elysia has no adapter in `@better-agent/adapters` (only express/fastify), but+// `BetterAgentApp.handler` already speaks the Web `Request`/`Response` pair+// Elysia's own handlers do, so this route calls it directly instead of waiting+// on one. `parse: 'none'` is load-bearing, as on the /trpc mount in// apps/api/src/main.ts: the global request-logging hook references `body`,-// which makes Elysia infer body parsing for every route and consume the-// stream before the handler runs; `request.clone()` then throws "Body is-// disturbed or locked". With parsing off, the body is read via-// `request.clone()` for the project-access check below and `chatApp.handler`-// gets the original, unconsumed `request` so it can re-read it itself.+// which makes Elysia infer body parsing for every route and consume the stream+// before the handler runs; `request.clone` then throws "Body is disturbed or+// locked". With parsing off, the body is read via `request.clone` for the+// project-access check below and `chatApp.handler` gets the original,+// unconsumed `request` so it can re-read it itself.//-// M15-003: this route is where `deps` lives, so everything below it reaches-// Postgres/ClickHouse through `ctx` — the chat app, the conversation lookup-// and the access check included. That is what removed the four lazy loaders-// this file used to open with (ADR-022 R6).+// This route is where `deps` lives, so everything below it reaches+// Postgres/ClickHouse through `ctx` — the chat app, the conversation lookup and+// the access check included. That is what removed the four lazy loaders this+// file used to open with.import { defineRoutes } from '../../http/define';import { getProjectAccess } from '../../shared/access-lookups';diff --git a/packages/core/src/modules/assistant/assistant.rpc.ts b/packages/core/src/modules/assistant/assistant.rpc.tsindex 95910aa21..78e423193 100644--- a/packages/core/src/modules/assistant/assistant.rpc.ts+++ b/packages/core/src/modules/assistant/assistant.rpc.ts@@ -1,9 +1,9 @@-// Ported from the V1 tRPC chat router (M5-005).+// Ported from the V1 tRPC chat router.//-// M11-001: every procedure is on its V1 twin's builder. `protectedProcedure`-// runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser,-// exactly as V1 does — `models` takes no input and needs no object-id check-// of its own, so the handler is the query and nothing else (ADR-022 R10).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does — `models` takes no input and needs no object-id check of its own, so+// the handler is the query and nothing else.import { createTRPCRouter, protectedProcedure } from '../../rpc/base';import {diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex a837a1496..e93ec73aa 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -1,20 +1,19 @@// Moved from V1's agents directory (the Better Agent chat app + its tools,-// prompt and Prisma persistence) and V1's tRPC filter-command agent (M5-005,-// ADR-007's module map: assistant owns "S"). The bulk of the logic lives-// under ./src — this file is the module's public entry point, the same shape-// as insight.service.ts drawing from insight/src/*.+// prompt and Prisma persistence) and V1's tRPC filter-command agent (ADR-007's+// module map: assistant owns "S"). The bulk of the logic lives under./src —+// this file is the module's public entry point, the same shape as+// insight.service.ts drawing from insight/src/*.//-// M15-003: every export takes `deps`. `./src/app.ts` and-// `./src/filter-command.ts` construct nothing at import time any more, so the-// three lazy loaders that used to stand between this file and them are gone-// (ADR-022 R6/R15) — a static import here builds no agent, opens no provider-// client and reaches no database.+// Every export takes `deps`. `./src/app.ts` and `./src/filter-command.ts`+// construct nothing at import time any more, so the three lazy loaders that+// used to stand between this file and them are gone (R15) — a static import+// here builds no agent, opens no provider client and reaches no database.//// The chat app is memoized PER `deps` object rather than per process: a Ctx// builds one `ServiceDeps` per unit of work (context.ts's// `installLazyServices`), so two calls inside one chat request share an app-// while two requests do not — the same trade `cacheable-per-deps.ts`-// records for the cross-module caches.+// while two requests do not — the same trade `cacheable-per-deps.ts` records+// for the cross-module caches.import type { ServiceDeps, Services } from '../../services';import type { PageContext } from './assistant.constants';diff --git a/packages/core/src/modules/assistant/src/app.ts b/packages/core/src/modules/assistant/src/app.tsindex 58111928b..aa02fe273 100644--- a/packages/core/src/modules/assistant/src/app.ts+++ b/packages/core/src/modules/assistant/src/app.ts@@ -1,12 +1,10 @@-// Moved from V1's agents/app.ts (M5-005, ADR-007's module map: assistant-// owns "S").+// Moved from V1's agents/app.ts (ADR-007's module map: assistant owns "S").//-// M15-003: the app is BUILT from the `deps` `assistant.routes.ts` already-// holds, not constructed at module scope (ADR-022 R6/R15). Importing this-// file now opens nothing — no provider client, no agent, no conversation-// store — and every tool handler closes over the same `deps`, which is what-// `@better-agent/core`'s context-free tool-handler signature ruled out doing-// as an argument.+// The app is BUILT from the `deps` `assistant.routes.ts` already holds, not+// constructed at module scope (R15). Importing this file now opens nothing — no+// provider client, no agent, no conversation store — and every tool handler+// closes over the same `deps`, which is what `@better-agent/core`'s+// context-free tool-handler signature ruled out doing as an argument.import { betterAgent, defineAgent } from '@better-agent/core';import type { ServiceDeps } from '../../../services';import { type ChatAgentContext, chatContextSchema } from './context';diff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.tsindex 9bf3ecfac..3ab89e2c9 100644--- a/packages/core/src/modules/assistant/src/filter-command.ts+++ b/packages/core/src/modules/assistant/src/filter-command.ts@@ -1,11 +1,11 @@-// Moved from V1's tRPC filter-command agent (M5-005). The one caller is+// Moved from V1's tRPC filter-command agent. The one caller is// `overview.rpc.ts`'s `runFilterCommand` procedure, which reaches it through// `ctx.services.assistant`.//-// M15-003: the agent app and its five tools are BUILT from the `deps` that-// procedure already holds (ADR-022 R6/R15) — importing this file constructs-// nothing, and the tool handlers close over `deps` because-// `@better-agent/core`'s tool-handler signature has no slot for them.+// The agent app and its five tools are BUILT from the `deps` that procedure+// already holds (R15) — importing this file constructs nothing, and the tool+// handlers close over `deps` because `@better-agent/core`'s tool-handler+// signature has no slot for them.import {type AgentToolDefinition,betterAgent,diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.tsindex d202aaa76..d1d1bece9 100644--- a/packages/core/src/modules/assistant/src/persistence.ts+++ b/packages/core/src/modules/assistant/src/persistence.ts@@ -6,7 +6,7 @@ import { chatRunContext } from './run-context';// `ConversationStore`'s `load`/`save` signatures are @better-agent/core's own// interface — betterAgent calls them with no `Ctx`/`ServiceDeps` to thread// through, so the store is BUILT from the deps the route already holds and-// closes over them (ADR-022 R6/R15).+// closes over them (R15)./*** Prisma-backed `ConversationStore` for Better Agent.diff --git a/packages/core/src/modules/assistant/src/providers.ts b/packages/core/src/modules/assistant/src/providers.tsindex cdf518488..cac647ce4 100644--- a/packages/core/src/modules/assistant/src/providers.ts+++ b/packages/core/src/modules/assistant/src/providers.ts@@ -1,13 +1,13 @@// Ported from @openpanel/ai (dissolved into core — M4-005). Moved out of// `clients/ai/` by M15-008: the assistant is its only consumer, so ADR-022 A2-// puts it in this module's `src/` — which is also what removes its upward-// edge onto `assistant.constants`.+// puts it in this module's `src/` — which is also what removes its upward edge+// onto `assistant.constants`.//// SERVER-ONLY. This module instantiates `@better-agent/providers` clients from// the credentials the config loader parsed (ADR-022 R9: config in). Never// value-import it from the browser (apps/start) — import the model-// catalog/types from-// `@openpanel/core/modules/assistant/assistant.constants` instead.+// catalog/types from `@openpanel/core/modules/assistant/assistant.constants`+// instead.import { createAnthropic } from '@better-agent/providers/anthropic';import { createOpenAI } from '@better-agent/providers/openai';import type { CoreConfig } from '../../../config';@@ -16,12 +16,12 @@ import type { ChatModelEntry } from '../assistant.constants';export type { ChatModelEntry } from '../assistant.constants';export { CHAT_MODELS as ALLOWED_MODELS } from '../assistant.constants';-// A provider client is memoized per `CoreConfig`, not per process (ADR-022-// R16: what a thing owns dies with its owner, and nothing outlives the thing-// that opened it). `loadConfig` runs once per boot, so a running API still-// builds each client exactly once; a second config in the same process — a-// test, a second boot — gets a client carrying ITS credentials rather than the-// first config's, and both are collected with the config that produced them.+// A provider client is memoized per `CoreConfig`, not per process (ADR-022 R16:+// what a thing owns dies with its owner, and nothing outlives the thing that+// opened it). `loadConfig` runs once per boot, so a running API still builds+// each client exactly once; a second config in the same process — a test, a+// second boot — gets a client carrying ITS credentials rather than the first+// config's, and both are collected with the config that produced them.//// There is nothing here to close: `createOpenAI`/`createAnthropic` return a// closure over a base URL and a header set that calls the global `fetch`. Theydiff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.tsindex 07aef2b88..33097a962 100644--- a/packages/core/src/modules/assistant/src/report-runner.ts+++ b/packages/core/src/modules/assistant/src/report-runner.ts@@ -1,16 +1,15 @@-// Ported from V1's MCP `runReport` / `runReportFromConfig` (M5-005), now+// Ported from V1's MCP `runReport` / `runReportFromConfig`, now// `modules/mcp/src/tools/analytics/reports.ts`.//-// ADR-007 explicitly defers unifying MCP's tool definitions with assistant's,-// so `modules/mcp/src/tools/analytics/reports.ts` keeps its own copy of this+// Explicitly defers unifying MCP's tool definitions with assistant's, so+// `modules/mcp/src/tools/analytics/reports.ts` keeps its own copy of this// dispatch — reaching into another module's tool tree is not the fix.//// The result is a second copy of this dispatch logic, which is exactly the// "four independent wrapper layers over the same 34 *Core functions"-// TARGET_ARCHITECTURE already records as accepted technical debt — this-// becomes a third layer, not a new problem. Both copies call the same-// @openpanel/db primitives and must be kept in sync by hand until that debt-// is paid down.+// TARGET_ARCHITECTURE already records as accepted technical debt — this becomes+// a third layer, not a new problem. Both copies call the same @openpanel/db+// primitives and must be kept in sync by hand until that debt is paid down.import type { CoreConfig } from '../../../config';import type { ServiceDeps } from '../../../services';diff --git a/packages/core/src/modules/assistant/src/tools/index.ts b/packages/core/src/modules/assistant/src/tools/index.tsindex 47dd5b0cf..48e100842 100644--- a/packages/core/src/modules/assistant/src/tools/index.ts+++ b/packages/core/src/modules/assistant/src/tools/index.ts@@ -16,10 +16,10 @@ import * as ui from './ui';// A tool is BUILT per unit of work, from the `deps` the route already holds:// `@better-agent/core`'s tool-handler signature has no context parameter, so-// each handler closes over them instead (ADR-022 R6/R15). The lists are typed-// loosely as `(deps) => AgentToolDefinition` — without the cast, TypeScript-// tries to compute the union of every tool's schema + result type and hits-// its instantiation depth limit.+// each handler closes over them instead (R15). The lists are typed loosely as+// `(deps) => AgentToolDefinition` — without the cast, TypeScript tries to+// compute the union of every tool's schema + result type and hits its+// instantiation depth limit.type ToolFactory = (deps: ServiceDeps) => AgentToolDefinition;type ToolList = ToolFactory[];diff --git a/packages/core/src/modules/assistant/src/tools/references.ts b/packages/core/src/modules/assistant/src/tools/references.tsindex 11416aedc..9cf60d8e4 100644--- a/packages/core/src/modules/assistant/src/tools/references.ts+++ b/packages/core/src/modules/assistant/src/tools/references.ts@@ -46,19 +46,19 @@ export const listReferences = (deps: ServiceDeps) =>endDate: endDate ?? context.pageContext?.filters?.endDate,});- // KNOWN DEFECT, deliberately left (M15-101): these two bounds do not- // agree, and neither is safe for every shape `resolveDateRange` returns.- // It yields `YYYY-MM-DD` from explicit dates and from its 30-day- // default, but `YYYY-MM-DD HH:mm:ss` in the PROJECT's timezone when the- // page carries a range preset (`chart-dates.ts` `getDatesFromRange`).- // On that second shape the `lte` concatenation builds- // "2026-09-10 23:59:59T23:59:59.999Z", which is an Invalid Date, and the- // `gte` is parsed as LOCAL time rather than UTC. Do NOT "align" the two- // by appending `T00:00:00.000Z` to the `gte` — that reads as equivalent- // only if `range.startDate` were always date-only, and it is not.- // Repairing it changes which rows the preset path returns, and picking- // the right window means settling which clock `Reference.date` is stored- // in — `modules/reference`'s `getChartReferences` owns that answer.+ // KNOWN DEFECT, deliberately left: these two bounds do not agree, and+ // neither is safe for every shape `resolveDateRange` returns. It yields+ // `YYYY-MM-DD` from explicit dates and from its 30-day default, but+ // `YYYY-MM-DD HH:mm:ss` in the PROJECT's timezone when the page carries a+ // range preset (`chart-dates.ts` `getDatesFromRange`). On that second+ // shape the `lte` concatenation builds "2026-09-10+ // 23:59:59T23:59:59.999Z", which is an Invalid Date, and the `gte` is+ // parsed as LOCAL time rather than UTC. Do NOT "align" the two by+ // appending `T00:00:00.000Z` to the `gte` — that reads as equivalent only+ // if `range.startDate` were always date-only, and it is not. Repairing it+ // changes which rows the preset path returns, and picking the right+ // window means settling which clock `Reference.date` is stored in —+ // `modules/reference`'s `getChartReferences` owns that answer.const db = deps.db;const rows = await db.reference.findMany({where: {diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.tsindex e2e7ecd65..a10e24338 100644--- a/packages/core/src/modules/auth/auth.constants.ts+++ b/packages/core/src/modules/auth/auth.constants.ts@@ -1,9 +1,9 @@-// Moved from packages/validation/src/index.ts (M6-003, ADR-008's module map:-// auth owns "C"). packages/validation/src/index.ts becomes a re-export shim-// for these symbols (same shape as packages/validation/src/cohort.validation.ts-// since M5-003), so apps/start and packages/trpc keep resolving them through-// packages/validation's existing barrel unchanged. `zProvider` is new here —-// it validated `signInOAuth`'s input inline in packages/trpc/src/routers/auth.ts+// Moved from packages/validation/src/index.ts (ADR-008's module map: auth owns+// "C"). packages/validation/src/index.ts becomes a re-export shim for these+// symbols (same shape as packages/validation/src/cohort.validation.ts since+// M5-003), so apps/start and packages/trpc keep resolving them through+// packages/validation's existing barrel unchanged. `zProvider` is new here — it+// validated `signInOAuth`'s input inline in packages/trpc/src/routers/auth.ts// and was never exported, but it is vocabulary the same way the rest of this// file is.//diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.tsindex 3783ee5ae..20e827b68 100644--- a/packages/core/src/modules/auth/auth.routes.ts+++ b/packages/core/src/modules/auth/auth.routes.ts@@ -1,13 +1,12 @@-// The github/google OAuth callbacks (M6-003), same shape as gsc.routes.ts-// (M5-002): DELEGATE PATTERN, token-exchange/session logic lives in-// auth.service.ts's `completeOAuthCallback`. `main.ts` mounts-// `dashboardRoutes` unconditionally on every HTTP-serving boot, so this route-// is live.+// The github/google OAuth callbacks, same shape as gsc.routes.ts: DELEGATE+// PATTERN, token-exchange/session logic lives in auth.service.ts's+// `completeOAuthCallback`. `main.ts` mounts `dashboardRoutes` unconditionally+// on every HTTP-serving boot, so this route is live.//-// NAMED GAP: per-route cookie signing is not wired yet (gsc.routes.ts's-// header names the same gap), so `ctx.cookies.get()` here reads the raw,-// unsigned cookie value. V1's Fastify controller does not sign these cookies-// either (only the GSC flow does), so this is not a parity regression.+// NAMED GAP: per-route cookie signing is not wired yet (gsc.routes.ts's header+// names the same gap), so `ctx.cookies.get` here reads the raw, unsigned cookie+// value. V1's Fastify controller does not sign these cookies either (only the+// GSC flow does), so this is not a parity regression.import { redirect } from 'elysia';import { z } from 'zod';diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.tsindex f946fe8f0..2b2f1c8e3 100644--- a/packages/core/src/modules/auth/auth.rpc.ts+++ b/packages/core/src/modules/auth/auth.rpc.ts@@ -1,19 +1,18 @@-// Ported from packages/trpc/src/routers/auth.ts (M6-003).+// Ported from packages/trpc/src/routers/auth.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// V1's `rateLimitMiddleware` wrappers are mounted below through-// `createRateLimitMiddleware` (rpc/base.ts) with V1's own limits, procedure-// for procedure. Blocks are keyed per procedure and per trusted IP, and-// escalate on repeat offence — see rpc/rate-limit.ts.+// `createRateLimitMiddleware` (rpc/base.ts) with V1's own limits, procedure for+// procedure. Blocks are keyed per procedure and per trusted IP, and escalate on+// repeat offence — see rpc/rate-limit.ts.//-// This module has no queue/cron of its own, so there is no-// `ctx.services.auth` entry here — same shape as `user`/`project`.+// This module has no queue/cron of its own, so there is no `ctx.services.auth`+// entry here — same shape as `user`/`project`.import { z } from 'zod';import {diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.tsindex 207ea2dbf..d98c1ef1f 100644--- a/packages/core/src/modules/auth/auth.service.access.test.ts+++ b/packages/core/src/modules/auth/auth.service.access.test.ts@@ -1,10 +1,9 @@-// M10-002 (docs/TECH_DEBT.md §5b): auth.service.ts is now the ONLY place-// the ladder is bound to real lookups, via the lazy,-// memoized `getAccessChecks()`. This proves that seam still takes a fake-// `AccessLookups` cleanly — mocking `../../shared/access-lookups`, which-// auth.service.ts reaches only through a dynamic import and which owns all-// four lookups since M15-005 — and that ADR-011's fail-closed ordering,-// messages and write-level gate are unchanged.+// Auth.service.ts is now the ONLY place the ladder is bound to real lookups,+// via the lazy, memoized `getAccessChecks`. This proves that seam still takes a+// fake `AccessLookups` cleanly — mocking `../../shared/access-lookups`, which+// auth.service.ts reaches only through a dynamic import and which owns all four+// lookups since M15-005 — and that ADR-011's fail-closed ordering, messages and+// write-level gate are unchanged.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -58,8 +57,8 @@ afterAll(() => {function authService() {// 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.+ // composition root stays a flat list. Every member reaches the mocked lookups+ // above.return createAuthService({} as import('../../services').ServiceDeps,testServices()diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex d98e57e0a..620c7979c 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -1,18 +1,18 @@-// Moved from @openpanel/auth (M4-007): token issuance/hashing, argon2-// password hashing, TOTP, the OAuth clients and cookie helpers. The-// Prisma-touching half — creating, validating and invalidating a `sessions`-// row — moved here too (M8-005, `./src/login-session.ts`).+// Moved from @openpanel/auth: token issuance/hashing, argon2 password hashing,+// TOTP, the OAuth clients and cookie helpers. The Prisma-touching half —+// creating, validating and invalidating a `sessions` row — moved here too+// (`./src/login-session.ts`).//-// 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.+// 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.//-// M10-004: every module in this wave, INCLUDING auth's own remaining lazy-// imports, moves to `ServiceDeps`. `signUpWithEmail`/`signInWithEmail`/TOTP/+// Every module in this wave, INCLUDING auth's own remaining lazy imports, moves+// to `ServiceDeps`. `signUpWithEmail`/`signInWithEmail`/TOTP/// password-reset/OAuth-callback all take `deps` now and reach Postgres as-// `deps.db`; `./src/login-session.ts` and `./src/registration.ts` do the-// same and are plain static imports here (neither cycles back to this file).+// `deps.db`; `./src/login-session.ts` and `./src/registration.ts` do the same+// and are plain static imports here (neither cycles back to this file).// `auth.rpc.ts` already carries a `Ctx` and passes it straight through.import { z } from 'zod';@@ -95,20 +95,19 @@ type ProjectAccessChecks = AccessChecks<IProjectAccess>;let accessChecksPromise: Promise<ProjectAccessChecks> | undefined;/**- * The single binding of the ladder to real lookups- * (M10-002, docs/TECH_DEBT.md §5b) — memoized: `createAccessChecks` runs- * exactly once per process, on however many requests, no matter how many of- * this function's callers invoke it. Nothing runs at module-import time or at- * `createAuthService` construction time; the binding is built on the first- * actual check. An earlier attempt bound it at module scope and hung- * `bun test` for 30 minutes.+ * The single binding of the ladder to real lookups — memoized:+ * `createAccessChecks` runs exactly once per process, on however many requests,+ * no matter how many of this function's callers invoke it. Nothing runs at+ * module-import time or at `createAuthService` construction time; the binding+ * is built on the first actual check. An earlier attempt bound it at module+ * scope and hung `bun test` for 30 minutes.*- * Still a `Promise` because the contract is awaited at every call site and- * was what each module's own access file used to resolve lazily.+ * Still a `Promise` because the contract is awaited at every call site and was+ * what each module's own access file used to resolve lazily.*- * `integration.service.ts` and `subscription.service.ts` import this- * directly instead of going through `ctx.services.auth`: both are called with- * a bare `userId` and no `ctx`. Operator-authorized (docs/TECH_DEBT.md §5b).+ * `integration.service.ts` and `subscription.service.ts` import this directly+ * instead of going through `ctx.services.auth`: both are called with a bare+ * `userId` and no `ctx`. Operator-authorized.*/export function getAccessChecks(): Promise<ProjectAccessChecks> {if (!accessChecksPromise) {@@ -137,15 +136,15 @@ export function resetAccessChecksForTests(): void {}/**- * The one login check in the tree (ADR-022 R10).+ * The one login check in the tree.** `protectedProcedure` already refuses an anonymous caller and hands the- * handler a `session.userId` that is a `string`, so a protected procedure- * needs nothing here. This is for the paths the builder cannot decide: the- * share-aware `chartProcedure` / `overviewProcedure`, which are public- * because a valid share link is an alternative to being signed in, and only- * demand a user when no share was presented. Until M15-007 it was copied,- * unexported, into 28 `*.rpc.ts` files.+ * handler a `session.userId` that is a `string`, so a protected procedure needs+ * nothing here. This is for the paths the builder cannot decide: the+ * share-aware `chartProcedure` / `overviewProcedure`, which are public because+ * a valid share link is an alternative to being signed in, and only demand a+ * user when no share was presented. Until M15-007 it was copied, unexported,+ * into 28 `*.rpc.ts` files.*/export function requireLogin(userId: string | null | undefined): string {if (!userId) {@@ -156,20 +155,20 @@ export function requireLogin(userId: string | null | undefined): string {/*** 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.+ * 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(deps: ServiceDeps,_services: () => Services) {- // One function per member, closing over `deps`, so the return statement- // below stays a plain index (ADR-022 R4) — nothing here is a `return { ... }`- // literal with logic inside it.+ // One function per member, closing over `deps`, so the return statement below+ // stays a plain index — nothing here is a `return {... }` literal with logic+ // inside it.async function requireProjectAccess(args: Parameters<ProjectAccessChecks['requireProjectAccess']>[0]): ReturnType<ProjectAccessChecks['requireProjectAccess']> {@@ -208,9 +207,9 @@ export function createAuthService(}/**- * The session cookie's other half. `http/session.ts` reaches it here- * rather than deep-importing `./src/login-session` (ADR-022 R22), which- * is also what keeps the demo-user branch inside one function.+ * The session cookie's other half. `http/session.ts` reaches it here rather+ * than deep-importing `./src/login-session`, which is also what keeps the+ * demo-user branch inside one function.*/function checkSessionToken(token: string | null | undefined@@ -272,27 +271,26 @@ export function createAuthService(};}-// ------------------------------------------------------------------------// The Prisma-touching half (M6-003): sign-up/sign-in, TOTP challenges,-// password reset, share unlock and the github/google OAuth callback. This-// is the logic packages/trpc/src/routers/auth.ts and-// apps/api/src/controllers/oauth-callback.controller.tsx held inline —-// neither ever had a `packages/db/src/services/*` home to move from, unlike-// every other M5/M6 module, so it is written directly here (DELEGATE-// PATTERN: both V1's trpc router and this package's own auth.rpc.ts call-// these same functions).+// ---------------------------------------------------------------------- The+// Prisma-touching half: sign-up/sign-in, TOTP challenges, password reset, share+// unlock and the github/google OAuth callback. This is the logic+// packages/trpc/src/routers/auth.ts and+// apps/api/src/controllers/oauth-callback.controller.tsx held inline — neither+// ever had a `packages/db/src/services/*` home to move from, unlike every other+// M5/M6 module, so it is written directly here (DELEGATE PATTERN: both V1's+// trpc router and this package's own auth.rpc.ts call these same functions).//// Session/registration access is `deps.db`, via static imports of-// `./src/login-session` and `./src/registration` (M10-004) — neither cycles-// back to this file, so there is nothing to keep lazy there. Share is the one-// real cycle (M6-004) — share.service.ts statically imports this file's own-// `hashPassword` — so `signInToShare` reaches it through the composition-// root's `services()` thunk instead of importing it at all.+// `./src/login-session` and `./src/registration` — neither cycles back to this+// file, so there is nothing to keep lazy there. Share is the one real cycle —+// share.service.ts statically imports this file's own `hashPassword` — so+// `signInToShare` reaches it through the composition root's `services` thunk+// instead of importing it at all.//// None of these functions take a `TrpcContext`/`Ctx` directly — they take a// `deps: ServiceDeps` plus exactly the other primitives they touch-// (`setCookie`, `cookies.get`, `logger`), so this file has no dependency on-// the rpc layer that calls it.+// (`setCookie`, `cookies.get`, `logger`), so this file has no dependency on the+// rpc layer that calls it.import { generateSecureId } from '@openpanel/shared';import { decrypt, encrypt } from '@openpanel/shared/server';@@ -877,8 +875,8 @@ export interface SignInShareInput {}/** Share's three lookups arrive through the composition root's thunk- * (ADR-022 R3), not a dynamic import: `share.service.ts` statically imports- * this file's `hashPassword`, so a static edge back would be a real cycle. */+ * Not a dynamic import: `share.service.ts` statically imports this file's+ * `hashPassword`, so a static edge back would be a real cycle. *//** A week, as V1's `maxAge` was. */const SHARE_ACCESS_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;diff --git a/packages/core/src/modules/auth/src/access.ts b/packages/core/src/modules/auth/src/access.tsindex 0e7301fd4..cf2038a5d 100644--- a/packages/core/src/modules/auth/src/access.ts+++ b/packages/core/src/modules/auth/src/access.ts@@ -1,7 +1,7 @@-// 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.+// The permission ladder. M15-009 (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@@ -12,9 +12,9 @@// database — `bun test` loads this package with no DATABASE_URL and no Prisma// client — and it is the same seam `createCacheMiddleware` and// `createRateLimitMiddleware` already use in rpc/base.ts. `auth.service.ts`'s-// `createAccessChecks` call binds it to the real services (M10-002); V1's-// now-deleted `@openpanel/trpc` used to bind it the same way; a test binds-// it to two functions.+// `createAccessChecks` call binds it to the real services; V1's now-deleted+// `@openpanel/trpc` used to bind it the same way; a test binds it to two+// functions.import { TRPCForbiddenError } from '../../../rpc/errors';diff --git a/packages/core/src/modules/auth/src/constants.ts b/packages/core/src/modules/auth/src/constants.tsindex c7510b399..f3617f2d2 100644--- a/packages/core/src/modules/auth/src/constants.ts+++ b/packages/core/src/modules/auth/src/constants.ts@@ -1,6 +1,6 @@// Deployment-derived: the session cookie's domain and `secure` flag come from// the dashboard's own URL, so they are computed from the config the boot path-// already holds rather than read at import (ADR-022 R7).+// already holds rather than read at import.import type { CoreConfig } from '../../../config';import type { CookieOptions } from '../../../shared/cookie';import { parseCookieDomain } from './cookie-domain';diff --git a/packages/core/src/modules/auth/src/login-session.ts b/packages/core/src/modules/auth/src/login-session.tsindex a7387e79b..75ad30113 100644--- a/packages/core/src/modules/auth/src/login-session.ts+++ b/packages/core/src/modules/auth/src/login-session.ts@@ -1,12 +1,10 @@-// Moved from packages/db/src/services/auth-session.service.ts (M8-005).-// Postgres-backed login sessions (a `sessions` row keyed by the hash of a-// browser's cookie). Not to be confused with session.service.ts's ClickHouse-// visitor sessions.+// Moved from packages/db/src/services/auth-session.service.ts. Postgres-backed+// login sessions (a `sessions` row keyed by the hash of a browser's cookie).+// Not to be confused with session.service.ts's ClickHouse visitor sessions.//-// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone. `http/session.ts`'s-// `resolveSession` already carried an (until-now-unused) `AppDeps` for-// exactly this.+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb` lazy loader is gone. `http/session.ts`'s `resolveSession` already+// carried an (until-now-unused) `AppDeps` for exactly this.import type { Session, User } from '@openpanel/db/src/prisma-client';import type { ServiceDeps } from '../../../services';diff --git a/packages/core/src/modules/auth/src/oauth.ts b/packages/core/src/modules/auth/src/oauth.tsindex e9e205035..fc51b33c4 100644--- a/packages/core/src/modules/auth/src/oauth.ts+++ b/packages/core/src/modules/auth/src/oauth.ts@@ -10,7 +10,7 @@ export * as Arctic from 'arctic';// Built per call, not at import: an arctic client is a credential holder with// no socket, so there is nothing to keep alive and nothing to construct at-// module scope (ADR-022 R15).+// module scope.export function githubClient(config: CoreConfig): GitHub {const { clientId, clientSecret, redirectUri } = config.auth.github;return new GitHub(clientId, clientSecret, redirectUri);diff --git a/packages/core/src/modules/auth/src/registration.ts b/packages/core/src/modules/auth/src/registration.tsindex 765fe1e75..651e197da 100644--- a/packages/core/src/modules/auth/src/registration.ts+++ b/packages/core/src/modules/auth/src/registration.ts@@ -1,4 +1,4 @@-// M10-004: reaches Postgres as `deps.db`; the `loadDb()` lazy loader is gone.+// Reaches Postgres as `deps.db`; the `loadDb` lazy loader is gone.import type { ServiceDeps } from '../../../services';diff --git a/packages/core/src/modules/chart/chart.constants.ts b/packages/core/src/modules/chart/chart.constants.tsindex 97271d9b2..732849c34 100644--- a/packages/core/src/modules/chart/chart.constants.ts+++ b/packages/core/src/modules/chart/chart.constants.ts@@ -1,7 +1,7 @@-// The chart module's isomorphic surface (ADR-022 R8): limits, zod schemas and-// the column allow-lists shared by more than one file here. Imports zod and-// sibling `*.constants.ts` only — anything needing `sql`, `deps` or a-// ClickHouse type belongs in a service or a `src/` file.+// The chart module's isomorphic surface: limits, zod schemas and the column+// allow-lists shared by more than one file here. Imports zod and sibling+// `*.constants.ts` only — anything needing `sql`, `deps` or a ClickHouse type+// belongs in a service or a `src/` file.import { z } from 'zod';import { zChartEvent } from '../report/report.constants';@@ -9,8 +9,8 @@ import { zChartEvent } from '../report/report.constants';/*** Window the REST retention routes (`/insights/:projectId/retention`,* `/engagement`) read when the caller names none; M31-003's default for the- * same fix, wider than engagement's 60-day churn bucket. Not applied to- * callers of the service that pass no dates: those still read all time.+ * same fix, wider than engagement's 60-day churn bucket. Not applied to callers+ * of the service that pass no dates: those still read all time.*/export const RETENTION_SERIES_DEFAULT_RANGE = '3m';diff --git a/packages/core/src/modules/chart/chart.rpc.ts b/packages/core/src/modules/chart/chart.rpc.tsindex b9468097f..93e05d295 100644--- a/packages/core/src/modules/chart/chart.rpc.ts+++ b/packages/core/src/modules/chart/chart.rpc.ts@@ -1,8 +1,8 @@-// Ported from packages/trpc/src/routers/chart.ts (M7-003).+// Ported from packages/trpc/src/routers/chart.ts.//-// M11-001: the seven member-only procedures are back on `protectedProcedure`,-// so `enforceAccess` reads the top-level `projectId` before the input is-// parsed, exactly as V1 does.+// The seven member-only procedures are back on `protectedProcedure`, so+// `enforceAccess` reads the top-level `projectId` before the input is parsed,+// exactly as V1 does.//// `chartProcedure` (funnel, conversion, chart, aggregate, cohort) is V1's// share-aware builder: `publicProcedure` plus one middleware that admits andiff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex a551f652e..193e186e0 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -1,9 +1,9 @@// Every ClickHouse statement this module runs is a `sql` fragment from// src/sql.ts. Funnel, conversion, sankey and retention are dispatched to the-// sibling `*.service.ts` files.-// The one thing still value-imported from `@openpanel/db` under `./src/` is-// ADR-013's `sql` tag, which ADR-007 keeps in `packages/db` by name: a-// compile-time template tag, no client and no request scope.+// sibling `*.service.ts` files. The one thing still value-imported from+// `@openpanel/db` under `./src/` is ADR-013's `sql` tag, which ADR-007 keeps in+// `packages/db` by name: a compile-time template tag, no client and no request+// scope.import { getChartPrevStartEndDate } from '@openpanel/shared';import { flatten, map, pipe, prop, sort, uniq } from 'ramda';@@ -739,21 +739,21 @@ export async function getFunnelStepProfiles(// --- service -----------------------------------------------------------------// The funnel, conversion, sankey and retention services live in this module's-// own sibling files, not in modules of their own (ADR-007 gives one service-// per module), so they FOLD INTO `chart` rather than becoming four-// more `Services` members: chart.service.ts is already the dispatcher every-// caller goes through (`getFunnelChart` / `getConversionChart` /-// `getSankeyChart` / `getRetentionChart`), and a `Services` key per file-// would name four things that are not modules.+// own sibling files, not in modules of their own (ADR-007 gives one service per+// module), so they FOLD INTO `chart` rather than becoming four more `Services`+// members: chart.service.ts is already the dispatcher every caller goes through+// (`getFunnelChart` / `getConversionChart` / `getSankeyChart` /+// `getRetentionChart`), and a `Services` key per file would name four things+// that are not modules.export function createChartService(deps: ServiceDeps,services: () => Services) {- // 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.+ // The four chart sub-modules each expose their own `create*Service(deps)`.+ // `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, services);const conversion = createConversionService(deps, services);const sankey = createSankeyService(deps, services);diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.tsindex e26e2d9ca..4be02ceca 100644--- a/packages/core/src/modules/chart/conversion.service.ts+++ b/packages/core/src/modules/chart/conversion.service.ts@@ -253,7 +253,7 @@ function toSeries(}/** See funnel.service.ts's `createFunnelService` for why each chart- * sub-module carries its own factory (M10-009, ADR-007). */+ * Sub-module carries its own factory. */export function createConversionService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/chart/funnel.service.ts b/packages/core/src/modules/chart/funnel.service.tsindex 28ed1d8c0..3e97a60a1 100644--- a/packages/core/src/modules/chart/funnel.service.ts+++ b/packages/core/src/modules/chart/funnel.service.ts@@ -433,11 +433,10 @@ export async function getFunnelProfileIds(}/**- * `ctx.services.chart`'s funnel half, as its own module factory (ADR-007:- * "each service is `createXService(deps)`"). `createChartService` composes- * this rather than re-binding these functions itself, so the chart module- * keeps one registry key while every `*.service.ts` file exposes its own- * factory (M10-009).+ * `ctx.services.chart`'s funnel half, as its own module factory (ADR-007: "each+ * service is `createXService(deps)`"). `createChartService` composes this+ * rather than re-binding these functions itself, so the chart module keeps one+ * registry key while every `*.service.ts` file exposes its own factory.*/export function createFunnelService(deps: ServiceDeps,diff --git a/packages/core/src/modules/chart/retention.service.test.ts b/packages/core/src/modules/chart/retention.service.test.tsindex 778d9eaed..fce7194f4 100644--- a/packages/core/src/modules/chart/retention.service.test.ts+++ b/packages/core/src/modules/chart/retention.service.test.ts@@ -19,8 +19,8 @@ import {const PROJECT_ID = 'test-retention-cohort';-// M10-003: retention reaches ClickHouse as `deps.ch`, so the suite builds the-// same `ServiceDeps` main.ts does (pointed at `openpanel_test` by preload.ts).+// Retention reaches ClickHouse as `deps.ch`, so the suite builds the same+// `ServiceDeps` main.ts does (pointed at `openpanel_test` by preload.ts).let deps: ServiceDeps;const { day, week } = RETENTION_FIXTURE;/** RU1-RU5 and WU1-WU2, per the dataset table in retention-fixtures.ts. */diff --git a/packages/core/src/modules/chart/retention.service.ts b/packages/core/src/modules/chart/retention.service.tsindex a75b9ba2f..1c13d40d7 100644--- a/packages/core/src/modules/chart/retention.service.ts+++ b/packages/core/src/modules/chart/retention.service.ts@@ -388,7 +388,7 @@ export function processCohortData(}/** See funnel.service.ts's `createFunnelService` for why each chart- * sub-module carries its own factory (M10-009, ADR-007). */+ * Sub-module carries its own factory. */export function createRetentionService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/chart/sankey.service.ts b/packages/core/src/modules/chart/sankey.service.tsindex 28a8aafe1..8c78a7863 100644--- a/packages/core/src/modules/chart/sankey.service.ts+++ b/packages/core/src/modules/chart/sankey.service.ts@@ -535,7 +535,7 @@ export async function getUserFlowCore(}/** See funnel.service.ts's `createFunnelService` for why each chart- * sub-module carries its own factory (M10-009, ADR-007). */+ * Sub-module carries its own factory. */export function createSankeyService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/chart/src/compiled.ts b/packages/core/src/modules/chart/src/compiled.tsindex 49af85639..7df111f05 100644--- a/packages/core/src/modules/chart/src/compiled.ts+++ b/packages/core/src/modules/chart/src/compiled.ts@@ -90,11 +90,11 @@ function flatten(* `profile.properties[` followed by the key as a bound `String` param and a* closing `]`. Collapsing those three pieces is what keeps a narrowed* `profile.properties.<key>` ref pointing at the CTE's scalar column once the- * key stopped being part of the SQL text (M12-003).+ * key stopped being part of the SQL text.** A value can no longer be rewritten even in principle: only a param the- * resolver placed in that exact position is eligible, and it is replaced by- * an identifier rather than edited.+ * resolver placed in that exact position is eligible, and it is replaced by an+ * identifier rather than edited.*/export function fragmentWithProfileRefs(fragment: SqlFragment,diff --git a/packages/core/src/modules/chart/src/conversion.sql.ts b/packages/core/src/modules/chart/src/conversion.sql.tsindex 34a49b64b..df239ec73 100644--- a/packages/core/src/modules/chart/src/conversion.sql.ts+++ b/packages/core/src/modules/chart/src/conversion.sql.ts@@ -1,12 +1,13 @@-// The conversion statement as a pure `sql` fragment (ADR-013).+// The conversion statement as a pure `sql` fragment.//-// The field resolver and both filter compilers return fragments; their output — breakdown expressions, per-step filter clauses and-// the cohort joins — is interpolated directly. `compiledText` is left with the-// `b_<index>` aliases this file generates itself.+// The field resolver and both filter compilers return fragments; their output —+// breakdown expressions, per-step filter clauses and the cohort joins — is+// interpolated directly. `compiledText` is left with the `b_<index>` aliases+// this file generates itself.//-// Cluster note: `events`, `profiles` and `groups` are Distributed on Cloud.-// The profile / group / cohort joins are LEFT ANY JOIN and run under the-// client's `distributed_product_mode: 'allow'`; no `IN (subquery)` is involved.+// Cluster note: `events`, `profiles` and `groups` are Distributed on Cloud. The+// profile / group / cohort joins are LEFT ANY JOIN and run under the client's+// `distributed_product_mode: 'allow'`; no `IN (subquery)` is involved.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IInterval } from '../../report/report.constants';diff --git a/packages/core/src/modules/chart/src/field-resolution.test.ts b/packages/core/src/modules/chart/src/field-resolution.test.tsindex 6d696dd72..c607a7f38 100644--- a/packages/core/src/modules/chart/src/field-resolution.test.ts+++ b/packages/core/src/modules/chart/src/field-resolution.test.ts@@ -2,20 +2,19 @@* Unit tests for the event-field resolution helpers.** Background — these helpers exist because the chart, funnel, and conversion- * services used to inline whatever field name the dashboard sent (saved- * report, autocomplete picker, raw API call) directly into SQL. That worked- * for the common case but produced UNKNOWN_IDENTIFIER errors when:+ * services used to inline whatever field name the dashboard sent (saved report,+ * autocomplete picker, raw API call) directly into SQL. That worked for the+ * common case but produced UNKNOWN_IDENTIFIER errors when:*- * - older clients sent camelCase names (`referrerName`) that don't match- * the snake_case ClickHouse schema;- * - users picked utm_* in the property filter UI without realising those- * live in the `properties` map on the events table;- * - a saved report referenced a custom property (`temple_name`) as if it- * were a top-level column.+ * Older clients sent camelCase names (`referrerName`) that don't match the+ * snake_case ClickHouse schema; - users picked utm_* in the property filter UI+ * without realising those live in the `properties` map on the events table; - a+ * saved report referenced a custom property (`temple_name`) as if it were a+ * top-level column.** All five errors logged in HyperDX 2026-05-14 → 2026-05-17 are covered here.*- * Ported from packages/db/src/services/chart-field-resolution.test.ts (M7-003).+ * Ported from packages/db/src/services/chart-field-resolution.test.ts.*/import { describe, expect, it } from 'bun:test';import { isKnownEventField, normalizeEventField } from './field-resolution';diff --git a/packages/core/src/modules/chart/src/field-resolution.ts b/packages/core/src/modules/chart/src/field-resolution.tsindex c4cea0f10..618a0b871 100644--- a/packages/core/src/modules/chart/src/field-resolution.ts+++ b/packages/core/src/modules/chart/src/field-resolution.ts@@ -1,21 +1,21 @@/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */// V1's chart field resolution, moved verbatim from-// packages/db/src/services/chart.service.ts (M7-003): how a report's field-// name (`referrerName`, `utm_source`, `properties.x.*`, `profile.email`,-// `group.name`, `cohort:<id>`, `has_profile`) becomes a ClickHouse-// expression, plus the profile-CTE narrowing helpers.+// packages/db/src/services/chart.service.ts: how a report's field name+// (`referrerName`, `utm_source`, `properties.x.*`, `profile.email`,+// `group.name`, `cohort:<id>`, `has_profile`) becomes a ClickHouse expression,+// plus the profile-CTE narrowing helpers.//-// M12-003 converted every resolver onto the `sql` tag: each one returns a-// `SqlFragment` whose values — cohort ids, cohort labels, project ids and the+// Converted every resolver onto the `sql` tag: each one returns a `SqlFragment`+// whose values — cohort ids, cohort labels, project ids and the// `properties[...]` map keys — bind as `{pN:Type}` params, and whose// identifiers go through `sql.id`. Callers interpolate the fragment directly;// nothing wraps it in `compiledText` any more.//-// The one piece of text this file still builds is the backtick-quoted CTE-// alias `` `profile.properties.<key>` `` (see `profilePropertiesCteSelect`),-// which is an identifier `sql.id` cannot express — three dot-separated parts —-// and which `collectProfilePropertyKeys` already guards. It goes through-// `compiled.ts`, the module's one text seam.+// The one piece of text this file still builds is the backtick-quoted CTE alias+// `` `profile.properties.<key>` `` (see `profilePropertiesCteSelect`), which is+// an identifier `sql.id` cannot express — three dot-separated parts — and which+// `collectProfilePropertyKeys` already guards. It goes through `compiled.ts`,+// the module's one text seam.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IChartBreakdown } from '../../report/report.constants';@@ -261,7 +261,7 @@ export function cohortBreakdownLabelExpr(/*** The membership subselect both filter compilers use for `inCohort` /* `notInCohort`. V1 wrote a plain `IN (subquery)` here; ADR-013 conversions- * never change `IN` / `GLOBAL IN` in either direction (docs/ENVIRONMENT.md).+ * never change `IN` / `GLOBAL IN` in either direction.*/export function buildCohortMembersSubselect(cohortIds: string[],@@ -451,8 +451,8 @@ export function getSelectPropertyKey(const match = matchPropertyMapPrefix(property);if (!match) {// Not a map access: a top-level column, or a name the caller has already- // vetted with `isKnownEventField`. `sql.id` throws on anything else- // rather than inlining it (ADR-013 R3).+ // vetted with `isKnownEventField`. `sql.id` throws on anything else rather+ // than inlining it.return sql.id(property);}diff --git a/packages/core/src/modules/chart/src/filter-cast.ts b/packages/core/src/modules/chart/src/filter-cast.tsindex be03880b0..49e259e94 100644--- a/packages/core/src/modules/chart/src/filter-cast.ts+++ b/packages/core/src/modules/chart/src/filter-cast.ts@@ -1,7 +1,7 @@/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */-// Moved from packages/db/src/services/filter-cast.ts (M8-005) — the typed-cast-// half of `buildFilterWhere` (./table-filter-where.ts) and of-// `./filter-where.ts` (the event-property compiler).+// Moved from packages/db/src/services/filter-cast.ts — the typed-cast half of+// `buildFilterWhere` (./table-filter-where.ts) and of `./filter-where.ts` (the+// event-property compiler).//// Both filter compilers call the same pair now: `castFragment` and// `buildTypedClauseFragment` bind every value as a `{name:Type}` param. Thediff --git a/packages/core/src/modules/chart/src/filter-where.ts b/packages/core/src/modules/chart/src/filter-where.tsindex 7d18d3bf4..c1db10958 100644--- a/packages/core/src/modules/chart/src/filter-where.ts+++ b/packages/core/src/modules/chart/src/filter-where.ts@@ -1,8 +1,8 @@/** biome-ignore-all lint/style/useDefaultSwitchClause: operator switches are exhaustive by design */// V1's event filter compiler (`getEventFiltersWhereClause`), converted onto the-// `sql` tag (M12-002): every VALUE binds as a `{name:Type}` param and every-// identifier goes through `sql.id` or a static fragment. The column expression-// for a `properties.*` / `group.*` filter comes from field-resolution.ts, which+// `sql` tag: every VALUE binds as a `{name:Type}` param and every identifier+// goes through `sql.id` or a static fragment. The column expression for a+// `properties.*` / `group.*` filter comes from field-resolution.ts, which// returns a fragment of its own since M12-003 and is interpolated directly.import {@@ -428,8 +428,8 @@ export function getEventFiltersWhereClause(if (tableScope === 'events' && !EVENT_TOP_LEVEL_COLUMNS.has(name)) {return;}- // ADR-013 R3: the sessions branch has no closed set here, so `sql.id`- // validates the shape and throws rather than inlining anything else.+ // The sessions branch has no closed set here, so `sql.id` validates the+ // shape and throws rather than inlining anything else.const column =tableScope === 'events'? sql.id(name, EVENT_COLUMN_ALLOWLIST)diff --git a/packages/core/src/modules/chart/src/funnel.sql.test.ts b/packages/core/src/modules/chart/src/funnel.sql.test.tsindex bea3f7832..8b101f337 100644--- a/packages/core/src/modules/chart/src/funnel.sql.test.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.test.ts@@ -1,14 +1,14 @@/*** SQL-shape tests for the funnel statements. Ported from- * packages/db/src/services/funnel-sql.test.ts (M7-004).+ * packages/db/src/services/funnel-sql.test.ts.*- * Strategy, same as sql.test.ts: render the statement, then run- * `EXPLAIN <sql>` with its bound params against the isolated `openpanel_test`- * ClickHouse (pinned by test/preload.ts). EXPLAIN parses and resolves columns- * without executing, so a breakdown expression referencing a join alias that- * was never added fails here as UNKNOWN_IDENTIFIER — which is exactly the- * class of bug that made funnel "View Users" return "No users found" for- * profile-property and cohort breakdowns.+ * Strategy, same as sql.test.ts: render the statement, then run `EXPLAIN <sql>`+ * with its bound params against the isolated `openpanel_test` ClickHouse+ * (pinned by test/preload.ts). EXPLAIN parses and resolves columns without+ * executing, so a breakdown expression referencing a join alias that was never+ * added fails here as UNKNOWN_IDENTIFIER — which is exactly the class of bug+ * that made funnel "View Users" return "No users found" for profile-property+ * and cohort breakdowns.** Text assertions look at the rendered `query` with placeholder NUMBERS* normalised away: a fragment reused in two clauses renders `{p3:String}` indiff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.tsindex 7933f6fc7..e0efb69d2 100644--- a/packages/core/src/modules/chart/src/funnel.sql.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.ts@@ -1,11 +1,10 @@-// Every ClickHouse statement the funnel service runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse statement the funnel service runs, as pure `sql` fragments.//-// The chart and the profile list are built from ONE base: a breakdown expression only works if the join it-// references was added, and the joins depend on the breakdowns, so building-// the selects in one place and the joins in another is exactly the bug that-// made funnel "View Users" return "No users found" for profile-property and-// cohort breakdowns.+// The chart and the profile list are built from ONE base: a breakdown+// expression only works if the join it references was added, and the joins+// depend on the breakdowns, so building the selects in one place and the joins+// in another is exactly the bug that made funnel "View Users" return "No users+// found" for profile-property and cohort breakdowns.//// The field resolver and filter compiler render text (see compiled.ts); their// output — filter clauses, breakdown expressions, the profile CTE columns anddiff --git a/packages/core/src/modules/chart/src/retention.sql.ts b/packages/core/src/modules/chart/src/retention.sql.tsindex 95f61d61e..94efa5392 100644--- a/packages/core/src/modules/chart/src/retention.sql.ts+++ b/packages/core/src/modules/chart/src/retention.sql.ts@@ -1,5 +1,4 @@-// Every ClickHouse query the retention service runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse query the retention service runs, as pure `sql` fragments.//// The filter compiler renders text (see compiled.ts); its output is the only// thing spliced into the cohort statement.@@ -43,7 +42,7 @@ const COUNT_CRITERIA: Record<IRetentionCriteria, string> = {/*** Without both dates the statement reads the project's whole lifetime, as V1- * did: the MCP tools pass none and their contracts rely on it (M34-002).+ * did: the MCP tools pass none and their contracts rely on it.*/export interface RetentionSeriesQueryInput {projectId: string;diff --git a/packages/core/src/modules/chart/src/run-query.ts b/packages/core/src/modules/chart/src/run-query.tsindex 67c4963c3..8edcffe02 100644--- a/packages/core/src/modules/chart/src/run-query.ts+++ b/packages/core/src/modules/chart/src/run-query.ts@@ -1,16 +1,16 @@// The chart module's one ClickHouse entry point.//-// M10-003: the client is `deps.ch` — the same round-robin/retry proxy-// `main.ts` builds and hands to every scope — instead of a lazy+// The client is `deps.ch` — the same round-robin/retry proxy `main.ts` builds+// and hands to every scope — instead of a lazy// `import('@openpanel/db/src/clickhouse/client')`. Reaching it through the-// scope is what puts the request's `requestId` on the query's log line-// (ADR-018 R1); the lazy loader had no request scope to carry.+// scope is what puts the request's `requestId` on the query's log line; the+// lazy loader had no request scope to carry.//// `deps.ch.query` is `chQuery`'s own transport (`withRetry(client =>// client.query(...))`), and the Int-meta coercion below is the same one-// `chQuery` applies — ClickHouse's JSON format returns every Int*/UInt*-// column as a string, so a caller's `count: number` only holds if it is-// parsed back out here. Same shape as the overview module's run-query.ts.+// `chQuery` applies — ClickHouse's JSON format returns every Int*/UInt* column+// as a string, so a caller's `count: number` only holds if it is parsed back+// out here. Same shape as the overview module's run-query.ts.import {type SqlFragment,diff --git a/packages/core/src/modules/chart/src/sankey.sql.ts b/packages/core/src/modules/chart/src/sankey.sql.tsindex 77f5a4c81..b554939e9 100644--- a/packages/core/src/modules/chart/src/sankey.sql.ts+++ b/packages/core/src/modules/chart/src/sankey.sql.ts@@ -1,13 +1,13 @@-// Every ClickHouse statement the sankey (user-flow) service runs, as pure-// `sql` fragments (ADR-013).+// Every ClickHouse statement the sankey (user-flow) service runs, as pure `sql`+// fragments.//// The filter compiler renders text (see compiled.ts); only its output is// spliced.//-// Cluster note: `events` is Distributed on Cloud, and the-// `session_id IN (SELECT session_id FROM start_event_sessions)` HAVING clauses-// are plain `IN (subquery)` over a CTE. Whether these should be `GLOBAL IN` on-// a cluster is an open question.+// Cluster note: `events` is Distributed on Cloud, and the `session_id IN+// (SELECT session_id FROM start_event_sessions)` HAVING clauses are plain `IN+// (subquery)` over a CTE. Whether these should be `GLOBAL IN` on a cluster is+// an open question.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { compiledText } from './compiled';@@ -21,8 +21,8 @@ export const TOP_ENTRY_EVENTS = 3;/*** Consecutive-repeat dedup, shared by every mode. V1 spelled it as an* `arrayFilter` whose lambda indexed its own captured `groupArray`, which- * ClickHouse re-materialises once per element: Theta(n^2) in the longest- * single session's event count, fatal on a tenant with one very long session+ * ClickHouse re-materialises once per element: Theta(n^2) in the longest single+ * session's event count, fatal on a tenant with one very long session* (docs/ANALYTICS_PERFORMANCE.md section 6.1). `arrayCompact` is the built-in* for exactly this and is linear; the result is byte-identical.*/diff --git a/packages/core/src/modules/chart/src/sql.test.ts b/packages/core/src/modules/chart/src/sql.test.tsindex 3285068a7..8bf4aba7a 100644--- a/packages/core/src/modules/chart/src/sql.test.ts+++ b/packages/core/src/modules/chart/src/sql.test.ts@@ -1,25 +1,25 @@/*** SQL-shape tests for the chart statements. Ported from- * packages/db/src/services/chart-sql.test.ts (M7-003); the overview- * `getRawWhereClause` cases stayed there with their subject.+ * packages/db/src/services/chart-sql.test.ts; the overview `getRawWhereClause`+ * cases stayed there with their subject.** Strategy: render the statement, then run `EXPLAIN <sql>` with its bound* params against the isolated `openpanel_test` ClickHouse (pinned by* test/preload.ts). EXPLAIN parses, resolves columns and builds the plan- * without executing, so UNKNOWN_IDENTIFIER / AMBIGUOUS_IDENTIFIER / bad JOIN- * ON expressions surface without seeded data. WITH FILL TO < FROM is a- * runtime check, so it is covered by a plain string assertion instead.+ * without executing, so UNKNOWN_IDENTIFIER / AMBIGUOUS_IDENTIFIER / bad JOIN ON+ * expressions surface without seeded data. WITH FILL TO < FROM is a runtime+ * check, so it is covered by a plain string assertion instead.** Text assertions look at the rendered `query`; chart-level values are- * `{pN:Type}` placeholders there, filter/breakdown expressions are the- * verbatim V1 text (see field-resolution.ts's header).+ * `{pN:Type}` placeholders there, filter/breakdown expressions are the verbatim+ * V1 text (see field-resolution.ts's header).** The statements' only Postgres read (the project's cohorts, for the* all-cohorts breakdown) is stubbed to "no cohorts": that is the precondition* the all-cohorts cases assert on, and it keeps this file independent of- * whichever partial `prisma-client` mock a module-root service test left- * behind (bun runs every file in one shared registry without `--isolate`).- * The real Postgres cohort path runs in ../chart.service.test.ts.+ * whichever partial `prisma-client` mock a module-root service test left behind+ * (bun runs every file in one shared registry without `--isolate`). The real+ * Postgres cohort path runs in../chart.service.test.ts.*/import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test';@@ -71,9 +71,9 @@ interface Rendered {params: Record<string, unknown>;/*** `sql` with every `{pN:Type}` substituted back to the literal V1 emitted.- * Since M12-003 the field resolver binds `properties[<key>]` keys too, so- * an assertion about the SHAPE of a map access reads this; an assertion- * about what is bound reads `sql`/`params`.+ * Since M12-003 the field resolver binds `properties[<key>]` keys too, so an+ * assertion about the SHAPE of a map access reads this; an assertion about+ * what is bound reads `sql`/`params`.*/text: string;}diff --git a/packages/core/src/modules/chart/src/sql.ts b/packages/core/src/modules/chart/src/sql.tsindex f099dafa6..159c94555 100644--- a/packages/core/src/modules/chart/src/sql.ts+++ b/packages/core/src/modules/chart/src/sql.ts@@ -1,17 +1,16 @@-// Every ClickHouse query the chart module runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse query the chart module runs, as pure `sql` fragments.//// The field resolver and filter compiler render text (see compiled.ts); their// output is spliced, everything else is bound. Dates bind as strings: a String// param in a DateTime position is parsed exactly like the literal it replaces.//// Cluster note: `events`, `profiles`, `groups` and `cohort_members` are-// Distributed on Cloud. The cohort CTEs, the profile / group / cohort-// LEFT ANY JOINs and any `IN (SELECT ...)` a filter compiles run under the-// client's `distributed_product_mode: 'allow'`.+// Distributed on Cloud. The cohort CTEs, the profile / group / cohort LEFT ANY+// JOINs and any `IN (SELECT...)` a filter compiles run under the client's+// `distributed_product_mode: 'allow'`.//-// The keyed part records below are a local, function-scoped builder (ADR-013-// R5): assigning clauses by key keeps a stable clause order.+// The keyed part records below are a local, function-scoped builder: assigning+// clauses by key keeps a stable clause order.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type {@@ -689,7 +688,7 @@ function profileFieldsToSelect(refs: string[]): SqlFragment[] {fields.push(field);}}- // ADR-013 R3: V1 spliced these unchecked (trpc chart.ts:781).+ // V1 spliced these unchecked (trpc chart.ts:781).return fields.map((field) => sql.id(field, PROFILE_COLUMNS));}diff --git a/packages/core/src/modules/chart/src/table-filter-where.test.ts b/packages/core/src/modules/chart/src/table-filter-where.test.tsindex 28f0052aa..2f3363c80 100644--- a/packages/core/src/modules/chart/src/table-filter-where.test.ts+++ b/packages/core/src/modules/chart/src/table-filter-where.test.ts@@ -2,16 +2,15 @@* Unit tests for `buildFilterWhere`.** No ClickHouse needed. Since M12-003 the compiler returns bound- * `SqlFragment`s, so each clause is rendered through `toStatement()` and its+ * `SqlFragment`s, so each clause is rendered through `toStatement` and its* params substituted back in: what the assertions say is unchanged, a value- * that used to appear as an escaped literal now appears in `query_params`.- * The interesting part is- * the `profile.*` branch: the field name arrives from the caller (saved- * report, URL state, raw API call) and used to be concatenated into the SQL- * text as-is, so a name that was not a column produced whatever SQL the caller- * wrote. It now resolves against the known profiles columns and the filter is- * dropped when it does not, which is what the `group.*` and `session.*`- * branches already did.+ * that used to appear as an escaped literal now appears in `query_params`. The+ * interesting part is the `profile.*` branch: the field name arrives from the+ * caller (saved report, URL state, raw API call) and used to be concatenated+ * into the SQL text as-is, so a name that was not a column produced whatever+ * SQL the caller wrote. It now resolves against the known profiles columns and+ * the filter is dropped when it does not, which is what the `group.*` and+ * `session.*` branches already did.*/import { describe, expect, it } from 'bun:test';diff --git a/packages/core/src/modules/client/client.routes.ts b/packages/core/src/modules/client/client.routes.tsindex 78955c0ef..26e3ad09a 100644--- a/packages/core/src/modules/client/client.routes.ts+++ b/packages/core/src/modules/client/client.routes.ts@@ -1,18 +1,18 @@-// The /manage/clients REST surface (M6-002), delegating its CRUD bodies to+// The /manage/clients REST surface, delegating its CRUD bodies to// client.service.ts's createClientForOrganization/updateClientForOrganization/// etc — the same functions the tRPC router (client.rpc.ts) calls. Response// envelopes (`{ data }` / `{ success }`) match V1's `reply.send(...)` shape// (byte-unchanged URL surface).//-// Body schemas are local, not a client.constants.ts file: the module map-// gives client "R,H,S" only, no "C" (unlike project, whose zCreateProject /+// Body schemas are local, not a client.constants.ts file: the module map gives+// client "R,H,S" only, no "C" (unlike project, whose zCreateProject /// zUpdateProject moved with ProjectTypeNames).//// `authenticateAllowedClient` (http/client-auth.ts) is filled in and-// `publicApiRoutes` is mounted in main.ts, so this route is live.-// `allow: ['root']` mirrors V1's rule: only root clients may manage-// resources. (A client minted through client.service.ts cannot currently-// authenticate at all — see that file's FIXME on `createClientForOrganization`.)+// `publicApiRoutes` is mounted in main.ts, so this route is live. `allow:+// ['root']` mirrors V1's rule: only root clients may manage resources. (A+// client minted through client.service.ts cannot currently authenticate at all+// — see that file's FIXME on `createClientForOrganization`.)import { z } from 'zod';import { defineRoutes } from '../../http/define';diff --git a/packages/core/src/modules/client/client.rpc.ts b/packages/core/src/modules/client/client.rpc.tsindex 3cf53eccc..117d6d928 100644--- a/packages/core/src/modules/client/client.rpc.ts+++ b/packages/core/src/modules/client/client.rpc.ts@@ -1,16 +1,15 @@-// Ported from V1's client router (M6-002).+// Ported from V1's client router.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// `ctx.services.client` carries this module's factory (M10-004).+// `ctx.services.client` carries this module's factory.//-// The permission ladder itself is bound once, in auth.service.ts (M10-002);-// every procedure here reaches it through `ctx.services.auth`.+// The permission ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/client/client.service.test.ts b/packages/core/src/modules/client/client.service.test.tsindex 2925ce3f4..277a13609 100644--- a/packages/core/src/modules/client/client.service.test.ts+++ b/packages/core/src/modules/client/client.service.test.ts@@ -1,10 +1,10 @@-// The subject is built by its factory over a fake `ServiceDeps` (M10-004), so-// Postgres needs no module mock at all — `deps.db` IS the fake below, same-// idiom as reference.service.test.ts. `@openpanel/redis` is still stubbed:+// The subject is built by its factory over a fake `ServiceDeps`, so Postgres+// needs no module mock at all — `deps.db` IS the fake below, same idiom as+// reference.service.test.ts. `@openpanel/redis` is still stubbed:// `getClientByIdCached` calls `cacheable(...)` inside `createClientService`-// itself now (not at this module's import time), but the binding is-// resolved at `client.service.ts`'s own import time, so the mock must still-// land before that import — hence the `await import` in `beforeAll`.+// itself now (not at this module's import time), but the binding is resolved at+// `client.service.ts`'s own import time, so the mock must still land before+// that import — hence the `await import` in `beforeAll`.import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.tsindex d938a4bce..cca15de7f 100644--- a/packages/core/src/modules/client/client.service.ts+++ b/packages/core/src/modules/client/client.service.ts@@ -1,20 +1,19 @@-// Moved from V1's clients service (M6-002, module map: client owns "R,H,S" —-// no constants file, per the module map). Client CRUD lives only here now;-// no packages/db re-export shim exists in this tree.+// Moved from V1's clients service (module map: client owns "R,H,S" — no+// constants file, per the module map). Client CRUD lives only here now; no+// packages/db re-export shim exists in this tree.//// The /manage REST CRUD bodies (client.routes.ts's listClients/getClient/// createClient/updateClient/deleteClient) call the same// create/update/delete/list functions the tRPC router (client.rpc.ts) does.//-// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone. No dependency on-// project.service.ts here (the reverse direction exists, for cache-// invalidation) — project-ownership checks below query `db.project`-// directly.+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb` lazy loader is gone. No dependency on project.service.ts here (the+// reverse direction exists, for cache invalidation) — project-ownership checks+// below query `db.project` directly.//-// M15-005: `getClientByIdCached` is a module-scope `cacheablePerDb`, keyed on-// the Postgres client rather than on the scope. Its L1 LRU has to survive-// across calls to be worth anything, and the ingest hot path+// `getClientByIdCached` is a module-scope `cacheablePerDb`, keyed on the+// Postgres client rather than on the scope. Its L1 LRU has to survive across+// calls to be worth anything, and the ingest hot path// (`ingest/src/client-auth.ts`, `http/client-auth.ts`) now passes the scope it// holds instead of reading a boot-scoped singleton through the deleted compat// seam. One instance per process to read, one to invalidate.diff --git a/packages/core/src/modules/cohort/cohort.constants.ts b/packages/core/src/modules/cohort/cohort.constants.tsindex 51fed8a48..f4fc8db35 100644--- a/packages/core/src/modules/cohort/cohort.constants.ts+++ b/packages/core/src/modules/cohort/cohort.constants.ts@@ -1,17 +1,16 @@-// Moved from packages/validation/src/cohort.validation.ts (M5-003, ADR-008's-// module map: cohort owns "C"). packages/validation/src/cohort.validation.ts-// becomes a re-export shim of this file's `./modules/cohort/cohort.constants`-// subpath (same shape as packages/db/src/gsc.ts since M5-002), so-// apps/start and packages/db/src/types.ts keep resolving these symbols-// through packages/validation's existing barrel unchanged.+// Moved from packages/validation/src/cohort.validation.ts (ADR-008's module+// map: cohort owns "C"). packages/validation/src/cohort.validation.ts becomes a+// re-export shim of this file's `./modules/cohort/cohort.constants` subpath+// (same shape as packages/db/src/gsc.ts since M5-002), so apps/start and+// packages/db/src/types.ts keep resolving these symbols through+// packages/validation's existing barrel unchanged.//-// Isomorphic by the AGENTS.md rule: zod, another `*.constants.ts`, or-// nothing. `zChartEventFilter` used to be a diverged local copy here-// (TODO(P7) in M5-003) to dodge a TDZ from importing it through-// packages/validation's barrel before that barrel finished initializing;-// now that it lives in report.constants.ts — an isomorphic, cycle-free-// sibling — importing it directly is safe, and the duplicate is gone-// (M7-006).+// Isomorphic by the AGENTS.md rule: zod, another `*.constants.ts`, or nothing.+// `zChartEventFilter` used to be a diverged local copy here (TODO(P7) in+// M5-003) to dodge a TDZ from importing it through packages/validation's barrel+// before that barrel finished initializing; now that it lives in+// report.constants.ts — an isomorphic, cycle-free sibling — importing it+// directly is safe, and the duplicate is gone.import { z } from 'zod';import { zChartEventFilter } from '../report/report.constants';diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.tsindex ddf37ec86..f74566421 100644--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts@@ -132,8 +132,8 @@ test('cohortRefresh fans out one enqueueCompute per non-static cohort', async ()});// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot pins-// (apps/worker/src/boot-cron.ts). The cadence now lives on the job itself-// (ADR-021), so this reads it straight off the registry.+// (apps/worker/src/boot-cron.ts). The cadence now lives on the job itself, so+// this reads it straight off the registry.test('the cohort cron fragment carries V1 id and cadence unchanged', () => {expect(queues.cron.jobs.cohortRefresh.cron).toEqual({pattern: '*/30 * * * *',diff --git a/packages/core/src/modules/cohort/cohort.jobs.ts b/packages/core/src/modules/cohort/cohort.jobs.tsindex 9d001c0fb..a420ce41e 100644--- a/packages/core/src/modules/cohort/cohort.jobs.ts+++ b/packages/core/src/modules/cohort/cohort.jobs.ts@@ -1,11 +1,11 @@-// Ported from apps/worker/src/jobs/cohort.compute.ts + cron.cohort-refresh.ts-// (M5-003); the schedule moved onto the job at ADR-021 (M10-007).+// Ported from apps/worker/src/jobs/cohort.compute.ts + cron.cohort-refresh.ts;+// the schedule moved onto the job at ADR-021.//// `cohortCompute` is this module's own queue — registry key `cohortCompute`// EXACTLY (ADR-005's acceptance note: no env rename, so-// COHORTCOMPUTE_CONCURRENCY keeps working). `cohortRefresh` is a cron-// fragment, spread into the ONE `cron` queue by jobs.registry.ts. Scheduler-// id and cadence are V1's, unchanged (apps/worker/src/boot-cron.ts).+// COHORTCOMPUTE_CONCURRENCY keeps working). `cohortRefresh` is a cron fragment,+// spread into the ONE `cron` queue by jobs.registry.ts. Scheduler id and+// cadence are V1's, unchanged (apps/worker/src/boot-cron.ts).import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/cohort/cohort.rpc.ts b/packages/core/src/modules/cohort/cohort.rpc.tsindex 0a14c44ba..09d501eef 100644--- a/packages/core/src/modules/cohort/cohort.rpc.ts+++ b/packages/core/src/modules/cohort/cohort.rpc.ts@@ -1,14 +1,13 @@-// Ported from packages/trpc/src/routers/cohort.ts (M5-003).+// Ported from packages/trpc/src/routers/cohort.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// The per-project access ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The per-project access ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.//// CRUD (list/get/create/update/delete) reads/writes Prisma's `cohort` table// directly, matching V1's router — cohort.service.ts owns only the@@ -44,10 +43,9 @@ const EXPORT_PROFILES_MAX_LIMIT = 10_000;const EXPORT_PROFILES_DEFAULT_LIMIT = 10_000;/**- * `mostEvents` and `popularRoutes` read the project's whole history before- * this window existed (docs/UNPROVEN_ENDPOINTS.md §4.4). The default is the- * one `profile.powerUsers` got for the same cause (M31-003); the cohort page- * passes no range, so this is what it shows.+ * `mostEvents` and `popularRoutes` read the project's whole history before this+ * window existed. The default is the one `profile.powerUsers` got for the same+ * cause; the cohort page passes no range, so this is what it shows.*/const COHORT_ACTIVITY_DEFAULT_RANGE = '3m';@@ -114,8 +112,8 @@ export const cohortRouter = createTRPCRouter({}),// No project-access check here, matching V1 (packages/trpc/src/routers/- // cohort.ts) exactly — protectedProcedure's session check is the only- // gate today. Preserved as found: ADR-011 invariant 1 forbids deleting an+ // cohort.ts) exactly — protectedProcedure's session check is the only gate+ // today. Preserved as found: ADR-011 invariant 1 forbids deleting an// in-handler check, and this router does not serve live traffic yet.create: protectedProcedure.input(zCohortInput)diff --git a/packages/core/src/modules/cohort/cohort.service.test.ts b/packages/core/src/modules/cohort/cohort.service.test.tsindex bb2cac16d..1acb3ef4d 100644--- a/packages/core/src/modules/cohort/cohort.service.test.ts+++ b/packages/core/src/modules/cohort/cohort.service.test.ts@@ -1,13 +1,13 @@-// M10-009: every function under test takes `ServiceDeps`, so `deps.db` and-// `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 `ch-query`, which is what the subject now calls.+// Every function under test takes `ServiceDeps`, so `deps.db` and `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 `ch-query`, which is what the subject now calls.//// The pure SQL-shape builders (buildEventCriteriaQuery,// buildPropertyBasedCohortQuery, deriveCohortQuerySettings) have their own-// file, src/cohort-sql.test.ts, and need none of this — they take no-// ClickHouse connection.+// file, src/cohort-sql.test.ts, and need none of this — they take no ClickHouse+// connection.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -217,8 +217,8 @@ test('createCohortService() delegates updateMembership and listRefreshableCohortseedCohort({ id: 'c2', isStatic: true });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.+ // The container's members are closures over `deps`, not the bare functions,+ // so identity is no longer the observable — delegation is.expect((await service.listRefreshableCohortIds()).sort()).toEqual(['c1']);chCommand.mockClear();diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.tsindex 42597d6d4..31a188c7d 100644--- a/packages/core/src/modules/cohort/cohort.service.ts+++ b/packages/core/src/modules/cohort/cohort.service.ts@@ -53,30 +53,29 @@ export function cohortMaterializeLimit(config: CoreConfig): number {);}-// Property cohorts aggregate every profile row for the project, so they are-// the one cohort query that can outgrow the server's memory headroom. Two-// opt-in knobs bound them; with NEITHER set, no per-query settings are-// applied and the server's own defaults govern — upstream behavior is-// unchanged.+// Property cohorts aggregate every profile row for the project, so they are the+// one cohort query that can outgrow the server's memory headroom. Two opt-in+// knobs bound them; with NEITHER set, no per-query settings are applied and the+// server's own defaults govern — upstream behavior is unchanged.//-// COHORT_QUERY_MEMORY_LIMIT_BYTES hard cap for these queries-// COHORT_QUERY_SPILL_BYTES GROUP BY spills to disk past this+// COHORT_QUERY_MEMORY_LIMIT_BYTES hard cap for these queries+// COHORT_QUERY_SPILL_BYTES GROUP BY spills to disk past this//-// A GROUP BY only starts spilling once it crosses the threshold, so the-// spill threshold must sit BELOW the memory limit — inverted, the query is-// killed before it ever writes to disk (ClickHouse Cloud ships exactly that-// inversion by default, which is how these queries OOM'd instead of-// spilling). When only the limit is set — or the pair is inverted — the-// threshold derives as limit/3. Spilling early costs little: the volume-// spilled is set by the data, not the threshold (measured on 8.3M profiles,-// ~281MB spilled whether the threshold was 300, 512 or 768MB, at-// 6.9s/6.7s/6.0s, while peak memory climbed 410/695/893MiB).+// A GROUP BY only starts spilling once it crosses the threshold, so the spill+// threshold must sit BELOW the memory limit — inverted, the query is killed+// before it ever writes to disk (ClickHouse Cloud ships exactly that inversion+// by default, which is how these queries OOM'd instead of spilling). When only+// the limit is set — or the pair is inverted — the threshold derives as+// limit/3. Spilling early costs little: the volume spilled is set by the data,+// not the threshold (measured on 8.3M profiles, ~281MB spilled whether the+// threshold was 300, 512 or 768MB, at 6.9s/6.7s/6.0s, while peak memory climbed+// 410/695/893MiB).//-// A standalone function of its two parsed inputs (not a module-level read),-// so a test can exercise every branch by calling it directly — bun:test-// shares one module registry per file even under --isolate, so vitest's-// vi.resetModules()-per-case porting has no equivalent (see AGENTS.md; this-// was the one vi.resetModules site in the suite, ADR-010's tail table).+// A standalone function of its two parsed inputs (not a module-level read), so+// a test can exercise every branch by calling it directly — bun:test shares one+// module registry per file even under --isolate, so vitest's+// vi.resetModules-per-case porting has no equivalent (see AGENTS.md; this was+// the one vi.resetModules site in the suite, ADR-010's tail table).export function deriveCohortQuerySettings({memoryLimitBytes,spillBytes: spillBytesParsed,@@ -347,14 +346,14 @@ function normalizeProfileColumn(name: string): string {return name.replace(/^profile\./, 'profiles.');}-// SQL for a profile filter's column: either a properties Map lookup or a-// plain column, qualified with the table name. Cohort definitions come from-// the API, so both halves are user-controlled: the Map key is a *value* and-// binds as one, and the plain column goes through `sql.id`, which throws-// rather than inlining anything that is not a bare (once-qualified)-// identifier (ADR-013 R3). V1 inlined it verbatim — the one input class whose-// behaviour changes is a non-identifier column name, which V1 turned into a-// ClickHouse `UNKNOWN_IDENTIFIER` and V2 rejects before the round trip.+// SQL for a profile filter's column: either a properties Map lookup or a plain+// column, qualified with the table name. Cohort definitions come from the API,+// so both halves are user-controlled: the Map key is a *value* and binds as+// one, and the plain column goes through `sql.id`, which throws rather than+// inlining anything that is not a bare (once-qualified) identifier. V1 inlined+// it verbatim — the one input class whose behaviour changes is a non-identifier+// column name, which V1 turned into a ClickHouse `UNKNOWN_IDENTIFIER` and V2+// rejects before the round trip.function profileColumnAccess(normalizedName: string): SqlFragment {if (normalizedName.startsWith('profiles.properties.')) {const propKey = normalizedName.replace('profiles.properties.', '');@@ -933,9 +932,8 @@ export async function listCohortMemberProfiles(? sql`AND ${sql.join(extraConditions, ' AND ')}`: sql.empty;- // M12-003: converted with `buildFilterWhere`, which now returns fragments.- // V1's plain `IN (subquery)` on the Distributed `cohort_members` is kept as- // written (docs/ENVIRONMENT.md).+ // Converted with `buildFilterWhere`, which now returns fragments. V1's plain+ // `IN (subquery)` on the Distributed `cohort_members` is kept as written.const rows = await chQuery<{ id: string; total_count: number }>(deps,sql`@@ -970,9 +968,8 @@ export async function listCohortMemberProfiles(/*** The window `mostEvents` / `popularRoutes` read. Both had no date filter, so- * they scanned the project's whole event history however small the cohort- * (docs/UNPROVEN_ENDPOINTS.md §4.4). `YYYY-MM-DD HH:mm:ss`, as- * `getChartStartEndDate` returns it.+ * they scanned the project's whole event history however small the cohort.+ * `YYYY-MM-DD HH:mm:ss`, as `getChartStartEndDate` returns it.*/export interface CohortActivityWindow {startDate: string;@@ -1008,7 +1005,7 @@ export function cohortMemberEventsQuery(): SqlFragment {// V1's plain `IN (subquery)` on the Distributed `cohort_members` is kept as// written — a conversion changes the binding of values and nothing about the- // distribution semantics (docs/ENVIRONMENT.md).+ // distribution semantics.return sql`SELECT name, count() AS countFROM ${sql.id(TABLE.events)}@@ -1118,14 +1115,14 @@ export function createCohortService(* Enqueue a recompute for a cohort.** Uses `deduplicationId` rather than `jobId`. A fixed jobId makes BullMQ- * short-circuit `add` for as long as *any* record for that id exists in- * Redis — and `removeOnComplete: { age }` is not a TTL, it only trims on- * some other job in the queue finishing. That deadlocks: nothing can be- * added because the completed record is still there, and the record is- * never collected because nothing gets added. `deduplicationId`, in- * contrast, is released by `moveToFinished` on both completion and- * terminal failure, so it only collapses a compute that is genuinely still- * in flight (ADR-005: "cohort must NOT be normalised onto jobId").+ * short-circuit `add` for as long as *any* record for that id exists in Redis+ * — and `removeOnComplete: { age }` is not a TTL, it only trims on some other+ * job in the queue finishing. That deadlocks: nothing can be added because+ * the completed record is still there, and the record is never collected+ * because nothing gets added. `deduplicationId`, in contrast, is released by+ * `moveToFinished` on both completion and terminal failure, so it only+ * collapses a compute that is genuinely still in flight (ADR-005: "cohort+ * must NOT be normalised onto jobId").*/async function enqueueCompute(cohortId: string): Promise<void> {await deps.queues.cohortCompute.cohortCompute.add(diff --git a/packages/core/src/modules/cohort/src/cohort-activity-sql.test.ts b/packages/core/src/modules/cohort/src/cohort-activity-sql.test.tsindex 6bd1e5e2b..a70a23a34 100644--- a/packages/core/src/modules/cohort/src/cohort-activity-sql.test.ts+++ b/packages/core/src/modules/cohort/src/cohort-activity-sql.test.ts@@ -1,7 +1,7 @@// SQL-shape tests for the cohort detail page's `mostEvents` / `popularRoutes`// statements. M36-005 bounded both to a window: before it they had no date// filter and read the project's whole event history however small the cohort-// was (docs/UNPROVEN_ENDPOINTS.md §4.4). Pure builders — no ClickHouse.+// was. Pure builders — no ClickHouse.import { describe, expect, test } from 'bun:test';import {diff --git a/packages/core/src/modules/cohort/src/cohort-sql.test.ts b/packages/core/src/modules/cohort/src/cohort-sql.test.tsindex 0d4f78cfd..182586cc8 100644--- a/packages/core/src/modules/cohort/src/cohort-sql.test.ts+++ b/packages/core/src/modules/cohort/src/cohort-sql.test.ts@@ -1,30 +1,30 @@// SQL-shape tests for property-based cohort queries. Ported from-// packages/db/src/services/cohort-property-sql.test.ts (M5-003) — minus its-// itCH ClickHouse-reachability EXPLAIN check: `mock.module` substitutions-// apply process-wide, not per file, so a sibling file's+// packages/db/src/services/cohort-property-sql.test.ts — minus its itCH+// ClickHouse-reachability EXPLAIN check: `mock.module` substitutions apply+// process-wide, not per file, so a sibling file's// `@openpanel/db/src/clickhouse/client` mock (cohort.service.test.ts) can-// silently replace this file's "real" import too, making a reachability-// check meaningless. No module in core's suite ports that pattern for the-// same reason; the generated SQL was verified against local ClickHouse by-// hand instead (see the M5-003 task summary).+// silently replace this file's "real" import too, making a reachability check+// meaningless. No module in core's suite ports that pattern for the same+// reason; the generated SQL was verified against local ClickHouse by hand+// instead (see the M5-003 task summary).//-// String assertions need no mocking at all: cohort.service.ts's db/ch access-// is lazy, and buildPropertyBasedCohortQuery / deriveCohortQuerySettings-// touch neither — see cohort.service.ts's header.+// String assertions need no mocking at all: cohort.service.ts's db/ch access is+// lazy, and buildPropertyBasedCohortQuery / deriveCohortQuerySettings touch+// neither — see cohort.service.ts's header.//-// M12-004: the builders return `SqlFragment`s now, so every assertion below-// runs against the RENDERED statement plus its bound params rather than a-// finished string. The assertions themselves are unchanged in what they-// claim, except the one about quotes in a user-controlled property key: a-// quote no longer needs escaping because the key is not in the SQL text at-// all, so that test asserts the binding instead.+// The builders return `SqlFragment`s now, so every assertion below runs against+// the RENDERED statement plus its bound params rather than a finished string.+// The assertions themselves are unchanged in what they claim, except the one+// about quotes in a user-controlled property key: a quote no longer needs+// escaping because the key is not in the SQL text at all, so that test asserts+// the binding instead.//-// V1's `PROFILE_COHORT_QUERY_SETTINGS` test used `vi.resetModules()` +-// `vi.stubEnv()` to re-import the module under different env vars — the-// suite's only `vi.resetModules` site (ADR-010's tail table). bun:test shares-// one module registry per file even under `--isolate`, so re-importing would-// not re-evaluate a module-level const. `deriveCohortQuerySettings` exists-// so this ports as direct calls instead.+// V1's `PROFILE_COHORT_QUERY_SETTINGS` test used `vi.resetModules` ++// `vi.stubEnv` to re-import the module under different env vars — the suite's+// only `vi.resetModules` site (ADR-010's tail table). bun:test shares one+// module registry per file even under `--isolate`, so re-importing would not+// re-evaluate a module-level const. `deriveCohortQuerySettings` exists so this+// ports as direct calls instead.import { expect, test } from 'bun:test';import {diff --git a/packages/core/src/modules/conversation/conversation.constants.ts b/packages/core/src/modules/conversation/conversation.constants.tsindex 5fc2f9b19..5c339eb3a 100644--- a/packages/core/src/modules/conversation/conversation.constants.ts+++ b/packages/core/src/modules/conversation/conversation.constants.ts@@ -1,6 +1,6 @@// Shared with the frontend (chat-drawer-header.tsx, title-stream.tsx) so the-// page size / title length and the zod defaults never drift apart (ADR-022-// R8, "Not covered by any rule" #3 in docs/review/conversation.md).+// page size / title length and the zod defaults never drift apart ("Not covered+// by any rule" #3 in docs/review/conversation.md).//// Isomorphic by the AGENTS.md rule: zod and nothing else.diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.tsindex 940a43bda..22ded6b45 100644--- a/packages/core/src/modules/conversation/conversation.rpc.ts+++ b/packages/core/src/modules/conversation/conversation.rpc.ts@@ -1,20 +1,19 @@-// Ported from packages/trpc/src/routers/conversation.ts (M5-006).+// Ported from packages/trpc/src/routers/conversation.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. `enforceAccess` reads the raw,-// pre-zod input and only a TOP-LEVEL `projectId` (ADR-011) — `list` and-// `rename` both take one, so their project access is already enforced-// before the handler runs. `get` and `delete` take only `id`, invisible to-// `enforceAccess`, so their ownership check stays in the handler. `get`-// denies with NOT_FOUND rather than FORBIDDEN — the documented exception+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. `enforceAccess` reads the raw, pre-zod input and only a TOP-LEVEL+// `projectId` — `list` and `rename` both take one, so their project access is+// already enforced before the handler runs. `get` and `delete` take only `id`,+// invisible to `enforceAccess`, so their ownership check stays in the handler.+// `get` denies with NOT_FOUND rather than FORBIDDEN — the documented exception// the ADR-011 auth benchmark is built around (controller// verification/contracts/auth/README.md).//-// `ctx.services.conversation` carries this module's factory (M10-004).+// `ctx.services.conversation` carries this module's factory.//-// The per-project access ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The per-project access ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/conversation/conversation.service.test.ts b/packages/core/src/modules/conversation/conversation.service.test.tsindex cbf9d82cc..f51420320 100644--- a/packages/core/src/modules/conversation/conversation.service.test.ts+++ b/packages/core/src/modules/conversation/conversation.service.test.ts@@ -1,6 +1,6 @@-// The subject is built by its factory over a fake `ServiceDeps` (M10-004), so-// Postgres needs no module mock at all — `deps.db` IS the fake below, same-// idiom as reference.service.test.ts.+// The subject is built by its factory over a fake `ServiceDeps`, so Postgres+// needs no module mock at all — `deps.db` IS the fake below, same idiom as+// reference.service.test.ts.import { beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';diff --git a/packages/core/src/modules/conversation/conversation.service.ts b/packages/core/src/modules/conversation/conversation.service.tsindex d80381eb7..e8f723ec6 100644--- a/packages/core/src/modules/conversation/conversation.service.ts+++ b/packages/core/src/modules/conversation/conversation.service.ts@@ -1,5 +1,5 @@-// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone.+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb` lazy loader is gone.import type {ChatMessage,diff --git a/packages/core/src/modules/dashboard/dashboard.rpc.ts b/packages/core/src/modules/dashboard/dashboard.rpc.tsindex 62568eac4..a37a1ac39 100644--- a/packages/core/src/modules/dashboard/dashboard.rpc.ts+++ b/packages/core/src/modules/dashboard/dashboard.rpc.ts@@ -1,15 +1,14 @@-// Ported from packages/trpc/src/routers/dashboard.ts (M7-006).+// Ported from packages/trpc/src/routers/dashboard.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// The dashboardId-keyed procedures are invisible to `enforceAccess`; their-// in-handler `requireProjectAccess` through `ctx.services.auth` (M10-002) is-// the only check that fires.+// in-handler `requireProjectAccess` through `ctx.services.auth` is the only+// check that fires.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.tsindex a3164e65f..a10fce82f 100644--- a/packages/core/src/modules/dashboard/dashboard.service.ts+++ b/packages/core/src/modules/dashboard/dashboard.service.ts@@ -1,12 +1,11 @@// Moved from packages/db/src/services/dashboard.service.ts, plus the// create/update/delete mutation bodies packages/trpc/src/routers/dashboard.ts-// held inline (M7-006, ADR-008's module map: dashboard owns "R,S").+// held inline (ADR-008's module map: dashboard owns "R,S").//-// M10-003: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` / `loadIdService()` lazy loaders are gone, so-// this module value-imports neither `@openpanel/db` nor its own package-// barrel — the Prisma row types below are `import type`, erased at runtime-// (docs/TECH_DEBT.md §4).+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb` / `loadIdService` lazy loaders are gone, so this module+// value-imports neither `@openpanel/db` nor its own package barrel — the Prisma+// row types below are `import type`, erased at runtime.import type { Dashboard, Prisma } from '@openpanel/db/src/prisma-client';import { PrismaError } from 'prisma-error-enum';diff --git a/packages/core/src/modules/email/email.constants.ts b/packages/core/src/modules/email/email.constants.tsindex 483225016..bb757c0b3 100644--- a/packages/core/src/modules/email/email.constants.ts+++ b/packages/core/src/modules/email/email.constants.ts@@ -1,5 +1,5 @@-// Moved from packages/constants/index.ts (M6-004, ADR-008's module map:-// email owns "C"). packages/constants was deleted whole at M11-009.+// Moved from packages/constants/index.ts (ADR-008's module map: email owns+// "C"). packages/constants was deleted whole at M11-009.//// Keys must match the template `category` in @openpanel/email. Each entry's// label + description drive the account email-preferences toggles.diff --git a/packages/core/src/modules/email/email.rpc.ts b/packages/core/src/modules/email/email.rpc.tsindex 14c660a85..986aad23b 100644--- a/packages/core/src/modules/email/email.rpc.ts+++ b/packages/core/src/modules/email/email.rpc.ts@@ -1,18 +1,17 @@-// Ported from packages/trpc/src/routers/email.ts (M6-004).+// Ported from packages/trpc/src/routers/email.ts.//-// Deliberately R + C only (no `email.service.ts`): the three procedures'-// bodies are three small `db.emailUnsubscribe` calls, inlined here the same-// way conversation.rpc.ts inlines its organization lookup. Sending/templates-// stay in @openpanel/email (TARGET_ARCHITECTURE §7); core's-// `clients/email.ts` already wraps that package for the one thing this-// module doesn't need — sending.+// Deliberately R + C only (no `email.service.ts`): the three procedures' bodies+// are three small `db.emailUnsubscribe` calls, inlined here the same way+// conversation.rpc.ts inlines its organization lookup. Sending/templates stay+// in @openpanel/email (TARGET_ARCHITECTURE §7); core's `clients/email.ts`+// already wraps that package for the one thing this module doesn't need —+// sending.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// This module has no queue/cron of its own, so there is no// `ctx.services.email`, same as `user`/`reference`.diff --git a/packages/core/src/modules/email/src/sequence.test.ts b/packages/core/src/modules/email/src/sequence.test.tsindex 6da599b1b..0dea73020 100644--- a/packages/core/src/modules/email/src/sequence.test.ts+++ b/packages/core/src/modules/email/src/sequence.test.ts@@ -1,8 +1,8 @@// Unit tests for the sequence runner. Moved from-// apps/worker/src/jobs/lib/email-sequence.test.ts (M6-003). `sendEmail` is-// mocked, so these assert decisions — which step fires, whether the pointer-// moves, whether side effects run — rather than delivery. `mock.module` is-// not hoisted, so the subject is imported inside `beforeAll` — see AGENTS.md.+// apps/worker/src/jobs/lib/email-sequence.test.ts. `sendEmail` is mocked, so+// these assert decisions — which step fires, whether the pointer moves, whether+// side effects run — rather than delivery. `mock.module` is not hoisted, so the+// subject is imported inside `beforeAll` — see AGENTS.md.import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { subDays } from 'date-fns';diff --git a/packages/core/src/modules/email/src/sequence.ts b/packages/core/src/modules/email/src/sequence.tsindex 45d45a964..119bb95a1 100644--- a/packages/core/src/modules/email/src/sequence.ts+++ b/packages/core/src/modules/email/src/sequence.ts@@ -1,28 +1,27 @@-// 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+// Moved from apps/worker/src/jobs/lib/email-sequence.ts, and out of `shared/`+// at M15-009: it sends email, so it sits in the module that owns email, not in+// the layer below every transport. Its two callers — the onboarding drip+// (modules/onboarding) and the wind-down track// (modules/organization/src/wind-down.ts) — reach it sideways, module to// module.//-// A day-gated email sequence runner. Each subject carries a pointer (the-// last step whose email was sent) and an anchor date. On every tick the-// runner resolves the next step, checks the day gate and the step's own-// guard, sends, then advances the pointer.+// A day-gated email sequence runner. Each subject carries a pointer (the last+// step whose email was sent) and an anchor date. On every tick the runner+// resolves the next step, checks the day gate and the step's own guard, sends,+// then advances the pointer.//// Three deliberate differences from the original inline implementation in// cron.onboarding.ts, all of which matter once a sequence ends in deletion://// 1. The pointer resolves by step name and an *unknown* name completes the-// sequence rather than restarting it. The old `findIndex` returned -1 for a-// renamed or removed step, which silently sent the subject back to step 0.-// 2. `'skip'` advances past a step; `false` only defers it. The old code had-// one value for both, so a step that should be passed over stalled the-// sequence permanently.-// 3. `requireDelivery` refuses to advance unless the email actually went out.-// `sendEmail` returns null instead of throwing when a send is suppressed or-// misconfigured, so a step with side effects could otherwise fire on an-// email nobody received.+// sequence rather than restarting it. The old `findIndex` returned -1 for a+// renamed or removed step, which silently sent the subject back to step 0. 2.+// `'skip'` advances past a step; `false` only defers it. The old code had one+// value for both, so a step that should be passed over stalled the sequence+// permanently. 3. `requireDelivery` refuses to advance unless the email+// actually went out. `sendEmail` returns null instead of throwing when a send+// is suppressed or misconfigured, so a step with side effects could otherwise+// fire on an email nobody received.import { differenceInDays } from 'date-fns';import {diff --git a/packages/core/src/modules/event/event.constants.ts b/packages/core/src/modules/event/event.constants.tsindex b6ae4fe78..975bb2c3d 100644--- a/packages/core/src/modules/event/event.constants.ts+++ b/packages/core/src/modules/event/event.constants.ts@@ -1,8 +1,7 @@-// Isomorphic vocabulary for the event module (ADR-022 R8). These are column-// whitelists, not query logic — moved here from event.service.ts / src/sql.ts-// so a value-import (mcp's property-values tool today; a future dashboard-// form tomorrow) has a `*.constants.ts` to reach instead of a service or-// query-builder file.+// Isomorphic vocabulary for the event module. These are column whitelists, not+// query logic — moved here from event.service.ts / src/sql.ts so a value-import+// (mcp's property-values tool today; a future dashboard form tomorrow) has a+// `*.constants.ts` to reach instead of a service or query-builder file./*** Top-level filterable columns on the `events` table. These apply todiff --git a/packages/core/src/modules/event/event.jobs.ts b/packages/core/src/modules/event/event.jobs.tsindex 9a7132b3e..4ab45a453 100644--- a/packages/core/src/modules/event/event.jobs.ts+++ b/packages/core/src/modules/event/event.jobs.ts@@ -1,8 +1,8 @@// Ported from apps/worker/src/jobs/cron.ts's `flushEvents` case +-// boot-cron.ts's `flush`/`flushEvents` schedule (M8-004); the schedule moved-// onto the job at ADR-021 (M10-007). The event buffer (Redis → ClickHouse-// `events`) is this module's domain, so its flush cron fragment lives here-// rather than on the ingest module that merely writes to it.+// boot-cron.ts's `flush`/`flushEvents` schedule; the schedule moved onto the+// job at ADR-021. The event buffer (Redis → ClickHouse `events`) is this+// module's domain, so its flush cron fragment lives here rather than on the+// ingest module that merely writes to it.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/event/event.rpc.ts b/packages/core/src/modules/event/event.rpc.tsindex 5f825483b..2bca0e82a 100644--- a/packages/core/src/modules/event/event.rpc.ts+++ b/packages/core/src/modules/event/event.rpc.ts@@ -1,11 +1,10 @@-// Ported from packages/trpc/src/routers/event.ts (M7-002).+// Ported from packages/trpc/src/routers/event.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// `bots` was V1's only `publicProcedure` here (anonymous callers were let in// when a share-overview row existed); ADR-011 makes it protected.@@ -40,11 +39,11 @@ const DEFAULT_BOTS_LIMIT = 8;/*** `pagesTimeseries` returns every page in the project, so its size is the- * project's page cardinality, not its traffic: unbounded it is 5,050,763 rows- * / 486 MiB on the busiest anchor (M31-002). 50 is enough to carry any chart- * legend or table page the result could feed, and caps the response at- * `50 x buckets`. The origin+path-filtered `pageTimeseries` below is bounded- * by its own filters and stays unbounded here.+ * project's page cardinality, not its traffic: unbounded it is 5,050,763 rows /+ * 486 MiB on the busiest anchor. 50 is enough to carry any chart legend or+ * table page the result could feed, and caps the response at `50 x buckets`.+ * The origin+path-filtered `pageTimeseries` below is bounded by its own filters+ * and stays unbounded here.*/const PAGES_TIMESERIES_TOP_PAGES_PER_BUCKET = 50;diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.tsindex 663e25359..9930073e1 100644--- a/packages/core/src/modules/event/event.service.ts+++ b/packages/core/src/modules/event/event.service.ts@@ -1,6 +1,6 @@-// The event read path. Every query is a `sql` fragment (src/sql.ts), per-// ADR-013; the two filter compilers (`getEventFiltersWhereClause`,-// `buildFilterWhere`) are shared, and src/filter-clauses.ts is the bridge.+// The event read path. Every query is a `sql` fragment (src/sql.ts); the two+// filter compilers (`getEventFiltersWhereClause`, `buildFilterWhere`) are+// shared, and src/filter-clauses.ts is the bridge.import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import type { EventMeta, Prisma } from '@openpanel/db/src/prisma-client';diff --git a/packages/core/src/modules/event/src/create-event-id.test.ts b/packages/core/src/modules/event/src/create-event-id.test.tsindex 755c1a135..70774ba73 100644--- a/packages/core/src/modules/event/src/create-event-id.test.ts+++ b/packages/core/src/modules/event/src/create-event-id.test.ts@@ -1,7 +1,7 @@-// Ported from packages/db/src/services/create-event-id.test.ts (M7-002).-// M10-005: `createEvent` takes `ServiceDeps` and writes through-// `deps.buffers.event`, so the buffer is handed in rather than mocked onto a-// module specifier — no `mock.module` and no restore to get wrong.+// Ported from packages/db/src/services/create-event-id.test.ts. M10-005:+// `createEvent` takes `ServiceDeps` and writes through `deps.buffers.event`, so+// the buffer is handed in rather than mocked onto a module specifier — no+// `mock.module` and no restore to get wrong.import { beforeAll, describe, expect, mock, test } from 'bun:test';import type { ServiceDeps } from '../../../services';diff --git a/packages/core/src/modules/event/src/sql.ts b/packages/core/src/modules/event/src/sql.tsindex f25942713..a84fcc144 100644--- a/packages/core/src/modules/event/src/sql.ts+++ b/packages/core/src/modules/event/src/sql.ts@@ -1,16 +1,15 @@-// Every ClickHouse query the event module runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse query the event module runs, as pure `sql` fragments.//// Dates bind as `YYYY-MM-DD HH:mm:ss` strings on purpose: a String param in a// DateTime64 position is parsed exactly like the literal it replaces, so the// result sets cannot drift by a millisecond truncation.//-// Cluster note: `events`, `profiles`, `groups` and-// `cohort_members` are Distributed on Cloud. The identity-stitching and cohort-// `IN (SELECT ...)` subqueries, the profile/group LEFT ANY JOINs and any-// `IN (SELECT ...)` a filter compiles keep V1's exact shape and run under the-// client's `distributed_product_mode: 'allow'` as before — converting a query-// is not the place to change its cluster semantics. Every `IN` list binds as+// Cluster note: `events`, `profiles`, `groups` and `cohort_members` are+// Distributed on Cloud. The identity-stitching and cohort `IN (SELECT...)`+// subqueries, the profile/group LEFT ANY JOINs and any `IN (SELECT...)` a+// filter compiles keep V1's exact shape and run under the client's+// `distributed_product_mode: 'allow'` as before — converting a query is not the+// place to change its cluster semantics. Every `IN` list binds as// `Array(String)`, a literal list to the planner.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/export/export.routes.ts b/packages/core/src/modules/export/export.routes.tsindex c9347c5c3..0823efa71 100644--- a/packages/core/src/modules/export/export.routes.ts+++ b/packages/core/src/modules/export/export.routes.ts@@ -1,30 +1,29 @@// Ported from apps/api/src/routes/export.router.ts + insights.router.ts and-// their controllers (M7-007). V1's Fastify routes stay the LIVE surface-// (DELEGATE PATTERN) and already call these same `@openpanel/db`-re-exported-// `*Core` functions (M7-001..006 moved the implementations; the V1-// controllers were updated to delegate as each module landed). This file is-// the same surface rebuilt on Elysia, so the target port has somewhere to-// land at P8 without redesigning the API it replaces — no new query logic,-// every call below is the same function V1's controller calls.+// their controllers. V1's Fastify routes stay the LIVE surface (DELEGATE+// PATTERN) and already call these same `@openpanel/db`-re-exported `*Core`+// functions (M7-001..006 moved the implementations; the V1 controllers were+// updated to delegate as each module landed). This file is the same surface+// rebuilt on Elysia, so the target port has somewhere to land at P8 without+// redesigning the API it replaces — no new query logic, every call below is the+// same function V1's controller calls.//// `allow: ['read', 'root']` mirrors V1's rule (utils/auth.ts's// `validateExportRequest`, shared by both `/export` and `/insights`: a// `write`-type client may not read analytics back out).//-// M9-004 mounted this surface and landed the missing half: V1's-// `parseQueryString` pre-pass is now `http/query.ts`'s `transform` hook,-// registered LOCAL on both surfaces below. Every zod schema here is the one V1-// validates AFTER that hook runs, so without it a plain `?limit=5` fails-// validation.+// Mounted this surface and landed the missing half: V1's `parseQueryString`+// pre-pass is now `http/query.ts`'s `transform` hook, registered LOCAL on both+// surfaces below. Every zod schema here is the one V1 validates AFTER that hook+// runs, so without it a plain `?limit=5` fails validation.//// `listDashboards`/`listReports` (insights.controller.ts) are mounted under-// `/manage/projects/:projectId/dashboards[...]` in V1 (manage.router.ts) —-// that surface belongs to the project module, not here.+// `/manage/projects/:projectId/dashboards[...]` in V1 (manage.router.ts) — that+// surface belongs to the project module, not here.//-// The 18 `overviewColumns` routes are written out rather than looped: a-// mutable reassignment of the Elysia chain inside a `for` loop widens past-// what `defineRoutes`'s `const T` inference can carry, same reason every-// other module here writes its routes as one static `.get()`/`.post()` chain.+// The 18 `overviewColumns` routes are written out rather than looped: a mutable+// reassignment of the Elysia chain inside a `for` loop widens past what+// `defineRoutes`'s `const T` inference can carry, same reason every other+// module here writes its routes as one static `.get`/`.post` chain.import { DateTime } from '@openpanel/shared';import { z } from 'zod';diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.tsindex 70f02b1cc..ea92575e4 100644--- a/packages/core/src/modules/export/export.service.ts+++ b/packages/core/src/modules/export/export.service.ts@@ -4,14 +4,13 @@// event/session/profile/group/gsc/report services already ported to core// (M7-001..006). This file holds only the plumbing every route shares —// resolving a project id and a date range — ported verbatim from-// apps/api/src/controllers/{export,insights}.controller.ts. No new query-// logic: every resolution here already existed in V1's controllers.+// apps/api/src/controllers/{export,insights}.controller.ts. No new query logic:+// every resolution here already existed in V1's controllers.//-// M10-003: `loadDb()` and `loadCore()` are gone. Postgres is `deps.db`, and-// the sibling services these routes delegate to are imported by RELATIVE-// path — the hazard the old `loadCore()` guarded against was re-entering-// this package's own barrel (`@openpanel/core`) mid-evaluation, which a-// relative import cannot do (docs/TECH_DEBT.md §4).+// `loadDb` and `loadCore` are gone. Postgres is `deps.db`, and the sibling+// services these routes delegate to are imported by RELATIVE path — the hazard+// the old `loadCore` guarded against was re-entering this package's own barrel+// (`@openpanel/core`) mid-evaluation, which a relative import cannot do.import { resolveDateRange } from '@openpanel/shared';import type { AuthenticatedClient } from '../../http/client-auth';@@ -73,8 +72,8 @@ export async function resolveExportProjectId(/*** `/insights/:projectId/*`'s project-id resolution — `resolveClientProjectId`- * is the single client->project resolution point (ADR-011 A-iii invariant- * 12), already what apps/api's insights.controller.ts `getProjectId` calls.+ * is the single client->project resolution point (ADR-011 A-iii invariant 12),+ * already what apps/api's insights.controller.ts `getProjectId` calls.*/export async function resolveInsightsProjectId(deps: ServiceDeps,diff --git a/packages/core/src/modules/group/group.constants.ts b/packages/core/src/modules/group/group.constants.tsindex 6383218c3..79ef9a20b 100644--- a/packages/core/src/modules/group/group.constants.ts+++ b/packages/core/src/modules/group/group.constants.ts@@ -1,5 +1,5 @@-// Moved from packages/validation/src/index.ts (M7-002, ADR-008's module map:-// group owns "C"). validation's index re-exports this file's+// Moved from packages/validation/src/index.ts (ADR-008's module map: group owns+// "C"). validation's index re-exports this file's// `./modules/group/group.constants` subpath, so packages/trpc's group router// and apps/start's add-group / edit-group modals keep resolving these symbols// through packages/validation unchanged.diff --git a/packages/core/src/modules/group/group.jobs.ts b/packages/core/src/modules/group/group.jobs.tsindex a563b1c30..1e573b364 100644--- a/packages/core/src/modules/group/group.jobs.ts+++ b/packages/core/src/modules/group/group.jobs.ts@@ -1,7 +1,7 @@// Ported from apps/worker/src/jobs/cron.ts's `flushGroups` case +-// boot-cron.ts's `flush`/`flushGroups` schedule (M8-004); the schedule moved-// onto the job at ADR-021 (M10-007). The group buffer (Redis → ClickHouse-// `groups`) is this module's domain.+// boot-cron.ts's `flush`/`flushGroups` schedule; the schedule moved onto the+// job at ADR-021. The group buffer (Redis → ClickHouse `groups`) is this+// module's domain.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/group/group.rpc.ts b/packages/core/src/modules/group/group.rpc.tsindex 610165710..17af9268e 100644--- a/packages/core/src/modules/group/group.rpc.ts+++ b/packages/core/src/modules/group/group.rpc.ts@@ -1,11 +1,11 @@-// Ported from packages/trpc/src/routers/group.ts (M7-002).+// Ported from packages/trpc/src/routers/group.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. Every procedure below carries a-// top-level `projectId`, so `enforceAccess` already covers it (ADR-011) - the-// explicit `requireProjectAccess` calls in the handlers are the tree-wide-// M15-007 pattern (ADR-022 R10), not the resolved-from-another-id exception.+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. Every procedure below carries a top-level `projectId`, so+// `enforceAccess` already covers it - the explicit `requireProjectAccess` calls+// in the handlers are the tree-wide M15-007 pattern, not the+// resolved-from-another-id exception.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/group/group.service.ts b/packages/core/src/modules/group/group.service.tsindex 073fd361c..c532eae24 100644--- a/packages/core/src/modules/group/group.service.ts+++ b/packages/core/src/modules/group/group.service.ts@@ -1,4 +1,4 @@-// Every query is a `sql` fragment (src/sql.ts), per ADR-013. The one write+// Every query is a `sql` fragment (src/sql.ts). The one write// (`writeGroupToCh`) goes through `deps.ch.insert`.import { toDots } from '@openpanel/shared';diff --git a/packages/core/src/modules/group/src/sql.ts b/packages/core/src/modules/group/src/sql.tsindex 5fa2a1005..6b70424a8 100644--- a/packages/core/src/modules/group/src/sql.ts+++ b/packages/core/src/modules/group/src/sql.ts@@ -1,9 +1,8 @@-// Every ClickHouse query the group module runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse query the group module runs, as pure `sql` fragments.//-// Cluster note: `groups`, `profiles` and `events` are-// Distributed on Cloud. No query here carries an `IN (subquery)`; the `IN`-// lists bind as `Array(String)` params, which is a literal list to the planner.+// Cluster note: `groups`, `profiles` and `events` are Distributed on Cloud. No+// query here carries an `IN (subquery)`; the `IN` lists bind as `Array(String)`+// params, which is a literal list to the planner.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.tsindex 6111dd2ab..5ed8084f1 100644--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts@@ -217,8 +217,8 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async});// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot pins-// (apps/worker/src/boot-cron.ts). The cadence now lives on the job itself-// (ADR-021), so this reads it straight off the registry.+// (apps/worker/src/boot-cron.ts). The cadence now lives on the job itself, so+// this reads it straight off the registry.test('the gsc cron fragment carries V1 id and cadence unchanged', () => {expect(queues.cron.jobs.gscSync.cron).toEqual({ pattern: '0 3 * * *' });});diff --git a/packages/core/src/modules/gsc/gsc.jobs.ts b/packages/core/src/modules/gsc/gsc.jobs.tsindex ceab165f8..c989fffdb 100644--- a/packages/core/src/modules/gsc/gsc.jobs.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.ts@@ -1,10 +1,10 @@-// Ported from apps/worker/src/jobs/gsc.ts + boot-cron.ts's gscSync schedule-// (M5-002); the schedule moved onto the job at ADR-021 (M10-007).+// Ported from apps/worker/src/jobs/gsc.ts + boot-cron.ts's gscSync schedule;+// the schedule moved onto the job at ADR-021.//-// `gscProjectSync` / `gscProjectBackfill` are this module's own queue (`gsc`-// in the registry — ADR-005's registry key). `gscSync` is a cron fragment,-// spread into the ONE `cron` queue by jobs.registry.ts. Scheduler id and-// cadence are V1's, unchanged (apps/worker/src/boot-cron.ts).+// `gscProjectSync` / `gscProjectBackfill` are this module's own queue (`gsc` in+// the registry — ADR-005's registry key). `gscSync` is a cron fragment, spread+// into the ONE `cron` queue by jobs.registry.ts. Scheduler id and cadence are+// V1's, unchanged (apps/worker/src/boot-cron.ts).import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/gsc/gsc.routes.ts b/packages/core/src/modules/gsc/gsc.routes.tsindex b4044ad25..5a7b20be0 100644--- a/packages/core/src/modules/gsc/gsc.routes.ts+++ b/packages/core/src/modules/gsc/gsc.routes.ts@@ -1,13 +1,13 @@-// The GSC OAuth callback (M5-002). V1's Fastify controller+// The GSC OAuth callback. V1's Fastify controller// (apps/api/src/controllers/gsc-oauth-callback.controller.ts) stays the LIVE// route (DELEGATE PATTERN) and delegates its token-exchange/upsert logic to// gsc.service.ts's `completeGscOAuthCallback` — the same function this route// calls. This route is not yet reachable: main.ts does not mount// `dashboardRoutes` until a real `AppDeps` exists (P3/P4/P8).//-// NAMED GAP: per-route cookie signing is not wired yet (http/context.ts:147-// — "app.ts lists the signed names (P3)"), so `ctx.cookies.get()` here reads-// the raw, unsigned cookie value. V1's Fastify controller still verifies the+// NAMED GAP: per-route cookie signing is not wired yet (http/context.ts:147 —+// "app.ts lists the signed names (P3)"), so `ctx.cookies.get` here reads the+// raw, unsigned cookie value. V1's Fastify controller still verifies the// signature; this route only re-checks the state match, and should not be// treated as a signature-verified equivalent until that wiring lands.diff --git a/packages/core/src/modules/gsc/gsc.rpc.ts b/packages/core/src/modules/gsc/gsc.rpc.tsindex 7859cc521..69edc2f57 100644--- a/packages/core/src/modules/gsc/gsc.rpc.ts+++ b/packages/core/src/modules/gsc/gsc.rpc.ts@@ -1,14 +1,13 @@-// Ported from packages/trpc/src/routers/gsc.ts (M5-002).+// Ported from packages/trpc/src/routers/gsc.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// The per-project access ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The per-project access ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/gsc/gsc.service.test.ts b/packages/core/src/modules/gsc/gsc.service.test.tsindex 47aecfad7..e01a892f4 100644--- a/packages/core/src/modules/gsc/gsc.service.test.ts+++ b/packages/core/src/modules/gsc/gsc.service.test.ts@@ -85,9 +85,9 @@ const project = {findUnique: mock(async ({ where: { id } }: { where: { id: string } }) =>id === 'proj_missing' ? null : { id, organizationId: 'org_1' }),- // `resolveGscDateRange` reaches organization.service's `getSettingsForProject`- // over the SAME deps (M10-009), which reads the project's organization- // rather than going through a mocked module.+ // `resolveGscDateRange` reaches organization.service's+ // `getSettingsForProject` over the SAME deps, which reads the project's+ // organization rather than going through a mocked module.findUniqueOrThrow: mock(async () => ({organization: { timezone: 'UTC' },})),@@ -99,12 +99,11 @@ const ch = {insert: mock(async () => undefined),};-// 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 `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+// The subject's functions take `ServiceDeps`, so `deps.db`/`deps.ch` ARE the+// fakes above — no `@openpanel/db` module mock is needed for either. The one+// module still mocked is core's own `ch-query`, which is what the subject now+// calls. `mock.module` has no per-file scope under bare `bun test` (AGENTS.md),+// so snapshot the real module into a plain object FIRST and restore it in// afterAll — restoring via the live import binding would re-apply the mock.const realChQuery = { ...(await import('../../ch-query')) };mock.module('../../ch-query', () => ({@@ -153,11 +152,11 @@ const validateAuthorizationCode = mock(async () => ({accessTokenExpiresAt: () => new Date('2026-09-04T00:00:00.000Z'),}));// Spread the real module — see the clickhouse/client mock above for why a-// partial factory here is a process-wide hazard, not a local one. Surfaced-// by M6-001: @openpanel/db's organization.service.ts shim (imported below)-// now re-exports from @openpanel/core's full barrel, which reaches this-// same auth.service.ts for createAuthService — a partial replacement here-// used to be invisible because nothing else in this file's chain needed it.+// partial factory here is a process-wide hazard, not a local one. Surfaced by+// M6-001: @openpanel/db's organization.service.ts shim (imported below) now+// re-exports from @openpanel/core's full barrel, which reaches this same+// auth.service.ts for createAuthService — a partial replacement here used to be+// invisible because nothing else in this file's chain needed it.const actualAuthService = await import('../auth/auth.service');mock.module('../auth/auth.service', () => ({...actualAuthService,@@ -171,12 +170,12 @@ const getChartStartEndDate = mock(() => ({startDate: '2026-09-01T00:00:00.000Z',endDate: '2026-09-03T00:00:00.000Z',}));-// M10-009: `resolveGscDateRange` reaches these two through the DEEP modules-// they live in, not through this package's barrel (`core-no-self-barrel`), so-// that is what has to be mocked — mocking `@openpanel/core` would no longer-// intercept anything. Each factory spreads its real module: `mock.module`-// replaces a specifier process-wide under bare `bun test` (AGENTS.md), and-// both are restored from a plain-object snapshot in afterAll below.+// `resolveGscDateRange` reaches these two through the DEEP modules they live+// in, not through this package's barrel (`core-no-self-barrel`), so that is+// what has to be mocked — mocking `@openpanel/core` would no longer intercept+// anything. Each factory spreads its real module: `mock.module` replaces a+// specifier process-wide under bare `bun test` (AGENTS.md), and both are+// restored from a plain-object snapshot in afterAll below.const realOrganizationService = {...(await import('../organization/organization.service')),};diff --git a/packages/core/src/modules/gsc/gsc.service.ts b/packages/core/src/modules/gsc/gsc.service.tsindex 3e62925fd..602d10554 100644--- a/packages/core/src/modules/gsc/gsc.service.ts+++ b/packages/core/src/modules/gsc/gsc.service.ts@@ -1,17 +1,16 @@-// Moved from packages/db/src/gsc.ts + packages/db/src/services/gsc.service.ts-// (M5-002) — the GSC OAuth token lifecycle, the Search Console API client,-// ClickHouse read/write, the AI-tool wrapper functions and the+// Moved from packages/db/src/gsc.ts + packages/db/src/services/gsc.service.ts —+// the GSC OAuth token lifecycle, the Search Console API client, ClickHouse+// read/write, the AI-tool wrapper functions and the// gscProjectSync/gscProjectBackfill job bodies. packages/db/src/gsc.ts and-// packages/db/src/services/gsc.service.ts become re-export shims of this-// file (same shape as packages/db/src/encryption.ts since M4-006).+// packages/db/src/services/gsc.service.ts become re-export shims of this file+// (same shape as packages/db/src/encryption.ts since M4-006).//-// M10-009: every exported function takes `ServiceDeps` and reaches Postgres-// as `deps.db` and ClickHouse as `deps.ch`; the `loadDb()`/`loadChClient()`-// lazy loaders are gone, so the requestId minted at the edge reaches the query-// (ADR-018, docs/TECH_DEBT.md §4). `getGscCannibalization` is `cacheablePerDeps`-// (M15-004): `cacheable` keys on the call's ARGUMENTS-// (packages/redis/cachable.ts), so the caller's deps travel beside the key-// rather than inside it and the Redis key stays byte-identical.+// Every exported function takes `ServiceDeps` and reaches Postgres as `deps.db`+// and ClickHouse as `deps.ch`; the `loadDb`/`loadChClient` lazy loaders are+// gone, so the requestId minted at the edge reaches the query.+// `getGscCannibalization` is `cacheablePerDeps`: `cacheable` keys on the call's+// ARGUMENTS (packages/redis/cachable.ts), so the caller's deps travel beside+// the key rather than inside it and the Redis key stays byte-identical.//// DELIBERATE BEHAVIOUR CHANGE, recorded: the reads and the four sync inserts// used @openpanel/db's `originalCh` (the first configured node, no retry).@@ -20,9 +19,9 @@// (`wait_end_of_query`, insert block size) to those inserts. Same rows, same// tables; strictly more failover.//-// ClickHouse queries here still go through raw SQL strings, not the `sql`-// tag: ADR-013 converts the analytics read path one query per P7 task, and-// this module's queries haven't been converted yet.+// ClickHouse queries here still go through raw SQL strings, not the `sql` tag:+// ADR-013 converts the analytics read path one query per P7 task, and this+// module's queries haven't been converted yet.import type { ClickHouseSettings } from '@clickhouse/client';import { decrypt, encrypt } from '@openpanel/shared/server';@@ -718,9 +717,9 @@ export async function getGscQueries(return result.json();}-// ---------------------------------------------------------------------------+// --------------------------------------------------------------------------// Connection CRUD — moved from packages/trpc/src/routers/gsc.ts's-// getConnection/selectSite/disconnect handler bodies (M5-002).+// getConnection/selectSite/disconnect handler bodies.// ---------------------------------------------------------------------------export interface GscConnectionSummary {@@ -779,10 +778,10 @@ export async function disconnectGscConnection(await db.gscConnection.deleteMany({ where: { projectId } });}-// ----------------------------------------------------------------------------// Dashboard aggregate queries — moved from packages/trpc/src/routers/gsc.ts-// (M5-002). The trpc router itself stays on V1 (DELEGATE PATTERN); this is-// its date-resolution and search/AI-engine breakdown logic.+// --------------------------------------------------------------------------+// Dashboard aggregate queries — moved from packages/trpc/src/routers/gsc.ts.+// The trpc router itself stays on V1 (DELEGATE PATTERN); this is its+// date-resolution and search/AI-engine breakdown logic.// ---------------------------------------------------------------------------export interface GscDateRangeInput {@@ -1282,9 +1281,9 @@ export async function gscGetCannibalizationCore();}-// ----------------------------------------------------------------------------// Job bodies — moved from apps/worker/src/jobs/gsc.ts (M5-002). Each fully-// owns its status-update bookkeeping so the worker file is a bare dispatch.+// --------------------------------------------------------------------------+// Job bodies — moved from apps/worker/src/jobs/gsc.ts. Each fully owns its+// status-update bookkeeping so the worker file is a bare dispatch.// ---------------------------------------------------------------------------/** The `gscSync` cron fan-out: every project with a connected GSC site. */@@ -1420,11 +1419,11 @@ export async function runGscProjectBackfill(}}-// ---------------------------------------------------------------------------+// --------------------------------------------------------------------------// OAuth callback — moved from apps/api/src/controllers/gsc-oauth-callback.-// controller.ts's business logic (M5-002). Cookie reading/signing and the-// redirect stay with each transport (Fastify today, Elysia's gsc.routes.ts-// once it is live) — this is the part that is transport-agnostic.+// controller.ts's business logic. Cookie reading/signing and the redirect stay+// with each transport (Fastify today, Elysia's gsc.routes.ts once it is live) —+// this is the part that is transport-agnostic.// ---------------------------------------------------------------------------export interface GscOAuthCallbackInput {diff --git a/packages/core/src/modules/health/health.routes.ts b/packages/core/src/modules/health/health.routes.tsindex 9de4345ff..b8f279d37 100644--- a/packages/core/src/modules/health/health.routes.ts+++ b/packages/core/src/modules/health/health.routes.ts@@ -6,8 +6,8 @@// `AppDeps` started carrying the real clients; before that, porting it would// have been a fake check rather than a deferred one. `/healthz/ready` never// waited for them: its two inputs are the shutdown flag and the events-consumer-// heartbeat, both real from P9 (M9-002), and a readiness probe that ignores a-// draining process is the one that actually loses requests.+// heartbeat, both real from P9, and a readiness probe that ignores a draining+// process is the one that actually loses requests.//// `GET /` lands here too: V1 served it from the public-API scope// (apps/api/src/app.ts:400), hidden from the OpenAPI document like the probes,@@ -19,11 +19,11 @@ import { chQuery } from '../../ch-query';import { defineRoutes } from '../../http/define';import { currentReadiness } from './src/readiness';-// The first zod schema through the OpenAPI plugin (ADR-003): response schemas-// generate with `io: 'output'`, which is what zod 4's native Standard Schema-// JSON conversion does by default for the `response` slot — no-// `mapJsonSchema` override needed, and none is added, because that hook gets-// no `io` argument and would collapse the input/output split the ADR requires.+// The first zod schema through the OpenAPI plugin: response schemas generate+// with `io: 'output'`, which is what zod 4's native Standard Schema JSON+// conversion does by default for the `response` slot — no `mapJsonSchema`+// override needed, and none is added, because that hook gets no `io` argument+// and would collapse the input/output split the ADR requires.const healthLiveResponseSchema = z.object({ live: z.literal(true) });// V1's two readiness bodies, verbatim: `{ready:true}` at 200, and@@ -86,9 +86,9 @@ export const healthRoutes = defineRoutes((app) =>.get('/healthcheck',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 ch-query.ts).+ // Core's own `chQuery` over `ctx.ch` — the same round-robin + retry+ // proxy every real read takes (`ctx.ch.query` IS `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/health/health.rpc.ts b/packages/core/src/modules/health/health.rpc.tsindex cd23d97b0..a6b9c6375 100644--- a/packages/core/src/modules/health/health.rpc.ts+++ b/packages/core/src/modules/health/health.rpc.ts@@ -3,12 +3,11 @@// router named `health` exists; the 28 real ones arrived with their module// waves (P5-P8). Public, as a liveness probe has to be.//-// R2 (M15-111): no frontend caller exists for this procedure, and by the-// letter of the rule a health module is routes-only. Left in place — see the-// M15-111 report — because `../../rpc.router.test.ts:16-34` pins this exact-// procedure ("the composed appRouter serves the health procedure", asserting-// a 200 from `/trpc/health.live`), and that file is outside this module's-// scope to edit.+// R2: no frontend caller exists for this procedure, and by the letter of the+// rule a health module is routes-only. Left in place — see the M15-111 report —+// because `../../rpc.router.test.ts:16-34` pins this exact procedure ("the+// composed appRouter serves the health procedure", asserting a 200 from+// `/trpc/health.live`), and that file is outside this module's scope to edit.import { createTRPCRouter, publicProcedure } from '../../rpc/base';export const healthRouter = createTRPCRouter({diff --git a/packages/core/src/modules/import/import.constants.ts b/packages/core/src/modules/import/import.constants.tsindex 3af36ad88..9d4a5a1bf 100644--- a/packages/core/src/modules/import/import.constants.ts+++ b/packages/core/src/modules/import/import.constants.ts@@ -1,7 +1,7 @@// Moved from packages/validation/src/index.ts + packages/importer/src/-// providers/metadata.ts (M5-004, ADR-008's module map: import owns "C").-// packages/validation/src/import.validation.ts becomes a re-export shim of-// this file (same shape as packages/validation/src/cohort.validation.ts since+// providers/metadata.ts (ADR-008's module map: import owns "C").+// packages/validation/src/import.validation.ts becomes a re-export shim of this+// file (same shape as packages/validation/src/cohort.validation.ts since// M5-003), so apps/start and packages/db/src/types.ts keep resolving these// symbols through packages/validation's existing barrel unchanged.//diff --git a/packages/core/src/modules/import/import.jobs.ts b/packages/core/src/modules/import/import.jobs.tsindex 7e33d34dc..99ce92a5a 100644--- a/packages/core/src/modules/import/import.jobs.ts+++ b/packages/core/src/modules/import/import.jobs.ts@@ -1,15 +1,15 @@-// Ported from apps/worker/src/jobs/import.ts (M5-004).+// Ported from apps/worker/src/jobs/import.ts.//-// `import` is this module's own queue AND its only job — the registry key,-// the Redis name and the BullMQ job name are all `import`-// (legacyCompat.import already discriminates on `{type: 'import', payload}`,-// jobs/compat.ts). Unlike gsc/cohort/insight, this queue has no cron-// fragment: imports are always user-triggered (import.rpc.ts's create/retry).+// `import` is this module's own queue AND its only job — the registry key, the+// Redis name and the BullMQ job name are all `import` (legacyCompat.import+// already discriminates on `{type: 'import', payload}`, jobs/compat.ts). Unlike+// gsc/cohort/insight, this queue has no cron fragment: imports are always+// user-triggered (import.rpc.ts's create/retry).//// Core's own worker has no live BullMQ job to hand `updateImportStatus` for-// progress reporting (see import.service.ts's `ImportJobProgress` header),-// so this handler runs with the no-op default — inert until ADR-007's P9-// worker cutover, same as gsc/cohort/insight's job handlers today.+// progress reporting (see import.service.ts's `ImportJobProgress` header), so+// this handler runs with the no-op default — inert until ADR-007's P9 worker+// cutover, same as gsc/cohort/insight's job handlers today.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/import/import.routes.ts b/packages/core/src/modules/import/import.routes.tsindex 760390f98..5a83626d1 100644--- a/packages/core/src/modules/import/import.routes.ts+++ b/packages/core/src/modules/import/import.routes.ts@@ -1,19 +1,19 @@// Ported from apps/api/src/routes/import.router.ts +-// apps/api/src/controllers/import.controller.ts's business logic (M5-004).-// V1's Fastify controller stays the LIVE route (DELEGATE PATTERN) and-// delegates its ClickHouse insert to import.service.ts's-// `insertRawEventsBatch` — the same function this route calls.+// apps/api/src/controllers/import.controller.ts's business logic. V1's Fastify+// controller stays the LIVE route (DELEGATE PATTERN) and delegates its+// ClickHouse insert to import.service.ts's `insertRawEventsBatch` — the same+// function this route calls.//// NAMED GAP, same as gsc.routes.ts: this route is 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;-// main.ts also does not mount `publicApiRoutes` until a real `AppDeps`-// exists. `allow: ['read', 'root']` mirrors V1's rule (utils/auth.ts's-// `validateImportRequest`: a `write`-type client may not import).+// `authenticateClient` (http/client-auth.ts) is a P8 stub that always returns+// null, so `clientAuth` 401s every request until it is filled in; main.ts also+// does not mount `publicApiRoutes` until a real `AppDeps` exists. `allow:+// ['read', 'root']` mirrors V1's rule (utils/auth.ts's `validateImportRequest`:+// a `write`-type client may not import).//-// V1 has no request-body schema for this route (ADR-003: "/profile,-// /import, /event and /tools have no request schemas today, and adding them-// would be a behaviour change"), so the body is typed but not shape-validated.+// V1 has no request-body schema for this route (ADR-003: "/profile, /import,+// /event and /tools have no request schemas today, and adding them would be a+// behaviour change"), so the body is typed but not shape-validated.//// `client.projectId` is `null` for a root client (M6-002 widened// AuthenticatedClient to match IServiceClientWithProject); V1's controllerdiff --git a/packages/core/src/modules/import/import.rpc.ts b/packages/core/src/modules/import/import.rpc.tsindex 90024e3f7..33e0c7907 100644--- a/packages/core/src/modules/import/import.rpc.ts+++ b/packages/core/src/modules/import/import.rpc.ts@@ -1,19 +1,18 @@-// Ported from packages/trpc/src/routers/import.ts (M5-004).+// Ported from packages/trpc/src/routers/import.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// V1's router has no compute-heavy or ClickHouse-touching logic to delegate-// (it is Prisma CRUD + a BullMQ enqueue, unlike gsc/cohort), so+// V1's router has no compute-heavy or ClickHouse-touching logic to delegate (it+// is Prisma CRUD + a BullMQ enqueue, unlike gsc/cohort), so// packages/trpc/src/routers/import.ts stays completely unmodified — there is// nothing here for it to delegate to.//-// The per-project access ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The per-project access ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.tsindex 959c956f0..df5cc5330 100644--- a/packages/core/src/modules/import/import.service.test.ts+++ b/packages/core/src/modules/import/import.service.test.ts@@ -1,8 +1,8 @@-// M10-009: import.service.ts takes its clients from `ServiceDeps`, so this-// file hands in fakes as `deps.db` / `deps.ch` and mocks NO module at all.-// That is the point of the conversion: a module mock of-// `@openpanel/db/src/clickhouse/client` replaced that specifier for every-// other FILE in the process (bare `bun test` shares one module registry).+// Import.service.ts takes its clients from `ServiceDeps`, so this file hands in+// fakes as `deps.db` / `deps.ch` and mocks NO module at all. That is the point+// of the conversion: a module mock of `@openpanel/db/src/clickhouse/client`+// replaced that specifier for every other FILE in the process (bare `bun test`+// shares one module registry).import { beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';diff --git a/packages/core/src/modules/import/import.service.ts b/packages/core/src/modules/import/import.service.tsindex df29873dc..0357d3459 100644--- a/packages/core/src/modules/import/import.service.ts+++ b/packages/core/src/modules/import/import.service.ts@@ -1,18 +1,18 @@// Moved from packages/db/src/services/import.service.ts (the ClickHouse-// staging/session pipeline) + apps/worker/src/jobs/import.ts (the job body-// and provider dispatch) + apps/api/src/controllers/import.controller.ts-// (the /import/events bulk-insert path) — M5-004, ADR-008's module map:-// import owns "S". packages/db/src/services/import.service.ts is deleted-// outright: nothing outside the worker job file it moves with reached it-// through @openpanel/db's barrel (same as cohort.service.ts, M5-003).+// staging/session pipeline) + apps/worker/src/jobs/import.ts (the job body and+// provider dispatch) + apps/api/src/controllers/import.controller.ts (the+// /import/events bulk-insert path) — M5-004, ADR-008's module map: import owns+// "S". packages/db/src/services/import.service.ts is deleted outright: nothing+// outside the worker job file it moves with reached it through @openpanel/db's+// barrel (same as cohort.service.ts).//-// db/ch access is LAZY (`load*` below), not a static top-level import — see+// Db/ch access is LAZY (`load*` below), not a static top-level import — see// gsc.service.ts's header for the full reasoning (jobs.registry.ts and// services.ts pull this module into the eager barrel chain nearly every core-// test file reaches). The provider classes are behind a dynamic `import()`-// for the same reason: they eagerly import `formatClickhouseDate` from-// @openpanel/db's clickhouse client, which constructs a real pino transport-// at import time.+// test file reaches). The provider classes are behind a dynamic `import` for+// the same reason: they eagerly import `formatClickhouseDate` from+// @openpanel/db's clickhouse client, which constructs a real pino transport at+// import time.//// ClickHouse queries here still go through raw `ch`/`chQuery` calls, not the// `sql` tag: ADR-013 converts the analytics read path one query per P7 task,diff --git a/packages/core/src/modules/import/src/providers/umami.ts b/packages/core/src/modules/import/src/providers/umami.tsindex 872251c4c..267d837f2 100644--- a/packages/core/src/modules/import/src/providers/umami.ts+++ b/packages/core/src/modules/import/src/providers/umami.ts@@ -8,11 +8,11 @@ import { parse } from 'csv-parse';import { assocPath } from 'ramda';import { z } from 'zod';import type { Logger } from '../../../../logger';-// M10-009: core's own date helper, not @openpanel/db's — importing+// Core's own date helper, not @openpanel/db's — importing// `@openpanel/db/src/clickhouse/client` constructs a ClickHouse client and a// pino-pretty transport at import time (fatal under bun:test's `--isolate`-// worker threads, AGENTS.md's eager-barrel-chain hazard) and is a value-// import of `@openpanel/db` from core. See shared/ch-dates.ts's header.+// worker threads, AGENTS.md's eager-barrel-chain hazard) and is a value import+// of `@openpanel/db` from core. See shared/ch-dates.ts's header.import { formatClickhouseDate } from '../../../../shared/ch-dates';import {getReferrerWithQuery,diff --git a/packages/core/src/modules/ingest/ingest.constants.ts b/packages/core/src/modules/ingest/ingest.constants.tsindex 2a50fd571..0fda3a53c 100644--- a/packages/core/src/modules/ingest/ingest.constants.ts+++ b/packages/core/src/modules/ingest/ingest.constants.ts@@ -1,10 +1,10 @@-// The ingestion wire contract (M8-002, ADR-008's module map: ingest owns "C").-// Moved from packages/validation/src/track.validation.ts,+// The ingestion wire contract (ADR-008's module map: ingest owns "C"). Moved+// from packages/validation/src/track.validation.ts,// packages/validation/src/event-blocklist.ts and packages/constants'// RESERVED_EVENT_NAMES — all three enforce the same thing (what a caller may// name an event and what a track body may contain), so they are one file here.-// packages/validation and packages/constants re-export this; the SDK deep-import-// retarget is P11.+// packages/validation and packages/constants re-export this; the SDK+// deep-import retarget is P11.//// Isomorphic by rule: zod, another *.constants.ts, or nothing.diff --git a/packages/core/src/modules/ingest/ingest.routes.ts b/packages/core/src/modules/ingest/ingest.routes.tsindex cba704c97..1fbb7fa46 100644--- a/packages/core/src/modules/ingest/ingest.routes.ts+++ b/packages/core/src/modules/ingest/ingest.routes.ts@@ -1,32 +1,31 @@-// Ported from apps/api/src/routes/track.router.ts + track.controller.ts-// (M8-002). V1's Fastify router stays the LIVE route (DELEGATE PATTERN) and-// its controller and hooks delegate into ingest.service.ts — the same-// functions this file calls.+// Ported from apps/api/src/routes/track.router.ts + track.controller.ts. V1's+// Fastify router stays the LIVE route (DELEGATE PATTERN) and its controller and+// hooks delegate into ingest.service.ts — the same functions this file calls.//// THE HOOK ORDER IS THE CONTRACT (ADR-002 "behaviour that must be preserved-// explicitly" 5): duplicate -> clientAuth -> isBot. Here it holds by-// lifecycle phase rather than by registration luck — measured on Elysia-// 1.4.30, a route declaring all three runs-// `derive -> transform -> macro resolve -> beforeHandle`. So the duplicate-// check is a `transform` (V1's `preValidation`), `clientAuth` is the macro,-// and the bot check is a `beforeHandle`, which is what lets it read-// `client.secretVerified` the way V1's `isBotHook` reads the-// `req.clientSecretAuth` side channel `validateSdkRequest` sets.+// explicitly" 5): duplicate -> clientAuth -> isBot. Here it holds by lifecycle+// phase rather than by registration luck — measured on Elysia 1.4.30, a route+// declaring all three runs `derive -> transform -> macro resolve ->+// beforeHandle`. So the duplicate check is a `transform` (V1's+// `preValidation`), `clientAuth` is the macro, and the bot check is a+// `beforeHandle`, which is what lets it read `client.secretVerified` the way+// V1's `isBotHook` reads the `req.clientSecretAuth` side channel+// `validateSdkRequest` sets.//// Both routes carry the whole chain because V1's `fastify.addHook` calls are// plugin-scoped, so `GET /track/device-id` goes through it too.//-// M9-004 mounted this surface and closed the two gaps its header used to-// record. V1's `subscriptionHook` (the wind-down gate) is now the last link in-// the chain — `duplicate -> clientAuth -> isBot -> subscription`, V1's-// registration order exactly — with `selfHosted` read off `AppDeps.config`-// instead of `process.env`. And `POST /event`, the legacy compat route ADR-015-// entry 1 was reversed to KEEP, is here beside `/track`: same hook chain plus-// the per-client usage counter the deferred removal decision needs, recorded-// after authentication (so a label can only ever be a client id that exists)-// and before the hooks that can short-circuit (so a client whose events are-// dropped as bot/wind-down traffic still counts as a client that would break-// if `/event` disappeared).+// Mounted this surface and closed the two gaps its header used to record. V1's+// `subscriptionHook` (the wind-down gate) is now the last link in the chain —+// `duplicate -> clientAuth -> isBot -> subscription`, V1's registration order+// exactly — with `selfHosted` read off `AppDeps.config` instead of+// `process.env`. And `POST /event`, the legacy compat route ADR-015 entry 1 was+// reversed to KEEP, is here beside `/track`: same hook chain plus the+// per-client usage counter the deferred removal decision needs, recorded after+// authentication (so a label can only ever be a client id that exists) and+// before the hooks that can short-circuit (so a client whose events are dropped+// as bot/wind-down traffic still counts as a client that would break if+// `/event` disappeared).import type { AppDeps, HttpCtx } from '../../context';import { defineRoutes } from '../../http/define';@@ -44,9 +43,9 @@ import {} from './ingest.service';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-// inject. It still constructs no client at import time.+// The Kafka producer is a sibling now, not an `AppDeps` field: kafka.ts moved+// into this module, so there is nothing left for main.ts to inject. It still+// constructs no client at import time.import { produceIncomingEvent } from './src/kafka';const TAGS = ['Track'];diff --git a/packages/core/src/modules/ingest/ingest.service.test.ts b/packages/core/src/modules/ingest/ingest.service.test.tsindex 9f0332845..269efe0c0 100644--- a/packages/core/src/modules/ingest/ingest.service.test.ts+++ b/packages/core/src/modules/ingest/ingest.service.test.ts@@ -1,15 +1,15 @@/**- * Tests for:- * - getOverrideDeviceId — the guard around a track event's caller-supplied- * `__deviceId` (it becomes a Redis key segment, a BullMQ jobId and a ClickHouse- * device_id, so it must be trimmed, non-empty, and length-bounded).- * - handleReplay — replay files a chunk under the session id the SDK echoes back;- * it needs no device resolution and trusts the client-sent session id.- * - ingestTrack — the single events transport (ADR-004): every tracked event goes- * to Kafka via the injected producer, with no branch and no fallback queue.+ * Tests for: - getOverrideDeviceId — the guard around a track event's+ * caller-supplied `__deviceId` (it becomes a Redis key segment, a BullMQ jobId+ * and a ClickHouse device_id, so it must be trimmed, non-empty, and+ * length-bounded). - handleReplay — replay files a chunk under the session id+ * the SDK echoes back; it needs no device resolution and trusts the client-sent+ * session id. - ingestTrack — the single events transport: every tracked event+ * goes to Kafka via the injected producer, with no branch and no fallback+ * queue.*- * Moved from apps/api/src/controllers/track.controller.test.ts with M8-002.- * The producer and the buffers are arguments now, so V1's `vi.mock` of+ * Moved from apps/api/src/controllers/track.controller.test.ts with M8-002. The+ * producer and the buffers are arguments now, so V1's `vi.mock` of* @openpanel/queue and its `vi.spyOn(replayBuffer)` become plain stubs — same* assertions. Geo/ASN and the salts are still module-level, so those keep a* `mock.module` (unhoisted, hence the `await import` in `beforeAll`).@@ -60,13 +60,13 @@ let ingestTrack: typeof import('./ingest.service').ingestTrack;// The profile module is spread and then overridden by name: event.service// imports more of profile.service than ingest.service does. Overriding-// `identifyProfile` (not just `upsertProfile`) is what keeps the identify-// path off Postgres and the profile buffer — profile.service calls its own-// local `upsertProfile`, not the exported binding.+// `identifyProfile` (not just `upsertProfile`) is what keeps the identify path+// off Postgres and the profile buffer — profile.service calls its own local+// `upsertProfile`, not the exported binding.//-// M15-005: ingest.service.ts calls salt.service.ts's module-scope `getSalts`-// with the scope it holds, so that is the specifier mocked here,-// spread-actual like the rest.+// Ingest.service.ts calls salt.service.ts's module-scope `getSalts` with the+// scope it holds, so that is the specifier mocked here, spread-actual like the+// rest.let realSaltService: typeof import('../salt/salt.service');beforeAll(async () => {const profile = await import('../profile/profile.service');diff --git a/packages/core/src/modules/ingest/ingest.service.ts b/packages/core/src/modules/ingest/ingest.service.tsindex 45d36d5c1..ca25b1722 100644--- a/packages/core/src/modules/ingest/ingest.service.ts+++ b/packages/core/src/modules/ingest/ingest.service.ts@@ -1,8 +1,7 @@-// The ingestion pipeline (M8-002). Ported from apps/api's-// track.controller.ts, its three route hooks (duplicate / client / is-bot)-// and utils/ids.ts. V1's Fastify controller and hooks stay the LIVE route-// (DELEGATE PATTERN) and call the functions below; ingest.routes.ts is the-// V2 half over the same functions.+// The ingestion pipeline. Ported from apps/api's track.controller.ts, its three+// route hooks (duplicate / client / is-bot) and utils/ids.ts. V1's Fastify+// controller and hooks stay the LIVE route (DELEGATE PATTERN) and call the+// functions below; ingest.routes.ts is the V2 half over the same functions.//// Nothing here throws for a caller error: each transport owns its own status// codes and bodies, so the pipeline returns a `TrackOutcome` and V1 maps it@@ -175,8 +174,8 @@ export function getTimestamp(payload: ITrackHandlerPayload['payload']): { timestamp: number; isTimestampFromThePast: boolean } {const safeTimestamp = timestamp || Date.now();- // `/event` has no body schema (ADR-003), so `payload` can be a string or- // null; `'properties' in payload` throws on a primitive.+ // `/event` has no body schema, so `payload` can be a string or null;+ // `'properties' in payload` throws on a primitive.const userDefinedTimestamp =typeof payload === 'object' && payload !== null && 'properties' in payload? (payload?.properties?.__timestamp as string | undefined)@@ -626,9 +625,9 @@ export async function isIngestionWoundDown(}/**- * `POST /event` — the legacy compat route (ADR-004/ADR-015 entry 1, REVERSED:- * kept, not deleted, because production still has projects posting to it).- * Ported from apps/api/src/controllers/event.controller.ts.+ * `POST /event` — the legacy compat route (ADR-015 entry 1, REVERSED: kept, not+ * deleted, because production still has projects posting to it). Ported from+ * apps/api/src/controllers/event.controller.ts.** It is NOT `ingestTrack` with a different body: the legacy payload carries a* client-supplied ISO `timestamp`, has no `type` discriminator, no schema, and@@ -657,10 +656,10 @@ export async function ingestLegacyEvent(return { status: 'missing-project-id' };}- // An event with no name is not an event. V1 answered 202 and wrote a row- // with `name = ''`, which then shows up in every picker and breakdown.- // The status stays 202 — this route has no body schema (ADR-003) and the- // HTTP contract must not change — but nothing is written.+ // An event with no name is not an event. V1 answered 202 and wrote a row with+ // `name = ''`, which then shows up in every picker and breakdown. The status+ // stays 202 — this route has no body schema and the HTTP contract must not+ // change — but nothing is written.const name = (request.body as { name?: unknown } | null | undefined)?.name;if (typeof name !== 'string' || name.trim() === '') {return { status: 'ok' };diff --git a/packages/core/src/modules/ingest/legacy-event.test.ts b/packages/core/src/modules/ingest/legacy-event.test.tsindex cc9220a1d..09415b4b6 100644--- a/packages/core/src/modules/ingest/legacy-event.test.ts+++ b/packages/core/src/modules/ingest/legacy-event.test.ts@@ -1,7 +1,7 @@/*** Tests for the legacy `POST /event` compat route (ADR-015 entry 1, reversed:- * the route is KEPT, produces to Kafka exactly like /track, and is measured- * per client so the deferred removal decision has data).+ * the route is KEPT, produces to Kafka exactly like /track, and is measured per+ * client so the deferred removal decision has data).** Ported from apps/api/src/controllers/event.controller.test.ts with M9-004,* when the controller and its usage hook moved into this module. The producer@@ -9,7 +9,7 @@* stub, and the counter lives on core's one registry rather than prom-client's* global one — same assertions.*- * The `mixan-*` header fallback moved with the validator itself (M8-002) — see+ * The `mixan-*` header fallback moved with the validator itself — see* `src/client-auth.test.ts`.*/@@ -62,9 +62,9 @@ mock.module('../../clients/geo', () => ({ getGeoLocation, getAsnInfo }));let ingestLegacyEvent: typeof import('./ingest.service').ingestLegacyEvent;-// M15-005: ingest.service.ts calls salt.service.ts's module-scope `getSalts`-// with the scope it holds, so that is the specifier mocked here —-// spread-actual like everywhere else this module is overridden.+// Ingest.service.ts calls salt.service.ts's module-scope `getSalts` with the+// scope it holds, so that is the specifier mocked here — spread-actual like+// everywhere else this module is overridden.let realSaltService: typeof import('../salt/salt.service');beforeAll(async () => {realSaltService = { ...(await import('../salt/salt.service')) };@@ -96,7 +96,7 @@ const buffers = {} as unknown as Buffers;// The legacy route produces to Kafka and never touches Postgres/ClickHouse;-// `deps` is on `IngestTransport` for the profile writes /track makes (M10-005).+// `deps` is on `IngestTransport` for the profile writes /track makes.const transportDeps = {buffers,config: testCoreConfig(),diff --git a/packages/core/src/modules/ingest/src/bot-check.test.ts b/packages/core/src/modules/ingest/src/bot-check.test.tsindex f6120dc40..dd65741e6 100644--- a/packages/core/src/modules/ingest/src/bot-check.test.ts+++ b/packages/core/src/modules/ingest/src/bot-check.test.ts@@ -1,6 +1,6 @@/**- * Tests for checkIngestBot — the bot filter V1 runs as `isBotHook` on- * ingestion (apps/api/src/hooks/is-bot.hook.test.ts, moved with M8-002).+ * Tests for checkIngestBot — the bot filter V1 runs as `isBotHook` on ingestion+ * (apps/api/src/hooks/is-bot.hook.test.ts, moved with M8-002).** The key behaviour guarded here: requests authenticated with a client secret* (server-side SDKs) are never treated as bots, regardless of user agent. Bot@@ -17,8 +17,8 @@ const createBotEvent = mock(let checkIngestBot: typeof import('../ingest.service').checkIngestBot;-// M10-005: `checkIngestBot` takes `ServiceDeps` first and hands it to-// `createBotEvent`, which is mocked below — nothing here reads a client.+// `checkIngestBot` takes `ServiceDeps` first and hands it to `createBotEvent`,+// which is mocked below — nothing here reads a client.const deps = {} as unknown as import('../../../services').ServiceDeps;// Spread the real modules and override by name: ingest.service re-exportsdiff --git a/packages/core/src/modules/ingest/src/client-auth.test.ts b/packages/core/src/modules/ingest/src/client-auth.test.tsindex 57df1767a..738433719 100644--- a/packages/core/src/modules/ingest/src/client-auth.test.ts+++ b/packages/core/src/modules/ingest/src/client-auth.test.ts@@ -2,15 +2,16 @@* Tests for validateIngestRequest — V1's `validateSdkRequest`, moved with* M8-002.*- * The `mixan-*` case comes from apps/api/src/controllers/event.controller.test.ts:- * ADR-015 entry 5 is pending the `/event` usage metric, so the legacy header- * fallback stays. `secretVerified` is what V1 exposed as- * `request.clientSecretAuth` — the side channel the bot check reads — and- * since main #481 it is true only when the secret verified.+ * The `mixan-*` case comes from+ * apps/api/src/controllers/event.controller.test.ts: ADR-015 entry 5 is pending+ * the `/event` usage metric, so the legacy header fallback stays.+ * `secretVerified` is what V1 exposed as `request.clientSecretAuth` — the side+ * channel the bot check reads — and since main #481 it is true only when the+ * secret verified.** The `secret verification` block guards main #481: `secretVerified` and- * revenue ingestion follow whether the secret verified against the stored- * hash, not whether a secret string was on the request.+ * revenue ingestion follow whether the secret verified against the stored hash,+ * not whether a secret string was on the request.*/import {@@ -63,10 +64,10 @@ mock.module('@openpanel/redis', () => ({getRedisCache: () => ({ get: redisGet, setex: redisSetex }),}));-// M15-005: client-auth.ts takes the caller's scope and reads-// `client.service.ts`'s module-scope `cacheablePerDb` — mocked at that-// specifier, spread-actual so the rest of the module (which `services.ts`'s-// own import of it still needs) stays intact.+// Client-auth.ts takes the caller's scope and reads `client.service.ts`'s+// module-scope `cacheablePerDb` — mocked at that specifier, spread-actual so+// the rest of the module (which `services.ts`'s own import of it still needs)+// stays intact.const realClientService = { ...(await import('../../client/client.service')) };mock.module('../../client/client.service', () => ({...realClientService,diff --git a/packages/core/src/modules/ingest/src/client-auth.ts b/packages/core/src/modules/ingest/src/client-auth.tsindex 68f0594cc..7e14d5ca4 100644--- a/packages/core/src/modules/ingest/src/client-auth.ts+++ b/packages/core/src/modules/ingest/src/client-auth.ts@@ -10,8 +10,8 @@// CORS-before-secret ordering, the ip and profile_id project filters, the// `__revenue` gate, the body-field credential fallback, the `mixan-*` header// fallback (ADR-015 entry 5 is deferred, not taken) and the 5-minute verify-// cache whose key holds base64(<plaintext secret>) — a recorded finding-// ADR-011 leaves to Carl, not to a port.+// cache whose key holds base64(<plaintext secret>) — a recorded finding ADR-011+// leaves to Carl, not to a port.import { getRedisCache } from '@openpanel/redis';import { path } from 'ramda';@@ -61,10 +61,9 @@ export type IngestAuthOutcome =client: IServiceClientWithProject;/*** Whether the supplied client secret VERIFIED against the stored hash- * (main #481). The bot hook reads it as "this is a server-side SDK,- * never a bot", so it must not be true for any string a browser- * happens to send — the side channel survives as a field on the- * outcome (ADR-011 A-i).+ * (main #481). The bot hook reads it as "this is a server-side SDK, never+ * a bot", so it must not be true for any string a browser happens to send+ * — the side channel survives as a field on the outcome (ADR-011 A-i).*/secretVerified: boolean;}diff --git a/packages/core/src/modules/ingest/src/consumer-handler.ts b/packages/core/src/modules/ingest/src/consumer-handler.tsindex 29c118d75..35562e02e 100644--- a/packages/core/src/modules/ingest/src/consumer-handler.ts+++ b/packages/core/src/modules/ingest/src/consumer-handler.ts@@ -1,13 +1,13 @@-// One `Ctx` per Kafka message, so the consumer's `handleEvent` is the same-// kind of work scope an HTTP request or a job run is (ADR-007).+// One `Ctx` per Kafka message, so the consumer's `handleEvent` is the same kind+// of work scope an HTTP request or a job run is.//// The requestId comes out of the envelope's `headers` map — the copy `/track`// puts there, which ADR-018 R3 keeps as the consumer's source — and is-// sanitised exactly as an inbound HTTP `request-id` is, because it lands in-// the same log storage. Before M10-006 the handler read it only to bind a-// `reqId` log field: the ClickHouse writes, the buffer writes and the-// session-end enqueue the message caused all ran on boot-scoped clients, so-// the chain ended at the log line (docs/TECH_DEBT.md §2).+// sanitised exactly as an inbound HTTP `request-id` is, because it lands in the+// same log storage. Before M10-006 the handler read it only to bind a `reqId`+// log field: the ClickHouse writes, the buffer writes and the session-end+// enqueue the message caused all ran on boot-scoped clients, so the chain ended+// at the log line.import { type AppDeps, createCtx } from '../../../context';import { REQUEST_ID_HEADER, REQUEST_ID_LOG_FIELD } from '../../../logger';diff --git a/packages/core/src/modules/ingest/src/consumer.test.ts b/packages/core/src/modules/ingest/src/consumer.test.tsindex a80523238..5d02f97e1 100644--- a/packages/core/src/modules/ingest/src/consumer.test.ts+++ b/packages/core/src/modules/ingest/src/consumer.test.ts@@ -1,12 +1,12 @@/**- * Delivery contract of the Kafka events consumer (ADR-004): at-least-once.- * An offset is resolved once its message has been handled, dead-lettered, or- * deliberately skipped — never merely because it failed.+ * Delivery contract of the Kafka events consumer: at-least-once. An offset is+ * resolved once its message has been handled, dead-lettered, or deliberately+ * skipped — never merely because it failed.*- * Ported from apps/worker/src/jobs/events.kafka-consumer.test.ts (M8-003)- * with the assertions unchanged. The batch handler is exercised directly with- * injected dependencies; the broker, the metrics registry and `incomingEvent`- * are all out of the picture — which is why no `mock.module` appears here.+ * Ported from apps/worker/src/jobs/events.kafka-consumer.test.ts with the+ * assertions unchanged. The batch handler is exercised directly with injected+ * dependencies; the broker, the metrics registry and `incomingEvent` are all+ * out of the picture — which is why no `mock.module` appears here.*/import { describe, expect, mock, test } from 'bun:test';@@ -323,8 +323,8 @@ describe('handler failure', () => {await handler.eachBatch(payload);- // Dropped WITHOUT being recorded — and still acked. Holding the offset- // back here is what rebuilt the redelivery loop (M20-001, gate M20).+ // Dropped WITHOUT being recorded — and still acked. Holding the offset back+ // here is what rebuilt the redelivery loop (gate M20).expect(metrics.deadLetterFailed).toHaveBeenCalledWith(String(PARTITION));expect(metrics.deadLettered).not.toHaveBeenCalled();expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1', '2']);@@ -372,15 +372,15 @@ describe('unparseable messages', () => {});/**- * M21-001 deleted the offset watermark, whose only outputs were the- * `reprocessed` counter and a warn line — drill 08 measured 161 real- * duplicates and 0 of those lines, because `resetWatermarks()` fired on- * GROUP_JOIN and a failed durability flush never advanced it.+ * Deleted the offset watermark, whose only outputs were the `reprocessed`+ * counter and a warn line — drill 08 measured 161 real duplicates and 0 of+ * those lines, because `resetWatermarks` fired on GROUP_JOIN and a failed+ * durability flush never advanced it.** These are the regression tests for the half of that claim that matters: the* functional statement in the resolve loop was always `resolveOffset(m.offset)`- * and never read the watermark, so a redelivery must resolve and commit- * exactly what it did before.+ * and never read the watermark, so a redelivery must resolve and commit exactly+ * what it did before.*/describe('a redelivery after the watermark was deleted', () => {test('resolves every offset again, in ascending order', async () => {@@ -441,15 +441,15 @@ describe('a redelivery after the watermark was deleted', () => {});/**- * The regression test for drill 03's loss (M18-001).+ * The regression test for drill 03's loss.** The event a handler accepted lives in an in-process array until the buffer* pushes it to Redis, and kafkajs commits whatever `resolveOffset` marked the- * moment `eachBatch` returns — `autoCommit` is on and this consumer never- * turns it off, so `consumer.stop()` is NOT the commit point. Resolving an- * offset for an event that is still only in memory is exactly how a graceful- * restart lost 2 of 44,075 events: the offsets were committed, the process- * exited, and nothing was redelivered.+ * moment `eachBatch` returns — `autoCommit` is on and this consumer never turns+ * it off, so `consumer.stop` is NOT the commit point. Resolving an offset for+ * an event that is still only in memory is exactly how a graceful restart lost+ * 2 of 44,075 events: the offsets were committed, the process exited, and+ * nothing was redelivered.** `resolveOffset` is therefore the commit in these tests. It is the only thing* that decides what gets committed.@@ -539,10 +539,9 @@ describe('durability before commit', () => {});test('opens the durability window before the first handler buffers anything', async () => {- // The window's lower bound is what makes the gate answer for THIS batch:- // a failed write drops the events it knows the broker will redeliver, so- // "everything queued is settled" is no longer "my events are in Redis"- // (M18-007).+ // The window's lower bound is what makes the gate answer for THIS batch: a+ // failed write drops the events it knows the broker will redeliver, so+ // "everything queued is settled" is no longer "my events are in Redis".let handled = 0;let handledWhenOpened = -1;const { deps, openDurabilityWindow } = makeDeps({@@ -566,9 +565,9 @@ describe('durability before commit', () => {test('a failed flush resolves NOTHING, so a redelivery is guaranteed', async () => {// Asserted directly rather than left to the drill. With the re-queue gone- // (M18-007) the only thing standing between a failed flush and a lost- // batch is that its offsets are never resolved — every message, not just- // the tail, and regardless of how many of them the handlers finished.+ // the only thing standing between a failed flush and a lost batch is that+ // its offsets are never resolved — every message, not just the tail, and+ // regardless of how many of them the handlers finished.const { deps, handleEvent } = makeDeps({flushBufferedEvents: mock(() =>Promise.reject(new Error('redis is unreachable'))@@ -689,10 +688,10 @@ describe('durability before commit', () => {});/**- * M20-001 end to end: the consumer wired to the REAL capped-list recorder+ * End to end: the consumer wired to the REAL capped-list recorder* (`@openpanel/redis`'s `createDeadLetterRecorder`) instead of a mock, against- * an in-memory stand-in for the one MULTI it issues. Redis itself is out of- * the picture; the LPUSH/LTRIM arithmetic is not.+ * an in-memory stand-in for the one MULTI it issues. Redis itself is out of the+ * picture; the LPUSH/LTRIM arithmetic is not.*/describe('dead letter to a capped redis list', () => {const LIST_KEY = 'dead_letter:events-test';diff --git a/packages/core/src/modules/ingest/src/consumer.ts b/packages/core/src/modules/ingest/src/consumer.tsindex f6ddd05f8..340859ae3 100644--- a/packages/core/src/modules/ingest/src/consumer.ts+++ b/packages/core/src/modules/ingest/src/consumer.ts@@ -1,15 +1,14 @@-// Ported from apps/worker/src/jobs/events.kafka-consumer.ts (M8-003). The-// delivery contract is ADR-004's and is unchanged line for line: per-key-// serial groups, the ascending contiguous-prefix offset walk, at-least-once,-// bounded in-consumer retry, and a dead-letter on exhaustion. Only the-// dead-letter DESTINATION and its failure behaviour changed (M20-001): the-// record goes to a capped Redis list, and the event is dropped whether or not-// that write lands.+// Ported from apps/worker/src/jobs/events.kafka-consumer.ts. The delivery+// contract is ADR-004's and is unchanged line for line: per-key serial groups,+// the ascending contiguous-prefix offset walk, at-least-once, bounded+// in-consumer retry, and a dead-letter on exhaustion. Only the dead-letter+// DESTINATION and its failure behaviour changed: the record goes to a capped+// Redis list, and the event is dropped whether or not that write lands.//-// The kafkajs client, the topic/consumer-group names, the DLQ producer and-// the retry bounds are all INJECTED, and stay so now that they live one-// directory away in ./kafka.ts (M11-003): injection is what keeps those names-// byte-identical, because this file never spells one.+// The kafkajs client, the topic/consumer-group names, the DLQ producer and the+// retry bounds are all INJECTED, and stay so now that they live one directory+// away in./kafka.ts: injection is what keeps those names byte-identical,+// because this file never spells one.import type {Consumer,@@ -21,11 +20,11 @@ import type { IncomingEventPayload } from './incoming-event';export interface KafkaConsumerHandle {/**- * Stop fetching, then wait for the in-flight `eachBatch` to finish. Split- * out from `stop()` so a graceful shutdown has a point where nothing new can- * enter the event buffer but the consumer has not been torn down yet — that- * is where shutdown flushes whatever was buffered OUTSIDE a Kafka batch- * (M18-001, drill 03). Events buffered inside one are already durable: see+ * Stop fetching, then wait for the in-flight `eachBatch` to finish. Split out+ * from `stop` so a graceful shutdown has a point where nothing new can enter+ * the event buffer but the consumer has not been torn down yet — that is+ * where shutdown flushes whatever was buffered OUTSIDE a Kafka batch (drill+ * 03). Events buffered inside one are already durable: see* `flushBufferedEvents` below.*/stopConsuming: () => Promise<void>;@@ -41,18 +40,17 @@ const HEARTBEAT_EVERY = 16;const RETRY_BACKOFF_FACTOR = 2;/**- * Ceiling on the wait a batch takes before it returns from a failed- * durability flush and lets the broker redeliver it.+ * Ceiling on the wait a batch takes before it returns from a failed durability+ * flush and lets the broker redeliver it.** The wait itself is seeded from `initialRetryMs` and doubled per consecutive- * failure — the consumer's own retry convention — but it is capped HERE- * rather than at `maxRetryMs`, which is sized for a flaky handler (1s by- * default) and not for a dependency that is down. Without any cap a failed- * flush redelivers in ~90ms and spins: drill 02's re-run measured ~162 laps- * per message in one 96s outage, hammering Redis and Kafka at the worst- * possible moment. 5s keeps a ~15s outage to single-digit redeliveries and- * stays well below the 30s session timeout, so waiting cannot cost the- * consumer its group membership (M18-007).+ * failure — the consumer's own retry convention — but it is capped HERE rather+ * than at `maxRetryMs`, which is sized for a flaky handler (1s by default) and+ * not for a dependency that is down. Without any cap a failed flush redelivers+ * in ~90ms and spins: drill 02's re-run measured ~162 laps per message in one+ * 96s outage, hammering Redis and Kafka at the worst possible moment. 5s keeps+ * a ~15s outage to single-digit redeliveries and stays well below the 30s+ * session timeout, so waiting cannot cost the consumer its group membership.*/const DURABILITY_RETRY_MAX_MS = 5000;@@ -65,7 +63,7 @@ export type DeadLetterReason = 'parse_error' | 'handler_error';** Two implementations satisfy this, and the seam exists so the choice is one* line in `apps/api`'s wiring: `@openpanel/redis`'s `createDeadLetterRecorder`- * (the capped list, in use since M20-001) and ./kafka.ts's+ * (the capped list, in use since M20-001) and./kafka.ts's* `produceDeadLetterEvent` (the DLQ topic, kept because Carl's decision was* explicitly "for now"; a DLQ message produced from these bytes is replayable* onto the events topic unchanged).@@ -93,7 +91,7 @@ export interface ConsumerMetrics {deadLettered: (partition: string, reason: DeadLetterReason) => void;/*** The message was DROPPED WITHOUT being recorded — the dead-letter write- * failed. Not "will be retried": nothing retries it (M20-001).+ * failed. Not "will be retried": nothing retries it.*/deadLetterFailed: (partition: string) => void;}@@ -116,14 +114,14 @@ export interface EventsBatchHandlerDeps {* message has been handled and BEFORE the first `resolveOffset`, because* kafkajs commits the resolved offsets as soon as `eachBatch` returns* (`autoCommit` defaults to true and this consumer does not turn it off) —- * not at `consumer.stop()`.+ * not at `consumer.stop`.*- * The gate MUST reject when the events THIS batch buffered are not in- * Redis: drill 03 lost 2 of 44,075 events on a graceful restart because the- * offsets of events that existed only in the event buffer's in-process array- * were committed anyway (M18-001). The window is what makes "this batch's"- * answerable at all, now that a failed write drops the events it knows the- * broker will redeliver instead of keeping them (M18-007).+ * The gate MUST reject when the events THIS batch buffered are not in Redis:+ * drill 03 lost 2 of 44,075 events on a graceful restart because the offsets+ * of events that existed only in the event buffer's in-process array were+ * committed anyway. The window is what makes "this batch's" answerable at+ * all, now that a failed write drops the events it knows the broker will+ * redeliver instead of keeping them.*/openDurabilityWindow: () => () => Promise<void>;logger: ConsumerLogger;@@ -157,12 +155,12 @@ export interface EventsBatchHandler {* the per-key serial groups and the failure paths are testable without a* broker.*- * Delivery contract (ADR-004): at-least-once. An offset is resolved only once- * its message has been handled, dead-lettered, or deliberately skipped —- * never merely because it failed. Since M20-001 a dead-letter always counts as- * finished, because the message is dropped either way; the one place an- * unresolved offset is still correct is a failed DURABILITY flush, which- * leaves the whole batch for redelivery (M18-001).+ * Delivery contract: at-least-once. An offset is resolved only once its message+ * has been handled, dead-lettered, or deliberately skipped — never merely+ * because it failed. Since M20-001 a dead-letter always counts as finished,+ * because the message is dropped either way; the one place an unresolved offset+ * is still correct is a failed DURABILITY flush, which leaves the whole batch+ * for redelivery.*/export function createEventsBatchHandler(deps: EventsBatchHandlerDeps@@ -170,9 +168,9 @@ export function createEventsBatchHandler(const sleep = deps.sleep ?? defaultSleep;/**- * Park the message and DROP it. The drop is unconditional: whether the- * record was stored or not, this message's offset is resolved by the caller- * and the event is gone from the pipeline (M20-001, gate M20).+ * Park the message and DROP it. The drop is unconditional: whether the record+ * was stored or not, this message's offset is resolved by the caller and the+ * event is gone from the pipeline (gate M20).** There is deliberately no retry, no backoff and no unresolved offset here.* The dead-letter destination is Redis, and Redis being unavailable is@@ -185,8 +183,8 @@ export function createEventsBatchHandler(** The two counters are what carry the volume, since a capped list makes* 50,000 drops look like 12: `deadLettered` = recorded and dropped,- * `deadLetterFailed` = dropped WITHOUT being recorded. Neither means- * "will be retried".+ * `deadLetterFailed` = dropped WITHOUT being recorded. Neither means "will be+ * retried".*/const deadLetter = async (message: KafkaMessage,@@ -364,9 +362,9 @@ export function createEventsBatchHandler(}const pk = `${batch.topic}-${batch.partition}`;- // Opened before the first handler buffers anything, so the gate answers- // for THIS batch's events and not for whatever else was pending when it- // finished (M18-007).+ // Opened before the first handler buffers anything, so the gate answers for+ // THIS batch's events and not for whatever else was pending when it+ // finished.const closeDurabilityWindow = deps.openDurabilityWindow();// Group by partition key (= deviceId or `${projectId}:${profileId}`).@@ -405,10 +403,10 @@ export function createEventsBatchHandler(}// No "unresolvable" branch: a message is handled or dropped, and a- // dropped one is still finished (M20-001). The only gap this walk- // can now stop at is the isRunning/isStale early return above, and- // the only offsets left uncommitted are a whole batch whose- // durability flush failed — see below.+ // dropped one is still finished. The only gap this walk can now stop+ // at is the isRunning/isStale early return above, and the only+ // offsets left uncommitted are a whole batch whose durability flush+ // failed — see below.await processMessage(m, batch.partition);processed.add(m.offset);diff --git a/packages/core/src/modules/ingest/src/deduplicate.ts b/packages/core/src/modules/ingest/src/deduplicate.tsindex e6df816e1..e55ec058f 100644--- a/packages/core/src/modules/ingest/src/deduplicate.ts+++ b/packages/core/src/modules/ingest/src/deduplicate.ts@@ -1,6 +1,6 @@-// Ported from apps/api/src/utils/deduplicate.ts (M8-002). The web SDK can fire-// the same event twice (pagehide + visibilitychange); a short-lived Redis lock-// keyed on the whole payload collapses the pair.+// Ported from apps/api/src/utils/deduplicate.ts. The web SDK can fire the same+// event twice (pagehide + visibilitychange); a short-lived Redis lock keyed on+// the whole payload collapses the pair.import { getLock } from '@openpanel/redis';import fastJsonStableHash from 'fast-json-stable-hash';diff --git a/packages/core/src/modules/ingest/src/device-id.test.ts b/packages/core/src/modules/ingest/src/device-id.test.tsindex 089394beb..e0f89b64c 100644--- a/packages/core/src/modules/ingest/src/device-id.test.ts+++ b/packages/core/src/modules/ingest/src/device-id.test.ts@@ -2,8 +2,8 @@* Tests for getDeviceId's session resolution against the device-keyed session* store. The id is reused from the live blob only while it's within the idle* window; a lingering (past-window) blob must NOT be reused — see the guard in- * device-id.ts. Override device ids resolve through the same path with a- * single read.+ * device-id.ts. Override device ids resolve through the same path with a single+ * read.** Moved from apps/api/src/utils/ids.test.ts with M8-002. The buffer is now an* argument, so the stub replaces V1's spy on the module singleton — same@@ -140,12 +140,12 @@ describe('getDeviceId — session resolution', () => {});/**- * M18-003 made the cache client fail fast, so this read now rejects in- * microseconds instead of after ioredis's 20-attempt reconnect cycle. The- * degradation itself must be untouched: the api and the worker only agree on- * a session because they derive the SAME id from project/device/time bucket,- * so a faster failure that changed the id would split every session an- * outage touched.+ * Made the cache client fail fast, so this read now rejects in microseconds+ * instead of after ioredis's 20-attempt reconnect cycle. The degradation+ * itself must be untouched: the api and the worker only agree on a session+ * because they derive the SAME id from project/device/time bucket, so a+ * faster failure that changed the id would split every session an outage+ * touched.*/it('mints the SAME deterministic id whether the session read misses or rejects', async () => {const { buffer: emptyStore } = stubBuffer(null);diff --git a/packages/core/src/modules/ingest/src/device-id.ts b/packages/core/src/modules/ingest/src/device-id.tsindex c056acbd4..af5dfa358 100644--- a/packages/core/src/modules/ingest/src/device-id.ts+++ b/packages/core/src/modules/ingest/src/device-id.ts@@ -1,6 +1,6 @@-// Ported from apps/api/src/utils/ids.ts (M8-002). Device and session identity-// for an incoming event: the salted device id, and the session id the API-// answers with synchronously while the worker persists the blob async.+// Ported from apps/api/src/utils/ids.ts. Device and session identity for an+// incoming event: the salted device id, and the session id the API answers with+// synchronously while the worker persists the blob async.import crypto from 'node:crypto';import type { SessionBuffer } from '../../../buffers/session-buffer';diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.test.tsindex 3db311fcf..c985eacb8 100644--- a/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts@@ -1,12 +1,12 @@-// Ported from apps/worker/src/jobs/events.incoming-events.test.ts (M8-003)-// with every assertion unchanged. What changed is the seam: V1 reached the-// session buffer, `createEvent` and the sessions queue through-// `vi.mock('@openpanel/db')` / `vi.mock('@openpanel/queue')`; here they are-// recording doubles handed in as `IncomingEventDeps`, so the assertions are-// on calls the code under test actually made and no `mock.module` is needed.+// Ported from apps/worker/src/jobs/events.incoming-events.test.ts with every+// assertion unchanged. What changed is the seam: V1 reached the session buffer,+// `createEvent` and the sessions queue through `vi.mock('@openpanel/db')` /+// `vi.mock('@openpanel/queue')`; here they are recording doubles handed in as+// `IncomingEventDeps`, so the assertions are on calls the code under test+// actually made and no `mock.module` is needed.//-// The session_end enqueue is asserted through the real `sessionEndJobPayload`-// / `sessionEndEnqueueOptions` — the same functions V1's producer+// The session_end enqueue is asserted through the real `sessionEndJobPayload` /+// `sessionEndEnqueueOptions` — the same functions V1's producer// (`enqueueSessionEndV2`) calls — so the jobId and the `{payload, snapshot}`// mapping are still pinned here, not re-implemented by the test.@@ -575,10 +575,10 @@ describe('duplicate marker', () => {});/**- * THE REGRESSION TEST THAT MATTERS. A blocking Redis call in this path is- * how drill 02's consumer was evicted past its 30 s session timeout, and- * M19 proved an eviction is the only reassignment that costs duplicate- * rows. M18-003 removed that trigger; this must not put it back.+ * THE REGRESSION TEST THAT MATTERS. A blocking Redis call in this path is how+ * drill 02's consumer was evicted past its 30 s session timeout, and M19+ * proved an eviction is the only reassignment that costs duplicate rows.+ * M18-003 removed that trigger; this must not put it back.*/test('Redis unavailable: the event is processed normally and nothing throws', async () => {const { deps, createEvent, ingest, markDuplicate, duplicateMarked } = ctx;@@ -606,11 +606,10 @@ describe('duplicate marker', () => {test('the marker runs alongside the handler, never in front of it', async () => {// "Not slowed" asserted structurally rather than with a stopwatch: the- // marker is started BEFORE the handler's own Redis work and awaited- // AFTER it, so a slow marker overlaps a slow session read instead of- // adding to it. A serial check would give mark:start, mark:end,- // ingest:start — which is the shape that would put M18-003's eviction- // trigger back.+ // marker is started BEFORE the handler's own Redis work and awaited AFTER+ // it, so a slow marker overlaps a slow session read instead of adding to+ // it. A serial check would give mark:start, mark:end, ingest:start — which+ // is the shape that would put M18-003's eviction trigger back.const timeline: string[] = [];const slow = () => new Promise((resolve) => setTimeout(resolve, 20));const { deps, ingest, markDuplicate } = ctx;diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.tsindex e2c48e397..d01d92d2e 100644--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts@@ -1,15 +1,15 @@-// Ported from apps/worker/src/jobs/events.incoming-event.ts (M8-003): the-// Kafka consumer's per-message handler — the step that turns one topic-// payload into session lifecycle decisions and ClickHouse rows.+// Ported from apps/worker/src/jobs/events.incoming-event.ts: the Kafka+// consumer's per-message handler — the step that turns one topic payload into+// session lifecycle decisions and ClickHouse rows.//// Everything that touches Redis, Postgres, ClickHouse or a queue is INJECTED-// (`IncomingEventDeps`), the way session-end.ts does it, so the tests drive-// the real code with recording doubles instead of `mock.module`.-// `createIncomingEventDeps` binds it to ONE MESSAGE'S ctx (M10-006): the-// buffers, the Postgres client and the session-end enqueue all ride the scope-// carrying that envelope's requestId, so the id the producer stamped reaches-// the row the consumer writes (ADR-018 R1). The two lookups a work scope-// cannot supply arrive as `IncomingEventBindings` from the composition root.+// (`IncomingEventDeps`), the way session-end.ts does it, so the tests drive the+// real code with recording doubles instead of `mock.module`.+// `createIncomingEventDeps` binds it to ONE MESSAGE'S ctx: the buffers, the+// Postgres client and the session-end enqueue all ride the scope carrying that+// envelope's requestId, so the id the producer stamped reaches the row the+// consumer writes. The two lookups a work scope cannot supply arrive as+// `IncomingEventBindings` from the composition root.import { getTime, isSameDomain, parsePath } from '@openpanel/shared';import { anyPass, isEmpty, isNil, mergeDeepRight, omit, reject } from 'ramda';@@ -110,7 +110,7 @@ export interface IncomingEventDeps {* The one lookup a work scope cannot supply, resolved once at the composition* root (`apps/api`'s main.ts) rather than per message.*- * M15-005 removed the other two: `getProjectByIdCached` is now a module-scope+ * Removed the other two: `getProjectByIdCached` is now a module-scope* `cacheablePerDb` keyed on the Postgres client, so the message's own scope* reaches the same process-lived cache ingest, http and mcp read.*/@@ -126,11 +126,11 @@ export interface IncomingEventBindings {payload: IServiceCreateEventPayload): Promise<unknown>;/**- * `@openpanel/redis`'s `createDuplicateEventMarker`, already bound to the- * TTL `apps/api` parsed. Injected rather than built here because the TTL is- * configuration and `packages/core` reads no environment (ADR-022 R7), and- * because building it once at the composition root keeps the key prefix and- * the TTL out of the per-message path.+ * `@openpanel/redis`'s `createDuplicateEventMarker`, already bound to the TTL+ * `apps/api` parsed. Injected rather than built here because the TTL is+ * configuration and `packages/core` reads no environment, and because+ * building it once at the composition root keeps the key prefix and the TTL+ * out of the per-message path.*/markDuplicateEvent(eventId: string): Promise<boolean>;}diff --git a/packages/core/src/modules/ingest/src/incoming-event.ts b/packages/core/src/modules/ingest/src/incoming-event.tsindex 559984903..1444c28b5 100644--- a/packages/core/src/modules/ingest/src/incoming-event.ts+++ b/packages/core/src/modules/ingest/src/incoming-event.ts@@ -2,9 +2,9 @@//// This is a WIRE FORMAT, not an internal type: a rolling deploy overlaps a V1// producer with a V2 consumer on the same topic, so it stays byte-compatible-// with V1's `EventsQueuePayloadIncomingEvent['payload']` (ADR-004). A leaf-// file, so both ./kafka.ts's producer and the consumer can name the payload-// without reaching into the ingest service.+// with V1's `EventsQueuePayloadIncomingEvent['payload']`. A leaf file, so+// both./kafka.ts's producer and the consumer can name the payload without+// reaching into the ingest service.import type { parseUserAgent } from '@openpanel/shared/server';import type { GeoLocation } from '../../../clients/geo';diff --git a/packages/core/src/modules/ingest/src/ingest.metrics.ts b/packages/core/src/modules/ingest/src/ingest.metrics.tsindex 827129fd7..0e30d5335 100644--- a/packages/core/src/modules/ingest/src/ingest.metrics.ts+++ b/packages/core/src/modules/ingest/src/ingest.metrics.ts@@ -1,20 +1,19 @@-// The ingest-path collectors, moved from apps/worker/src/metrics.ts (M8-003)-// onto core's one registry. Names, labels and help strings are V1's; the-// worker-side copies die with apps/worker (P9). Until then V1's consumer and-// incoming-event delegate inject their own counters (both take `metrics` as a-// dependency), so V1's `/metrics` body is unchanged and these are the V2-// bindings.+// The ingest-path collectors, moved from apps/worker/src/metrics.ts onto core's+// one registry. Names, labels and help strings are V1's; the worker-side copies+// die with apps/worker (P9). Until then V1's consumer and incoming-event+// delegate inject their own counters (both take `metrics` as a dependency), so+// V1's `/metrics` body is unchanged and these are the V2 bindings.import client from 'prom-client';import { registry } from '../../../metrics';import type { ConsumerMetrics, DeadLetterReason } from './consumer';-// Events whose producer-minted id had already been seen (M21-001). This is a-// MARKER, not a dedupe: the event is inserted either way and this counter is-// the whole point of the check. It replaces `kafka_events_reprocessed_total`,-// which was keyed on a Kafka offset in one process's heap and therefore blind-// to every duplicate that mattered — drill 08 measured 161 real duplicates and-// 0 reprocessed increments.+// Events whose producer-minted id had already been seen. This is a MARKER, not+// a dedupe: the event is inserted either way and this counter is the whole+// point of the check. It replaces `kafka_events_reprocessed_total`, which was+// keyed on a Kafka offset in one process's heap and therefore blind to every+// duplicate that mattered — drill 08 measured 161 real duplicates and 0+// reprocessed increments.//// It UNDERCOUNTS by design: a duplicate whose marker could not be written// (Redis away) is not counted, because the check fails open rather than@@ -35,11 +34,11 @@ export const kafkaHandlerFailuresTotal = new client.Counter({registers: [registry],});-// Messages recorded in the dead-letter list after their attempts were-// exhausted (or after they failed to parse), then DROPPED. One increment per-// message. The list is capped at the last N, so this counter — not the list —-// is the only thing that tells 50,000 drops apart from 12 (M20-001). The-// series name is unchanged: the destination moved, the meaning did not.+// Messages recorded in the dead-letter list after their attempts were exhausted+// (or after they failed to parse), then DROPPED. One increment per message. The+// list is capped at the last N, so this counter — not the list — is the only+// thing that tells 50,000 drops apart from 12. The series name is unchanged:+// the destination moved, the meaning did not.export const kafkaDeadLetteredTotal = new client.Counter({name: 'kafka_events_dead_lettered_total',help: 'Kafka event messages recorded in the dead-letter list and dropped',@@ -47,10 +46,10 @@ export const kafkaDeadLetteredTotal = new client.Counter({registers: [registry],});-// The dead-letter write itself failed, so the message was DROPPED WITHOUT-// being recorded — Redis unreachable, most likely, which is also when handlers-// fail. This is real loss, not a stuck partition: the offset is resolved-// anyway and nothing retries the message (M20-001, gate M20).+// The dead-letter write itself failed, so the message was DROPPED WITHOUT being+// recorded — Redis unreachable, most likely, which is also when handlers fail.+// This is real loss, not a stuck partition: the offset is resolved anyway and+// nothing retries the message (gate M20).export const kafkaDeadLetterFailedTotal = new client.Counter({name: 'kafka_events_dead_letter_failed_total',help: 'Kafka event messages dropped without being recorded (dead-letter write failed)',@@ -82,11 +81,11 @@ export const ingestConsumerMetrics = {const LEGACY_EVENT_CLIENT_ID_LABEL = 'client_id';/**- * ADR-015 entry 1 was reversed: `POST /event` is kept as a legacy compat route- * rather than deleted, because production still has projects posting to it.- * This counter is the evidence the deferred removal decision needs — when it- * reads zero for every client, `/event` and the `mixan-*` header fallback can- * both go (ADR-015 entry 5 is pending the same measurement).+ * Entry 1 was reversed: `POST /event` is kept as a legacy compat route rather+ * than deleted, because production still has projects posting to it. This+ * counter is the evidence the deferred removal decision needs — when it reads+ * zero for every client, `/event` and the `mixan-*` header fallback can both go+ * (ADR-015 entry 5 is pending the same measurement).** Moved from apps/api/src/metrics.ts, which registered on prom-client's global* registry because `fastify-metrics` served that one. V2 has exactly onediff --git a/packages/core/src/modules/ingest/src/kafka.ts b/packages/core/src/modules/ingest/src/kafka.tsindex 437224ce0..a68f06502 100644--- a/packages/core/src/modules/ingest/src/kafka.ts+++ b/packages/core/src/modules/ingest/src/kafka.ts@@ -1,15 +1,15 @@-// Moved from packages/queue/src/kafka.ts (M11-003), byte-for-byte apart from-// the three repointed imports and the de-duplicated `DeadLetterMessage` below.-// What kept it out of core was the import direction, not the code: it lived-// in @openpanel/queue, a package that imports @openpanel/core for its logger,-// so core could not import it back. Moving the file takes it out of that-// cycle — `createLogger` is a sibling now, and both the producer and the-// consumer sit in the module that owns the transport (ADR-004: Kafka is the-// sole events transport — no topic, group or envelope changes with the move).+// Moved from packages/queue/src/kafka.ts, byte-for-byte apart from the three+// repointed imports and the de-duplicated `DeadLetterMessage` below. What kept+// it out of core was the import direction, not the code: it lived in+// @openpanel/queue, a package that imports @openpanel/core for its logger, so+// core could not import it back. Moving the file takes it out of that cycle —+// `createLogger` is a sibling now, and both the producer and the consumer sit+// in the module that owns the transport (ADR-004: Kafka is the sole events+// transport — no topic, group or envelope changes with the move).//-// NOTHING here constructs a Kafka client at import time: `getKafka()` is lazy-// and only `assertKafkaConfigured` reads the broker list eagerly, so core-// stays importable with no broker and `bun test` still runs offline.+// NOTHING here constructs a Kafka client at import time: `getKafka` is lazy and+// only `assertKafkaConfigured` reads the broker list eagerly, so core stays+// importable with no broker and `bun test` still runs offline.import {type Admin,@@ -55,9 +55,9 @@ export const kafkaLogger = (config: CoreConfig): ILogger => {return kafkaLoggerInstance;};-// Kafka/Redpanda is the sole events transport (ADR-004): there is no fallback,-// so an unset KAFKA_BROKERS must fail loudly at boot rather than quietly at the-// first event.+// Kafka/Redpanda is the sole events transport: there is no fallback, so an+// unset KAFKA_BROKERS must fail loudly at boot rather than quietly at the first+// event.export const assertKafkaConfigured = (config: KafkaConfig): void => {if (config.brokers.length === 0) {throw new Error(@@ -106,9 +106,9 @@ const getProducer = async (config: CoreConfig): Promise<Producer> => {const tuning = resolveProducerTuning(config.kafka);const p = client.producer({idempotent: true,- // Stays 1 (not 5) to avoid in-flight reordering after a transient- // broker hiccup: with idempotency on and low retries, reordered batches- // trip OUT_OF_ORDER_SEQUENCE_NUMBER and stick the producer per-partition.+ // Stays 1 (not 5) to avoid in-flight reordering after a transient broker+ // hiccup: with idempotency on and low retries, reordered batches trip+ // OUT_OF_ORDER_SEQUENCE_NUMBER and stick the producer per-partition.// ADR-023 measured raising it at +2-3% and rejected it; batching is what// amortises the round-trip. KAFKA_PRODUCER_MAX_IN_FLIGHT still raises it// for a measurement run — read docs/KAFKA_PRODUCER_OPTIONS.md first: itdiff --git a/packages/core/src/modules/ingest/src/producer-batcher.test.ts b/packages/core/src/modules/ingest/src/producer-batcher.test.tsindex 58b61e65f..7472fd388 100644--- a/packages/core/src/modules/ingest/src/producer-batcher.test.ts+++ b/packages/core/src/modules/ingest/src/producer-batcher.test.ts@@ -3,12 +3,12 @@* Batching exists to amortise the produce round-trip, and it is only adoptable* if it changes nothing a caller can observe:*- * (i) per-key ordering survives — same-key messages leave in produce- * order, inside one `send()` and across consecutive sends;- * (ii) a caller's promise settles on its OWN batch, so a failed send- * rejects exactly the callers whose messages were in it;- * (iii) a partially filled batch still goes out inside the linger window;- * (iv) a failed batch still runs the fatal-producer recovery path.+ * (i) per-key ordering survives — same-key messages leave in produce order,+ * inside one `send` and across consecutive sends; (ii) a caller's promise+ * settles on its OWN batch, so a failed send rejects exactly the callers whose+ * messages were in it; (iii) a partially filled batch still goes out inside the+ * linger window; (iv) a failed batch still runs the fatal-producer recovery+ * path.** No broker: `send` is injected, which is the same seam `kafka.ts` fills with* the real producer call.diff --git a/packages/core/src/modules/ingest/src/producer-batcher.ts b/packages/core/src/modules/ingest/src/producer-batcher.tsindex 5ef2ae1b8..0d6ae384b 100644--- a/packages/core/src/modules/ingest/src/producer-batcher.ts+++ b/packages/core/src/modules/ingest/src/producer-batcher.ts@@ -1,20 +1,19 @@-// Option 2 of the produce-path options (M16-002): amortise the produce-// round-trip by accumulating messages and sending them as ONE `send()`-// carrying MANY messages, instead of one awaited `send()` per /track request.+// Option 2 of the produce-path options: amortise the produce round-trip by+// accumulating messages and sending them as ONE `send` carrying MANY messages,+// instead of one awaited `send` per /track request.//// It is OFF unless the config loader says otherwise — see `producer-tuning.ts`.//// Two invariants the tests hold this file to://-// 1. ORDER. Messages leave in the order they were enqueued: within a batch-// because the array keeps that order (kafkajs partitions per message by-// key, and same-key messages in one `send()` land in one partition batch-// in array order), and across batches because this file keeps exactly-// ONE send outstanding at a time. That second half is why the guarantee-// does not depend on `maxInFlightRequests` staying at 1.-// 2. SETTLEMENT. A caller's promise settles on ITS OWN batch's result. A-// failed send rejects exactly the callers whose messages were in it, and-// no others.+// 1. ORDER. Messages leave in the order they were enqueued: within a batch+// because the array keeps that order (kafkajs partitions per message by key,+// and same-key messages in one `send` land in one partition batch in array+// order), and across batches because this file keeps exactly ONE send+// outstanding at a time. That second half is why the guarantee does not depend+// on `maxInFlightRequests` staying at 1. 2. SETTLEMENT. A caller's promise+// settles on ITS OWN batch's result. A failed send rejects exactly the callers+// whose messages were in it, and no others.interface BatchWaiter {resolve: () => void;diff --git a/packages/core/src/modules/ingest/src/producer-errors.test.ts b/packages/core/src/modules/ingest/src/producer-errors.test.tsindex d73680467..65fce21ae 100644--- a/packages/core/src/modules/ingest/src/producer-errors.test.ts+++ b/packages/core/src/modules/ingest/src/producer-errors.test.ts@@ -1,8 +1,8 @@/*** The producer's fatal-error classification, split out of `kafka.ts` with- * M16-002's batching. Only these failures invalidate the idempotent- * producer's PID/sequence state; everything else must be retried against the- * SAME producer rather than silently rebuilding it.+ * M16-002's batching. Only these failures invalidate the idempotent producer's+ * PID/sequence state; everything else must be retried against the SAME producer+ * rather than silently rebuilding it.*/import { describe, expect, mock, test } from 'bun:test';diff --git a/packages/core/src/modules/ingest/src/producer-errors.ts b/packages/core/src/modules/ingest/src/producer-errors.tsindex 5c1110a2b..1d21254ca 100644--- a/packages/core/src/modules/ingest/src/producer-errors.ts+++ b/packages/core/src/modules/ingest/src/producer-errors.ts@@ -1,8 +1,7 @@-// The producer's error classification, split out of `kafka.ts` (M16-002) so-// the batching path can be tested against the same code the single-message-// path uses: a batch that fails must reset the producer exactly like a lone-// message did, and that is only provable if the recovery wrapper is reachable-// without a broker.+// The producer's error classification, split out of `kafka.ts` so the batching+// path can be tested against the same code the single-message path uses: a+// batch that fails must reset the producer exactly like a lone message did, and+// that is only provable if the recovery wrapper is reachable without a broker.// Kafka error codes that mean the producer's PID/sequence state is// permanently out of sync with the broker for some partition — only adiff --git a/packages/core/src/modules/ingest/src/producer-tuning.ts b/packages/core/src/modules/ingest/src/producer-tuning.tsindex ea1da1247..ad039a4b0 100644--- a/packages/core/src/modules/ingest/src/producer-tuning.ts+++ b/packages/core/src/modules/ingest/src/producer-tuning.ts@@ -1,10 +1,10 @@-// The Kafka producer's throughput knobs (M16-002, turned on by ADR-023),-// resolved in one place.+// The Kafka producer's throughput knobs (turned on by ADR-023), resolved in one+// place.//// The three fields are required members of `KafkaConfig`-// (`packages/core/src/config.ts`): the config loader always sets them, so-// there is no fallback here and no second default anywhere. This file only-// decides whether the configured size batches at all.+// (`packages/core/src/config.ts`): the config loader always sets them, so there+// is no fallback here and no second default anywhere. This file only decides+// whether the configured size batches at all.import type { KafkaConfig } from '../../../config';diff --git a/packages/core/src/modules/ingest/wind-down.test.ts b/packages/core/src/modules/ingest/wind-down.test.tsindex 112e099e2..75d55b99c 100644--- a/packages/core/src/modules/ingest/wind-down.test.ts+++ b/packages/core/src/modules/ingest/wind-down.test.ts@@ -4,8 +4,8 @@** Ported from apps/api/src/hooks/subscription.hook.test.ts with M9-004, when* V1's `subscriptionHook` moved into the ingest module. Same three behaviours- * matter: it gates on the wind-down STEP rather than the subscription state- * (so an expired trial keeps ingesting until it has actually been warned), the+ * matter: it gates on the wind-down STEP rather than the subscription state (so+ * an expired trial keeps ingesting until it has actually been warned), the* caller answers 202 rather than a 4xx (the SDKs retry everything except 401* and 2xx), and it fails open. `SELF_HOSTED` is a `selfHosted` argument now —* core reads no environment — so V1's `vi.stubEnv` becomes a parameter.diff --git a/packages/core/src/modules/insight/insight.constants.ts b/packages/core/src/modules/insight/insight.constants.tsindex f71f17c65..a89cc7082 100644--- a/packages/core/src/modules/insight/insight.constants.ts+++ b/packages/core/src/modules/insight/insight.constants.ts@@ -1,7 +1,6 @@-// Moved from packages/validation/src/types.insights.ts (M11-006, ADR-008's-// module map: insight owns "C"). Plain TypeScript, no zod — isomorphic by the-// AGENTS.md rule, which constrains a constants file's imports, and this file-// has none.+// Moved from packages/validation/src/types.insights.ts (ADR-008's module map:+// insight owns "C"). Plain TypeScript, no zod — isomorphic by the AGENTS.md+// rule, which constrains a constants file's imports, and this file has none.// The two list procedures' page bounds. Vocabulary, not implementation: the// dashboard pages that call `insight.list` / `insight.listAll` size their owndiff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.tsindex f06d83644..178e332af 100644--- a/packages/core/src/modules/insight/insight.jobs.test.ts+++ b/packages/core/src/modules/insight/insight.jobs.test.ts@@ -26,9 +26,9 @@ function stubLogger(): Logger {}// A plain object literal, not createCtx/extendCtx: `services` is installed-// there as a getter with no setter (the lazy-build seam, ADR-007), which-// makes it unassignable afterwards — exactly what a fake `services.insight`-// needs to be for a handler test.+// there as a getter with no setter (the lazy-build seam), which makes it+// unassignable afterwards — exactly what a fake `services.insight` needs to be+// for a handler test.function stubJobCtx(insight: Partial<ReturnType<typeof createInsightService>>,jobName = 'test'@@ -95,9 +95,9 @@ test('the insight jobs registry declares insightsProject on the insights queue',});test('the insight cron fragment is spread into the cron queue', () => {- // Subset, not exact equality: other modules (e.g. gsc, M5-002) spread- // their own fragments into the same cron queue. jobs.registry.test.ts owns- // the exhaustive membership check.+ // Subset, not exact equality: other modules (e.g. gsc) spread their own+ // fragments into the same cron queue. jobs.registry.test.ts owns the+ // exhaustive membership check.expect(Object.keys(queues.cron.jobs)).toEqual(expect.arrayContaining(['insightCleanup', 'insightsDaily', 'weeklyDigest']));@@ -236,9 +236,9 @@ test('weeklyDigest delegates to sendWeeklyDigests', async () => {expect(called).toBe(true);});-// Byte-identity with the ids/cadences schedulers.test.ts's golden snapshot-// pins (apps/worker/src/boot-cron.ts). The cadences now live on the jobs-// themselves (ADR-021), so this reads them straight off the registry.+// Byte-identity with the ids/cadences schedulers.test.ts's golden snapshot pins+// (apps/worker/src/boot-cron.ts). The cadences now live on the jobs themselves,+// so this reads them straight off the registry.test('the insight cron fragment carries V1 ids and cadences unchanged', () => {expect(queues.cron.jobs.insightsDaily.cron).toEqual({pattern: '0 2 * * *',diff --git a/packages/core/src/modules/insight/insight.jobs.ts b/packages/core/src/modules/insight/insight.jobs.tsindex 0a68c2e36..d190af1bf 100644--- a/packages/core/src/modules/insight/insight.jobs.ts+++ b/packages/core/src/modules/insight/insight.jobs.ts@@ -1,11 +1,12 @@// Ported from apps/worker/src/jobs/insights.ts, insights-enrich.ts,-// cron.insight-cleanup.ts and cron.weekly-digest.ts (M5-001); the schedules-// moved onto the jobs at ADR-021 (M10-007).+// cron.insight-cleanup.ts and cron.weekly-digest.ts; the schedules moved onto+// the jobs at ADR-021.//// `insightsProject` is this module's own queue (`insights` in the registry —// ADR-005's registry key). `insightsDaily` / `insightCleanup` / `weeklyDigest`// are cron fragments, spread into the ONE `cron` queue by jobs.registry.ts.-// Scheduler ids and cadences are V1's, unchanged (apps/worker/src/boot-cron.ts).+// Scheduler ids and cadences are V1's, unchanged+// (apps/worker/src/boot-cron.ts).import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/insight/insight.rpc.ts b/packages/core/src/modules/insight/insight.rpc.tsindex 4feddc122..69c87f272 100644--- a/packages/core/src/modules/insight/insight.rpc.ts+++ b/packages/core/src/modules/insight/insight.rpc.ts@@ -1,14 +1,13 @@-// Ported from packages/trpc/src/routers/insight.ts (M5-001).+// Ported from packages/trpc/src/routers/insight.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// The permission ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The permission ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.tsindex d0f7579bc..0298dfa6b 100644--- a/packages/core/src/modules/insight/insight.service.test.ts+++ b/packages/core/src/modules/insight/insight.service.test.ts@@ -1,8 +1,8 @@-// M10-009: the subject's functions take `ServiceDeps`, so `deps.db` IS the-// fake below and no Prisma module mock is needed. The intra-package modules-// (store, referrer-spikes, legacy-scan) are still `mock.module`'d — that works-// here with no import-time side effects to race because every mock is-// registered before the subject's first call, not before its import.+// The subject's functions take `ServiceDeps`, so `deps.db` IS the fake below+// and no Prisma module mock is needed. The intra-package modules (store,+// referrer-spikes, legacy-scan) are still `mock.module`'d — that works here+// with no import-time side effects to race because every mock is registered+// before the subject's first call, not before its import.import { beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';@@ -24,9 +24,9 @@ const $executeRaw = mock((..._args: unknown[]) => {executeRawCalls.push(_args);return Promise.resolve(executeRawReturns.shift() ?? 0);});-// M15-114: the explain cache is `deps.redis` (ADR-022 R16), so the fake is a-// map on the scope — no `@openpanel/redis` module mock, which would replace-// that barrel process-wide for every other file in the run.+// The explain cache is `deps.redis`, so the fake is a map on the scope — no+// `@openpanel/redis` module mock, which would replace that barrel process-wide+// for every other file in the run.const redisStore = new Map<string, string>();const redis = {get: mock((key: string) => Promise.resolve(redisStore.get(key) ?? null)),diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.tsindex ebe85802c..70b9e5b7e 100644--- a/packages/core/src/modules/insight/insight.service.ts+++ b/packages/core/src/modules/insight/insight.service.ts@@ -1,28 +1,28 @@// Moved from packages/db/src/services/insights* + referrer-spikes.service.ts-// (M5-001, the AI engine module). ADR-007: "Moves to core: src/services/**-// (33 services + insights/)".+// (the AI engine module). ADR-007: "Moves to core: src/services/** (33 services+// + insights/)".//// Plain exported functions, not only methods on `createInsightService`'s// container — the same shape as modules/auth/auth.service.ts, because V1's// worker (apps/worker, no core Ctx today) and V1's trpc router both need a-// direct call, not one that requires building a Ctx first. `createInsightService`-// is the `ctx.services.insight` binding for code that already has a Ctx.+// direct call, not one that requires building a Ctx first.+// `createInsightService` is the `ctx.services.insight` binding for code that+// already has a Ctx.//-// M10-009: every exported function takes `ServiceDeps` and reaches Postgres-// as `deps.db` and ClickHouse as `deps.ch`; the `loadDb()`/`loadCh()` lazy-// loaders are gone, so the requestId minted at the edge reaches the query-// (ADR-018, docs/TECH_DEBT.md §4). M15-202 removed the last five `load*`-// functions here — engine, store, detection modules, referrer spikes and the-// legacy detector are all plain static imports of this module's own `src/`.+// Every exported function takes `ServiceDeps` and reaches Postgres as `deps.db`+// and ClickHouse as `deps.ch`; the `loadDb`/`loadCh` lazy loaders are gone, so+// the requestId minted at the edge reaches the query. M15-202 removed the last+// five `load*` functions here — engine, store, detection modules, referrer+// spikes and the legacy detector are all plain static imports of this module's+// own `src/`.//-// M12-007: the engine and its five detection modules run on the `sql` tag-// (ADR-013); `createEngine` therefore takes the scope's deps rather than a bare-// ClickHouse client, so the requestId reaches every module statement.-// `legacy-scan.ts` is the last clix holdout in this module (M12-008).+// The engine and its five detection modules run on the `sql` tag;+// `createEngine` therefore takes the scope's deps rather than a bare ClickHouse+// client, so the requestId reaches every module statement. `legacy-scan.ts` is+// the last clix holdout in this module.//-// M15-114: the explain cache runs on `deps.redis` (ADR-022 R16) — the app-// shell owns that connection's lifecycle; this module never opens one of-// its own.+// The explain cache runs on `deps.redis` — the app shell owns that connection's+// lifecycle; this module never opens one of its own.import { sendEmail } from '../../clients/email';import type { Logger } from '../../logger';diff --git a/packages/core/src/modules/insight/src/cached-query.ts b/packages/core/src/modules/insight/src/cached-query.tsindex 690d30f70..d0852d64d 100644--- a/packages/core/src/modules/insight/src/cached-query.ts+++ b/packages/core/src/modules/insight/src/cached-query.ts@@ -1,17 +1,17 @@-// M12-007: the replacement for `cached-clix.ts` (ADR-013 decision 21).+// The replacement for `cached-clix.ts` (ADR-013 decision 21).//-// The wrapper it replaces memoised `clix`'s `execute()` on-// `sha256(query.toSQL() + '|' + timezone)` — safe only because clix inlined-// every value into the text it hashed. The `sql` tag renders `{pN:Type}`-// placeholders whose names come from a per-render counter, so two statements-// that differ only in their bound values render to the SAME text: the key must-// carry the params as well, or one project's window would serve another's.+// The wrapper it replaces memoised `clix`'s `execute` on `sha256(query.toSQL ++// '|' + timezone)` — safe only because clix inlined every value into the text+// it hashed. The `sql` tag renders `{pN:Type}` placeholders whose names come+// from a per-render counter, so two statements that differ only in their bound+// values render to the SAME text: the key must carry the params as well, or one+// project's window would serve another's.//// Everything else is deliberately unchanged from the clix wrapper: the `Map`// belongs to the caller (per module+window, never module-level — it is keyed by// nothing tenant-scoped), the timezone defaults to `'UTC'` exactly as// `clix(client, timezone)` did (query-builder.ts:696) and travels as-// `session_timezone` in `clickhouse_settings` exactly as `.execute()` sent it+// `session_timezone` in `clickhouse_settings` exactly as `.execute` sent it// (query-builder.ts:562).import crypto from 'node:crypto';@@ -28,10 +28,10 @@ export type StatementRunner = <T extends object>() => Promise<T[]>;/**- * @param deps the scope's ClickHouse client + logger (so the requestId reaches- * the query — ADR-018).- * @param cache per module+window result cache; omit to disable memoisation.- * @param timezone `session_timezone` for every statement run through it.+ * @param deps the scope's ClickHouse client + logger (so the requestId reaches+ * the query — ADR-018). @param cache per module+window result cache; omit to+ * disable memoisation. @param timezone `session_timezone` for every statement+ * run through it.*/export function createStatementCache(deps: ChScope,diff --git a/packages/core/src/modules/insight/src/legacy-scan.ts b/packages/core/src/modules/insight/src/legacy-scan.tsindex 3b218bb0c..541c1f366 100644--- a/packages/core/src/modules/insight/src/legacy-scan.ts+++ b/packages/core/src/modules/insight/src/legacy-scan.ts@@ -1,20 +1,20 @@// The pre-engine insight detector, kept for V1 parity — no live callers today.//-// M12-008: the ten statements moved off clix onto the ADR-013 `sql` tag. The-// conversion changes how values reach the server and nothing else: every-// statement below renders byte-identically to the clix output it replaces,-// with the project id and the computed window bound as `{pN:Type}` params.-// clix always sent `session_timezone` (query-builder.ts:562) and defaulted it-// to `'UTC'` (`:696`), so `chQuery` sends the same value.+// The ten statements moved off clix onto the ADR-013 `sql` tag. The conversion+// changes how values reach the server and nothing else: every statement below+// renders byte-identically to the clix output it replaces, with the project id+// and the computed window bound as `{pN:Type}` params. clix always sent+// `session_timezone` (query-builder.ts:562) and defaulted it to `'UTC'`+// (`:696`), so `chQuery` sends the same value.//// Nine of the ten statements are BROKEN AND WERE ALWAYS BROKEN. clix's-// `having(column, operator, value)` escaped-// its comparand as a VALUE, so every `'<column> * <n>'` threshold below reaches-// ClickHouse as a quoted string and the comparison fails with TYPE_MISMATCH;-// three more read columns (`is_new`, `is_returning`, `event_name`, `status`)-// that no OpenPanel table has, and one puts a window function in HAVING. The-// defects are reproduced verbatim, not fixed: a conversion changes binding, not-// behaviour, and fixing them is a product decision with no caller to serve.+// `having(column, operator, value)` escaped its comparand as a VALUE, so every+// `'<column> * <n>'` threshold below reaches ClickHouse as a quoted string and+// the comparison fails with TYPE_MISMATCH; three more read columns (`is_new`,+// `is_returning`, `event_name`, `status`) that no OpenPanel table has, and one+// puts a window function in HAVING. The defects are reproduced verbatim, not+// fixed: a conversion changes binding, not behaviour, and fixing them is a+// product decision with no caller to serve.import {type SqlFragment,@@ -157,9 +157,9 @@ function since(days: number): SqlParam {/*** The pre-engine detector, kept for V1 parity — no live callers today.*- * M10-009: the class is no longer exported; `createLegacyInsightsScanner(deps)`- * below is the module's factory, so every service module in core is reached the- * same way (ADR-007) and nothing in the tree still exports a `*Service` class.+ * The class is no longer exported; `createLegacyInsightsScanner(deps)` below is+ * the module's factory, so every service module in core is reached the same way+ * and nothing in the tree still exports a `*Service` class.*/class LegacyInsightsScanner {constructor(private readonly deps: ChScope) {}diff --git a/packages/core/src/modules/insight/src/referrer-spikes.ts b/packages/core/src/modules/insight/src/referrer-spikes.tsindex 46835a02d..1c4e6e12c 100644--- a/packages/core/src/modules/insight/src/referrer-spikes.ts+++ b/packages/core/src/modules/insight/src/referrer-spikes.ts@@ -1,11 +1,10 @@-// M10-009: the ClickHouse CLIENT is `deps.ch` (the boot scope's round-robin-// proxy), so the requestId minted at the edge reaches these queries (ADR-018).-// Table names and the date helper are core's own copies-// (shared/ch-tables.ts, shared/ch-dates.ts).+// The ClickHouse CLIENT is `deps.ch` (the boot scope's round-robin proxy), so+// the requestId minted at the edge reaches these queries. Table names and the+// date helper are core's own copies (shared/ch-tables.ts, shared/ch-dates.ts).//-// M12-002 converted these three queries off clix: `getRawWhereClause` now-// returns a `SqlFragment` carrying bound params, and clix's `.execute()` has-// no `query_params` slot to carry them through. clix always sent+// Converted these three queries off clix: `getRawWhereClause` now returns a+// `SqlFragment` carrying bound params, and clix's `.execute` has 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';diff --git a/packages/core/src/modules/insight/src/store.ts b/packages/core/src/modules/insight/src/store.tsindex 82fd34c88..df59b75a1 100644--- a/packages/core/src/modules/insight/src/store.ts+++ b/packages/core/src/modules/insight/src/store.ts@@ -1,8 +1,8 @@-// M10-009: the store is a FACTORY over `ServiceDeps` — `deps.db` is the boot-// scope's client, so the requestId minted at the edge reaches every insight-// write (ADR-018, docs/TECH_DEBT.md §4). `Prisma` here is the namespace's JSON-// sentinel (`DbNull`), which arrives on the same scope as `deps.prisma`-// (M15-202) rather than by importing `@openpanel/db` from core.+// The store is a FACTORY over `ServiceDeps` — `deps.db` is the boot scope's+// client, so the requestId minted at the edge reaches every insight write.+// `Prisma` here is the namespace's JSON sentinel (`DbNull`), which arrives on+// the same scope as `deps.prisma` rather than by importing `@openpanel/db` from+// core.import type { Prisma } from '@openpanel/db/src/prisma-client';import type { ServiceDeps } from '../../../services';@@ -43,7 +43,7 @@ function toPersistedInsight(row: InsightRow): PersistedInsight {export function createInsightStore(deps: ServiceDeps): InsightStore {const db = deps.db;// `Prisma.DbNull` lives in the same module as the constructed client, so it- // arrives on the scope (ADR-022 R6) rather than through a lazy import.+ // arrives on the scope rather than through a lazy import.const { DbNull } = deps.prisma;return {// `cadence` isn't read — there is only one today ('daily') — but it staysdiff --git a/packages/core/src/modules/integration/integration.constants.test.ts b/packages/core/src/modules/integration/integration.constants.test.tsindex b4d542d04..2790a48c4 100644--- a/packages/core/src/modules/integration/integration.constants.test.ts+++ b/packages/core/src/modules/integration/integration.constants.test.ts@@ -1,5 +1,5 @@-// Ported from packages/validation/src/integrations.test.ts (M6-006, vitest ->-// bun:test per the module map).+// Ported from packages/validation/src/integrations.test.ts (vitest -> bun:test+// per the module map).import { describe, expect, it } from 'bun:test';import {diff --git a/packages/core/src/modules/integration/integration.constants.ts b/packages/core/src/modules/integration/integration.constants.tsindex 055175d6c..2dc244fdd 100644--- a/packages/core/src/modules/integration/integration.constants.ts+++ b/packages/core/src/modules/integration/integration.constants.ts@@ -1,15 +1,15 @@-// Moved from packages/validation/src/integrations.ts (M6-006, ADR-008's-// module map: integration owns "C"). packages/validation/src/index.ts becomes-// a re-export shim of this file (same shape as ./notification.constants.ts-// since M6-005), so packages/trpc's integration router and apps/start's-// integration forms keep resolving these symbols through-// packages/validation's existing barrel unchanged.+// Moved from packages/validation/src/integrations.ts (ADR-008's module map:+// integration owns "C"). packages/validation/src/index.ts becomes a re-export+// shim of this file (same shape as./notification.constants.ts since M6-005), so+// packages/trpc's integration router and apps/start's integration forms keep+// resolving these symbols through packages/validation's existing barrel+// unchanged.//-// `zSlackAuthResponse` does NOT move here even though it is zod-only and-// would pass `constants-stay-isomorphic`: it is Slack's OAuth token-exchange-// wire contract, not integration config a form validates against — nothing-// in apps/start ever sees it. It stays in `./src/slack-contract.ts`, defined-// as `zSlackConfig` minus the persisted `type` discriminant (see that file).+// `zSlackAuthResponse` does NOT move here even though it is zod-only and would+// pass `constants-stay-isomorphic`: it is Slack's OAuth token-exchange wire+// contract, not integration config a form validates against — nothing in+// apps/start ever sees it. It stays in `./src/slack-contract.ts`, defined as+// `zSlackConfig` minus the persisted `type` discriminant (see that file).import { z } from 'zod';diff --git a/packages/core/src/modules/integration/integration.jobs.ts b/packages/core/src/modules/integration/integration.jobs.tsindex fea8ef9a8..71d34825f 100644--- a/packages/core/src/modules/integration/integration.jobs.ts+++ b/packages/core/src/modules/integration/integration.jobs.ts@@ -1,7 +1,7 @@// Ported from apps/worker/src/jobs/cron.flush-exports.ts + boot-cron.ts's-// `flushExports` schedule (M9-003, the wave that deletes apps/worker).-// ADR-005's acceptance note gives `flushExports` to this module; the-// schedule moved onto the job at ADR-021 (M10-007).+// `flushExports` schedule (the wave that deletes apps/worker). ADR-005's+// acceptance note gives `flushExports` to this module; the schedule moved onto+// the job at ADR-021.//// `flushExports` is this module's fragment of the ONE `cron` queue's jobs,// spread into jobs.registry.ts. Scheduler id and cadence are V1's, unchanged.diff --git a/packages/core/src/modules/integration/integration.routes.ts b/packages/core/src/modules/integration/integration.routes.tsindex 15a6338ee..5211fe787 100644--- a/packages/core/src/modules/integration/integration.routes.ts+++ b/packages/core/src/modules/integration/integration.routes.ts@@ -1,16 +1,15 @@-// The Slack OAuth callback (M6-006), `GET /webhook/slack`. V1's Fastify-// controller (apps/api/src/controllers/webhook.controller.ts's `slackWebhook`)-// stays the LIVE route (DELEGATE PATTERN) and delegates its token-exchange/-// upsert logic to integration.service.ts's `completeSlackOAuthCallback` — the-// same function this route calls, same shape as gsc.routes.ts (M5-002) /-// auth.routes.ts (M6-003).+// The Slack OAuth callback, `GET /webhook/slack`. V1's Fastify controller+// (apps/api/src/controllers/webhook.controller.ts's `slackWebhook`) stays the+// LIVE route (DELEGATE PATTERN) and delegates its token-exchange/ upsert logic+// to integration.service.ts's `completeSlackOAuthCallback` — the same function+// this route calls, same shape as gsc.routes.ts / auth.routes.ts.//-// NAMED GAP, same as those two: this route is not yet reachable — main.ts-// does not mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8).-// V1's controller also renders an HTML error page from a local `error.html`-// file on failure; this route redirects to `/login?error=...` instead (same-// simplification gsc.routes.ts/auth.routes.ts already made for their own-// OAuth callbacks) since it serves no traffic yet.+// NAMED GAP, same as those two: this route is not yet reachable — main.ts does+// not mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8). V1's+// controller also renders an HTML error page from a local `error.html` file on+// failure; this route redirects to `/login?error=...` instead (same+// simplification gsc.routes.ts/auth.routes.ts already made for their own OAuth+// callbacks) since it serves no traffic yet.import { redirect } from 'elysia';import { z } from 'zod';diff --git a/packages/core/src/modules/integration/integration.rpc.ts b/packages/core/src/modules/integration/integration.rpc.tsindex 1a94a9f8c..9688f8706 100644--- a/packages/core/src/modules/integration/integration.rpc.ts+++ b/packages/core/src/modules/integration/integration.rpc.ts@@ -1,11 +1,10 @@-// Ported from packages/trpc/src/routers/integration.ts (M6-006).+// Ported from packages/trpc/src/routers/integration.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// Every access assertion (including the data-dependent "authorize against the// EXISTING row" rule) lives in integration.service.ts, not here — see thatdiff --git a/packages/core/src/modules/integration/integration.service.ts b/packages/core/src/modules/integration/integration.service.tsindex da6e3550c..0cd1edd14 100644--- a/packages/core/src/modules/integration/integration.service.ts+++ b/packages/core/src/modules/integration/integration.service.ts@@ -1,7 +1,7 @@-// Moved from packages/trpc/src/routers/integration.ts (M6-006, ADR-008's-// module map: integration owns "S"+"C"). V1's router stays the LIVE route-// (DELEGATE PATTERN) and delegates every handler body to these functions,-// same as notification's router does (M6-005).+// Moved from packages/trpc/src/routers/integration.ts (ADR-008's module map:+// integration owns "S"+"C"). V1's router stays the LIVE route (DELEGATE+// PATTERN) and delegates every handler body to these functions, same as+// notification's router does.//// Authorization here is data-dependent — an update must authorize against the// EXISTING row's scope, not the attacker-controlled input — so, unlike the@@ -13,13 +13,13 @@// `userId` (DELEGATE PATTERN), so these can't take a `ctx`/`deps` the way a// core-only module's checks would; `requireProjectAccess` /// `requireOrganizationAdmin` come from auth.service.ts's single,-// lazily-memoized `getAccessChecks()` (M10-002); `getOrganizationAccess` is a-// raw lookup (no ladder involved), reached directly from the sibling+// lazily-memoized `getAccessChecks`; `getOrganizationAccess` is a raw lookup+// (no ladder involved), reached directly from the sibling// `shared/access-lookups.ts`.//-// M10-009: every exported function takes `ServiceDeps` and reaches Postgres-// as `deps.db`; the `loadDb()` lazy loader is gone, so a requestId minted at-// the edge reaches the query (ADR-018, docs/TECH_DEBT.md §4).+// Every exported function takes `ServiceDeps` and reaches Postgres as+// `deps.db`; the `loadDb` lazy loader is gone, so a requestId minted at the+// edge reaches the query.import { z } from 'zod';import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';@@ -394,12 +394,11 @@ export async function deleteIntegration(return { id };}-// -- Slack OAuth callback ------------------------------------------------// Ported from apps/api/src/controllers/webhook.controller.ts's-// `slackWebhook` (M6-006). V1's Fastify controller stays the LIVE route-// (DELEGATE PATTERN) and delegates the token-exchange/upsert logic here, the-// same function this module's own `/webhook/slack` route-// (integration.routes.ts) calls.+// - Slack OAuth callback ----------------------------------------------- Ported+// from apps/api/src/controllers/webhook.controller.ts's `slackWebhook`. V1's+// Fastify controller stays the LIVE route (DELEGATE PATTERN) and delegates the+// token-exchange/upsert logic here, the same function this module's own+// `/webhook/slack` route (integration.routes.ts) calls.const slackOAuthMetadataSchema = z.object({organizationId: z.string(),@@ -489,7 +488,7 @@ type WithoutDeps<T extends (deps: ServiceDeps, ...args: never[]) => unknown> =: never;/** M10-009: this module had no factory at all — the one `*.service.ts` file- * `services.ts` did not register (docs/TECH_DEBT.md §5a). */+ * `services.ts` did not register. */export function createIntegrationService(deps: ServiceDeps,_services: () => Servicesdiff --git a/packages/core/src/modules/integration/src/export/index.ts b/packages/core/src/modules/integration/src/export/index.tsindex 8959858d7..cee4f6020 100644--- a/packages/core/src/modules/integration/src/export/index.ts+++ b/packages/core/src/modules/integration/src/export/index.ts@@ -1,5 +1,5 @@-// Moved from @openpanel/db's src/exports/ (M8-005) — object-store export-// batch creation, used by the flushExports cron job.+// Moved from @openpanel/db's src/exports/ — object-store export batch creation,+// used by the flushExports cron job.export {createBatch,diff --git a/packages/core/src/modules/integration/src/flush-exports.test.ts b/packages/core/src/modules/integration/src/flush-exports.test.tsindex 05ffb323f..8ec560c39 100644--- a/packages/core/src/modules/integration/src/flush-exports.test.ts+++ b/packages/core/src/modules/integration/src/flush-exports.test.ts@@ -1,7 +1,7 @@-// Moved from apps/worker/src/jobs/cron.flush-exports.test.ts (M9-003), plus-// the orchestration half V1 never covered: `runFlushExportsCron` now takes-// injected deps, so the fan-out, the watermark advance and the manifest-last-// upload order can be asserted with no infrastructure at all.+// Moved from apps/worker/src/jobs/cron.flush-exports.test.ts, plus the+// orchestration half V1 never covered: `runFlushExportsCron` now takes injected+// deps, so the fan-out, the watermark advance and the manifest-last upload+// order can be asserted with no infrastructure at all.import { describe, expect, it, mock } from 'bun:test';import { gunzipSync } from 'node:zlib';diff --git a/packages/core/src/modules/integration/src/flush-exports.ts b/packages/core/src/modules/integration/src/flush-exports.tsindex 6c2175668..c592ac71a 100644--- a/packages/core/src/modules/integration/src/flush-exports.ts+++ b/packages/core/src/modules/integration/src/flush-exports.ts@@ -1,5 +1,5 @@-// Ported from apps/worker/src/jobs/cron.flush-exports.ts (M9-003, the wave that-// deletes apps/worker). ADR-005's acceptance note gives `flushExports` to the+// Ported from apps/worker/src/jobs/cron.flush-exports.ts (the wave that deletes+// apps/worker). ADR-005's acceptance note gives `flushExports` to the// integration module. Behaviour is V1's, verbatim; Prisma, the ClickHouse// client and the object-store adapter factory arrive as injected deps so the// orchestration is testable without `mock.module` (same idiom as@@ -173,10 +173,10 @@ export async function runFlushExportsCron(}}- // ADR-022 R19: the adapters classify, this reads the flag. A permanent- // refusal (bad bucket, revoked key) is logged and left alone — the next tick- // would refuse identically. A retryable one fails the job at the end, so a- // provider outage is visible rather than a green run that exported nothing.+ // The adapters classify, this reads the flag. A permanent refusal (bad+ // bucket, revoked key) is logged and left alone — the next tick would refuse+ // identically. A retryable one fails the job at the end, so a provider outage+ // is visible rather than a green run that exported nothing.let retryableFailures = 0;await runWithConcurrency(items,diff --git a/packages/core/src/modules/integration/src/object-store/s3-adapter.ts b/packages/core/src/modules/integration/src/object-store/s3-adapter.tsindex 9e7451746..fc11a1b66 100644--- a/packages/core/src/modules/integration/src/object-store/s3-adapter.ts+++ b/packages/core/src/modules/integration/src/object-store/s3-adapter.ts@@ -98,8 +98,8 @@ export class S3Adapter implements IObjectStoreAdapter {// the network, and internal MinIO endpoints are a legitimate use.//// A refused endpoint is refused on every attempt, so it is classified- // permanent rather than left as a bare throw the caller would have to- // treat as retryable (ADR-022 R19).+ // permanent rather than left as a bare throw the caller would have to treat+ // as retryable.let addresses: string[] | null = null;if (this.config.endpoint) {try {diff --git a/packages/core/src/modules/integration/src/registry.ts b/packages/core/src/modules/integration/src/registry.tsindex 750349b70..e27a757e0 100644--- a/packages/core/src/modules/integration/src/registry.ts+++ b/packages/core/src/modules/integration/src/registry.ts@@ -1,7 +1,7 @@-// Ported from @openpanel/integrations (dissolved into core — M4-005). Moved-// out of `clients/integrations/` by M15-008: it dispatches to this module's-// own transports, so leaving it below them would have made every one of those-// edges point upward (ADR-022 R22/A2).+// Ported from @openpanel/integrations (dissolved into core — M4-005). Moved out+// of `clients/integrations/` by M15-008: it dispatches to this module's own+// transports, so leaving it below them would have made every one of those edges+// point upward (A2).import {type EncryptionKey,@@ -131,10 +131,10 @@ export interface IConfigSecret<C> {}/**- * ADR-022 R19: a delivery that the destination did not accept is a- * `ProviderError`, carrying the `retryable` the transport already classified.- * Returning the failed result instead is what let a 500 from a customer's- * webhook report as a delivered notification.+ * A delivery that the destination did not accept is a `ProviderError`, carrying+ * the `retryable` the transport already classified. Returning the failed result+ * instead is what let a 500 from a customer's webhook report as a delivered+ * notification.*/async function deliverWebhook(provider: string,diff --git a/packages/core/src/modules/integration/src/slack.ts b/packages/core/src/modules/integration/src/slack.tsindex daf3a36d2..a16fd2d9a 100644--- a/packages/core/src/modules/integration/src/slack.ts+++ b/packages/core/src/modules/integration/src/slack.ts@@ -1,7 +1,7 @@-// Ported from @openpanel/integrations (dissolved into core — M4-005). Moved-// out of `clients/integrations/` by M15-008: this module is its only consumer-// (ADR-022 A2).-// Cred to (@c_alares) https://github.com/christianalares/seventy-seven/blob/main/packages/integrations/src/slack/index.ts+// Ported from @openpanel/integrations (dissolved into core — M4-005). Moved out+// of `clients/integrations/` by M15-008: this module is its only consumer+// (ADR-022 A2). Cred to (@c_alares)+// https://github.com/christianalares/seventy-seven/blob/main/packages/integrations/src/slack/index.tsimport * as Slack from '@slack/bolt';import {@@ -24,9 +24,9 @@ const INSTALL_SCOPES = [];/**- * Built from the credentials the config loader parsed (ADR-022 R9). Without a- * client id there is no install flow, and the stub keeps the two members the- * integration module touches so an unconfigured deployment still boots.+ * Built from the credentials the config loader parsed. Without a client id+ * there is no install flow, and the stub keeps the two members the integration+ * module touches so an unconfigured deployment still boots.*/export function slackInstaller(config: CoreConfig): InstallProvider {const { clientId, clientSecret, stateSecret } = config.slack;diff --git a/packages/core/src/modules/mcp/mcp.routes.ts b/packages/core/src/modules/mcp/mcp.routes.tsindex b6cb044cb..bf39f378b 100644--- a/packages/core/src/modules/mcp/mcp.routes.ts+++ b/packages/core/src/modules/mcp/mcp.routes.ts@@ -1,21 +1,21 @@-// MCP's stateless POST transport, mounted at `/mcp` (M5-007, ADR-015 entry 2).+// MCP's stateless POST transport, mounted at `/mcp` (ADR-015 entry 2).//// `ctx.services.mcp` carries this module's factory the same as every other-// module now (M10-004) — `mcp.service.ts`'s own header explains why that-// file is now safe to reach through `ctx.services` instead of this route's-// former one-off `loadMcpService()`.+// module now — `mcp.service.ts`'s own header explains why that file is now safe+// to reach through `ctx.services` instead of this route's former one-off+// `loadMcpService`.//-// OPEN GAP: V1's 60/min rate limit (Fastify's activateRateLimiter) is still-// not ported, and the route IS live — `apps/api/src/main.ts` mounts-// `dashboardRoutes` for every non-worker role. So an unauthenticated caller-// can drive one argon2 verify per request: `src/auth.ts` caches a *correct*-// secret for 5 minutes under a key containing that secret's hash, which a-// wrong secret misses every time. Porting the limiter is a task for whoever-// owns the HTTP surface; nothing in this module can do it.+// OPEN GAP: V1's 60/min rate limit (Fastify's activateRateLimiter) is still not+// ported, and the route IS live — `apps/api/src/main.ts` mounts+// `dashboardRoutes` for every non-worker role. So an unauthenticated caller can+// drive one argon2 verify per request: `src/auth.ts` caches a *correct* secret+// for 5 minutes under a key containing that secret's hash, which a wrong secret+// misses every time. Porting the limiter is a task for whoever owns the HTTP+// surface; nothing in this module can do it.//-// The JSON-RPC body comes off the CONTEXT, not from `request.json()`: Elysia-// has already consumed the stream by the time the handler runs, and reading it-// twice throws "Body already used" (M9-004, caught by the auth contracts).+// The JSON-RPC body comes off the CONTEXT, not from `request.json`: Elysia has+// already consumed the stream by the time the handler runs, and reading it+// twice throws "Body already used" (caught by the auth contracts).import { defineRoutes } from '../../http/define';diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.tsindex 2be373d23..8f22073e7 100644--- a/packages/core/src/modules/mcp/mcp.service.test.ts+++ b/packages/core/src/modules/mcp/mcp.service.test.ts@@ -9,14 +9,14 @@* the real SDK server, `InMemoryTransport`, the wire-format handshake, tool* registration and dispatch — runs for real.*- * M15-003: `deps` and `services` are now ARGUMENTS, so the Postgres handle- * and the client lookup are supplied by the test rather than mocked into the- * module registry. The only surviving `mock.module` calls are for the two- * process-global seams MCP auth still reaches (`@openpanel/redis`'s- * `getCache` and argon2 verification), and both are restored in `afterAll`- * from a plain-object snapshot taken before the first `mock.module` call —- * restoring via the live `await import(...)` binding itself is a no-op once- * mocked, since namespace bindings track the current mock.+ * `deps` and `services` are now ARGUMENTS, so the Postgres handle and the+ * client lookup are supplied by the test rather than mocked into the module+ * registry. The only surviving `mock.module` calls are for the two+ * process-global seams MCP auth still reaches (`@openpanel/redis`'s `getCache`+ * and argon2 verification), and both are restored in `afterAll` from a+ * plain-object snapshot taken before the first `mock.module` call — restoring+ * via the live `await import(...)` binding itself is a no-op once mocked, since+ * namespace bindings track the current mock.*/import {@@ -94,8 +94,8 @@ const noopLogger = {const deps = {db: { project: { findUnique: mockFindUnique } },- // The tool runtime is handed `Prisma.DbNull` off the scope (ADR-022 R6);- // nothing in this suite writes a Json column, so a marker is enough.+ // The tool runtime is handed `Prisma.DbNull` off the scope; nothing in this+ // suite writes a Json column, so a marker is enough.prisma: { DbNull: 'DbNull', JsonNull: 'JsonNull' },logger: noopLogger,} as unknown as ServiceDeps;@@ -302,7 +302,7 @@ describe('handleStatelessMcpRequest — protocol', () => {});it('closes the ephemeral server — and with it the transport pair it opened', async () => {- // ADR-022 R16. `spyOn` calls through, so the close still really happens.+ // R16. `spyOn` calls through, so the close still really happens.const closeSpy = spyOn(McpServer.prototype, 'close');try {const res = await post(VALID_TOKEN, {diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.tsindex dfbff85af..916d592dd 100644--- a/packages/core/src/modules/mcp/mcp.service.ts+++ b/packages/core/src/modules/mcp/mcp.service.ts@@ -1,22 +1,22 @@-// Stateless-POST MCP transport (ADR-015 entry 2, M5-007). V1 kept a Redis-// session store (`mcp:session:<uuid>`, 30-min TTL) and a `Mcp-Session-Id`-// header that could stand in for the token on every request after the-// first — both removed here, along with GET/SSE (already an unconditional-// 405 — deletes nothing that ever worked) and DELETE. Every POST-// authenticates from scratch and gets its own ephemeral McpServer; nothing-// survives between requests, so there is no session to store, touch or-// close, and no cross-instance stickiness requirement.+// Stateless-POST MCP transport (ADR-015 entry 2). V1 kept a Redis session store+// (`mcp:session:<uuid>`, 30-min TTL) and a `Mcp-Session-Id` header that could+// stand in for the token on every request after the first — both removed here,+// along with GET/SSE (already an unconditional 405 — deletes nothing that ever+// worked) and DELETE. Every POST authenticates from scratch and gets its own+// ephemeral McpServer; nothing survives between requests, so there is no+// session to store, touch or close, and no cross-instance stickiness+// requirement.//// MCP is the one module the wave map allows to change its endpoint surface —// every other module in this wave preserves its V1 contract byte-for-byte.//-// M15-003: MCP is NOT a separate process and has no dependency builder of its-// own. `rest.routes.ts` mounts it with `.use(mcpRoutes(deps))`, so the route-// already holds the API's connections; this factory closes over them and-// hands them to `createMcpServer` per request (ADR-022 R6/R15, Carl's-// ruling). The `@modelcontextprotocol/sdk` tool-handler signature has no-// context parameter, which is a CLOSURE problem — solved by building the-// server where `deps` is in hand — not a context problem.+// MCP is NOT a separate process and has no dependency builder of its own.+// `rest.routes.ts` mounts it with `.use(mcpRoutes(deps))`, so the route already+// holds the API's connections; this factory closes over them and hands them to+// `createMcpServer` per request (R15, Carl's ruling). The+// `@modelcontextprotocol/sdk` tool-handler signature has no context parameter,+// which is a CLOSURE problem — solved by building the server where `deps` is in+// hand — not a context problem.import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import {@@ -166,11 +166,11 @@ async function runOnEphemeralServer(clientTransport.send(message).catch(reject);});} finally {- // ADR-022 R16: this function opened the pair, so this function closes it.- // `server.close()` closes `serverTransport`, and an InMemoryTransport- // closes its linked peer, so one call tears down both ends — and with- // them the SDK's response handlers and in-flight abort controllers,- // which a dropped-on-the-floor server would have kept alive until GC.+ // This function opened the pair, so this function closes it. `server.close`+ // closes `serverTransport`, and an InMemoryTransport closes its linked+ // peer, so one call tears down both ends — and with them the SDK's response+ // handlers and in-flight abort controllers, which a dropped-on-the-floor+ // server would have kept alive until GC.await server.close();}}@@ -261,8 +261,8 @@ function logToolResult(/*** The MCP tool tree reaches Postgres and ClickHouse through the `deps` this- * factory closes over — there is no singleton and no "no context" path left- * (ADR-022 R6). `extractToken` is pure and stays a bare re-export.+ * factory closes over — there is no singleton and no "no context" path left.+ * `extractToken` is pure and stays a bare re-export.*/export function createMcpService(deps: ServiceDeps, services: () => Services) {return {diff --git a/packages/core/src/modules/mcp/src/auth.test.ts b/packages/core/src/modules/mcp/src/auth.test.tsindex 65876b0cd..3102b8423 100644--- a/packages/core/src/modules/mcp/src/auth.test.ts+++ b/packages/core/src/modules/mcp/src/auth.test.ts@@ -25,12 +25,12 @@ const noopLogger = {child: () => noopLogger,};-// M15-003: the client lookup and the logger are ARGUMENTS now — `deps` and-// `services` come from the route, so only `@openpanel/redis`'s process-global-// `getCache` and argon2 verification are still mocked at the specifier the-// source resolves to (a whole-barrel replacement would drop every other-// export those barrels carry for any other file sharing this process —-// bun:test only isolates modules per file under `--isolate`, see AGENTS.md).+// The client lookup and the logger are ARGUMENTS now — `deps` and `services`+// come from the route, so only `@openpanel/redis`'s process-global `getCache`+// and argon2 verification are still mocked at the specifier the source resolves+// to (a whole-barrel replacement would drop every other export those barrels+// carry for any other file sharing this process — bun:test only isolates+// modules per file under `--isolate`, see AGENTS.md).const actualRedis = await import('@openpanel/redis');mock.module('@openpanel/redis', () => ({...actualRedis,diff --git a/packages/core/src/modules/mcp/src/integration/tools.test.ts b/packages/core/src/modules/mcp/src/integration/tools.test.tsindex 6c2922395..c737acd6b 100644--- a/packages/core/src/modules/mcp/src/integration/tools.test.ts+++ b/packages/core/src/modules/mcp/src/integration/tools.test.ts@@ -106,9 +106,9 @@ beforeAll(async () => {pinFixtureClock();await fixtures.setupFixtures(TEST_PROJECT_ID);- // M15-003: the tools take `deps`/`services` as arguments, so the suite- // builds the same graph `mcp.routes.ts` hands them at runtime — no compat- // seam, no process-global registration.+ // The tools take `deps`/`services` as arguments, so the suite builds the same+ // graph `mcp.routes.ts` hands them at runtime — no compat seam, no+ // process-global registration.const { testServiceDeps } = await import('../../../../../test/service-deps');const { createServices } = await import('../../../../services');const deps = await testServiceDeps();diff --git a/packages/core/src/modules/mcp/src/server.ts b/packages/core/src/modules/mcp/src/server.tsindex 580fe9490..c71db15e4 100644--- a/packages/core/src/modules/mcp/src/server.ts+++ b/packages/core/src/modules/mcp/src/server.ts@@ -8,10 +8,10 @@ const SERVER_VERSION = '1.0.0';/*** Create a fully configured McpServer for one authenticated request.*- * The API owns every connection (ADR-022 R6/R15, Carl's ruling): the server- * is bootstrapped from the `deps` `mcp.routes.ts` already holds, and each- * tool handler CLOSES OVER them — the SDK's tool-handler signature has no- * context parameter, which is a closure problem, not a context problem.+ * The API owns every connection (R15, Carl's ruling): the server is+ * bootstrapped from the `deps` `mcp.routes.ts` already holds, and each tool+ * handler CLOSES OVER them — the SDK's tool-handler signature has no context+ * parameter, which is a closure problem, not a context problem.*/export function createMcpServer(tools: McpToolDeps): McpServer {const server = new McpServer(diff --git a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.tsindex 36bde3936..3fc36b419 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/page-performance.test.ts@@ -15,16 +15,15 @@ const mockGetSettingsForProject = mock(() =>Promise.resolve({ timezone: 'UTC' }));-// M15-003: the tool reads the pages service off the `services` graph handed-// in with `deps`, so `getTopPages` is a plain stub on TOOLS below rather than-// a module mock. Only the two sibling module functions this file drives are-// still replaced, each at the specifier the source imports resolve to — a+// The tool reads the pages service off the `services` graph handed in with+// `deps`, so `getTopPages` is a plain stub on TOOLS below rather than a module+// mock. Only the two sibling module functions this file drives are still+// replaced, each at the specifier the source imports resolve to — a// whole-barrel replacement would drop every other export those modules carry// for any other file sharing this process (bun:test only isolates modules per// file under `--isolate`; see AGENTS.md) — and each is restored in `afterAll`-// from a plain-object snapshot taken BEFORE the first `mock.module` call,-// since restoring via the live `await import(...)` binding is a no-op once-// mocked.+// from a plain-object snapshot taken BEFORE the first `mock.module` call, since+// restoring via the live `await import(...)` binding is a no-op once mocked.const actualOrganizationService = await import('../../../../organization/organization.service');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 0f4916764..0917746f6 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/profiles.test.ts@@ -1,10 +1,10 @@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 ch-query.ts), so the client is HANDED IN rather-// than mocked onto `@openpanel/db/src/clickhouse/client` process-wide. Same-// assertions, one less shared-registry hazard.+// `findProfilesCore` takes `ServiceDeps` and reaches ClickHouse as `deps.ch`+// (through ch-query.ts), so the client is HANDED IN rather than mocked onto+// `@openpanel/db/src/clickhouse/client` process-wide. Same assertions, one less+// shared-registry hazard.const chQuery = mock(async (_params: {query: string;@@ -34,8 +34,8 @@ beforeAll(async () => {({ findProfilesCore } = await import('../../../../profile/profile.service'));});-// Since M7-002 the service hands ClickHouse a `sql` fragment (ADR-013): the-// text carries `{pN:Type}` placeholders and every value travels in params.+// Since M7-002 the service hands ClickHouse a `sql` fragment: the text carries+// `{pN:Type}` placeholders and every value travels in params.function captured(): { query: string; params: Record<string, unknown> } {const call = chQuery.mock.calls[0]?.[0];return {diff --git a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts b/packages/core/src/modules/mcp/src/tools/analytics/reports.tsindex ae1f52166..9f53d61b8 100644--- a/packages/core/src/modules/mcp/src/tools/analytics/reports.ts+++ b/packages/core/src/modules/mcp/src/tools/analytics/reports.ts@@ -294,17 +294,15 @@ export function registerReportTools(}/**- * Execute a saved report by ID. Dispatches on chart type:- * - funnel → getFunnel- * - metric → AggregateChartEngine.execute- * - others → ChartEngine.execute+ * Execute a saved report by ID. Dispatches on chart type: - funnel → getFunnel+ * - metric → AggregateChartEngine.execute - others → ChartEngine.execute*- * The assistant module (`../../assistant/src/report-runner.ts`, M5-005)- * carries its own copy of this dispatch for its in-app chat tools — ADR-007- * explicitly defers unifying MCP's tool definitions with assistant's (M5-007),- * so the two live as hand-synced copies rather than a shared helper.- * Deliberately returns the raw engine output here — the MCP tool reshapes it- * for LLM consumption, the chat renderer needs the full chart.+ * The assistant module (`../../assistant/src/report-runner.ts`) carries its own+ * copy of this dispatch for its in-app chat tools — ADR-007 explicitly defers+ * unifying MCP's tool definitions with assistant's, so the two live as+ * hand-synced copies rather than a shared helper. Deliberately returns the raw+ * engine output here — the MCP tool reshapes it for LLM consumption, the chat+ * renderer needs the full chart.*/async function runReport(deps: ServiceDeps,diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.tsindex f072cdd95..ea43da3a1 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.test.ts@@ -57,15 +57,14 @@ const mockGetDashboardById = mock();const mockGetProjectById = mock();const mockGetId = mock();-// M15-003: Postgres arrives on `deps.db` (see TOOLS below), so the only-// module mocks left are the three sibling functions this file asserts calls-// against. Each is replaced at the specifier the source imports resolve to —-// a whole-barrel replacement would drop every other export those modules-// carry for any other file sharing this process (bun:test only isolates-// modules per file under `--isolate`; see AGENTS.md) — and each is restored-// in `afterAll` from a plain-object snapshot taken BEFORE the first-// `mock.module` call, since restoring via the live `await import(...)`-// binding is a no-op once mocked.+// Postgres arrives on `deps.db` (see TOOLS below), so the only module mocks+// left are the three sibling functions this file asserts calls against. Each is+// replaced at the specifier the source imports resolve to — a whole-barrel+// replacement would drop every other export those modules carry for any other+// file sharing this process (bun:test only isolates modules per file under+// `--isolate`; see AGENTS.md) — and each is restored in `afterAll` from a+// plain-object snapshot taken BEFORE the first `mock.module` call, since+// restoring via the live `await import(...)` binding is a no-op once mocked.const actualDashboardService = await import('../../../dashboard/dashboard.service');diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts b/packages/core/src/modules/mcp/src/tools/dashboard-management.tsindex 679fc771e..63ec9c48d 100644--- a/packages/core/src/modules/mcp/src/tools/dashboard-management.ts+++ b/packages/core/src/modules/mcp/src/tools/dashboard-management.ts@@ -143,11 +143,11 @@ function reportUrl(return `${dashboardBaseUrl(config)}/${organizationId}/${projectId}/reports/${reportId}`;}-// `dbNull` is `Prisma.DbNull` (an explicit SQL NULL on a nullable Json-// column), threaded in as `unknown` rather than importing `@openpanel/db`-// here — same shape notification.service.ts's `isValidPayload` uses for the-// same sentinel. It arrives on `McpToolDeps.dbJsonNull`, resolved once by-// `mcp.service.ts` when it builds the server (ADR-022 R6).+// `dbNull` is `Prisma.DbNull` (an explicit SQL NULL on a nullable Json column),+// threaded in as `unknown` rather than importing `@openpanel/db` here — same+// shape notification.service.ts's `isValidPayload` uses for the same sentinel.+// It arrives on `McpToolDeps.dbJsonNull`, resolved once by `mcp.service.ts`+// when it builds the server.function reportData(report: z.infer<typeof reportSchema>, dbNull: unknown) {return {name: report.name,diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.tsindex cf7b263ec..37a9cbc1c 100644--- a/packages/core/src/modules/mcp/src/tools/shared.ts+++ b/packages/core/src/modules/mcp/src/tools/shared.ts@@ -9,9 +9,9 @@ import type { McpAuthContext } from '../auth';** `@modelcontextprotocol/sdk`'s tool-handler signature has no context* parameter, so the API's connections cannot be threaded through it as an- * argument. They are captured in a CLOSURE instead, when the per-request- * server is built from the `deps` the route already holds (ADR-022 R6/R15,- * Carl's ruling: `createMcpServer(deps)`).+ * argument. They are captured in a CLOSURE instead, when the per-request server+ * is built from the `deps` the route already holds (R15, Carl's ruling:+ * `createMcpServer(deps)`).*/export interface McpToolDeps {/** The API's connections. Postgres and ClickHouse are reached from here. */diff --git a/packages/core/src/modules/misc/misc.jobs.ts b/packages/core/src/modules/misc/misc.jobs.tsindex 963e86468..d24e563fd 100644--- a/packages/core/src/modules/misc/misc.jobs.ts+++ b/packages/core/src/modules/misc/misc.jobs.ts@@ -1,14 +1,13 @@// Ported from apps/worker/src/jobs/cron.ping.ts + boot-cron.ts's `ping`-// schedule (M7-008); `dataHealth` joined it at M9-003, the wave that deletes-// apps/worker (ADR-005's acceptance note gives it to this module).+// schedule; `dataHealth` joined it at M9-003, the wave that deletes apps/worker+// (ADR-005's acceptance note gives it to this module).//// `ping` is this module's fragment of the ONE `cron` queue's jobs: declared-// here and spread into jobs.registry.ts, same shape as-// organization.jobs.ts's `delete` (M6-001). Its `cron` is explicitly `null`-// (ADR-021's on-demand state, not "always scheduled") — `PING_SCHEDULE` in-// jobs/schedulers.ts adds it separately, conditionally on-// `SELF_HOSTED && production`, because it is the one scheduler that isn't-// always-on.+// here and spread into jobs.registry.ts, same shape as organization.jobs.ts's+// `delete`. Its `cron` is explicitly `null` (ADR-021's on-demand state, not+// "always scheduled") — `PING_SCHEDULE` in jobs/schedulers.ts adds it+// separately, conditionally on `SELF_HOSTED && production`, because it is the+// one scheduler that isn't always-on.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/misc/misc.routes.ts b/packages/core/src/modules/misc/misc.routes.tsindex 749f17803..b6129888a 100644--- a/packages/core/src/modules/misc/misc.routes.ts+++ b/packages/core/src/modules/misc/misc.routes.ts@@ -1,7 +1,7 @@// Ported from apps/api/src/routes/misc.router.ts +-// apps/api/src/controllers/misc.controller.ts (M7-008). V1's Fastify router-// stays the LIVE route (DELEGATE PATTERN) and calls the same misc.service.ts-// functions this file does.+// apps/api/src/controllers/misc.controller.ts. V1's Fastify router stays the+// LIVE route (DELEGATE PATTERN) and calls the same misc.service.ts functions+// this file does.//// `GET /misc/og/clear` and `GET /misc/favicon/clear` are dropped, not ported// (ADR-015 entry #6: RULED + DEAD — `docs/ANSWERS.md` §1.4 confirms nothingdiff --git a/packages/core/src/modules/misc/misc.service.ts b/packages/core/src/modules/misc/misc.service.tsindex 5f8180eef..2ccc7f66a 100644--- a/packages/core/src/modules/misc/misc.service.ts+++ b/packages/core/src/modules/misc/misc.service.ts@@ -1,25 +1,23 @@// Ported from apps/api/src/controllers/misc.controller.ts +-// apps/worker/src/jobs/cron.ping.ts (M7-008). V1's Fastify controller and the-// worker's `cron.ping.ts` stay the LIVE code paths (DELEGATE PATTERN) and-// call the functions below verbatim — no new behaviour.+// apps/worker/src/jobs/cron.ping.ts. V1's Fastify controller and the worker's+// `cron.ping.ts` stay the LIVE code paths (DELEGATE PATTERN) and call the+// functions below verbatim — no new behaviour.//// `GET/POST /misc/og/clear` and `/misc/favicon/clear` are NOT ported: ADR-015// entry #6 grades them RULED + DEAD (`docs/ANSWERS.md` §1.4 confirms no proxy// depends on them), so this wave is where V1 drops them too.//-// M10-005: the ClickHouse CLIENT is `deps.ch` — reads through-// 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-// own parity-tested copies of both (shared/ch-tables.ts, shared/ch-dates.ts,-// guarded by their `.parity.test.ts` siblings). Converting the STATEMENTS is-// ADR-013's P7 work, not this wave's.+// The ClickHouse CLIENT is `deps.ch` — reads through 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 own parity-tested copies of both+// (shared/ch-tables.ts, shared/ch-dates.ts, guarded by their `.parity.test.ts`+// siblings). Converting the STATEMENTS is ADR-013's P7 work, not this wave's.//-// M15-202: `getCache` is a plain static import (ADR-022 R6). It was lazy to-// survive core tests that partially mock `@openpanel/redis` without a-// `getCache` export; those mocks snapshot the real module and spread it now,-// so the loader bought nothing.+// `getCache` is a plain static import. It was lazy to survive core tests that+// partially mock `@openpanel/redis` without a `getCache` export; those mocks+// snapshot the real module and spread it now, so the loader bought nothing.import crypto from 'node:crypto';import { getCache, getRedisCache } from '@openpanel/redis';diff --git a/packages/core/src/modules/misc/src/data-health.ts b/packages/core/src/modules/misc/src/data-health.tsindex 57d654e1a..33454a851 100644--- a/packages/core/src/modules/misc/src/data-health.ts+++ b/packages/core/src/modules/misc/src/data-health.ts@@ -1,8 +1,8 @@-// Ported from apps/worker/src/jobs/cron.data-health.ts (M9-003, the wave that-// deletes apps/worker). ADR-005's acceptance note gives `dataHealth` to the-// misc module. Behaviour is V1's, verbatim; Prisma, the last-event lookup and+// Ported from apps/worker/src/jobs/cron.data-health.ts (the wave that deletes+// apps/worker). ADR-005's acceptance note gives `dataHealth` to the misc+// module. Behaviour is V1's, verbatim; Prisma, the last-event lookup and// `sendEmail` arrive as injected deps so the job is testable without-// `mock.module`. `misc.jobs.ts` binds them off the job's ctx (M10-006).+// `mock.module`. `misc.jobs.ts` binds them off the job's ctx.import type { CoreConfig } from '../../../config';import type { Logger } from '../../../logger';diff --git a/packages/core/src/modules/misc/src/image-proxy.test.ts b/packages/core/src/modules/misc/src/image-proxy.test.tsindex 991b9fbce..47d622082 100644--- a/packages/core/src/modules/misc/src/image-proxy.test.ts+++ b/packages/core/src/modules/misc/src/image-proxy.test.ts@@ -1,4 +1,4 @@-// Ported from apps/api/src/utils/image-proxy.test.ts (M7-008).+// Ported from apps/api/src/utils/image-proxy.test.ts.import { describe, expect, it } from 'bun:test';import sharp from 'sharp';diff --git a/packages/core/src/modules/misc/src/image-proxy.ts b/packages/core/src/modules/misc/src/image-proxy.tsindex 3d2bc7bb3..b2a7ac444 100644--- a/packages/core/src/modules/misc/src/image-proxy.ts+++ b/packages/core/src/modules/misc/src/image-proxy.ts@@ -1,11 +1,12 @@-// Ported verbatim from apps/api/src/utils/image-proxy.ts (M7-008).+// Ported verbatim from apps/api/src/utils/image-proxy.ts.//// These bytes come from a third-party server and are then served from the API// origin, which also serves the credentialed `/trpc` and `/oauth` endpoints.// Anything returned verbatim is therefore attacker-controlled content on a// trusted origin — an SVG passed through untouched executes its `<script>` as// the victim. Everything Sharp can decode is rasterized to PNG, which drops-// active content along with every other non-pixel payload (GHSA-r7hx-q6f4-vj6h).+// active content along with every other non-pixel payload+// (GHSA-r7hx-q6f4-vj6h).import sharp from 'sharp';import type { Logger } from '../../../logger';diff --git a/packages/core/src/modules/misc/src/parse-url-meta.ts b/packages/core/src/modules/misc/src/parse-url-meta.tsindex 894f4eb0f..5c088c8ff 100644--- a/packages/core/src/modules/misc/src/parse-url-meta.ts+++ b/packages/core/src/modules/misc/src/parse-url-meta.ts@@ -1,4 +1,4 @@-// Ported verbatim from apps/api/src/utils/parseUrlMeta.ts (M7-008).+// Ported verbatim from apps/api/src/utils/parseUrlMeta.ts.import urlMetadata from 'url-metadata';diff --git a/packages/core/src/modules/notification/notification.constants.ts b/packages/core/src/modules/notification/notification.constants.tsindex 4ea972f5b..f2b04b0f2 100644--- a/packages/core/src/modules/notification/notification.constants.ts+++ b/packages/core/src/modules/notification/notification.constants.ts@@ -1,20 +1,20 @@-// Moved from packages/validation/src/index.ts (M6-005, ADR-008's module map:-// notification owns "C"). packages/validation/src/index.ts becomes a-// re-export shim of this file (same shape as ./onboarding.constants.ts since-// M6-003), so packages/trpc's notification router and apps/start's-// notification rule form keep resolving these symbols through-// packages/validation's existing barrel unchanged.+// Moved from packages/validation/src/index.ts (ADR-008's module map:+// notification owns "C"). packages/validation/src/index.ts becomes a re-export+// shim of this file (same shape as./onboarding.constants.ts since M6-003), so+// packages/trpc's notification router and apps/start's notification rule form+// keep resolving these symbols through packages/validation's existing barrel+// unchanged.//// `zChartEvent`/`zChartEventFilter` are chart/report vocabulary that has not// moved to core yet (ADR-008's "report" module is a later wave), so per// `constants-stay-isomorphic` (zod, another `*.constants.ts`, or type-only —-// nothing else) they cannot be value-imported from packages/validation-// here. Diverged local copy instead, same treatment as-// ./modules/cohort/cohort.constants.ts's zChartEventFilter since M5-003 —-// including inlining `operators`/`chartSegments`/`filterValueTypes` as-// literal key tuples rather than importing them from packages/constants.-// TODO(report module): once report.constants.ts exists, delete this-// duplicate and import zChartEvent from there instead.+// nothing else) they cannot be value-imported from packages/validation here.+// Diverged local copy instead, same treatment+// as./modules/cohort/cohort.constants.ts's zChartEventFilter since M5-003 —+// including inlining `operators`/`chartSegments`/`filterValueTypes` as literal+// key tuples rather than importing them from packages/constants. TODO(report+// module): once report.constants.ts exists, delete this duplicate and import+// zChartEvent from there instead.//// Isomorphic by the AGENTS.md rule otherwise: zod and nothing else.diff --git a/packages/core/src/modules/notification/notification.jobs.ts b/packages/core/src/modules/notification/notification.jobs.tsindex 35997b473..b3bffa06a 100644--- a/packages/core/src/modules/notification/notification.jobs.ts+++ b/packages/core/src/modules/notification/notification.jobs.ts@@ -1,10 +1,10 @@-// Ported from apps/worker/src/jobs/notification.ts (M6-005).+// Ported from apps/worker/src/jobs/notification.ts.//-// `sendNotification` is this module's own queue (`notification` in the-// registry — ADR-005's registry key). legacyCompat.notification already-// discriminates on this exact job name (jobs/compat.ts), so this pins the two-// in agreement. No cron fragment — notifications are always triggered by a-// rule match, never scheduled.+// `sendNotification` is this module's own queue (`notification` in the registry+// — ADR-005's registry key). legacyCompat.notification already discriminates on+// this exact job name (jobs/compat.ts), so this pins the two in agreement. No+// cron fragment — notifications are always triggered by a rule match, never+// scheduled.import type { Prisma } from '@openpanel/db/src/prisma-client';import { z } from 'zod';@@ -41,10 +41,10 @@ export const notificationQueueJobs = {payload.notification as Prisma.NotificationUncheckedCreateInput);} catch (error) {- // ADR-022 R19: the transport classified this once. A destination that- // refused the request (4xx) will refuse the identical retry, so it is- // logged and the job completes; anything retryable is rethrown so the- // failure is recorded against the job.+ // The transport classified this once. A destination that refused the+ // request (4xx) will refuse the identical retry, so it is logged and+ // the job completes; anything retryable is rethrown so the failure is+ // recorded against the job.if (isProviderError(error) && !error.retryable) {ctx.logger.error({diff --git a/packages/core/src/modules/notification/notification.rpc.ts b/packages/core/src/modules/notification/notification.rpc.tsindex 92c824b66..fd47d2abf 100644--- a/packages/core/src/modules/notification/notification.rpc.ts+++ b/packages/core/src/modules/notification/notification.rpc.ts@@ -1,19 +1,18 @@-// Ported from packages/trpc/src/routers/notification.ts (M6-005).+// Ported from packages/trpc/src/routers/notification.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// `list`/`rules` have no access check here either — same gap V1's router has// (ported verbatim, not fixed; see notification.service.ts's header for why-// `deleteRule` and `createOrUpdateRule` re-check access against the-// *existing* rule's project, not just the input's).+// `deleteRule` and `createOrUpdateRule` re-check access against the *existing*+// rule's project, not just the input's).//-// The permission ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The permission ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/notification/notification.service.test.ts b/packages/core/src/modules/notification/notification.service.test.tsindex 32f218193..8e527715d 100644--- a/packages/core/src/modules/notification/notification.service.test.ts+++ b/packages/core/src/modules/notification/notification.service.test.ts@@ -43,10 +43,10 @@ function makeRule(overrides: Partial<FakeRule> & { id: string }): FakeRule {}const publishedEvents: unknown[] = [];-// M10-009: spread a plain-object SNAPSHOT of the real module and restore it in-// afterAll — `mock.module` has no per-file scope under bare `bun test`-// (AGENTS.md), and a partial factory deletes `getRedisCache` and friends for-// every file that runs next.+// Spread a plain-object SNAPSHOT of the real module and restore it in afterAll+// — `mock.module` has no per-file scope under bare `bun test` (AGENTS.md), and+// a partial factory deletes `getRedisCache` and friends for every file that+// runs next.const realRedis = { ...(await import('@openpanel/redis')) };mock.module('@openpanel/redis', () => ({...realRedis,@@ -124,10 +124,9 @@ const project = {findUniqueOrThrow: mock(async () => ({ organizationId: 'org_1' })),};-// M10-009: every function under test takes `ServiceDeps`, so `deps.db` IS the-// fake below. The `@openpanel/db/src/prisma-client` mock stays for-// `Prisma.JsonNull` / `Prisma.DbNull`, which `prismaSentinels()` reads from-// that module.+// Every function under test takes `ServiceDeps`, so `deps.db` IS the fake+// below. The `@openpanel/db/src/prisma-client` mock stays for `Prisma.JsonNull`+// / `Prisma.DbNull`, which `prismaSentinels` reads from that module.const actualPrismaClient = await import('@openpanel/db/src/prisma-client');mock.module('@openpanel/db/src/prisma-client', () => ({...actualPrismaClient,diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.tsindex dd9e2e683..f8499a51a 100644--- a/packages/core/src/modules/notification/notification.service.ts+++ b/packages/core/src/modules/notification/notification.service.ts@@ -1,19 +1,19 @@-// Moved from packages/db/src/services/notification.service.ts (M6-005,-// ADR-008's module map: "rules + dispatch stay together"). The delivery body-// moves here too, from apps/worker/src/jobs/notification.ts (DELEGATE-// PATTERN: that file becomes a thin wrapper calling `deliverNotification`).+// Moved from packages/db/src/services/notification.service.ts (ADR-008's module+// map: "rules + dispatch stay together"). The delivery body moves here too,+// from apps/worker/src/jobs/notification.ts (DELEGATE PATTERN: that file+// becomes a thin wrapper calling `deliverNotification`).//-// `createNotification` / `triggerNotification` / `checkNotificationRulesForEvent`-// / `checkNotificationRulesForSessionEnd` — the BullMQ-producer orchestration-// around a rule match — live in this module's own `src/notification-dispatch.ts`-// since M11-003, built on the rule matching, templates, cache and constants-// exported below. They are a separate file only so the enqueue side is not-// dragged into every import of this one.+// `createNotification` / `triggerNotification` /+// `checkNotificationRulesForEvent` / `checkNotificationRulesForSessionEnd` —+// the BullMQ-producer orchestration around a rule match — live in this module's+// own `src/notification-dispatch.ts` since M11-003, built on the rule matching,+// templates, cache and constants exported below. They are a separate file only+// so the enqueue side is not dragged into every import of this one.//-// Postgres is `deps.db` and `Prisma.DbNull` is `deps.prisma.DbNull`-// (M15-202): nothing here imports @openpanel/db as a value, which is what-// keeps constructing a client out of the eager barrel chain that-// jobs.registry.ts and services.ts pull this module into.+// Postgres is `deps.db` and `Prisma.DbNull` is `deps.prisma.DbNull`: nothing+// here imports @openpanel/db as a value, which is what keeps constructing a+// client out of the eager barrel chain that jobs.registry.ts and services.ts+// pull this module into.import type { Integration, Prisma } from '@openpanel/db/src/prisma-client';import { stripLeadingAndTrailingSlashes } from '@openpanel/shared';@@ -71,9 +71,9 @@ export type INotificationPayload =| { type: 'event'; event: IServiceCreateEventPayload }| { type: 'funnel'; funnel: IServiceEvent[] };-// M15-004: `getNotificationRulesByProjectId` is `cacheablePerDeps` — `cacheable`-// keys on the call's ARGUMENTS (packages/redis/cachable.ts), so the caller's-// deps travel beside the key rather than inside it and the Redis key stays+// `getNotificationRulesByProjectId` is `cacheablePerDeps` — `cacheable` keys on+// the call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps+// travel beside the key rather than inside it and the Redis key stays// byte-identical. Every function in this file now reads `deps.db`.// -- Rule cache --------------------------------------------------------diff --git a/packages/core/src/modules/notification/src/notification-dispatch.ts b/packages/core/src/modules/notification/src/notification-dispatch.tsindex 130867a74..ba20d60a9 100644Binary files a/packages/core/src/modules/notification/src/notification-dispatch.ts and b/packages/core/src/modules/notification/src/notification-dispatch.ts differdiff --git a/packages/core/src/modules/onboarding/onboarding.constants.ts b/packages/core/src/modules/onboarding/onboarding.constants.tsindex b6ec62f53..353d4ba64 100644--- a/packages/core/src/modules/onboarding/onboarding.constants.ts+++ b/packages/core/src/modules/onboarding/onboarding.constants.ts@@ -1,6 +1,6 @@-// Moved from packages/validation/src/index.ts (M6-003, ADR-008's module map:-// onboarding owns "C"). packages/validation/src/index.ts becomes a re-export-// shim for this symbol (same shape as ./cohort.validation.ts since M5-003).+// Moved from packages/validation/src/index.ts (ADR-008's module map: onboarding+// owns "C"). packages/validation/src/index.ts becomes a re-export shim for this+// symbol (same shape as./cohort.validation.ts since M5-003).//// Isomorphic by the AGENTS.md rule: zod and nothing else.diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.tsindex 959aeae2f..67f209e25 100644--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts@@ -124,8 +124,8 @@ test('onboarding does not log when the cron is a self-hosted no-op', async () =>});// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot pins-// (apps/worker/src/boot-cron.ts). The cadence now lives on the job itself-// (ADR-021), so this reads it straight off the registry.+// (apps/worker/src/boot-cron.ts). The cadence now lives on the job itself, so+// this reads it straight off the registry.test('the onboarding cron fragment carries V1 id and cadence unchanged', () => {expect(queues.cron.jobs.onboarding.cron).toEqual({pattern: '0 * * * *',diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.ts b/packages/core/src/modules/onboarding/onboarding.jobs.tsindex d0df44759..3f2bfce1d 100644--- a/packages/core/src/modules/onboarding/onboarding.jobs.ts+++ b/packages/core/src/modules/onboarding/onboarding.jobs.ts@@ -1,10 +1,9 @@// Ported from apps/worker/src/jobs/cron.onboarding.ts + boot-cron.ts's-// `onboarding` schedule (M6-003); the schedule moved onto the job at-// ADR-021 (M10-007).+// `onboarding` schedule; the schedule moved onto the job at ADR-021.//-// `onboarding` is this module's fragment of the ONE `cron` queue's jobs,-// spread into jobs.registry.ts. Scheduler id and cadence are V1's, unchanged-// (apps/worker/src/boot-cron.ts) — same shape as organization.jobs.ts (M6-001).+// `onboarding` is this module's fragment of the ONE `cron` queue's jobs, spread+// into jobs.registry.ts. Scheduler id and cadence are V1's, unchanged+// (apps/worker/src/boot-cron.ts) — same shape as organization.jobs.ts.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.ts b/packages/core/src/modules/onboarding/onboarding.rpc.tsindex 9fafbbf8f..56f60886a 100644--- a/packages/core/src/modules/onboarding/onboarding.rpc.ts+++ b/packages/core/src/modules/onboarding/onboarding.rpc.ts@@ -1,16 +1,15 @@-// Ported from packages/trpc/src/routers/onboarding.ts (M6-003).+// Ported from packages/trpc/src/routers/onboarding.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// `project`'s input can carry an existing `organizationId`, which-// `enforceAccess` gates on membership (not admin — joining an org you-// already belong to needs no more than that); this router repeats the check-// explicitly through the organization module's own lookup.+// `enforceAccess` gates on membership (not admin — joining an org you already+// belong to needs no more than that); this router repeats the check explicitly+// through the organization module's own lookup.import {createTRPCRouter,@@ -35,9 +34,9 @@ export const onboardingRouter = createTRPCRouter({const userId = ctx.session.userId;if (input.organizationId) {- // The auth service owns every access lookup (ADR-022 R10); this- // procedure is protected but the organization is an input, so the- // builder cannot decide it.+ // The auth service owns every access lookup; this procedure is+ // protected but the organization is an input, so the builder cannot+ // decide it.const access = await ctx.services.auth.getOrganizationAccess({userId,organizationId: input.organizationId,diff --git a/packages/core/src/modules/onboarding/onboarding.service.test.ts b/packages/core/src/modules/onboarding/onboarding.service.test.tsindex 58f4f6911..eca45e8ce 100644--- a/packages/core/src/modules/onboarding/onboarding.service.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.test.ts@@ -1,10 +1,10 @@// Onboarding email cron: the sequential drip driven by the// `organization.onboarding` pointer. Moved from-// apps/worker/src/jobs/cron.onboarding.test.ts (M6-003) — db, the-// organization module's event-count lookup, and email are mocked; asserts-// template selection, day gating, early completion on active subs, and usage-// personalization. `mock.module` is not hoisted, so the subject is imported-// inside `beforeAll` — see AGENTS.md.+// apps/worker/src/jobs/cron.onboarding.test.ts — db, the organization module's+// event-count lookup, and email are mocked; asserts template selection, day+// gating, early completion on active subs, and usage personalization.+// `mock.module` is not hoisted, so the subject is imported inside `beforeAll` —+// see AGENTS.md.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { subDays } from 'date-fns';@@ -15,8 +15,8 @@ const organizationUpdate = mock(async () => ({}));const dbMock = {organization: { findMany: organizationFindMany, update: organizationUpdate },};-// M10-009: `runOnboardingCron` takes `ServiceDeps` now, so `deps.db` IS the-// fake below — no Prisma module mock needed.+// `runOnboardingCron` takes `ServiceDeps` now, so `deps.db` IS the fake below —+// no Prisma module mock needed.const deps = {db: dbMock,config: testCoreConfig(),diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsindex 9727f6bb3..817930200 100644--- a/packages/core/src/modules/onboarding/onboarding.service.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -1,14 +1,14 @@-// New module (M6-003): the onboarding-project mutation inline in+// New module: the onboarding-project mutation inline in// packages/trpc/src/routers/onboarding.ts, plus the onboarding email drip// inline in apps/worker/src/jobs/cron.onboarding.ts. Neither had a-// packages/db/src/services/* home to move from — written directly here,-// same shape as auth.service.ts's Prisma-touching half (M6-003). DELEGATE-// PATTERN: V1's trpc router and cron job, and this package's own+// packages/db/src/services/* home to move from — written directly here, same+// shape as auth.service.ts's Prisma-touching half. DELEGATE PATTERN: V1's trpc+// router and cron job, and this package's own// onboarding.rpc.ts/onboarding.jobs.ts, all call these same functions.//-// M10-009: every exported function takes `ServiceDeps` and reaches Postgres-// as `deps.db`; the `loadDb()` lazy loader is gone, so the requestId minted at-// the edge reaches the query (ADR-018, docs/TECH_DEBT.md §4).+// Every exported function takes `ServiceDeps` and reaches Postgres as+// `deps.db`; the `loadDb` lazy loader is gone, so the requestId minted at the+// edge reaches the query.import crypto from 'node:crypto';import { getRecommendedPlan } from '@openpanel/payments';diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.tsindex 22fed8104..e693ab8d0 100644--- a/packages/core/src/modules/organization/organization.constants.ts+++ b/packages/core/src/modules/organization/organization.constants.ts@@ -1,10 +1,10 @@-// Moved from packages/validation/src/index.ts (M11-006, ADR-008's module map:+// Moved from packages/validation/src/index.ts (ADR-008's module map:// organization owns "C" for the member/invite/organization vocabulary).// `zProjectAccessGrant` is a per-project grant but every consumer is// organization-shaped (organization.rpc.ts's invite/access mutations), so it-// lives here and `zInviteUser` embeds it without a cross-file constants-// import. @openpanel/db's `code-migrations/constants.ts` keeps its own frozen-// copy of the schema (ADR-022, Carl's rulings) — it is not a consumer.+// lives here and `zInviteUser` embeds it without a cross-file constants import.+// @openpanel/db's `code-migrations/constants.ts` keeps its own frozen copy of+// the schema (Carl's rulings) — it is not a consumer.//// Isomorphic by the AGENTS.md rule: zod and nothing else.diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.tsindex 800f78333..445fed302 100644--- a/packages/core/src/modules/organization/organization.jobs.test.ts+++ b/packages/core/src/modules/organization/organization.jobs.test.ts@@ -110,8 +110,8 @@ test('delete delegates to runDeleteCron', async () => {});// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot pins-// (apps/worker/src/boot-cron.ts). The cadences now live on the jobs-// themselves (ADR-021), so this reads them straight off the registry.+// (apps/worker/src/boot-cron.ts). The cadences now live on the jobs themselves,+// so this reads them straight off the registry.test('the organization cron fragment carries V1 id and cadence unchanged', () => {expect(queues.cron.jobs.delete.cron).toEqual({ pattern: '0 * * * *' });expect(queues.cron.jobs.windDown.cron).toEqual({ pattern: '0 * * * *' });diff --git a/packages/core/src/modules/organization/organization.jobs.ts b/packages/core/src/modules/organization/organization.jobs.tsindex 2d5479bd1..0c26baa62 100644--- a/packages/core/src/modules/organization/organization.jobs.ts+++ b/packages/core/src/modules/organization/organization.jobs.ts@@ -1,7 +1,7 @@// Ported from apps/worker/src/jobs/cron.delete.ts + boot-cron.ts's `delete`-// schedule (M6-001); `windDown` joined it at M9-003, the wave that deletes-// apps/worker (ADR-005's acceptance note gives it to this module). The-// schedules moved onto the jobs at ADR-021 (M10-007).+// schedule; `windDown` joined it at M9-003, the wave that deletes apps/worker+// (ADR-005's acceptance note gives it to this module). The schedules moved onto+// the jobs at ADR-021.//// `delete` is this module's fragment of the ONE `cron` queue's jobs, spread// into jobs.registry.ts. Scheduler id and cadence are V1's, unchanged@@ -48,12 +48,12 @@ export const organizationCronJobs = {/*** The wind-down cron's dependencies, bound to the job's own ctx.*- * Two reaches stay dynamic. The sibling service's two ClickHouse counts are- * not on `OrganizationService`, and `src/win-back-pitch.ts` pulls the agent- * runtime — a static edge from here would drag either into jobs.registry.ts's- * eager import graph, which every core test file walks. M15-119 (R11) ruled- * this the ADR-022 "legitimate lazy asset load" exception, not the sibling-- * service defect R6 forbids: kept as is.+ * Two reaches stay dynamic. The sibling service's two ClickHouse counts are not+ * on `OrganizationService`, and `src/win-back-pitch.ts` pulls the agent runtime+ * — a static edge from here would drag either into jobs.registry.ts's eager+ * import graph, which every core test file walks. M15-119 (R11) ruled this the+ * ADR-022 "legitimate lazy asset load" exception, not the sibling- service+ * defect R6 forbids: kept as is.*/async function windDownDeps(ctx: Ctx, logger: Logger): Promise<WindDownDeps> {const [diff --git a/packages/core/src/modules/organization/organization.rpc.ts b/packages/core/src/modules/organization/organization.rpc.tsindex 5d2db2d27..8f2550bb3 100644--- a/packages/core/src/modules/organization/organization.rpc.ts+++ b/packages/core/src/modules/organization/organization.rpc.ts@@ -1,14 +1,13 @@-// Ported from packages/trpc/src/routers/organization.ts (M6-001).+// Ported from packages/trpc/src/routers/organization.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// The organization-admin ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The organization-admin ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.//// `getInvite` still drops V1's rate limiting: `rateLimitMiddleware` did NOT// move with M11-001. `createRateLimitMiddleware` in rpc/base.ts is the seamdiff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.tsindex f43c7ef92..be07d1d65 100644--- a/packages/core/src/modules/organization/organization.service.test.ts+++ b/packages/core/src/modules/organization/organization.service.test.ts@@ -403,12 +403,12 @@ const projectAccess = {const $transaction = mock(async (ops: Promise<unknown>[]) => Promise.all(ops));-// M10-009: every function under test takes `ServiceDeps`, so `deps.db` and-// `deps.ch` ARE the fakes below — the two `@openpanel/db` module mocks this-// file used to install are gone, and with them the process-wide leak they had-// to be restored from. `connectUserToOrganization` reaches-// `shared/access-lookups.ts` (cacheable, on the unscoped db), which is why-// the `@openpanel/redis` stand-in below stays.+// Every function under test takes `ServiceDeps`, so `deps.db` and `deps.ch` ARE+// the fakes below — the two `@openpanel/db` module mocks this file used to+// install are gone, and with them the process-wide leak they had to be restored+// from. `connectUserToOrganization` reaches `shared/access-lookups.ts`+// (cacheable, on the unscoped db), which is why the `@openpanel/redis` stand-in+// below stays.const chCommand = mock(async () => undefined);const deps = {logger: recordingLogger(),@@ -448,10 +448,10 @@ function cacheableStub(});}// Spread the real module for the same reason the clickhouse/client mock above-// does: `mock.module` replaces this specifier process-wide. Surfaced by-// M8-001, which put `createBuffers` on core's barrel — event-buffer.ts-// value-imports `publishEvent` from here, so a partial factory turns this-// file's own barrel import into a SyntaxError.+// does: `mock.module` replaces this specifier process-wide. Surfaced by M8-001,+// which put `createBuffers` on core's barrel — event-buffer.ts value-imports+// `publishEvent` from here, so a partial factory turns this file's own barrel+// import into a SyntaxError.const realRedis = { ...(await import('@openpanel/redis')) };mock.module('@openpanel/redis', () => ({...realRedis,diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex 143c9015f..851871ca5 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -560,10 +560,10 @@ export interface DeleteCronResult {/*** The `delete` cron fragment's body — moved from- * apps/worker/src/jobs/cron.delete.ts's `jobDelete` (M6-001). Finds- * organizations scheduled for deletion or orphaned (no admin member), and- * projects individually scheduled for deletion, then sweeps both out of- * ClickHouse and Postgres in one pass.+ * apps/worker/src/jobs/cron.delete.ts's `jobDelete`. Finds organizations+ * scheduled for deletion or orphaned (no admin member), and projects+ * individually scheduled for deletion, then sweeps both out of ClickHouse and+ * Postgres in one pass.*/export async function runDeleteCron(deps: ServiceDepsdiff --git a/packages/core/src/modules/organization/src/win-back-highlight.test.ts b/packages/core/src/modules/organization/src/win-back-highlight.test.tsindex ed7dd4da1..6583a52d4 100644--- a/packages/core/src/modules/organization/src/win-back-highlight.test.ts+++ b/packages/core/src/modules/organization/src/win-back-highlight.test.ts@@ -1,8 +1,8 @@-// Moved from apps/worker/src/jobs/lib/win-back-highlight.test.ts (M9-003).-// Asserts the gating and fallback decisions, which are the point of the-// module: a highlight is a bonus, never a reason an email fails or embarrasses-// us with tiny numbers. The stats lookups and the AI call are injected stubs —-// no `mock.module`, so every assertion is on a call the code under test made.+// Moved from apps/worker/src/jobs/lib/win-back-highlight.test.ts. Asserts the+// gating and fallback decisions, which are the point of the module: a highlight+// is a bonus, never a reason an email fails or embarrasses us with tiny+// numbers. The stats lookups and the AI call are injected stubs — no+// `mock.module`, so every assertion is on a call the code under test made.import { beforeEach, describe, expect, it, mock } from 'bun:test';import type { Logger } from '../../../logger';diff --git a/packages/core/src/modules/organization/src/win-back-highlight.ts b/packages/core/src/modules/organization/src/win-back-highlight.tsindex 66690b19c..5b6497000 100644--- a/packages/core/src/modules/organization/src/win-back-highlight.ts+++ b/packages/core/src/modules/organization/src/win-back-highlight.ts@@ -1,10 +1,10 @@-// Ported from apps/worker/src/jobs/lib/win-back-highlight.ts (M9-003, the-// wave that deletes apps/worker). Behaviour is V1's, verbatim; only the-// wiring changed — the two stats lookups and the AI call arrive as injected-// deps (`WinBackHighlightDeps`) instead of static imports, the same idiom the-// session lifecycle uses (modules/session/src/runtime.ts): `organization.jobs.ts`-// binds them off the job's ctx (M10-006), and tests hand in stubs, so no-// `mock.module` is needed anywhere.+// Ported from apps/worker/src/jobs/lib/win-back-highlight.ts (the wave that+// deletes apps/worker). Behaviour is V1's, verbatim; only the wiring changed —+// the two stats lookups and the AI call arrive as injected deps+// (`WinBackHighlightDeps`) instead of static imports, the same idiom the+// session lifecycle uses (modules/session/src/runtime.ts):+// `organization.jobs.ts` binds them off the job's ctx, and tests hand in stubs,+// so no `mock.module` is needed anywhere.import { format, subDays } from 'date-fns';import type { Logger } from '../../../logger';diff --git a/packages/core/src/modules/organization/src/wind-down.test.ts b/packages/core/src/modules/organization/src/wind-down.test.tsindex 438863cc2..883d60682 100644--- a/packages/core/src/modules/organization/src/wind-down.test.ts+++ b/packages/core/src/modules/organization/src/wind-down.test.ts@@ -1,4 +1,4 @@-// Moved from apps/worker/src/jobs/cron.wind-down.test.ts (M9-003).+// Moved from apps/worker/src/jobs/cron.wind-down.test.ts.//// Prisma, the event counts, the last-event lookup, the highlight builder and// the email transport are injected stubs — these assert the job's decisionsdiff --git a/packages/core/src/modules/organization/src/wind-down.ts b/packages/core/src/modules/organization/src/wind-down.tsindex 0093091da..ccb662594 100644--- a/packages/core/src/modules/organization/src/wind-down.ts+++ b/packages/core/src/modules/organization/src/wind-down.ts@@ -1,11 +1,11 @@-// Ported from apps/worker/src/jobs/cron.wind-down.ts (M9-003, the wave that-// deletes apps/worker). ADR-005's acceptance note gives `windDown` to the-// organization module. Behaviour is V1's, verbatim; only the wiring changed —-// Prisma, the two ClickHouse counts, the last-event lookup, the plan pricer,-// the highlight builder and `sendEmail` all arrive as injected deps-// (`WindDownDeps`), the same idiom the session lifecycle uses-// (modules/session/src/runtime.ts). `organization.jobs.ts` binds them off the-// job's ctx (M10-006); tests hand in stubs, so no `mock.module` is needed.+// Ported from apps/worker/src/jobs/cron.wind-down.ts (the wave that deletes+// apps/worker). ADR-005's acceptance note gives `windDown` to the organization+// module. Behaviour is V1's, verbatim; only the wiring changed — Prisma, the+// two ClickHouse counts, the last-event lookup, the plan pricer, the highlight+// builder and `sendEmail` all arrive as injected deps (`WindDownDeps`), the+// same idiom the session lifecycle uses (modules/session/src/runtime.ts).+// `organization.jobs.ts` binds them off the job's ctx; tests hand in stubs, so+// no `mock.module` is needed.import { getRecommendedPlan } from '@openpanel/payments';import { addDays, format, subDays } from 'date-fns';diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.tsindex 20356bf4e..dfa753934 100644--- a/packages/core/src/modules/overview/overview.rpc.ts+++ b/packages/core/src/modules/overview/overview.rpc.ts@@ -1,7 +1,7 @@// Ported from packages/trpc/src/routers/overview.ts.//-// M11-001: `overviewProcedure` is V1's own builder — `publicProcedure` plus-// one middleware that resolves share-or-membership off the raw+// `overviewProcedure` is V1's own builder — `publicProcedure` plus one+// middleware that resolves share-or-membership off the raw// `projectId`/`shareId`, BEFORE the input parser. `runFilterCommand` is a// `protectedProcedure`, as in V1.//@@ -10,7 +10,7 @@//// `liveData`'s ClickHouse queries used to live inline in packages/trpc's// router; they moved to `services.overview.getLiveData` (src/overview.sql.ts)-// so every query this module runs goes through the same `sql` tag (M7-005).+// so every query this module runs goes through the same `sql` tag.import { getChartPrevStartEndDate } from '@openpanel/shared';import { format } from 'date-fns';diff --git a/packages/core/src/modules/overview/overview.service.ts b/packages/core/src/modules/overview/overview.service.tsindex 18c2828b2..90abcacc2 100644--- a/packages/core/src/modules/overview/overview.service.ts+++ b/packages/core/src/modules/overview/overview.service.ts@@ -1,14 +1,14 @@// Ported from packages/db/src/services/overview.service.ts. The ClickHouse-// queries moved to src/overview.sql.ts (ADR-013, M7-005).+// queries moved to src/overview.sql.ts.//-// M10-005: `OverviewService` is no longer a class and there is no-// `overviewService` module singleton. Every method is a module-scope function-// taking `ServiceDeps` first and otherwise the same arguments, and+// `OverviewService` is no longer a class and there is no `overviewService`+// module singleton. Every method is a module-scope function taking+// `ServiceDeps` first and otherwise the same arguments, and// `createOverviewService(deps)` binds them under their old method names, so// `services.overview.getMetrics(input)` reads exactly as// `overviewService.getMetrics(input)` did. The caller-supplied-// `constructor(client)` slot is gone with it: the client is `deps.ch`, which-// is what puts the request's id on the query's log line (ADR-018 R1).+// `constructor(client)` slot is gone with it: the client is `deps.ch`, which is+// what puts the request's id on the query's log line.import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import { average, sum } from '@openpanel/shared';diff --git a/packages/core/src/modules/overview/pages.service.ts b/packages/core/src/modules/overview/pages.service.tsindex 41cbd997a..16c6f6736 100644--- a/packages/core/src/modules/overview/pages.service.ts+++ b/packages/core/src/modules/overview/pages.service.ts@@ -1,13 +1,13 @@-// Ported from packages/db/src/services/pages.service.ts. The ClickHouse-// queries moved to src/pages.sql.ts (ADR-013, M7-005).+// Ported from packages/db/src/services/pages.service.ts. The ClickHouse queries+// moved to src/pages.sql.ts.//-// M10-005: `PagesService` is no longer a class and there is no `pagesService`-// module singleton. It is registered as its OWN service (`services.pages`)-// rather than folded into `overview`, because both expose a `getTopPages` and-// they are different queries with different inputs — one over `events` scoped-// by search, one over `sessions` scoped by filters. Folding them would have-// had to rename one, which is a call-site contract this wave does not change.-// The caller-supplied `constructor(client)` slot is gone: the mcp+// `PagesService` is no longer a class and there is no `pagesService` module+// singleton. It is registered as its OWN service (`services.pages`) rather than+// folded into `overview`, because both expose a `getTopPages` and they are+// different queries with different inputs — one over `events` scoped by search,+// one over `sessions` scoped by filters. Folding them would have had to rename+// one, which is a call-site contract this wave does not change. The+// caller-supplied `constructor(client)` slot is gone: the mcp// `get_page_performance` tool constructed a fresh instance per call only to// dodge a module-singleton mocking hazard, and there is no singleton left to// dodge.diff --git a/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.tsindex ffeef8f34..e6933e27a 100644--- a/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts+++ b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts@@ -1,21 +1,20 @@/*** SQL-syntax tests for the overview module's `getRawWhereClause` (the UTM* remapping). Moved from packages/db/src/services/overview-sql.test.ts- * (M8-005) alongside its subject, which moved to core in M7-005 — same- * pattern as the chart cases moving to chart.sql.test.ts with theirs- * (M7-003). M12-002 put `getRawWhereClause` on the `sql` tag, so these- * assertions read the rendered statement AND its bound params instead of one- * escaped string; the rest of the overview module's queries already run- * through overview.sql.ts, covered by overview.sql.test.ts. M10-005 turned it- * from a class method into a module function — it never needed a client,- * being pure fragment building.+ * alongside its subject, which moved to core in M7-005 — same pattern as the+ * chart cases moving to chart.sql.test.ts with theirs. M12-002 put+ * `getRawWhereClause` on the `sql` tag, so these assertions read the rendered+ * statement AND its bound params instead of one escaped string; the rest of the+ * overview module's queries already run through overview.sql.ts, covered by+ * overview.sql.test.ts. M10-005 turned it from a class method into a module+ * function — it never needed a client, being pure fragment building.** Strategy: build the SQL string, then run `EXPLAIN <sql>` against the local* ClickHouse instance. EXPLAIN parses the query, resolves columns, and builds* the query plan without executing it — so we catch UNKNOWN_IDENTIFIER,- * AMBIGUOUS_IDENTIFIER and bad JOIN ON expressions without needing seeded- * data. WITH FILL TO < FROM is a runtime check, so it's covered by a plain- * string assertion instead.+ * AMBIGUOUS_IDENTIFIER and bad JOIN ON expressions without needing seeded data.+ * WITH FILL TO < FROM is a runtime check, so it's covered by a plain string+ * assertion instead.** Requires a locally reachable CH at http://localhost:23123/openpanel. All* `itCH` tests auto-skip if CH is unreachable.@@ -81,8 +80,8 @@ describe('overview.service / getRawWhereClause (UTM remapping)', () => {{ name: 'utm_source', operator: 'is', value: ['awn'] },]));- // M12-003: the map KEY binds too, so the shape is asserted on the- // statement and the key on the params.+ // The map KEY binds too, so the shape is asserted on the statement and the+ // key on the params.expect(query).toContain('properties[{p1:String}]');expect(query).not.toMatch(/(?<![._\w])utm_source\s*=/);expect(query_params).toEqual({ p1: '__query.utm_source', p2: 'awn' });diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.tsindex ac1eadcc3..0d2ead4ab 100644--- a/packages/core/src/modules/overview/src/overview.sql.ts+++ b/packages/core/src/modules/overview/src/overview.sql.ts@@ -1,10 +1,9 @@-// Every ClickHouse query OverviewService runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse query OverviewService runs, as pure `sql` fragments.//// Both filter compilers and the field resolver return fragments and are-// interpolated directly. `compiledText` is left with one job-// here: the `INTERVAL <n> <unit>` step keyword in a WITH FILL clause, which is-// SQL syntax, not a value.+// interpolated directly. `compiledText` is left with one job here: the+// `INTERVAL <n> <unit>` step keyword in a WITH FILL clause, which is SQL+// syntax, not a value.//// `toStartOf`/`toInterval`/`datetime` reproduce V1's `clix` static helpers// verbatim (query-builder.ts) rather than chart.sql.ts's own `intervalBucket`:@@ -211,7 +210,7 @@ export function metricsWithPageFilterQuery(// needs alongside the columns every other metric aggregates. A CTE is// re-executed once per reference, so each source is read exactly once here// and the window-wide totals are lifted off its own `WITH ROLLUP` row rather- // than from a second scan (M28-001).+ // than from a second scan.const filteredScreenViews = sql`SELECT${dateBucket} AS date,diff --git a/packages/core/src/modules/overview/src/pages.sql.ts b/packages/core/src/modules/overview/src/pages.sql.tsindex 3b8304d4c..05488da2f 100644--- a/packages/core/src/modules/overview/src/pages.sql.ts+++ b/packages/core/src/modules/overview/src/pages.sql.ts@@ -1,5 +1,5 @@// Every ClickHouse query PagesService/getPageConversionsCore runs, as pure-// `sql` fragments (ADR-013).+// `sql` fragments.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';@@ -31,10 +31,10 @@ function searchClause(search: string | undefined): SqlFragment {}export function topPagesQuery(input: TopPagesQueryInput): SqlFragment {- // M34-002: titles come from the requested range, not V1's `now() - 30 DAY`,- // which read a month of the widest Map column for any window and made the- // answer depend on the wall clock. A page titled only outside the range now- // resolves to '' (approved, Group C fix 8).+ // Titles come from the requested range, not V1's `now - 30 DAY`, which read a+ // month of the widest Map column for any window and made the answer depend on+ // the wall clock. A page titled only outside the range now resolves to ''+ // (approved, Group C fix 8).const titlesCte = sql`SELECT concat(origin, path) as page_key, anyLast(properties['__title']) as titleFROM events@@ -108,10 +108,9 @@ export interface PageTimeseriesQueryInput {/*** Keep only the `n` busiest pages in each date bucket. Omitted means* unbounded, which is one row per (origin, path, bucket) and on a project- * with per-user URL segments is millions of rows.- * `origin`/`path` break the ranking's ties so the truncated set is stable- * between calls; without them ClickHouse returns a different top-n on every- * run (measured, M31-002).+ * with per-user URL segments is millions of rows. `origin`/`path` break the+ * ranking's ties so the truncated set is stable between calls; without them+ * ClickHouse returns a different top-n on every run (measured).*/topPagesPerBucket?: number;}diff --git a/packages/core/src/modules/overview/src/run-query.ts b/packages/core/src/modules/overview/src/run-query.tsindex 0cff8d01c..b41eed429 100644--- a/packages/core/src/modules/overview/src/run-query.ts+++ b/packages/core/src/modules/overview/src/run-query.ts@@ -1,7 +1,7 @@// The overview module's one ClickHouse entry point.//-// M10-005: the client is `deps.ch` — the same round-robin/retry proxy-// `main.ts` builds and hands to every scope — instead of a lazy+// The client is `deps.ch` — the same round-robin/retry proxy `main.ts` builds+// and hands to every scope — instead of a lazy// `import('@openpanel/db/src/clickhouse/client')`. `OverviewService` /// `PagesService` were classes carrying a caller-supplied client precisely// because there was no scope to reach one through; there is now, so both arediff --git a/packages/core/src/modules/profile/profile.jobs.ts b/packages/core/src/modules/profile/profile.jobs.tsindex 86d6a2809..83ff5e8da 100644--- a/packages/core/src/modules/profile/profile.jobs.ts+++ b/packages/core/src/modules/profile/profile.jobs.ts@@ -1,9 +1,9 @@// Ported from apps/worker/src/jobs/cron.ts's `flushProfiles` /-// `flushProfileBackfill` cases + boot-cron.ts's `flush` schedules (M8-004);-// the schedules moved onto the jobs at ADR-021 (M10-007). Both buffers are-// this module's domain: the profile buffer (Redis → ClickHouse `profiles`)-// and the profile-backfill buffer, which patches a session's `profile_id`-// once a device is identified after the session row was already written.+// `flushProfileBackfill` cases + boot-cron.ts's `flush` schedules; the+// schedules moved onto the jobs at ADR-021. Both buffers are this module's+// domain: the profile buffer (Redis → ClickHouse `profiles`) and the+// profile-backfill buffer, which patches a session's `profile_id` once a device+// is identified after the session row was already written.import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/profile/profile.routes.test.ts b/packages/core/src/modules/profile/profile.routes.test.tsindex 66249daa2..0dd8e279e 100644--- a/packages/core/src/modules/profile/profile.routes.test.ts+++ b/packages/core/src/modules/profile/profile.routes.test.ts@@ -39,7 +39,7 @@ const authenticateClient = mock((_deps: unknown, _headers: Headers, _options: ClientAuthOptions) =>Promise.resolve(clientResult));-// M10-005: both take `ServiceDeps` first; the route hands them `ctx`.+// Both take `ServiceDeps` first; the route hands them `ctx`.const identifyProfile = mock((_deps: unknown,diff --git a/packages/core/src/modules/profile/profile.routes.ts b/packages/core/src/modules/profile/profile.routes.tsindex de9c18c69..674d9ea60 100644--- a/packages/core/src/modules/profile/profile.routes.ts+++ b/packages/core/src/modules/profile/profile.routes.ts@@ -1,10 +1,10 @@// Ported from apps/api/src/routes/profile.router.ts +-// apps/api/src/controllers/profile.controller.ts (M7-002). V1's Fastify-// controller stays the LIVE route (DELEGATE PATTERN) and delegates its bodies-// to profile.service.ts's `identifyProfile` / `adjustProfileProperty` — the-// same functions these routes call. Status codes and text bodies (`202` +-// profile id, `400 'No projectId'`, `404 'Not found'`, `400 'Not number'`)-// match V1's `reply.status(..).send(..)` byte for byte.+// apps/api/src/controllers/profile.controller.ts. V1's Fastify controller stays+// the LIVE route (DELEGATE PATTERN) and delegates its bodies to+// profile.service.ts's `identifyProfile` / `adjustProfileProperty` — the same+// functions these routes call. Status codes and text bodies (`202` + profile+// id, `400 'No projectId'`, `404 'Not found'`, `400 'Not number'`) match V1's+// `reply.status(..).send(..)` byte for byte.//// `ingest` is V1's `clientHook` (the SDK credential rules); V1's `isBotHook`// and `subscriptionHook` on this router live in the ingest module, not thisdiff --git a/packages/core/src/modules/profile/profile.rpc.ts b/packages/core/src/modules/profile/profile.rpc.tsindex 9d2910eaf..92963152b 100644--- a/packages/core/src/modules/profile/profile.rpc.ts+++ b/packages/core/src/modules/profile/profile.rpc.ts@@ -1,11 +1,10 @@-// Ported from packages/trpc/src/routers/profile.ts (M7-002).+// Ported from packages/trpc/src/routers/profile.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.tsindex d80c10b8e..a34642ed6 100644--- a/packages/core/src/modules/profile/profile.service.ts+++ b/packages/core/src/modules/profile/profile.service.ts@@ -1,4 +1,4 @@-// Every query is a `sql` fragment (src/sql.ts), per ADR-013. The exception is+// Every query is a `sql` fragment (src/sql.ts). The exception is// `buildFilterWhere`, the shared filter compiler; src/filter-clauses.ts is the// bridge to it.diff --git a/packages/core/src/modules/profile/src/sql.ts b/packages/core/src/modules/profile/src/sql.tsindex 7463a3e0b..eaa200970 100644--- a/packages/core/src/modules/profile/src/sql.ts+++ b/packages/core/src/modules/profile/src/sql.ts@@ -1,8 +1,7 @@-// Every ClickHouse query the profile module runs, as pure `sql` fragments-// (ADR-013).+// Every ClickHouse query the profile module runs, as pure `sql` fragments.//// Cluster note: `profiles`, `events` and `sessions` are Distributed on Cloud.-// `findProfilesQuery`'s three `IN (SELECT ...)` subqueries, and any a filter+// `findProfilesQuery`'s three `IN (SELECT...)` subqueries, and any a filter// compiles to, run under the client's `distributed_product_mode: 'allow'`.// Every `IN` list binds as `Array(String)`, a literal list to the planner.@@ -172,7 +171,7 @@ export interface ProfileListQuery extends ProfileWindow {}/**- * V1's `WHERE project_id = .. [AND search] [AND is_external = ..] [AND filters]`,+ * V1's `WHERE project_id =.. [AND search] [AND is_external =..] [AND filters]`,* plus the M31-003 window: V1 read every profile the project ever had, so the* cost grew with the tenant's lifetime rather than with anything the caller* asked for. `created_at` is the column the list already orders by, so the@@ -370,9 +369,9 @@ export function profilePropertyNamesQuery(projectId: string): SqlFragment {}/**- * M31-003: bounded to the caller's window. Unbounded this ranked every event- * the project ever recorded (44.2 M rows on the busiest anchor), so "power- * users of all time" is now "power users of the range".+ * Bounded to the caller's window. Unbounded this ranked every event the project+ * ever recorded (44.2 M rows on the busiest anchor), so "power users of all+ * time" is now "power users of the range".*/export function powerUsersQuery(query: ProfileWindow & {diff --git a/packages/core/src/modules/project/project.constants.ts b/packages/core/src/modules/project/project.constants.tsindex 38226bcde..69bf671f5 100644--- a/packages/core/src/modules/project/project.constants.ts+++ b/packages/core/src/modules/project/project.constants.ts@@ -1,18 +1,20 @@-// Moved from packages/constants/index.ts (M6-002, ADR-008's module map:-// project owns "C"). packages/constants/index.ts becomes a re-export shim of-// `ProjectTypeNames` (same shape as packages/validation/src/import.validation.ts-// since M5-004), so existing packages/constants importers keep resolving it-// unchanged. `zCreateProject`/`zUpdateProject` are the /manage REST body-// schemas (apps/api/src/controllers/manage.controller.ts), moved here with-// the CRUD bodies they validate (project.service.ts's+// Moved from packages/constants/index.ts (ADR-008's module map: project owns+// "C"). packages/constants/index.ts becomes a re-export shim of+// `ProjectTypeNames` (same shape as+// packages/validation/src/import.validation.ts since M5-004), so existing+// packages/constants importers keep resolving it unchanged.+// `zCreateProject`/`zUpdateProject` are the /manage REST body schemas+// (apps/api/src/controllers/manage.controller.ts), moved here with the CRUD+// bodies they validate (project.service.ts's// createProjectForOrganization/updateProjectForOrganization).//// The project filter/edit schemas below moved from-// packages/validation/src/index.ts (M11-006, same module map row). `zChartEvent`-// is imported by name, not re-exported: `zProjectFilterEvent` extends it as a+// packages/validation/src/index.ts (same module map row). `zChartEvent` is+// imported by name, not re-exported: `zProjectFilterEvent` extends it as a// bound identifier.//-// Isomorphic by the AGENTS.md rule: zod, another *.constants.ts, and nothing else.+// Isomorphic by the AGENTS.md rule: zod, another *.constants.ts, and nothing+// else.import { z } from 'zod';import { zChartEvent } from '../report/report.constants';diff --git a/packages/core/src/modules/project/project.routes.ts b/packages/core/src/modules/project/project.routes.tsindex 48e399b4c..d9eb535d0 100644--- a/packages/core/src/modules/project/project.routes.ts+++ b/packages/core/src/modules/project/project.routes.ts@@ -1,4 +1,4 @@-// The /manage/projects REST surface (M6-002). V1's Fastify controller+// The /manage/projects REST surface. V1's Fastify controller// (apps/api/src/controllers/manage.controller.ts) stays the LIVE route// (DELEGATE PATTERN) and delegates its CRUD bodies to project.service.ts's// createProjectForOrganization/updateProjectForOrganization/etc — the same@@ -6,11 +6,11 @@// match V1's `reply.send(...)` shape exactly (byte-unchanged URL surface).//// NAMED GAP, same as import.routes.ts: this route is 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;-// main.ts also does not mount `publicApiRoutes` until a real `AppDeps`-// exists. `allow: ['root']` mirrors V1's rule (utils/auth.ts's-// `validateManageRequest`: only root clients may manage resources).+// `authenticateClient` (http/client-auth.ts) is a P8 stub that always returns+// null, so `clientAuth` 401s every request until it is filled in; main.ts also+// does not mount `publicApiRoutes` until a real `AppDeps` exists. `allow:+// ['root']` mirrors V1's rule (utils/auth.ts's `validateManageRequest`: only+// root clients may manage resources).import { z } from 'zod';import { defineRoutes } from '../../http/define';diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.tsindex 139ac2835..d92dbf9ca 100644--- a/packages/core/src/modules/project/project.rpc.ts+++ b/packages/core/src/modules/project/project.rpc.ts@@ -1,16 +1,15 @@-// Ported from packages/trpc/src/routers/project.ts (M6-002).+// Ported from packages/trpc/src/routers/project.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// `ctx.services.project` carries this module's factory (M10-004).+// `ctx.services.project` carries this module's factory.//-// The project-access ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The project-access ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.tsindex c097920d3..2d539ea66 100644--- a/packages/core/src/modules/project/project.service.test.ts+++ b/packages/core/src/modules/project/project.service.test.ts@@ -1,12 +1,12 @@-// The subject is built by its factory over a fake `ServiceDeps` (M10-004), so-// Postgres needs no module mock at all — `deps.db` IS the fake below, same-// idiom as reference.service.test.ts. `getProjectEventsCount` /-// `getLastEventPerProject` (ClickHouse) stay a verbatim, still-lazy-loaded-// port with unchanged SQL (ADR-013 converts them in P7) — executed against-// local ClickHouse for this task's verification, not re-tested here.+// The subject is built by its factory over a fake `ServiceDeps`, so Postgres+// needs no module mock at all — `deps.db` IS the fake below, same idiom as+// reference.service.test.ts. `getProjectEventsCount` / `getLastEventPerProject`+// (ClickHouse) stay a verbatim, still-lazy-loaded port with unchanged SQL+// (ADR-013 converts them in P7) — executed against local ClickHouse for this+// task's verification, not re-tested here.//-// M15-005: `createProjectForOrganization`/`updateProjectForOrganization`-// invalidate a project's clients through `client.service.ts`'s module-scope+// `createProjectForOrganization`/`updateProjectForOrganization` invalidate a+// project's clients through `client.service.ts`'s module-scope// `getClientByIdCached`, which is built from the `cacheable` stub below — so// there is no seam left to mock here.@@ -163,10 +163,10 @@ function cacheableStub(set: () => async () => 'OK' as const,});}-// M10-009: each factory spreads a plain-object SNAPSHOT of the real module and-// is restored in afterAll. `mock.module` has no per-file scope under bare-// `bun test` (AGENTS.md), and a partial factory for `@openpanel/redis` deletes-// every export it does not name for whichever file runs next.+// Each factory spreads a plain-object SNAPSHOT of the real module and is+// restored in afterAll. `mock.module` has no per-file scope under bare `bun+// test` (AGENTS.md), and a partial factory for `@openpanel/redis` deletes every+// export it does not name for whichever file runs next.const realRedis = { ...(await import('@openpanel/redis')) };mock.module('@openpanel/redis', () => ({...realRedis,diff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.tsindex 1d5cb0c00..4053eac51 100644--- a/packages/core/src/modules/realtime/realtime.routes.test.ts+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts@@ -1,28 +1,27 @@-// The runnable ws proof this task's notes require: `app.handle()` cannot-// exercise a websocket upgrade (no real HTTP connection to upgrade), so this-// boots the actual Elysia app with `.listen()` (== `Bun.serve` under the-// hood, same as main.ts) on an ephemeral port and drives it with a real-// `WebSocket` client — the same shape `apps/api/e2e/boot-proof.sh` uses for-// the plain-HTTP ops surface, extended to a ws handshake.+// The runnable ws proof this task's notes require: `app.handle` cannot exercise+// a websocket upgrade (no real HTTP connection to upgrade), so this boots the+// actual Elysia app with `.listen` (== `Bun.serve` under the hood, same as+// main.ts) on an ephemeral port and drives it with a real `WebSocket` client —+// the same shape `apps/api/e2e/boot-proof.sh` uses for the plain-HTTP ops+// surface, extended to a ws handshake.//// The harness buffers messages/close events from the moment the socket is-// constructed: the server can send its "No active session" / "No access"-// frame and close the connection before the test ever gets to `await` a-// listener, and a listener attached after the fact misses an event that-// already fired.+// constructed: the server can send its "No active session" / "No access" frame+// and close the connection before the test ever gets to `await` a listener, and+// a listener attached after the fact misses an event that already fired.//// `./realtime.service` and `../../shared/access-lookups` (the real lookups-// auth.service.ts's `createAuthService` binds `ctx.services.auth` to,-// M10-002) are mocked (not a real Postgres/ClickHouse/Redis), and-// `../../http/session` for the same reason http/auth.test.ts mocks it:-// `resolveSession` is still a P6 stub.+// auth.service.ts's `createAuthService` binds `ctx.services.auth` to) are+// mocked (not a real Postgres/ClickHouse/Redis), and `../../http/session` for+// the same reason http/auth.test.ts mocks it: `resolveSession` is still a P6+// stub.//-// M12-005: every import here is STATIC. Bun 1.4.0's `mock.module` swaps an+// Every import here is STATIC. Bun 1.4.0's `mock.module` swaps an// already-loaded module's exports in place, so a subject imported above the// `mock.module` calls still sees them; the "not called" and "called with"// assertions on every mock below are what would go red if that ever stopped-// holding. The deferred loads this file used to need are gone with the-// module's own (docs/TECH_DEBT.md's no-lazy-loaders ruling).+// holding. The deferred loads this file used to need are gone with the module's+// own (docs/TECH_DEBT.md's no-lazy-loaders ruling).import { afterAll, afterEach, beforeEach, expect, mock, test } from 'bun:test';import { getSuperJson } from '@openpanel/shared';@@ -80,9 +79,9 @@ afterAll(() => {mock.module('./realtime.service', () => realService);});-// The real module, not `./src/access` (deleted, M10-002) — `ctx.services.auth`-// binds these same lookups in auth.service.ts, so mocking them here is what-// makes `ws.data.ctx.services.auth.getProjectAccess`/`getOrganizationAccess`+// The real module, not `./src/access` (deleted) — `ctx.services.auth` binds+// these same lookups in auth.service.ts, so mocking them here is what makes+// `ws.data.ctx.services.auth.getProjectAccess`/`getOrganizationAccess`// observable from the test.let projectAccess: { level: string } | null = null;let organizationAccess: { role: string } | null = null;@@ -310,12 +309,12 @@ test('wsOrganizationEvents: session but no org access -> "No access" then close'});});-// M30-003 / F2: `organization:subscription_updated` is an instance-wide-// channel. Before the fix the open handler subscribed to it unscoped, so a-// member of org_1 was sent the `organizationId` of every OTHER organization-// whose subscription changed. The scope handed to the subscription must be the-// id `getOrganizationAccess` just proved this caller is a member of — the-// filter itself is asserted in realtime.service.test.ts.+// / F2: `organization:subscription_updated` is an instance-wide channel. Before+// the fix the open handler subscribed to it unscoped, so a member of org_1 was+// sent the `organizationId` of every OTHER organization whose subscription+// changed. The scope handed to the subscription must be the id+// `getOrganizationAccess` just proved this caller is a member of — the filter+// itself is asserted in realtime.service.test.ts.test('wsOrganizationEvents: subscribes scoped to the organization the caller is a member of', async () => {session = { userId: 'user_1' };organizationAccess = { role: 'org:member' };diff --git a/packages/core/src/modules/realtime/realtime.routes.ts b/packages/core/src/modules/realtime/realtime.routes.tsindex deb7a9e2b..315f63b58 100644--- a/packages/core/src/modules/realtime/realtime.routes.ts+++ b/packages/core/src/modules/realtime/realtime.routes.ts@@ -1,29 +1,28 @@-// The `/live` websocket surface (M6-007), Elysia/Bun-native. Ported FRESH-// from apps/api/src/controllers/live.controller.ts's business logic, NOT-// delegated: V1's Fastify controller uses `@fastify/websocket`'s `WebSocket`-// (the `ws` package, Node EventEmitter semantics), which shares nothing with-// Elysia's `ElysiaWS`/Bun's native `ServerWebSocket` — there is no shim to-// delegate through, and touching the golden-harness-critical V1 ws stack for-// a few lines of framework glue is the risk this port avoids (task notes).-// V1's controller and router are LEFT UNTOUCHED. The shared logic —-// `getActiveVisitorCount`, the four `subscribeToPublishedEvent` calls — moved-// to realtime.service.ts's "/live websocket glue" section; both stacks call-// the exact same Redis subscription underneath.+// The `/live` websocket surface, Elysia/Bun-native. Ported FRESH from+// apps/api/src/controllers/live.controller.ts's business logic, NOT delegated:+// V1's Fastify controller uses `@fastify/websocket`'s `WebSocket` (the `ws`+// package, Node EventEmitter semantics), which shares nothing with Elysia's+// `ElysiaWS`/Bun's native `ServerWebSocket` — there is no shim to delegate+// through, and touching the golden-harness-critical V1 ws stack for a few lines+// of framework glue is the risk this port avoids (task notes). V1's controller+// and router are LEFT UNTOUCHED. The shared logic — `getActiveVisitorCount`,+// the four `subscribeToPublishedEvent` calls — moved to realtime.service.ts's+// "/live websocket glue" section; both stacks call the exact same Redis+// subscription underneath.//-// http/auth.ts's invariant 10 (binding, ADR-011): `/live/visitors/:projectId`-// stays unauthenticated; the other three keep session + access; all four-// keep REJECT-AFTER-UPGRADE — the socket accepts the upgrade, then the open-// handler sends a text frame and closes it, exactly like V1. This is why-// none of these routes requests the `session` macro: that macro would 401-// the HTTP upgrade request itself, which is a different (V1-divergent)-// behaviour.+// Http/auth.ts's invariant 10 (binding): `/live/visitors/:projectId` stays+// unauthenticated; the other three keep session + access; all four keep+// REJECT-AFTER-UPGRADE — the socket accepts the upgrade, then the open handler+// sends a text frame and closes it, exactly like V1. This is why none of these+// routes requests the `session` macro: that macro would 401 the HTTP upgrade+// request itself, which is a different (V1-divergent) behaviour.//-// NAMED GAP, same as every other H module this wave: not yet reachable.-// main.ts does not mount `dashboardRoutes` until a real `AppDeps` exists-// (P3/P4/P8), and `http/session.ts`'s `resolveSession` is still a P6 stub-// that always resolves `null` — so today, the three session-gated routes-// close every connection immediately after upgrade. That is the same gap-// http/auth.test.ts already documents for every other session-macro route.+// NAMED GAP, same as every other H module this wave: not yet reachable. main.ts+// does not mount `dashboardRoutes` until a real `AppDeps` exists (P3/P4/P8),+// and `http/session.ts`'s `resolveSession` is still a P6 stub that always+// resolves `null` — so today, the three session-gated routes close every+// connection immediately after upgrade. That is the same gap http/auth.test.ts+// already documents for every other session-macro route.import { setSuperJson } from '@openpanel/shared';import { z } from 'zod';@@ -74,8 +73,7 @@ function rejectNoAccess(ws: ClosableSocket) {export const realtimeRoutes = defineRoutes((app) =>app- // V1: wsVisitors. Unauthenticated by intent (ADR-011 invariant 10,- // docs/ANSWERS.md §3).+ // V1: wsVisitors. Unauthenticated by intent (ADR-011 invariant 10)..ws('/live/visitors/:projectId', {params: projectParams,async open(ws) {diff --git a/packages/core/src/modules/realtime/realtime.rpc.test.ts b/packages/core/src/modules/realtime/realtime.rpc.test.tsindex 5e6909879..2b9011680 100644--- a/packages/core/src/modules/realtime/realtime.rpc.test.ts+++ b/packages/core/src/modules/realtime/realtime.rpc.test.ts@@ -1,9 +1,8 @@-// Only the "is anyone logged in" boundary is exercised here — no database.-// The query bodies run on `deps.ch` (M12-005: statically imported `sql`-// fragments, no @openpanel/db client anywhere in the module); wiring this-// router end-to-end against a real ClickHouse is P6's (protectedProcedure)-// job, not this one's — see realtime.rpc.ts's header. Same shape as-// cohort.rpc.test.ts.+// Only the "is anyone logged in" boundary is exercised here — no database. The+// query bodies run on `deps.ch` (M12-005: statically imported `sql` fragments,+// no @openpanel/db client anywhere in the module); wiring this router+// end-to-end against a real ClickHouse is P6's (protectedProcedure) job, not+// this one's — see realtime.rpc.ts's header. Same shape as cohort.rpc.test.ts.import { expect, test } from 'bun:test';import { stubHttpCtx } from '../../../test/rpc-fixtures';diff --git a/packages/core/src/modules/realtime/realtime.rpc.ts b/packages/core/src/modules/realtime/realtime.rpc.tsindex a5b5053a7..5f0661242 100644--- a/packages/core/src/modules/realtime/realtime.rpc.ts+++ b/packages/core/src/modules/realtime/realtime.rpc.ts@@ -1,18 +1,17 @@-// Ported from packages/trpc/src/routers/realtime.ts (M6-007).+// Ported from packages/trpc/src/routers/realtime.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//// Each procedure also calls `requireProjectAccess({ level: 'read' })`-// explicitly; `enforceAccess` already does the same off the `projectId`-// input, and the redundant call is kept deliberately (ADR-011).+// explicitly; `enforceAccess` already does the same off the `projectId` input,+// and the redundant call is kept deliberately.//-// The permission ladder itself is bound once, in auth.service.ts-// (M10-002); every procedure here reaches it through `ctx.services.auth`.+// The permission ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/realtime/realtime.service.test.ts b/packages/core/src/modules/realtime/realtime.service.test.tsindex 8397277a7..e74a88e18 100644--- a/packages/core/src/modules/realtime/realtime.service.test.ts+++ b/packages/core/src/modules/realtime/realtime.service.test.ts@@ -1,27 +1,26 @@-// M10-005: realtime.service.ts takes `ServiceDeps` now, so the event buffer-// and the ClickHouse client are HANDED IN (`deps.buffers.event`, `deps.ch`)-// rather than mocked onto a module specifier.+// Realtime.service.ts takes `ServiceDeps` now, so the event buffer and the+// ClickHouse client are HANDED IN (`deps.buffers.event`, `deps.ch`) rather than+// mocked onto a module specifier.//-// M12-005: the subject and the real-module snapshot are STATIC imports.-// `@openpanel/redis` is a static import in the subject too (the R6 fix-// removed the `loadRedis` lazy hop) — Bun's `mock.module` still applies-// because it swaps an already-loaded module's exports in place, so a-// consumer that imported before the mock call still sees it — measured on-// Bun 1.4.0, and the subscribe assertions go red if it ever stops. That-// leaves this module with no deferred loads at all (docs/TECH_DEBT.md's-// no-lazy-loaders ruling).+// The subject and the real-module snapshot are STATIC imports.+// `@openpanel/redis` is a static import in the subject too (the R6 fix removed+// the `loadRedis` lazy hop) — Bun's `mock.module` still applies because it+// swaps an already-loaded module's exports in place, so a consumer that+// imported before the mock call still sees it — measured on Bun 1.4.0, and the+// subscribe assertions go red if it ever stops. That leaves this module with no+// deferred loads at all (docs/TECH_DEBT.md's no-lazy-loaders ruling).//// Every assertion below is the one it was before the deps switch: the same-// project scoping, the same 30-minute window, the same filter/limit wiring,-// the same subscribe/unsubscribe behaviour.+// project scoping, the same 30-minute window, the same filter/limit wiring, the+// same subscribe/unsubscribe behaviour.//// Scope: the "/live websocket glue" (new logic this wave adds) plus one// representative ClickHouse query (`getRealtimeActiveSessions`) proving the-// deps + filter/limit wiring. The other five queries are a verbatim-// port of packages/trpc/src/routers/realtime.ts's SQL — mechanical, not new-// behaviour — and are exercised end-to-end by realtime.rpc.test.ts's-// unauthenticated-boundary tests plus this repo's local ClickHouse run (see-// the task summary for the executed query + row count).+// deps + filter/limit wiring. The other five queries are a verbatim port of+// packages/trpc/src/routers/realtime.ts's SQL — mechanical, not new behaviour —+// and are exercised end-to-end by realtime.rpc.test.ts's+// unauthenticated-boundary tests plus this repo's local ClickHouse run (see the+// task summary for the executed query + row count).import { afterAll, beforeEach, expect, mock, test } from 'bun:test';import * as actualRedis from '@openpanel/redis';@@ -156,10 +155,10 @@ test('subscribeToProjectNotifications subscribes on notification:created and filexpect(onNotification).toHaveBeenCalledTimes(1);});-// M30-003 / F2: the `organization:subscription_updated` channel is-// instance-wide. Unfiltered, a subscriber saw the `organizationId` of every-// organization whose subscription changed — including ones it is not a-// member of. This test is red without the filter.+// / F2: the `organization:subscription_updated` channel is instance-wide.+// Unfiltered, a subscriber saw the `organizationId` of every organization whose+// subscription changed — including ones it is not a member of. This test is red+// without the filter.test('subscribeToOrganizationSubscriptionUpdates subscribes on organization:subscription_updated and filters by organizationId', async () => {const onUpdate = mock((_message: unknown) => undefined);await subject.subscribeToOrganizationSubscriptionUpdates('org_1', onUpdate);@@ -200,8 +199,8 @@ test('getRealtimeActiveSessions scopes the query to the project and the 30-minutconst result = await subject.getRealtimeActiveSessions(deps, 'proj_1');expect(chQuery).toHaveBeenCalledTimes(1);- // M12-005: the statement binds its values, so the project scoping and the- // window live in `query_params` — the assertion follows them there.+ // The statement binds its values, so the project scoping and the window live+ // in `query_params` — the assertion follows them there.const { query, query_params } = chQuery.mock.calls[0]![0];expect(query).toContain('project_id = {p1:String}');expect(query).toContain('created_at >= {p2:String}');diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsindex e7a40dcf5..3d6c5a65b 100644--- a/packages/core/src/modules/realtime/realtime.service.ts+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -496,13 +496,13 @@ export async function subscribeToProjectNotifications(/*** V1: `wsOrganizationEvents`. Scoped to the single organization the caller's- * membership was verified against, exactly as the three siblings above scope- * to a verified `projectId`.+ * membership was verified against, exactly as the three siblings above scope to+ * a verified `projectId`.** The channel is instance-wide: without this filter every subscriber saw the- * `organizationId` of every organization whose subscription changed, which is- * a cross-tenant identifier leak (M30-003 / F2). V1 had no filter either —- * this is a deliberate divergence, approved 2026-09-15.+ * `organizationId` of every organization whose subscription changed, which is a+ * cross-tenant identifier leak (F2). V1 had no filter either — this is a+ * deliberate divergence, approved 2026-09-15.*/export async function subscribeToOrganizationSubscriptionUpdates(organizationId: string,diff --git a/packages/core/src/modules/reference/reference.constants.ts b/packages/core/src/modules/reference/reference.constants.tsindex 85285febc..f9c2ece9e 100644--- a/packages/core/src/modules/reference/reference.constants.ts+++ b/packages/core/src/modules/reference/reference.constants.ts@@ -1,7 +1,7 @@-// Moved from packages/validation/src/index.ts (M11-006, ADR-008's module map:-// reference owns "C"). ADR-008 records two diverged `zCreateReference` copies-// in V1 as one of the two drift bugs the dissolution exists to prevent; this-// is now the only one.+// Moved from packages/validation/src/index.ts (ADR-008's module map: reference+// owns "C"). ADR-008 records two diverged `zCreateReference` copies in V1 as+// one of the two drift bugs the dissolution exists to prevent; this is now the+// only one.//// Isomorphic by the AGENTS.md rule: zod and nothing else.diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.tsindex 0ff337089..03ee4d4e9 100644--- a/packages/core/src/modules/reference/reference.rpc.ts+++ b/packages/core/src/modules/reference/reference.rpc.ts@@ -1,20 +1,17 @@-// Ported from packages/trpc/src/routers/reference.ts (M6-004).+// Ported from packages/trpc/src/routers/reference.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// M10-003: the handler bodies reach the module through-// `ctx.services.reference`, so the requestId minted at the edge reaches the-// Postgres call (ADR-018).+// The handler bodies reach the module through `ctx.services.reference`, so the+// requestId minted at the edge reaches the Postgres call.//-// The permission ladder itself is bound once, in auth.service.ts (M10-002);-// every procedure here reaches it through `ctx.services.auth`. `create` has-// no access check here either — same gap V1's router has (ported verbatim,-// not fixed).+// The permission ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`. `create` has no access+// check here either — same gap V1's router has (ported verbatim, not fixed).import { z } from 'zod';import {diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsindex bac7c1077..797392e0f 100644--- a/packages/core/src/modules/reference/reference.service.test.ts+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -1,7 +1,7 @@-// The subject is built by its factory over a fake `ServiceDeps` (M10-003), so-// Postgres needs no module mock at all — `deps.db` IS the fake below. Only the-// two sibling modules the service still calls as plain functions are mocked,-// at the specifier the source resolves through.+// The subject is built by its factory over a fake `ServiceDeps`, so Postgres+// needs no module mock at all — `deps.db` IS the fake below. Only the two+// sibling modules the service still calls as plain functions are mocked, at the+// specifier the source resolves through.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -105,11 +105,11 @@ const getChartStartEndDate = mock(() => ({startDate: '2026-08-25 00:00:00',endDate: '2026-09-01 23:59:59',}));-// M10-003: the module no longer reaches either through a lazy-// `@openpanel/core` hop — Postgres arrives as `deps.db` and these two are-// plain relative imports, so each is mocked at the specifier the source-// actually resolves through. Snapshot-before-mock so `afterAll` restores the-// real module rather than re-applying the mock.+// The module no longer reaches either through a lazy `@openpanel/core` hop —+// Postgres arrives as `deps.db` and these two are plain relative imports, so+// each is mocked at the specifier the source actually resolves through.+// Snapshot-before-mock so `afterAll` restores the real module rather than+// re-applying the mock.const actualOrganization = await import('../organization/organization.service');const realOrganization = { ...actualOrganization };mock.module('../organization/organization.service', () => ({diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsindex ebb83dcf6..92cbcce80 100644--- a/packages/core/src/modules/reference/reference.service.ts+++ b/packages/core/src/modules/reference/reference.service.ts@@ -1,16 +1,15 @@// Moved from packages/db/src/services/reference.service.ts, plus the// query/mutation bodies packages/trpc/src/routers/reference.ts held inline-// (M6-004, DELEGATE PATTERN: V1's router and this package's own-// reference.rpc.ts shared one implementation, same as-// conversation.service.ts since M5-006, until packages/trpc was retired at-// M11-004).+// (DELEGATE PATTERN: V1's router and this package's own reference.rpc.ts shared+// one implementation, same as conversation.service.ts since M5-006, until+// packages/trpc was retired at M11-004).//-// M10-003: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`. The `loadDb()` / `loadDateService()` / `loadOrganizationService()`-// lazy loaders are gone: nothing here value-imports `@openpanel/db` or this-// package's own barrel any more (the Prisma row type below is `import type`,-// erased at runtime), so there is no import-time client — and no pino-pretty-// worker per test file — left to defer (docs/TECH_DEBT.md §4).+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`. The+// `loadDb` / `loadDateService` / `loadOrganizationService` lazy loaders are+// gone: nothing here value-imports `@openpanel/db` or this package's own barrel+// any more (the Prisma row type below is `import type`, erased at runtime), so+// there is no import-time client — and no pino-pretty worker per test file —+// left to defer.import type { Reference } from '@openpanel/db/src/prisma-client';import type { ServiceDeps, Services } from '../../services';diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.tsindex df73da0c1..959eebde7 100644--- a/packages/core/src/modules/report/report.constants.ts+++ b/packages/core/src/modules/report/report.constants.ts@@ -1,8 +1,8 @@-// Ported from V1's packages/constants + packages/validation (M7-006,-// ADR-008's module map: report owns "C" for the chart/report/widget-// vocabulary) — neither package exists in this tree; every importer here-// (the chart engine, apps/start's report builder) reaches these symbols-// through this file directly.+// Ported from V1's packages/constants + packages/validation (ADR-008's module+// map: report owns "C" for the chart/report/widget vocabulary) — neither+// package exists in this tree; every importer here (the chart engine,+// apps/start's report builder) reaches these symbols through this file+// directly.//// `getDefaultIntervalByDates` is REWRITTEN from date-fns// (differenceInDays/isSameDay) to plain Date math per the module map. Every@@ -11,8 +11,8 @@// getters (getFullYear/getMonth/getDate) already read UTC — the helpers below// reproduce date-fns's local-calendar semantics exactly under that invariant,// and the only inputs this function ever receives are date-only strings-// (midnight boundaries), where date-fns's exact-duration-vs-calendar-day-// nuance cannot diverge from a plain ms division anyway.+// (midnight boundaries), where date-fns's exact-duration-vs-calendar-day nuance+// cannot diverge from a plain ms division anyway.//// Isomorphic by the AGENTS.md rule: zod and nothing else.@@ -646,11 +646,11 @@ export const chartColors = [*/const CHART_FORMULA_PATTERN = /^[A-Za-z0-9_ .,+\-*/()%^]*$/;-// Helper, not vocabulary — ADR-008 rules this the one genuine exception to-// the module-export rule: every consumer copies these 4 lines locally-// instead of importing them (apps/start/src/utils/object-to-zod-enums.ts is-// the frontend's copy). Kept private here for report.constants.ts's own use-// building the enums below.+// Helper, not vocabulary — ADR-008 rules this the one genuine exception to the+// module-export rule: every consumer copies these 4 lines locally instead of+// importing them (apps/start/src/utils/object-to-zod-enums.ts is the frontend's+// copy). Kept private here for report.constants.ts's own use building the enums+// below.function objectToZodEnums<K extends string>(obj: Record<K, unknown>): [K, ...K[]] {@@ -952,16 +952,16 @@ export const zReport = zReportInput.extend({// Alias for backward compatibilityexport const zChartInput = zReportInput;-// ----------------------------------------------------------------------------// Inferred report/chart types, moved from packages/validation/src/types.validation.ts-// (M11-006, ADR-008's module map: report owns "C" for the chart/report/widget-// vocabulary). They land beside the schemas they infer from, which is what-// removes that file's `import type { … } from './index'` back-edge.-// `IChartEvents` and `ISetCookie` do NOT come along: the first is a dead alias-// with no importers, the second is already ../../shared/cookie.ts.-// `UnionOmit` has no owning module — it is kept here, with the report types it-// is only ever applied to (apps/start's reportSlice), until M11-007 gives-// apps/start its own copy.+// --------------------------------------------------------------------------+// Inferred report/chart types, moved from+// packages/validation/src/types.validation.ts (ADR-008's module map: report+// owns "C" for the chart/report/widget vocabulary). They land beside the+// schemas they infer from, which is what removes that file's `import type { … }+// from './index'` back-edge. `IChartEvents` and `ISetCookie` do NOT come along:+// the first is a dead alias with no importers, the second is+// already../../shared/cookie.ts. `UnionOmit` has no owning module — it is kept+// here, with the report types it is only ever applied to (apps/start's+// reportSlice), until M11-007 gives apps/start its own copy.// ---------------------------------------------------------------------------export type UnionOmit<T, K extends keyof any> = T extends anydiff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.tsindex 4f1355619..61b0f13db 100644--- a/packages/core/src/modules/report/report.rpc.ts+++ b/packages/core/src/modules/report/report.rpc.ts@@ -1,16 +1,15 @@-// Ported from packages/trpc/src/routers/report.ts (M7-006).+// Ported from packages/trpc/src/routers/report.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// Most of this router's inputs carry a reportId or a dashboardId rather than-// a projectId, so `enforceAccess` is blind to them and the in-handler-// `requireProjectAccess` through `ctx.services.auth` (M10-002) is the only-// check that fires.+// Most of this router's inputs carry a reportId or a dashboardId rather than a+// projectId, so `enforceAccess` is blind to them and the in-handler+// `requireProjectAccess` through `ctx.services.auth` is the only check that+// fires.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/report/report.service.test.ts b/packages/core/src/modules/report/report.service.test.tsindex ccf1cdd7d..4bc6be516 100644--- a/packages/core/src/modules/report/report.service.test.ts+++ b/packages/core/src/modules/report/report.service.test.ts@@ -2,8 +2,8 @@* Unit tests for mergeGlobalFilters — the helper that combines report-level* global filters with each event series' own filters (AND semantics). Pure* function, no ClickHouse/Postgres needed. Ported from- * packages/db/src/services/reports.service.test.ts (M7-006), vitest -> bun:test.- * M10-003 moved the helper to ./src/series.ts — see that file for why.+ * packages/db/src/services/reports.service.test.ts, vitest -> bun:test. M10-003+ * moved the helper to./src/series.ts — see that file for why.*/import { describe, expect, it } from 'bun:test';import type { IChartEventFilter, IChartEventItem } from './report.constants';diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.tsindex 7531a6c73..dfb03c690 100644--- a/packages/core/src/modules/report/report.service.ts+++ b/packages/core/src/modules/report/report.service.ts@@ -1,13 +1,13 @@// Ported from V1's packages/db/src/services/reports.service.ts, plus the// create/update/move/delete/duplicate/layout mutation bodies V1's-// packages/trpc/src/routers/report.ts held inline (M7-006, ADR-008's module-// map: report owns "R,S,C") — neither package exists in this tree.+// packages/trpc/src/routers/report.ts held inline (ADR-008's module map: report+// owns "R,S,C") — neither package exists in this tree.//-// M10-003: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; `loadDb()` and the `@openpanel/core` self-barrel import are-// gone — the Prisma row types below are `import type`, erased at runtime-// (docs/TECH_DEBT.md §4). `onlyReportEvents`/`mergeGlobalFilters` moved to-// ./src/series.ts — see that file for why.+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`;+// `loadDb` and the `@openpanel/core` self-barrel import are gone — the Prisma+// row types below are `import type`, erased at runtime.+// `onlyReportEvents`/`mergeGlobalFilters` moved to./src/series.ts — see that+// file for why.import type {Report as DbReport,diff --git a/packages/core/src/modules/report/src/chart-dates.ts b/packages/core/src/modules/report/src/chart-dates.tsindex 21df66a03..48efe3d2b 100644--- a/packages/core/src/modules/report/src/chart-dates.ts+++ b/packages/core/src/modules/report/src/chart-dates.ts@@ -1,8 +1,7 @@// 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`.+// `shared/date.ts` at M15-009: 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 '@openpanel/shared';import type { IChartRange, IReportInput } from '../report.constants';diff --git a/packages/core/src/modules/report/src/previous-metric.ts b/packages/core/src/modules/report/src/previous-metric.tsindex 7e18fba14..c6aa8b235 100644--- a/packages/core/src/modules/report/src/previous-metric.ts+++ b/packages/core/src/modules/report/src/previous-metric.ts@@ -1,8 +1,8 @@// 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`.+// `shared/math.ts` at M15-009: 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 { round } from '@openpanel/shared';import { isNil } from 'ramda';diff --git a/packages/core/src/modules/report/src/series.ts b/packages/core/src/modules/report/src/series.tsindex e04b78959..27b6c786b 100644--- a/packages/core/src/modules/report/src/series.ts+++ b/packages/core/src/modules/report/src/series.ts@@ -1,9 +1,9 @@-// The two pure series helpers V1 kept on `reports.service`. They live here,-// not on report.service.ts, because the chart module needs them and-// report.service.ts imports the chart engine — a static import back would-// close a real cycle (report.service -> chart/funnel.service ->-// report.service). Nothing here touches a database, so both sides stay-// eager and neither needs a lazy loader (docs/TECH_DEBT.md §4 step 2).+// The two pure series helpers V1 kept on `reports.service`. They live here, not+// on report.service.ts, because the chart module needs them and+// report.service.ts imports the chart engine — a static import back would close+// a real cycle (report.service -> chart/funnel.service -> report.service).+// Nothing here touches a database, so both sides stay eager and neither needs a+// lazy loader.import type { IChartEventFilter, IChartEventItem } from '../report.constants';diff --git a/packages/core/src/modules/salt/salt.jobs.ts b/packages/core/src/modules/salt/salt.jobs.tsindex a1702dfd4..e915d104f 100644--- a/packages/core/src/modules/salt/salt.jobs.ts+++ b/packages/core/src/modules/salt/salt.jobs.ts@@ -1,9 +1,9 @@// Ported from apps/worker/src/jobs/cron.salt.ts + boot-cron.ts's `salt`-// schedule (M8-004); the schedule moved onto the job at ADR-021 (M10-007).+// schedule; the schedule moved onto the job at ADR-021.//-// `salt` is this module's fragment of the ONE `cron` queue's jobs, spread-// into jobs.registry.ts. Its schedule is now derived straight from `cron`-// below — id and cadence are V1's, unchanged (apps/worker/src/boot-cron.ts).+// `salt` is this module's fragment of the ONE `cron` queue's jobs, spread into+// jobs.registry.ts. Its schedule is now derived straight from `cron` below — id+// and cadence are V1's, unchanged (apps/worker/src/boot-cron.ts).import { z } from 'zod';import { defineJob } from '../../jobs/define';diff --git a/packages/core/src/modules/salt/salt.service.test.ts b/packages/core/src/modules/salt/salt.service.test.tsindex 0a374bc70..d3e6977e5 100644--- a/packages/core/src/modules/salt/salt.service.test.ts+++ b/packages/core/src/modules/salt/salt.service.test.ts@@ -1,16 +1,16 @@-// The subject is built over a fake `ServiceDeps` (M10-004), so Postgres needs-// no module mock at all — `deps.db` IS the fake below, same idiom as-// reference.service.test.ts. `@openpanel/redis`'s `cacheable` is still-// stubbed (module-level `getSalts` binds it at this file's first import), so-// `rotateSalt`'s `getSalts.clear()` never reaches a real Redis connection —-// same reasoning as before this wave, just without the `@openpanel/db` mock.+// The subject is built over a fake `ServiceDeps`, so Postgres needs no module+// mock at all — `deps.db` IS the fake below, same idiom as+// reference.service.test.ts. `@openpanel/redis`'s `cacheable` is still stubbed+// (module-level `getSalts` binds it at this file's first import), so+// `rotateSalt`'s `getSalts.clear` never reaches a real Redis connection — same+// reasoning as before this wave, just without the `@openpanel/db` mock.//// `getSalts` itself stays untested here: it is bare (no `deps` argument)// because ingest.service.ts's hot path calls it with none — see the module-// header — and its `cacheable(...)` wrapping binds at this module's-// first-ever evaluation, which a bare (non `--isolate`) `bun test` run does-// not let this file control. `fetchSalts` (the uncached read it wraps) is-// exercised directly instead.+// header — and its `cacheable(...)` wrapping binds at this module's first-ever+// evaluation, which a bare (non `--isolate`) `bun test` run does not let this+// file control. `fetchSalts` (the uncached read it wraps) is exercised directly+// instead.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';diff --git a/packages/core/src/modules/salt/salt.service.ts b/packages/core/src/modules/salt/salt.service.tsindex fd7cbb03d..2ba6cd308 100644--- a/packages/core/src/modules/salt/salt.service.ts+++ b/packages/core/src/modules/salt/salt.service.ts@@ -1,16 +1,16 @@// Moved from packages/db/src/services/salt.service.ts +-// apps/worker/src/jobs/cron.salt.ts (M8-004).+// apps/worker/src/jobs/cron.salt.ts.//-// M10-004: reaches Postgres as `deps.db`, no `@openpanel/db` import left.-// `main.ts` passes its own `deps` to `createInitialSalts` at boot;-// `salt.jobs.ts`'s handler passes its `JobCtx` (a `ServiceDeps` by-// construction) to `rotateSalt`.+// Reaches Postgres as `deps.db`, no `@openpanel/db` import left. `main.ts`+// passes its own `deps` to `createInitialSalts` at boot; `salt.jobs.ts`'s+// handler passes its `JobCtx` (a `ServiceDeps` by construction) to+// `rotateSalt`.//-// M15-005: `getSalts` is a module-scope `cacheablePerDb`, keyed on the-// Postgres client rather than on the scope — its L1 LRU has to survive across-// calls to be worth anything, and `ingest.service.ts`'s `/track` hot path now-// passes the scope it holds instead of reading a boot-scoped singleton through-// the deleted compat seam. `generateNewSalt` clears the same instance.+// `getSalts` is a module-scope `cacheablePerDb`, keyed on the Postgres client+// rather than on the scope — its L1 LRU has to survive across calls to be worth+// anything, and `ingest.service.ts`'s `/track` hot path now passes the scope it+// holds instead of reading a boot-scoped singleton through the deleted compat+// seam. `generateNewSalt` clears the same instance.import { generateSalt } from '@openpanel/shared/server';import { cacheablePerDb } from '../../cacheable-per-deps';diff --git a/packages/core/src/modules/session/session.jobs.ts b/packages/core/src/modules/session/session.jobs.tsindex 78aef8979..4aca1bf2d 100644--- a/packages/core/src/modules/session/session.jobs.ts+++ b/packages/core/src/modules/session/session.jobs.ts@@ -1,7 +1,8 @@-// Ported from apps/worker/src/jobs/sessions.ts (+ events.create-session-end.ts),-// cron.session-reaper.ts and cron.session-vacuum.ts (M7-001); `flushSessions`-// and `flushReplay` (apps/worker/src/jobs/cron.ts) join them here at M8-004.-// Schedules moved onto the jobs at ADR-021 (M10-007).+// Ported from apps/worker/src/jobs/sessions.ts (++// events.create-session-end.ts), cron.session-reaper.ts and+// cron.session-vacuum.ts; `flushSessions` and `flushReplay`+// (apps/worker/src/jobs/cron.ts) join them here at M8-004. Schedules moved onto+// the jobs at ADR-021.//// `sessions` is this module's own queue — registry key and Redis name// `sessions`, job name `session`, `removeOnComplete: true`, concurrency 1, all@@ -13,7 +14,7 @@//// Every handler reads its clients off `ctx` — the buffers and the Redis// connection main.ts built once, and the ClickHouse client the job's own-// requestId is bound to (M10-006, docs/TECH_DEBT.md §2).+// requestId is bound to.import { z } from 'zod';import { chQuery } from '../../ch-query';@@ -45,15 +46,15 @@ const FLUSH_SESSIONS_INTERVAL_MS = 10_000;const FLUSH_REPLAY_INTERVAL_MS = 10_000;// Wire-shape check only — V1 never validated it either (see-// jobs/compat.test.ts), and tightening it now would reject payloads the-// running system accepts.+// jobs/compat.test.ts), and tightening it now would reject payloads the running+// system accepts.//// The schema's INPUT is what the producer holds (`SessionEndJobData`, a real// `Date` on `event.createdAt`) and its OUTPUT is what a handler is actually// handed after BullMQ's JSON round-trip (`SessionEndJobWire`, a string there).-// `PayloadOf` reads the input and the handler reads the output, so the two-// stay honest without either side casting (ADR-022 R18). The transform is a-// type seam only — it returns the value it was given.+// `PayloadOf` reads the input and the handler reads the output, so the two stay+// honest without either side casting. The transform is a type seam only — it+// returns the value it was given.const sessionEndWireShape = z.object({event: z.object({ projectId: z.string(), deviceId: z.string() }),snapshot: z.object({@@ -74,9 +75,9 @@ const sessionEndPayload = z* The session-end job's dependencies, bound to the run's own ctx.** Two lookups stay dynamic, both for the same reason now that- * notification-dispatch.ts has moved into core (M11-003): keeping- * notification.service.ts — and the dispatch module built on it — out of- * jobs.registry.ts's eager import graph, which every core test file walks.+ * notification-dispatch.ts has moved into core: keeping notification.service.ts+ * — and the dispatch module built on it — out of jobs.registry.ts's eager+ * import graph, which every core test file walks.*/async function sessionEndDeps(ctx: Ctx,diff --git a/packages/core/src/modules/session/session.rpc.ts b/packages/core/src/modules/session/session.rpc.tsindex 11a379eeb..982382d2f 100644--- a/packages/core/src/modules/session/session.rpc.ts+++ b/packages/core/src/modules/session/session.rpc.ts@@ -1,15 +1,14 @@-// Ported from packages/trpc/src/routers/session.ts (M7-001).+// Ported from packages/trpc/src/routers/session.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// V1's file also exported `encodeCursor` / `decodeCursor`; nothing imports-// them and `shared/pagination.ts` already has the generic pair, so they were-// not ported.+// V1's file also exported `encodeCursor` / `decodeCursor`; nothing imports them+// and `shared/pagination.ts` already has the generic pair, so they were not+// ported.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 76912de3d..38034748a 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -1,6 +1,6 @@-// The session read path. Every query is a `sql` fragment (src/sql.ts), per-// ADR-013; `buildFilterWhere` is the shared filter compiler and-// src/filter-clauses.ts is the bridge to it.+// The session read path. Every query is a `sql` fragment (src/sql.ts);+// `buildFilterWhere` is the shared filter compiler and src/filter-clauses.ts is+// the bridge to it.//// `getSessionsCountCached` is `cacheablePerDeps`: `cacheable` keys on the// call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps have to@@ -495,8 +495,8 @@ export function createSessionService(}/** `event.service.ts` reaches this through the composition root's thunk- * (ADR-022 R3): `session-end.ts` statically imports the event module, so- * the two are a real cycle and an import back would be the wrong answer. */+ * `session-end.ts` statically imports the event module, so the two are a real+ * cycle and an import back would be the wrong answer. */function getById(sessionId: string,projectId: stringdiff --git a/packages/core/src/modules/session/src/runtime.ts b/packages/core/src/modules/session/src/runtime.tsindex 0b55a50f6..1938e94ce 100644--- a/packages/core/src/modules/session/src/runtime.ts+++ b/packages/core/src/modules/session/src/runtime.ts@@ -56,8 +56,8 @@ export interface SessionRuntime {/*** The two boot singletons the lifecycle needs, read off the work scope rather* than constructed here: `ctx.redis` and `ctx.buffers` are the same objects- * main.ts built once, so a job handler no longer opens a connection of its- * own and its writes stay inside the request's scope (ADR-007, ADR-018 R1).+ * main.ts built once, so a job handler no longer opens a connection of its own+ * and its writes stay inside the request's scope.*/export function sessionRuntimeFrom(ctx: Pick<Ctx, 'redis' | 'buffers' | 'config'>diff --git a/packages/core/src/modules/session/src/session-end.test.ts b/packages/core/src/modules/session/src/session-end.test.tsindex b10edc7fb..167c4e3ba 100644--- a/packages/core/src/modules/session/src/session-end.test.ts+++ b/packages/core/src/modules/session/src/session-end.test.ts@@ -1,7 +1,7 @@-// Ported from apps/worker/src/jobs/events.create-session-end.test.ts (M7-001).-// Covers the three-case logic (extended-after-enqueue skip, live vs snapshot,-// boundary), the first-writer idempotency claim, and that cleanup() is-// id-gated to the closed session.+// Ported from apps/worker/src/jobs/events.create-session-end.test.ts. Covers+// the three-case logic (extended-after-enqueue skip, live vs snapshot,+// boundary), the first-writer idempotency claim, and that cleanup is id-gated+// to the closed session.import { describe, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/session/src/session-end.ts b/packages/core/src/modules/session/src/session-end.tsindex 2f28d22b5..e9f0e72b4 100644--- a/packages/core/src/modules/session/src/session-end.ts+++ b/packages/core/src/modules/session/src/session-end.ts@@ -1,10 +1,10 @@// Ported from apps/worker/src/jobs/events.create-session-end.ts and-// utils/session-handler.ts (M7-001).+// utils/session-handler.ts.//// Everything that touches Redis, ClickHouse, a buffer or a queue is INJECTED// (`SessionEndDeps`): M10-006 moved the binding into `session.jobs.ts`, where// the job's `ctx` supplies every client, so the requestId that opened the-// session still labels the rows this close writes (ADR-018 R1).+// session still labels the rows this close writes.import type { CoreConfig } from '../../../config';import type { EnqueueOptions } from '../../../jobs/define';@@ -68,11 +68,11 @@ export interface SessionEndJobData {}/**- * `SessionEndJobData` as it comes back OFF the queue (ADR-022 R18). BullMQ- * stores job data as JSON, so `event.createdAt` is a string by the time a- * handler sees it however the producer typed it — `createSessionEnd`- * overwrites the field before use, and this type is what stops the next- * reader from trusting the `Date` the producer side declares.+ * `SessionEndJobData` as it comes back OFF the queue. BullMQ stores job data as+ * JSON, so `event.createdAt` is a string by the time a handler sees it however+ * the producer typed it — `createSessionEnd` overwrites the field before use,+ * and this type is what stops the next reader from trusting the `Date` the+ * producer side declares.*/export interface SessionEndJobWire {event: Omit<IServiceCreateEventPayload, 'createdAt'> & { createdAt: string };diff --git a/packages/core/src/modules/session/src/session-reaper.test.ts b/packages/core/src/modules/session/src/session-reaper.test.tsindex fdb6ccf8d..c238403ac 100644--- a/packages/core/src/modules/session/src/session-reaper.test.ts+++ b/packages/core/src/modules/session/src/session-reaper.test.ts@@ -1,6 +1,6 @@-// Ported from apps/worker/src/jobs/cron.session-reaper.test.ts (M7-001). The-// wall-clock deadman that closes idle sessions: stub Redis drives the-// wallclock ZSET + lock, so the assertions are on decisions, not side effects.+// Ported from apps/worker/src/jobs/cron.session-reaper.test.ts. The wall-clock+// deadman that closes idle sessions: stub Redis drives the wallclock ZSET ++// lock, so the assertions are on decisions, not side effects.import { describe, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/session/src/session-reaper.ts b/packages/core/src/modules/session/src/session-reaper.tsindex 9d350330c..88b7304f9 100644--- a/packages/core/src/modules/session/src/session-reaper.ts+++ b/packages/core/src/modules/session/src/session-reaper.ts@@ -1,4 +1,4 @@-// Ported from apps/worker/src/jobs/cron.session-reaper.ts (M7-001).+// Ported from apps/worker/src/jobs/cron.session-reaper.ts.import type { Logger } from '../../../logger';import type { IServiceCreateEventPayload } from '../../event/event.service';diff --git a/packages/core/src/modules/session/src/session-vacuum.test.ts b/packages/core/src/modules/session/src/session-vacuum.test.tsindex 03661ccfa..8e6aab13f 100644--- a/packages/core/src/modules/session/src/session-vacuum.test.ts+++ b/packages/core/src/modules/session/src/session-vacuum.test.ts@@ -1,6 +1,6 @@-// Ported from apps/worker/src/jobs/cron.session-vacuum.test.ts (M7-001). The-// daily backstop for sessions whose cleanup() leaked: a lingering blob →-// id-gated cleanup(); a missing blob → ZREM the orphan.+// Ported from apps/worker/src/jobs/cron.session-vacuum.test.ts. The daily+// backstop for sessions whose cleanup leaked: a lingering blob → id-gated+// cleanup; a missing blob → ZREM the orphan.import { describe, expect, test } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/session/src/session-vacuum.ts b/packages/core/src/modules/session/src/session-vacuum.tsindex a7aa275ab..33f216252 100644--- a/packages/core/src/modules/session/src/session-vacuum.ts+++ b/packages/core/src/modules/session/src/session-vacuum.ts@@ -1,4 +1,4 @@-// Ported from apps/worker/src/jobs/cron.session-vacuum.ts (M7-001).+// Ported from apps/worker/src/jobs/cron.session-vacuum.ts.import type { Logger } from '../../../logger';import { PROJECTS_SET_KEY, wallclockSetKey } from './keys';diff --git a/packages/core/src/modules/session/src/session.metrics.ts b/packages/core/src/modules/session/src/session.metrics.tsindex ca6ce7ff4..eb11efa04 100644--- a/packages/core/src/modules/session/src/session.metrics.ts+++ b/packages/core/src/modules/session/src/session.metrics.ts@@ -1,9 +1,9 @@-// The session lifecycle collectors, moved from apps/worker/src/metrics.ts-// (M7-001) onto core's one registry. Names, labels and buckets are V1's; the-// worker-side copies die with apps/worker (P9). The ingest-side-// `sessions_started_total` lives with the ingest path-// (modules/ingest/src/ingest.metrics.ts); the three at-scrape gauges joined-// this file at M9-002 — see `registerSessionScrapeMetrics` at the bottom.+// The session lifecycle collectors, moved from apps/worker/src/metrics.ts onto+// core's one registry. Names, labels and buckets are V1's; the worker-side+// copies die with apps/worker (P9). The ingest-side `sessions_started_total`+// lives with the ingest path (modules/ingest/src/ingest.metrics.ts); the three+// at-scrape gauges joined this file at M9-002 — see+// `registerSessionScrapeMetrics` at the bottom.import client from 'prom-client';import { registry } from '../../../metrics';@@ -12,7 +12,7 @@ import { registry } from '../../../metrics';const SESSION_PROJECTS_KEY = 'session:projects';/**- * The slice of the cache client the gauges use. `multi()` is V1's, and it is+ * The slice of the cache client the gauges use. `multi` is V1's, and it is* batching rather than a transaction — the ADR-006 swap replaces it with* `Promise.all` over Bun's auto-pipelining when packages/redis moves.*/diff --git a/packages/core/src/modules/session/src/sql.ts b/packages/core/src/modules/session/src/sql.tsindex a3a13e0b2..b45a060bd 100644--- a/packages/core/src/modules/session/src/sql.ts+++ b/packages/core/src/modules/session/src/sql.ts@@ -1,19 +1,19 @@-// Every ClickHouse query the session module runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/session.service.ts-// and apps/worker/src/jobs/events.create-session-end.ts (M7-001): the SQL text-// is V1's, with every value bound as a `{pN:Type}` parameter instead of an-// escaped literal, and each conversion was proven byte-equivalent against the-// local prod-copy (see the task report).+// Every ClickHouse query the session module runs, as pure `sql` fragments.+// Converted 1:1 from packages/db/src/services/session.service.ts and+// apps/worker/src/jobs/events.create-session-end.ts: the SQL text is V1's, with+// every value bound as a `{pN:Type}` parameter instead of an escaped literal,+// and each conversion was proven byte-equivalent against the local prod-copy+// (see the task report).//// Dates bind as V1's own `YYYY-MM-DD HH:mm:ss` strings on purpose: a String// param in a DateTime64 position is parsed exactly like the literal it// replaces, so the result sets cannot drift by a millisecond truncation.//-// Cluster note (docs/ENVIRONMENT.md): `sessions` and `session_replay_chunks`-// are Distributed on Cloud. The has_replay LEFT JOIN subquery and any-// `IN (SELECT ...)` a filter compiles to keep V1's exact shape and run under-// the client's `distributed_product_mode: 'allow'` as before — converting a-// query is not the place to change its cluster semantics.+// Cluster note: `sessions` and `session_replay_chunks` are Distributed on+// Cloud. The has_replay LEFT JOIN subquery and any `IN (SELECT...)` a filter+// compiles to keep V1's exact shape and run under the client's+// `distributed_product_mode: 'allow'` as before — converting a query is not the+// place to change its cluster semantics.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';@@ -134,11 +134,11 @@ function sessionListWindow(query: SessionListQuery): SqlFragment {}// No `FINAL`: it reads every column of the whole window and blocks-// read-in-order (measured 1.1 s → 0.15 s on a large project). A +1 whose-// `(id, version)` has a −1 is a pending collapse, which `FINAL` would have-// removed. Plain `sign = 1` alone returns those stale rows, and `LIMIT 1 BY id`-// drops the orphan +1 duplicates `FINAL` keeps. `GLOBAL` builds the −1 set once-// on the initiator instead of once per shard (docs/ENVIRONMENT.md).+// read-in-order (measured 1.1 s → 0.15 s on a large project). A +1 whose `(id,+// version)` has a −1 is a pending collapse, which `FINAL` would have removed.+// Plain `sign = 1` alone returns those stale rows, and `LIMIT 1 BY id` drops+// the orphan +1 duplicates `FINAL` keeps. `GLOBAL` builds the −1 set once on+// the initiator instead of once per shard.export function sessionListQuery(query: SessionListQuery): SqlFragment {const { projectId, take, lookbackDays, profileId, search } = query;const { filterClauses = {} } = query;diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.tsindex 733c3f758..f18127ade 100644--- a/packages/core/src/modules/session/src/usage.ts+++ b/packages/core/src/modules/session/src/usage.ts@@ -1,7 +1,7 @@-// Ported from apps/worker/src/jobs/sessions.ts (M7-001): after each-// session_end the owning project's and organization's event counters are-// refreshed, at most once an hour per project, and usage alert emails go out-// at 80% / 100% of the billing limit.+// Ported from apps/worker/src/jobs/sessions.ts: after each session_end the+// owning project's and organization's event counters are refreshed, at most+// once an hour per project, and usage alert emails go out at 80% / 100% of the+// billing limit.import type { Organization } from '@openpanel/db/src/prisma-client';import { cacheablePerDeps } from '../../../cacheable-per-deps';diff --git a/packages/core/src/modules/share/share.constants.ts b/packages/core/src/modules/share/share.constants.tsindex 2d46412f0..bac1d954a 100644--- a/packages/core/src/modules/share/share.constants.ts+++ b/packages/core/src/modules/share/share.constants.ts@@ -1,7 +1,7 @@-// Moved from packages/validation/src/index.ts (M6-004, ADR-008's module map:-// share owns "C"). packages/validation re-exports these for existing-// packages/validation importers — same shape as-// packages/validation/src/index.ts's onboarding/auth re-exports since M6-003.+// Moved from packages/validation/src/index.ts (ADR-008's module map: share owns+// "C"). packages/validation re-exports these for existing packages/validation+// importers — same shape as packages/validation/src/index.ts's onboarding/auth+// re-exports since M6-003.import { z } from 'zod';diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.tsindex 0940716b2..dcea4d4de 100644--- a/packages/core/src/modules/share/share.rpc.ts+++ b/packages/core/src/modules/share/share.rpc.ts@@ -1,19 +1,18 @@-// Ported from packages/trpc/src/routers/share.ts (M6-004).+// Ported from packages/trpc/src/routers/share.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// M10-003: the handler bodies reach the module through `ctx.services.share`,-// so the requestId minted at the edge reaches the Postgres call (ADR-018).+// The handler bodies reach the module through `ctx.services.share`, so the+// requestId minted at the edge reaches the Postgres call.//-// The permission ladder itself is bound once, in auth.service.ts (M10-002);-// every procedure here reaches it through `ctx.services.auth`.-// `createOverview` has no in-handler check — the same gap V1's router has,-// ported verbatim, not fixed.+// The permission ladder itself is bound once, in auth.service.ts; every+// procedure here reaches it through `ctx.services.auth`. `createOverview` has+// no in-handler check — the same gap V1's router has, ported verbatim, not+// fixed.import { z } from 'zod';import {diff --git a/packages/core/src/modules/share/share.service.test.ts b/packages/core/src/modules/share/share.service.test.tsindex 389c56978..eb34bddbf 100644--- a/packages/core/src/modules/share/share.service.test.ts+++ b/packages/core/src/modules/share/share.service.test.ts@@ -1,8 +1,8 @@-// The subject is built by its factory over a fake `ServiceDeps` (M10-003), so-// Postgres needs no module mock at all — `deps.db` IS the fake below. Only the-// three sibling modules the service calls as plain functions are mocked, each-// at the specifier the source resolves through, snapshot-before-mock so-// `afterAll` restores the real module instead of re-applying the mock.+// The subject is built by its factory over a fake `ServiceDeps`, so Postgres+// needs no module mock at all — `deps.db` IS the fake below. Only the three+// sibling modules the service calls as plain functions are mocked, each at the+// specifier the source resolves through, snapshot-before-mock so `afterAll`+// restores the real module instead of re-applying the mock.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';diff --git a/packages/core/src/modules/share/share.service.ts b/packages/core/src/modules/share/share.service.tsindex 04a7066fc..44453d460 100644--- a/packages/core/src/modules/share/share.service.ts+++ b/packages/core/src/modules/share/share.service.ts@@ -1,16 +1,14 @@-// Moved from packages/db/src/services/share.service.ts, plus the-// query/mutation bodies packages/trpc/src/routers/share.ts held inline-// (M6-004, DELEGATE PATTERN: V1's router and this package's own share.rpc.ts-// share one implementation, same as organization.service.ts since M6-001).-// packages/db keeps a re-export shim: auth.service.ts's signInToShare-// (M6-003) and packages/trpc's chart/overview routers still reach-// validateShareAccess/validateOverviewShareAccess through it.+// Moved from packages/db/src/services/share.service.ts, plus the query/mutation+// bodies packages/trpc/src/routers/share.ts held inline (DELEGATE PATTERN: V1's+// router and this package's own share.rpc.ts share one implementation, same as+// organization.service.ts since M6-001). packages/db keeps a re-export shim:+// auth.service.ts's signInToShare and packages/trpc's chart/overview routers+// still reach validateShareAccess/validateOverviewShareAccess through it.//-// M10-003: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` / `loadAccessService()` / `loadDashboardService()`-// / `loadReportsService()` lazy loaders are gone, so this module-// value-imports neither `@openpanel/db` nor its own package barrel-// (docs/TECH_DEBT.md §4).+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb` / `loadAccessService` / `loadDashboardService` /+// `loadReportsService` lazy loaders are gone, so this module value-imports+// neither `@openpanel/db` nor its own package barrel.import ShortUniqueId from 'short-unique-id';import { TRPCForbiddenError, TRPCNotFoundError } from '../../rpc/errors';@@ -86,8 +84,8 @@ export async function getShareReportByReportId(}/**- * @deprecated Zero call sites (ADR-015 register entry #14, graded DEAD).- * Ported as-is — removal is a separate P6/P7 task, not this one's.+ * @deprecated Zero call sites (ADR-015 register entry #14, graded DEAD). Ported+ * as-is — removal is a separate P6/P7 task, not this one's.*/export async function validateReportAccess(deps: ServiceDeps,diff --git a/packages/core/src/modules/subscription/subscription.constants.ts b/packages/core/src/modules/subscription/subscription.constants.tsindex 34e51cfa5..1449c1f94 100644--- a/packages/core/src/modules/subscription/subscription.constants.ts+++ b/packages/core/src/modules/subscription/subscription.constants.ts@@ -1,7 +1,7 @@-// Ported from V1's packages/validation/src/index.ts (M6-006, ADR-008's-// module map: subscription owns "C") — that package doesn't exist in this-// tree; apps/start's billing forms and this module's own-// subscription.rpc.ts resolve these symbols through this file directly.+// Ported from V1's packages/validation/src/index.ts (ADR-008's module map:+// subscription owns "C") — that package doesn't exist in this tree;+// apps/start's billing forms and this module's own subscription.rpc.ts resolve+// these symbols through this file directly.//// Isomorphic by the AGENTS.md rule: zod and nothing else.diff --git a/packages/core/src/modules/subscription/subscription.routes.ts b/packages/core/src/modules/subscription/subscription.routes.tsindex 3e17ca429..5c8b6c527 100644--- a/packages/core/src/modules/subscription/subscription.routes.ts+++ b/packages/core/src/modules/subscription/subscription.routes.ts@@ -1,19 +1,19 @@-// The Polar webhook (M6-006), `POST /webhook/polar`. Ported from V1's+// The Polar webhook, `POST /webhook/polar`. Ported from V1's// apps/api/src/controllers/webhook.controller.ts's `polarWebhook`, which// doesn't exist in this tree — this route is the only caller of// subscription.service.ts's `handlePolarWebhookEvent`.//-// RAW BYTES, deliberately: `validatePolarEvent` verifies Polar's signature-// over the exact request body, so this handler reads `await request.text()`-// and declares no `body` schema — any parsing (JSON or otherwise) before the+// RAW BYTES, deliberately: `validatePolarEvent` verifies Polar's signature over+// the exact request body, so this handler reads `await request.text` and+// declares no `body` schema — any parsing (JSON or otherwise) before the// signature check breaks it. V1 gets the same raw bytes via// `fastify-raw-body`'s `{ rawBody: true }` route config; this is the Elysia// equivalent named in ADR-002's plugin substitutions ("raw body → `await-// request.text()` in the one polar webhook handler").+// request.text` in the one polar webhook handler").//// `parse: 'none'` is what makes that possible: Elysia parses the body before// the handler runs by default, and reading the consumed stream throws "Body-// already used" (M9-004, which mounted this surface).+// already used" (which mounted this surface).import { defineRoutes } from '../../http/define';diff --git a/packages/core/src/modules/subscription/subscription.rpc.ts b/packages/core/src/modules/subscription/subscription.rpc.tsindex be3214d11..d8de1fd1e 100644--- a/packages/core/src/modules/subscription/subscription.rpc.ts+++ b/packages/core/src/modules/subscription/subscription.rpc.ts@@ -1,15 +1,14 @@-// Ported from packages/trpc/src/routers/subscription.ts (M6-006).+// Ported from packages/trpc/src/routers/subscription.ts.//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// Every procedure is on its V1 twin's builder. `protectedProcedure` runs+// `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser, exactly as+// V1 does. The explicit checks in the handlers below stay: `enforceAccess` only+// sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved from+// another id needs its own.//-// `requireOrganizationAdmin` lives in subscription.service.ts, not here —-// see that file's header. `ctx.services.subscription` carries this module's-// factory the same as every other module now (M10-004).+// `requireOrganizationAdmin` lives in subscription.service.ts, not here — see+// that file's header. `ctx.services.subscription` carries this module's factory+// the same as every other module now.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.tsindex f804e4771..1d111dfee 100644--- a/packages/core/src/modules/subscription/subscription.service.ts+++ b/packages/core/src/modules/subscription/subscription.service.ts@@ -1,21 +1,21 @@// Ported from V1's packages/trpc/src/routers/subscription.ts (checkout,// products, usage, cancel/pause/resume, save-discount, portal) and from-// apps/api/src/controllers/webhook.controller.ts's `polarWebhook` (M6-006) —-// neither exists in this tree; every caller reaches these functions through-// this file directly (subscription.rpc.ts, subscription.routes.ts).+// apps/api/src/controllers/webhook.controller.ts's `polarWebhook` — neither+// exists in this tree; every caller reaches these functions through this file+// directly (subscription.rpc.ts, subscription.routes.ts).//// `requireOrganizationAdmin` travels with the business logic here rather than// living in subscription.rpc.ts the way project.rpc.ts's simple ladder checks// do: every mutating procedure in this module gates on it first, before// touching Polar. `requireOrganizationAdmin` comes from auth.service.ts's-// single, lazily-memoized `getAccessChecks()` (M10-002) — independent of-// `ServiceDeps`, so it needs no change here.+// single, lazily-memoized `getAccessChecks` — independent of `ServiceDeps`, so+// it needs no change here.//-// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()`/`loadPrisma()` lazy loaders are gone.-// M15-202: `Prisma.DbNull` (the JSON-column null sentinel) arrives as-// `deps.prisma` — the app shell puts the two sentinels on `AppDeps` — rather-// than through a lazy import back into `context.ts`.+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb`/`loadPrisma` lazy loaders are gone. M15-202: `Prisma.DbNull` (the+// JSON-column null sentinel) arrives as `deps.prisma` — the app shell puts the+// two sentinels on `AppDeps` — rather than through a lazy import back into+// `context.ts`.import {applySubscriptionDiscount,@@ -354,14 +354,13 @@ export async function portal(return { url: created.customerPortalUrl };}-// -- Polar webhook --------------------------------------------------------+// - Polar webhook --------------------------------------------------------// Ported from V1's apps/api/src/controllers/webhook.controller.ts's-// `polarWebhook` + its private helpers (M6-006); that controller doesn't-// exist in this tree — this module's own `/webhook/polar` route-// (subscription.routes.ts) is the only caller.-// `validatePolarEvent` verifies the signature over the RAW body bytes; any-// body parsing before this call breaks that verification, which is why the-// route reads `await request.text()` rather than a parsed JSON body.+// `polarWebhook` + its private helpers; that controller doesn't exist in this+// tree — this module's own `/webhook/polar` route (subscription.routes.ts) is+// the only caller. `validatePolarEvent` verifies the signature over the RAW+// body bytes; any body parsing before this call breaks that verification, which+// is why the route reads `await request.text` rather than a parsed JSON body.type PolarEvent = ReturnType<typeof validatePolarEvent>;type PolarSubscriptionData = Extract<diff --git a/packages/core/src/modules/tools/src/ip-lookup.test.ts b/packages/core/src/modules/tools/src/ip-lookup.test.tsindex a506f6fa8..35ea8ad28 100644--- a/packages/core/src/modules/tools/src/ip-lookup.test.ts+++ b/packages/core/src/modules/tools/src/ip-lookup.test.ts@@ -1,7 +1,7 @@// Route-handler coverage for runIpLookup — the smell docs/review/tools.md-// (M14-133) flagged as "zero test coverage of the two route handlers."-// getGeoLocation is mocked; everything else (validation, rate limiting,-// private-range classification) runs for real.+// flagged as "zero test coverage of the two route handlers." getGeoLocation is+// mocked; everything else (validation, rate limiting, private-range+// classification) runs for real.import { beforeAll, describe, expect, it, mock } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/tools/src/ip-lookup.ts b/packages/core/src/modules/tools/src/ip-lookup.tsindex b6b350573..312f0d511 100644--- a/packages/core/src/modules/tools/src/ip-lookup.ts+++ b/packages/core/src/modules/tools/src/ip-lookup.ts@@ -1,5 +1,5 @@// Ported verbatim from apps/api/src/controllers/tools.controller.ts's-// `ipLookup` (M7-008).+// `ipLookup`.import { getGeoLocation } from '../../../clients/geo';import type { CoreConfig } from '../../../config';diff --git a/packages/core/src/modules/tools/src/rate-limit.ts b/packages/core/src/modules/tools/src/rate-limit.tsindex e2f200e18..b168e7147 100644--- a/packages/core/src/modules/tools/src/rate-limit.ts+++ b/packages/core/src/modules/tools/src/rate-limit.ts@@ -1,6 +1,6 @@// Shared in-memory rate limiter for the two public tools endpoints. Ported-// verbatim from apps/api/src/controllers/tools.controller.ts (M7-008): one-// process-local map, keyed per endpoint by the caller.+// verbatim from apps/api/src/controllers/tools.controller.ts: one process-local+// map, keyed per endpoint by the caller.// Both endpoints are public and unauthenticated, so a key (one per distinct// caller IP) that is only ever seen once would otherwise sit in the mapdiff --git a/packages/core/src/modules/tools/src/site-checker.test.ts b/packages/core/src/modules/tools/src/site-checker.test.tsindex e4406f96a..ac754d91b 100644--- a/packages/core/src/modules/tools/src/site-checker.test.ts+++ b/packages/core/src/modules/tools/src/site-checker.test.ts@@ -1,10 +1,10 @@// Route-handler coverage for runSiteCheck — the smell docs/review/tools.md-// (M14-133) flagged as "zero test coverage of the two route handlers." Only-// the pre-fetch guards (missing/invalid URL, SSRF rejection, rate limit) are-// covered here: they run with no outbound I/O. The full probe (fetch, TLS,-// robots.txt, hosting lookup) is 700 lines of live network calls and is left-// uncovered — exercising it would mean mocking most of the file's behaviour,-// which risks diverging from what it actually does more than it protects.+// flagged as "zero test coverage of the two route handlers." Only the pre-fetch+// guards (missing/invalid URL, SSRF rejection, rate limit) are covered here:+// they run with no outbound I/O. The full probe (fetch, TLS, robots.txt,+// hosting lookup) is 700 lines of live network calls and is left uncovered —+// exercising it would mean mocking most of the file's behaviour, which risks+// diverging from what it actually does more than it protects.import { describe, expect, it } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';diff --git a/packages/core/src/modules/tools/src/site-checker.ts b/packages/core/src/modules/tools/src/site-checker.tsindex d7af29dba..faa458653 100644--- a/packages/core/src/modules/tools/src/site-checker.ts+++ b/packages/core/src/modules/tools/src/site-checker.ts@@ -1,5 +1,5 @@// Ported verbatim from apps/api/src/controllers/tools.controller.ts's-// `siteChecker` (M7-008).+// `siteChecker`.import * as dns from 'node:dns/promises';import * as net from 'node:net';diff --git a/packages/core/src/modules/tools/tools.routes.ts b/packages/core/src/modules/tools/tools.routes.tsindex 46ba9680f..064b82d9b 100644--- a/packages/core/src/modules/tools/tools.routes.ts+++ b/packages/core/src/modules/tools/tools.routes.ts@@ -1,15 +1,14 @@// Ported from apps/api/src/routes/tools.router.ts +-// apps/api/src/controllers/tools.controller.ts (M7-008), calling the same-// src/site-checker.ts + src/ip-lookup.ts functions this file does. Mounted-// into publicApiRoutes since M9-004; both routes stay unauthenticated (V1's-// shape) and hidden from the OpenAPI document, matching V1's-// `schema: { hide: true }`.+// apps/api/src/controllers/tools.controller.ts, calling the same+// src/site-checker.ts + src/ip-lookup.ts functions this file does. Mounted into+// publicApiRoutes since M9-004; both routes stay unauthenticated (V1's shape)+// and hidden from the OpenAPI document, matching V1's `schema: { hide: true }`.//// The `/tools` prefix is spelled out here. V1 got it from// `instance.register(toolsRouter, { prefix: '/tools' })` (app.ts:386) over a-// router whose own urls were bare, and `defineRoutes` has no prefix-// mechanism — so the port dropped the segment and both routes answered at the-// root. apps/public's own pages call `${API_URL}/tools/ip-lookup` and+// router whose own urls were bare, and `defineRoutes` has no prefix mechanism —+// so the port dropped the segment and both routes answered at the root.+// apps/public's own pages call `${API_URL}/tools/ip-lookup` and// `/tools/site-checker`, so they were 404ing.import { z } from 'zod';diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.tsindex 73e29728e..1f0e89240 100644--- a/packages/core/src/modules/user/user.rpc.ts+++ b/packages/core/src/modules/user/user.rpc.ts@@ -1,12 +1,12 @@// Account deletion, profile updates and the deletion-blockers check.//-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser. The explicit checks in the handlers below stay:-// `enforceAccess` only sees a TOP-LEVEL `projectId` / `organizationId`, so-// anything resolved from another id needs its own (ADR-011).+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the+// input parser. The explicit checks in the handlers below stay: `enforceAccess`+// only sees a TOP-LEVEL `projectId` / `organizationId`, so anything resolved+// from another id needs its own.//-// `ctx.services.user` carries this module's factory (M10-004); it has no-// queue/cron of its own, same as `conversation`.+// `ctx.services.user` carries this module's factory; it has no queue/cron of+// its own, same as `conversation`.import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../../rpc/base';diff --git a/packages/core/src/modules/user/user.service.test.ts b/packages/core/src/modules/user/user.service.test.tsindex fe1eea6d5..12c3434ec 100644--- a/packages/core/src/modules/user/user.service.test.ts+++ b/packages/core/src/modules/user/user.service.test.ts@@ -1,6 +1,6 @@-// The subject is built by its factory over a fake `ServiceDeps` (M10-004), so-// Postgres needs no module mock at all — `deps.db` IS the fake below, same-// idiom as reference.service.test.ts.+// The subject is built by its factory over a fake `ServiceDeps`, so Postgres+// needs no module mock at all — `deps.db` IS the fake below, same idiom as+// reference.service.test.ts.import { beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.tsindex 5f70ede16..d92bb5e79 100644--- a/packages/core/src/modules/user/user.service.ts+++ b/packages/core/src/modules/user/user.service.ts@@ -1,7 +1,7 @@-// Moved from packages/db/src/services/user.service.ts (M6-001).+// Moved from packages/db/src/services/user.service.ts.//-// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone. Every caller — including+// Every function takes `ServiceDeps` and reaches Postgres as `deps.db`; the+// `loadDb` lazy loader is gone. Every caller — including// `onboarding.service.ts` and `auth.service.ts` — passes the `deps` it holds.import type { User } from '@openpanel/db/src/prisma-client';diff --git a/packages/core/src/pino-logger.ts b/packages/core/src/pino-logger.tsindex d7acdc934..2c7a3653c 100644--- a/packages/core/src/pino-logger.ts+++ b/packages/core/src/pino-logger.ts@@ -1,9 +1,8 @@// Concrete pino implementation. `../logger.ts` is the structural interface// every module and service codes against; this file is what actually-// instantiates pino, and it is deliberately the only place in core that-// imports it (ADR-007 layout: "pino instantiated in apps/api" — apps/api-// builds its named logger by calling `createLogger` from here rather than-// owning a copy).+// instantiates pino, and it is deliberately the only place in core that imports+// it (ADR-007 layout: "pino instantiated in apps/api" — apps/api builds its+// named logger by calling `createLogger` from here rather than owning a copy).//// Ported from @openpanel/logger, unchanged (dissolved into core — M4-003).diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.tsindex ba0e29cc0..3df5c178a 100644--- a/packages/core/src/rest.routes.ts+++ b/packages/core/src/rest.routes.ts@@ -1,8 +1,7 @@-// The three URL surfaces `app.ts` hangs CORS, OpenAPI and guards on-// (ADR-007 decision 19). Each is a factory over `AppDeps`, statically-// composed from `.use()`d modules — no filesystem discovery. Adding a-// module's HTTP half is one `.use()` on the surface it belongs to; most-// modules touch exactly one.+// The three URL surfaces `app.ts` hangs CORS, OpenAPI and guards on (ADR-007+// decision 19). Each is a factory over `AppDeps`, statically composed from+// `.use`d modules — no filesystem discovery. Adding a module's HTTP half is one+// `.use` on the surface it belongs to; most modules touch exactly one.import { openapi } from '@elysiajs/openapi';import { Elysia } from 'elysia';@@ -29,44 +28,44 @@ import { realtimeRoutes } from './modules/realtime/realtime.routes';import { subscriptionRoutes } from './modules/subscription/subscription.routes';import { toolsRoutes } from './modules/tools/tools.routes';-// ADR-002/ADR-003 pin: @elysiajs/openapi at the 1.4.15 fallback (2.0 is-// NO-GO per spike 6). `specPath` is set explicitly rather than taking the-// plugin's `${path}/json` default, because the ops surface's contract is-// exactly `/openapi.json`.+// ADR-002/ADR-003 pin: @elysiajs/openapi at the 1.4.15 fallback (2.0 is NO-GO+// per spike 6). `specPath` is set explicitly rather than taking the plugin's+// `${path}/json` default, because the ops surface's contract is exactly+// `/openapi.json`.const OPENAPI_SPEC_PATH = '/openapi.json';// `/metrics` is prometheus text exposition, not an OpenAPI-describable JSON// endpoint (ADR-003: "the transform that hides /metrics from the spec").const OPENAPI_EXCLUDED_PATHS = ['/metrics'];-// How long one collected exposition is served for before it is collected-// again. M29-001a measured a single `registry.metrics()` at 70-80 ms of the-// api's ONLY JavaScript thread on an idle process against 0.5-0.8 ms for-// `/healthz`, nearly all of it inside prom-client's heap-space collector,-// which on Bun is a JSC heap walk whose cost grows with the heap; under-// write load and a >=1 Hz scrape that was 21.96 % of the thread and every-// millisecond of it is a millisecond no event can be ingested. 5 s is chosen-// to sit strictly below the shortest scrape interval a Prometheus is sanely-// configured with, so a real scraper still collects fresh on every scrape,-// while a pathologically frequent one pays at most one collection per window.+// How long one collected exposition is served for before it is collected again.+// M29-001a measured a single `registry.metrics` at 70-80 ms of the api's ONLY+// JavaScript thread on an idle process against 0.5-0.8 ms for `/healthz`,+// nearly all of it inside prom-client's heap-space collector, which on Bun is a+// JSC heap walk whose cost grows with the heap; under write load and a >=1 Hz+// scrape that was 21.96 % of the thread and every millisecond of it is a+// millisecond no event can be ingested. 5 s is chosen to sit strictly below the+// shortest scrape interval a Prometheus is sanely configured with, so a real+// scraper still collects fresh on every scrape, while a pathologically frequent+// one pays at most one collection per window.const METRICS_EXPOSITION_TTL_MS = 5000;// A factory always takes `deps` even where its body is empty so a module// addition never changes the signature. Return types are left inferred, as-// `defineRoutes`'s `RouteApp` is: `.use()`'d plugins widen Elysia's type+// `defineRoutes`'s `RouteApp` is: `.use`'d plugins widen Elysia's type// parameters in a way the bare `Elysia` type cannot express.//-// import's /import/events is the first module to land here (M5-004);-// project's and client's /manage/* (M6-002) and profile's /profile* (M7-002)-// joined it — client-authed API surface, same as /import, not session-authed-// like dashboardRoutes. export's `/export` + `/insights` (M7-007) joined it-// too — `allow: ['read', 'root']` matches V1's shared `validateExportRequest`.-// None of it is yet reachable: the clientAuth macro's authenticator is a P8-// stub that always returns null (import.routes.ts's header), and main.ts-// 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, the ingest `clientAuth` tier, and-// the one route surface whose hook ORDER is part of the contract.+// Import's /import/events is the first module to land here; project's and+// client's /manage/* and profile's /profile* joined it — client-authed API+// surface, same as /import, not session-authed like dashboardRoutes. export's+// `/export` + `/insights` joined it too — `allow: ['read', 'root']` matches+// V1's shared `validateExportRequest`. None of it is yet reachable: the+// clientAuth macro's authenticator is a P8 stub that always returns null+// (import.routes.ts's header), and main.ts does not mount `publicApiRoutes`+// until a real `AppDeps` exists (P3/P4/P8). tools' `/site-checker` ++// `/ip-lookup` joined it too — unauthenticated like V1's, per the module map.+// ingest's `/track` + `/track/device-id` 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' })// Mounted on the SURFACE, not per module, so a new /manage or /export@@ -82,23 +81,20 @@ export const publicApiRoutes = (deps: AppDeps) =>.use(insightsRoutes(deps)).use(toolsRoutes(deps));-// gsc's callback was the first module to land here (M5-002); assistant's-// `/ai/agents/*` (M5-005), mcp's `/mcp` (M5-007) and auth's `/oauth/*`-// callbacks (M6-003) joined it. None is reachable in production yet: main.ts-// only mounts `dashboardRoutes` once a real `AppDeps` exists (P3/P4/P8) — see-// each module's own routes.ts header for its named gap. `/gsc` and `/mcp` are-// dashboard-scope routes absent from the CORS delegator's `corsPaths`-// allowlist (ADR-002 rule 4) and get `origin: '*'`; `/oauth` IS in-// `corsPaths` — a quirk to port verbatim when app.ts wires CORS, not-// something to fix here.-// integration's `/webhook/slack` and subscription's `/webhook/polar` (M6-006)-// joined it too — like `/oauth`, `/webhook` IS in the CORS delegator's-// `corsPaths` allowlist (ADR-002 rule 4), unlike `/gsc`/`/mcp`, and both are-// the same shape of unauthenticated third-party-redirected callback as-// `/oauth`'s.-// realtime's `/live/*` websockets (M6-007) joined it too — `/live` IS in-// `corsPaths`, same as `/trpc`/`/webhook`/`/oauth`/`/misc`/`/ai`.-// misc's `/misc/*` (M7-008) joined it too — `/misc` IS in `corsPaths`.+// Gsc's callback was the first module to land here; assistant's `/ai/agents/*`,+// mcp's `/mcp` and auth's `/oauth/*` callbacks joined it. None is reachable in+// production yet: main.ts only mounts `dashboardRoutes` once a real `AppDeps`+// exists (P3/P4/P8) — see each module's own routes.ts header for its named gap.+// `/gsc` and `/mcp` are dashboard-scope routes absent from the CORS delegator's+// `corsPaths` allowlist (ADR-002 rule 4) and get `origin: '*'`; `/oauth` IS in+// `corsPaths` — a quirk to port verbatim when app.ts wires CORS, not something+// to fix here. integration's `/webhook/slack` and subscription's+// `/webhook/polar` joined it too — like `/oauth`, `/webhook` IS in the CORS+// delegator's `corsPaths` allowlist (ADR-002 rule 4), unlike `/gsc`/`/mcp`, and+// both are the same shape of unauthenticated third-party-redirected callback as+// `/oauth`'s. realtime's `/live/*` websockets joined it too — `/live` IS in+// `corsPaths`, same as `/trpc`/`/webhook`/`/oauth`/`/misc`/`/ai`. misc's+// `/misc/*` joined it too — `/misc` IS in `corsPaths`.export const dashboardRoutes = (deps: AppDeps) =>new Elysia({ name: 'core/dashboard-routes' })// For `/mcp`; every other path on this surface is unmatched by the table.@@ -176,6 +172,6 @@ export const opsRoutes = (deps: AppDeps) =>// 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.+// and transport may not import a registry; 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.router.ts b/packages/core/src/rpc.router.tsindex a67169032..b059908ad 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -1,8 +1,8 @@// The one static composition point for every tRPC procedure this package-// serves. No `defineModule()`, no filesystem discovery — adding a module's-// RPC half is one line here, which is what keeps `AppRouter` a real type-// (ADR-007 decision 19). Only `health` exists so far; the 28 real routers-// land with their module waves (P5-P8).+// serves. No `defineModule`, no filesystem discovery — adding a module's RPC+// half is one line here, which is what keeps `AppRouter` a real type (ADR-007+// decision 19). Only `health` exists so far; the 28 real routers land with+// their module waves (P5-P8).import { chatRouter } from './modules/assistant/assistant.rpc';import { authRouter } from './modules/auth/auth.rpc';diff --git a/packages/core/src/rpc/base.test.ts b/packages/core/src/rpc/base.test.tsindex 0cc328434..ef8dcf67c 100644--- a/packages/core/src/rpc/base.test.ts+++ b/packages/core/src/rpc/base.test.ts@@ -132,12 +132,12 @@ test('the session is resolved once, before any procedure runs', async () => {expect(ctx.session).toEqual(TEST_SESSION);});-// M9-004 flipped this from "inherited" to "flattened", because tRPC merges-// middleware context with `{...ctx, ...next.ctx}` — a spread, which copies own-// enumerable properties ONLY. Under the prototype-chained shape every-// inherited field vanished the first time a middleware called `next({ ctx })`,-// and the next read was a TypeError inside a mutation (caught by the auth-// contract suite, group c/d).+// Flipped this from "inherited" to "flattened", because tRPC merges middleware+// context with `{...ctx,...next.ctx}` — a spread, which copies own enumerable+// properties ONLY. Under the prototype-chained shape every inherited field+// vanished the first time a middleware called `next({ ctx })`, and the next+// read was a TypeError inside a mutation (caught by the auth contract suite,+// group c/d).test('the HttpCtx is flattened onto own properties, and services stay lazy', async () => {const { ctx } = stubHttpCtx();const trpcCtx = await makeTrpcContext(ctx, new Headers(), {diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.tsindex 9f97fa906..b8354e3ee 100644--- a/packages/core/src/rpc/base.ts+++ b/packages/core/src/rpc/base.ts@@ -1,5 +1,5 @@// The tRPC instance, its context, and the middleware factories procedures are-// built from (ADR-009).+// built from.//// The tRPC context IS the Elysia-derived `HttpCtx`: `makeTrpcContext` adds the// tRPC-specific bits and overrides exactly one field. There is no `req`/`res`@@ -51,16 +51,16 @@ export interface Meta {export interface TrpcContext extends Omit<HttpCtx, 'session'> {readonly session: Session;/**- * The connection's peer address — the one address a client cannot forge,- * and therefore the rate limiter's last-resort fallback when no trusted- * header is present. It is NOT `ctx.ip`: that is the *attribution* ip,- * which prefers client-forwarded headers and would give every request its- * own bucket (ADR-002 "behaviour that must be preserved explicitly" 2).+ * The connection's peer address — the one address a client cannot forge, and+ * therefore the rate limiter's last-resort fallback when no trusted header is+ * present. It is NOT `ctx.ip`: that is the *attribution* ip, which prefers+ * client-forwarded headers and would give every request its own bucket+ * (ADR-002 "behaviour that must be preserved explicitly" 2).** `undefined` where the transport does not expose it. Elysia's- * `server.requestIP()` is not plumbed through `HttpCtx` yet, so the fetch- * mount leaves it unset and the limiter falls back to its shared- * `unknown` bucket — fail-closed, which is the documented intent.+ * `server.requestIP` is not plumbed through `HttpCtx` yet, so the fetch mount+ * leaves it unset and the limiter falls back to its shared `unknown` bucket —+ * fail-closed, which is the documented intent.*/readonly remoteAddress: string | undefined;/**@@ -146,28 +146,26 @@ export const procedure = t.procedure.use(stopWhenCancelled).use(mapDriverErrors);-// ----------------------------------------------------------------------------// The procedure stack (M11-001), ported from packages/trpc/src/trpc.ts:35-155.+// --------------------------------------------------------------------------+// The procedure stack, ported from packages/trpc/src/trpc.ts:35-155.//-// ADR-011 is this code's law; invariants 1-13 are binding. Three properties of-// the port are load-bearing and are the reason it is a middleware stack rather-// than per-handler code:+// Is this code's law; invariants 1-13 are binding. Three properties of the port+// are load-bearing and are the reason it is a middleware stack rather than+// per-handler code://-// 1. AUTHENTICATION RUNS BEFORE INPUT PARSING. tRPC runs `.use()` middleware-// ahead of the `.input()` parser, so an anonymous caller gets UNAUTHORIZED-// whatever it sends. Doing the same check inside a handler inverts that:-// the caller learns the input shape first, and 176 procedures changed-// answer from 401 to 400 when core mounted the bare `procedure`-// (docs/RPC_PROCEDURE_SET_EQUIVALENCE.md).-// 2. THE CHECK CANNOT BE FORGOTTEN. It is a property of the builder, not of a-// line a port might drop. Three procedures (`client.list`,-// `subscription.getCurrent`, `subscription.usage`) had no check at all-// while this stack was missing.-// 3. `enforceAccess` READS THE RAW, PRE-ZOD INPUT (ADR-011 invariant 2) and-// only its TOP-LEVEL `projectId` / `organizationId`. A procedure that-// resolves the project from a reportId/dashboardId is invisible to it and-// keeps its in-handler check — ADR-011 counts 58 of those, and a redundant-// check is harmless where a missing one is not.+// 1. AUTHENTICATION RUNS BEFORE INPUT PARSING. tRPC runs `.use` middleware+// ahead of the `.input` parser, so an anonymous caller gets UNAUTHORIZED+// whatever it sends. Doing the same check inside a handler inverts that: the+// caller learns the input shape first, and 176 procedures changed answer from+// 401 to 400 when core mounted the bare `procedure`. 2. THE CHECK CANNOT BE+// FORGOTTEN. It is a property of the builder, not of a line a port might drop.+// Three procedures (`client.list`, `subscription.getCurrent`,+// `subscription.usage`) had no check at all while this stack was missing. 3.+// `enforceAccess` READS THE RAW, PRE-ZOD INPUT (ADR-011 invariant 2) and only+// its TOP-LEVEL `projectId` / `organizationId`. A procedure that resolves the+// project from a reportId/dashboardId is invisible to it and keeps its+// in-handler check — ADR-011 counts 58 of those, and a redundant check is+// harmless where a missing one is not.//// The lookups arrive through `ctx.services.auth` (M10-002 bound the ladder// there, once, in auth.service.ts); core reaches no database directly.@@ -181,8 +179,8 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {try {// Narrowed, not merely copied: the spread of the checked union member is- // what gives every handler below a `session.userId` of type `string`, so- // a procedure reads it instead of re-deriving it through a per-file+ // what gives every handler below a `session.userId` of type `string`, so a+ // procedure reads it instead of re-deriving it through a per-file// `requireLogin` (ADR-022 R10 — 38 of those, deleted at M15-007).return next({ctx: {@@ -505,10 +503,10 @@ export interface RateLimitOptions {* both are boot-scope concerns, and injecting it is what lets a procedure be* tested without one.*- * The fingerprint is derived from `headers` and `remoteAddress`. `ip` is in- * the signature because ADR-009 names it, but a limiter must never key on it:- * it is the attribution address, which prefers client-forwarded headers and- * would give every request its own bucket (ADR-002 preserved-behaviour 2).+ * The fingerprint is derived from `headers` and `remoteAddress`. `ip` is in the+ * signature because ADR-009 names it, but a limiter must never key on it: it is+ * the attribution address, which prefers client-forwarded headers and would+ * give every request its own bucket (ADR-002 preserved-behaviour 2).*/export type EnforceRateLimit = (args: RateLimitOptions & {diff --git a/packages/core/src/rpc/deadline.ts b/packages/core/src/rpc/deadline.tsindex 94741c2ab..b85532362 100644--- a/packages/core/src/rpc/deadline.ts+++ b/packages/core/src/rpc/deadline.ts@@ -1,11 +1,10 @@-// How long a tRPC call may run, and what a caller is told when it stops-// (M36-001).+// How long a tRPC call may run, and what a caller is told when it stops.//// 30 s is the ceiling the dashboard already lived under: Elysia's Bun adapter// defaults `idleTimeout` to 30 s, and a non-streamed tRPC response writes no-// byte before it completes, so nothing that took longer was ever delivered.-// The deadline keeps that ceiling but turns the silent socket close into an-// error, and stops the work behind it.+// byte before it completes, so nothing that took longer was ever delivered. The+// deadline keeps that ceiling but turns the silent socket close into an error,+// and stops the work behind it.import { TRPCError } from '@trpc/server';diff --git a/packages/core/src/rpc/handler.ts b/packages/core/src/rpc/handler.tsindex 5fd5ffa31..cd92d007a 100644--- a/packages/core/src/rpc/handler.ts+++ b/packages/core/src/rpc/handler.ts@@ -1,5 +1,4 @@-// The tRPC mount: the official fetch adapter, one handler, one `onError`-// (ADR-009).+// The tRPC mount: the official fetch adapter, one handler, one `onError`.//// Three of the four `onError` branches are V1's (apps/api/src/app.ts:175-206)// with one change and no others: the fields come from `ctx` and the `Request`,diff --git a/packages/core/src/services.test.ts b/packages/core/src/services.test.tsindex 944d57855..161db9a41 100644--- a/packages/core/src/services.test.ts+++ b/packages/core/src/services.test.ts@@ -1,8 +1,8 @@-// The composition root's two runtime invariants (ADR-022 R3). Neither is-// visible to `tooling/gates/conformance.sh`, which reads signatures only.+// The composition root's two runtime invariants. 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.+// 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';diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex 35b0e3ef1..0aad3b2c6 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -1,6 +1,6 @@// The composition root (ADR-007 build step 4). `auth` is the first module to-// land here (M4-007); the Ctx <-> Services circularity was proven compiling-// before it with an empty interface.+// land here; the Ctx <-> Services circularity was proven compiling before it+// with an empty interface.import type { Ctx } from './context';import { createAssistantService } from './modules/assistant/assistant.service';@@ -79,11 +79,11 @@ export interface Services {profile: ReturnType<typeof createProfileService>;group: ReturnType<typeof createGroupService>;chart: ReturnType<typeof createChartService>;- // One key per `*.service.ts` (M10-009): the chart module is four files- // besides `chart.service.ts`, so each is bound here too. `chart` keeps the- // composed facade its own callers already use — the factories build stateless- // closures over `deps`, so binding a sub-module twice binds the same- // functions, not a second piece of state.+ // One key per `*.service.ts`: the chart module is four files besides+ // `chart.service.ts`, so each is bound here too. `chart` keeps the composed+ // facade its own callers already use — the factories build stateless closures+ // over `deps`, so binding a sub-module twice binds the same functions, not a+ // second piece of state.funnel: ReturnType<typeof createFunnelService>;conversion: ReturnType<typeof createConversionService>;sankey: ReturnType<typeof createSankeyService>;@@ -109,8 +109,8 @@ export interface Services {// Stays a hoisted `function` declaration, not a `const` arrow: the one static// ESM cycle that ran through it died with the compat seam at M15-005, but a-// `const` here would still put any future cycle in a temporal dead zone that-// no typecheck reports and that fails at process boot.+// `const` here would still put any future cycle in a temporal dead zone that no+// typecheck reports and that fails at process boot.export function createServices(deps: ServiceDeps): Services {// 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,diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.tsindex 02e4a8c03..7fd53fdcb 100644--- a/packages/core/src/shared/access-lookups.ts+++ b/packages/core/src/shared/access-lookups.ts@@ -1,12 +1,12 @@-// The concrete, Prisma-backed access lookups (M8-005, moved from+// The concrete, Prisma-backed access lookups (moved from// packages/db/src/services/access.service.ts). Deliberately a sibling of-// 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.+// 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.//-// M15-005: Postgres comes from `context.ts`'s `unscopedDb()`. Two of the three-// lookups here are `cacheable`, whose key is derived from the call's ARGUMENTS+// Postgres comes from `context.ts`'s `unscopedDb`. Two of the three lookups+// here are `cacheable`, whose key is derived from the call's ARGUMENTS// (packages/redis/cachable.ts), so they cannot take a `ServiceDeps` leading// parameter at all; the third (`getClientAccess`) delegates to them and stays// symmetric. Their bare signature is also a protected wire contract —@@ -16,8 +16,8 @@// `ctx.db` is, not a second one.//// `getProjectById` is spelled here rather than imported from-// `project.service.ts`: `shared/` sits below `modules/` (ADR-022 R22) and the-// ladder reads one field off the row.+// `project.service.ts`: `shared/` sits below `modules/` and the ladder reads+// one field off the row.import type { AccessLevel } from '@openpanel/db/src/prisma-client';import { cacheable } from '@openpanel/redis';diff --git a/packages/core/src/shared/als-session.ts b/packages/core/src/shared/als-session.tsindex dadaf8959..66492f219 100644--- a/packages/core/src/shared/als-session.ts+++ b/packages/core/src/shared/als-session.ts@@ -1,8 +1,8 @@-// 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.+// Moved from packages/db/src/session-context.ts, and out of+// `modules/session/src/` at M15-009: 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 —diff --git a/packages/core/src/shared/ch-dates.ts b/packages/core/src/shared/ch-dates.tsindex a38451cde..74cae7758 100644--- a/packages/core/src/shared/ch-dates.ts+++ b/packages/core/src/shared/ch-dates.ts@@ -1,13 +1,13 @@// ClickHouse's date literal format, shared across modules.//-// M10-009: `@openpanel/db/src/clickhouse/client.ts` owns these too, but-// importing it constructs a real ClickHouse client and a real pino logger at-// module load and is a value import of `@openpanel/db` from core — see-// ch-tables.ts's header for the full reasoning. Five modules already carry a-// byte-identical private copy in their own `src/dates.ts` (chart, event,-// group, profile, session); folding those into this file is its own task, not-// this one's. `ch-dates.parity.test.ts` asserts this file and @openpanel/db's-// agree on every input, so the copy cannot drift silently.+// `@openpanel/db/src/clickhouse/client.ts` owns these too, but importing it+// constructs a real ClickHouse client and a real pino logger at module load and+// is a value import of `@openpanel/db` from core — see ch-tables.ts's header+// for the full reasoning. Five modules already carry a byte-identical private+// copy in their own `src/dates.ts` (chart, event, group, profile, session);+// folding those into this file is its own task, not this one's.+// `ch-dates.parity.test.ts` asserts this file and @openpanel/db's agree on+// every input, so the copy cannot drift silently.const CLICKHOUSE_DATE_SUFFIX = /(\.\d{3})?Z+$/;diff --git a/packages/core/src/shared/ch-tables.parity.test.ts b/packages/core/src/shared/ch-tables.parity.test.tsindex b027f7ed6..ad44b7532 100644--- a/packages/core/src/shared/ch-tables.parity.test.ts+++ b/packages/core/src/shared/ch-tables.parity.test.ts@@ -17,9 +17,9 @@ describe('ch-tables parity with @openpanel/db', () => {});// The cluster VERDICT is the config loader's since M15-006- // (`config.clickhouseClustered` = CLICKHOUSE_CLUSTER);- // @openpanel/db still reads it itself. Feeding db's verdict in is what makes- // this a parity check of the NAME derivation rather than of two env reads.+ // (`config.clickhouseClustered` = CLICKHOUSE_CLUSTER); @openpanel/db still+ // reads it itself. Feeding db's verdict in is what makes this a parity check+ // of the NAME derivation rather than of two env reads.it('derives the same mutation table name for the same verdict', () => {const clustered = dbClient.isClickhouseClustered();for (const name of Object.values(TABLE_NAMES)) {diff --git a/packages/core/src/shared/ch-tables.ts b/packages/core/src/shared/ch-tables.tsindex dbfeab353..454c3e3d2 100644--- a/packages/core/src/shared/ch-tables.ts+++ b/packages/core/src/shared/ch-tables.ts@@ -1,17 +1,17 @@// The physical ClickHouse table names core reads and writes, plus the two// cluster helpers that derive from them.//-// M10-009: these live in `@openpanel/db/src/clickhouse/client.ts` too, and-// that module is where the migrations (`@openpanel/db`'s `code-migrations/`,-// M15-204) still take them from — but importing it constructs a real ClickHouse client and a real pino-// logger at module load, which is the cost every `load*()` lazy loader in this-// package existed to defer, and it is a value import of `@openpanel/db` from-// core, which `core-uses-ctx-not-db-internals` now forbids. Core takes the+// These live in `@openpanel/db/src/clickhouse/client.ts` too, and that module+// is where the migrations (`@openpanel/db`'s `code-migrations/`) still take+// them from — but importing it constructs a real ClickHouse client and a real+// pino logger at module load, which is the cost every `load*` lazy loader in+// this package existed to defer, and it is a value import of `@openpanel/db`+// from core, which `core-uses-ctx-not-db-internals` now forbids. Core takes the// map, not the client: `ch` itself is always `ctx.ch` / `deps.ch`.//// The duplication is policed, not trusted: `ch-tables.parity.test.ts` asserts-// this map and @openpanel/db's are identical, so a table added on one side-// and not the other fails the suite rather than a query.+// this map and @openpanel/db's are identical, so a table added on one side and+// not the other fails the suite rather than a query.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/shared/client-secret.ts b/packages/core/src/shared/client-secret.tsindex 9a6260b5f..0f1df3cf3 100644--- a/packages/core/src/shared/client-secret.ts+++ b/packages/core/src/shared/client-secret.ts@@ -14,8 +14,8 @@ export function hashClientSecret(secret: string): Promise<string> {/*** Reads both formats: scrypt, and the argon2 rows the ported client, project* and onboarding services minted while they imported the user-password hasher- * by mistake (M15-104). A malformed stored hash is a failed verification,- * never a 500 on the ingest path.+ * by mistake. A malformed stored hash is a failed verification, never a 500 on+ * the ingest path.*/export async function verifyClientSecret(secret: string,diff --git a/packages/core/src/shared/encryption.test.ts b/packages/core/src/shared/encryption.test.tsindex d56345fbd..d8096b307 100644--- a/packages/core/src/shared/encryption.test.ts+++ b/packages/core/src/shared/encryption.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, it } from 'bun:test';import {decrypt,diff --git a/packages/core/src/shared/group-by-labels.ts b/packages/core/src/shared/group-by-labels.tsindex b31d65645..660b7662d 100644--- a/packages/core/src/shared/group-by-labels.ts+++ b/packages/core/src/shared/group-by-labels.ts@@ -1,5 +1,5 @@-// Moved from packages/common/src/group-by-labels.ts (M11-006, ADR-007 shared/-// layout). Sole consumer: modules/chart/src/engine/fetch.ts.+// Moved from packages/common/src/group-by-labels.ts (ADR-007 shared/ layout).+// Sole consumer: modules/chart/src/engine/fetch.ts.export interface ISerieDataItem {label_0: string | null | undefined;label_1?: string | null | undefined;diff --git a/packages/core/src/shared/headers.ts b/packages/core/src/shared/headers.tsindex 3e7a0e5b0..73bba398a 100644--- a/packages/core/src/shared/headers.ts+++ b/packages/core/src/shared/headers.ts@@ -1,13 +1,13 @@// A lowercase header record — Fastify's `IncomingHttpHeaders`, or a `Headers`-// 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+// 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.+// Moved down out of `modules/ingest/src/`. 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/id.test.ts b/packages/core/src/shared/id.test.tsindex 0af5f2b93..caad20cea 100644--- a/packages/core/src/shared/id.test.ts+++ b/packages/core/src/shared/id.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, test } from 'bun:test';import { generateId, shortId } from '@openpanel/shared';diff --git a/packages/core/src/shared/json.test.ts b/packages/core/src/shared/json.test.tsindex 2dda50cd5..f792b75b7 100644--- a/packages/core/src/shared/json.test.ts+++ b/packages/core/src/shared/json.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, test } from 'bun:test';import { getSafeJson, getSuperJson, setSuperJson } from '@openpanel/shared';diff --git a/packages/core/src/shared/json.ts b/packages/core/src/shared/json.tsindex 2b20787eb..61463a209 100644--- a/packages/core/src/shared/json.ts+++ b/packages/core/src/shared/json.ts@@ -1,6 +1,6 @@// A re-export seam, not an implementation: the JSON helpers moved to-// @openpanel/shared in M15-010 (ADR-022 R21), and every caller inside core-// imports them from there.+// @openpanel/shared in M15-010, and every caller inside core imports them from+// there.//// This file survives for ONE importer: packages/db/src/clickhouse/client.ts// reaches `getSafeJson` by relative path across the package boundarydiff --git a/packages/core/src/shared/object.test.ts b/packages/core/src/shared/object.test.tsindex 87853dcd4..d3ee86b61 100644--- a/packages/core/src/shared/object.test.ts+++ b/packages/core/src/shared/object.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, it } from 'bun:test';import { toDots } from '@openpanel/shared';diff --git a/packages/core/src/shared/parser-user-agent.test.ts b/packages/core/src/shared/parser-user-agent.test.tsindex 90d7f9e88..6f4736e63 100644--- a/packages/core/src/shared/parser-user-agent.test.ts+++ b/packages/core/src/shared/parser-user-agent.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, it } from 'bun:test';import { getDevice, parseUserAgent } from '@openpanel/shared/server';diff --git a/packages/core/src/shared/request-id.ts b/packages/core/src/shared/request-id.tsindex 4e0e0ab1a..33fc06cb8 100644--- a/packages/core/src/shared/request-id.ts+++ b/packages/core/src/shared/request-id.ts@@ -1,8 +1,8 @@-// ADR-018 R2: an inbound request-id is honoured but never trusted verbatim —-// it reaches log storage and a log search. Two transports are handed one from-// outside the process — the HTTP edge (`http/hooks.ts`) and the Kafka consumer,-// which reads the id the producer stamped into the envelope — so the rule that-// decides what is safe to bind to a logger lives here rather than in either.+// An inbound request-id is honoured but never trusted verbatim — it reaches log+// storage and a log search. Two transports are handed one from outside the+// process — the HTTP edge (`http/hooks.ts`) and the Kafka consumer, which reads+// the id the producer stamped into the envelope — so the rule that decides what+// is safe to bind to a logger lives here rather than in either.import { generateId } from '@openpanel/shared';import { REQUEST_ID_LENGTH } from '../logger';diff --git a/packages/core/src/shared/safe-fetch.test.ts b/packages/core/src/shared/safe-fetch.test.tsindex c4c2cd187..ff29876e8 100644--- a/packages/core/src/shared/safe-fetch.test.ts+++ b/packages/core/src/shared/safe-fetch.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { afterAll, beforeAll, describe, expect, it } from 'bun:test';import http from 'node:http';import type { AddressInfo } from 'node:net';diff --git a/packages/core/src/shared/session.ts b/packages/core/src/shared/session.tsindex 0a9179f6c..f3d2ea1c1 100644--- a/packages/core/src/shared/session.ts+++ b/packages/core/src/shared/session.ts@@ -1,10 +1,10 @@// The one "nobody is signed in" session value.//-// It lives below every transport on purpose (ADR-022 R22): `rpc/base.ts` maps-// `HttpCtx.session()`'s `null` onto it at the tRPC boundary, and+// It lives below every transport on purpose: `rpc/base.ts` maps+// `HttpCtx.session`'s `null` onto it at the tRPC boundary, and// `modules/auth/src/login-session.ts` returns it from every non-session branch-// of `validateSessionToken`. Defining it in the module and reaching for it-// from `rpc/` was the shortest path to working code and an upward import; one+// of `validateSessionToken`. Defining it in the module and reaching for it from+// `rpc/` was the shortest path to working code and an upward import; one// constant at the bottom of the stack is the same behaviour with no edge.import type { Session } from '../context';diff --git a/packages/core/src/shared/slug.test.ts b/packages/core/src/shared/slug.test.tsindex cdda4e724..44dbd10b3 100644--- a/packages/core/src/shared/slug.test.ts+++ b/packages/core/src/shared/slug.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, it } from 'bun:test';import { slug } from '@openpanel/shared';diff --git a/packages/core/src/shared/ssrf.test.ts b/packages/core/src/shared/ssrf.test.tsindex 502516562..4f5835c13 100644--- a/packages/core/src/shared/ssrf.test.ts+++ b/packages/core/src/shared/ssrf.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, it, mock } from 'bun:test';import {assertSafeUrl,diff --git a/packages/core/src/shared/try-catch.test.ts b/packages/core/src/shared/try-catch.test.tsindex 2aae51018..46a47756b 100644--- a/packages/core/src/shared/try-catch.test.ts+++ b/packages/core/src/shared/try-catch.test.ts@@ -1,8 +1,8 @@-// Subject moved to @openpanel/shared (M15-010, ADR-022 R21); the suite did-// not follow it. Nothing runs a `test` script in packages/shared yet — the-// root `test` script names its four workspaces explicitly and root-// package.json was outside M15-010's scope — so moving this file would take-// it out of every gate. Move it when that line can gain the filter.+// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs+// a `test` script in packages/shared yet — the root `test` script names its+// four workspaces explicitly and root package.json was outside M15-010's scope+// — so moving this file would take it out of every gate. Move it when that line+// can gain the filter.import { describe, expect, test } from 'bun:test';import { tryCatch } from '@openpanel/shared';diff --git a/packages/core/src/slug-id.ts b/packages/core/src/slug-id.tsindex bed787fff..750418425 100644--- a/packages/core/src/slug-id.ts+++ b/packages/core/src/slug-id.ts@@ -1,14 +1,13 @@// Slug-based primary-id generation for project/dashboard/organization rows.-// Moved from packages/db/src/services/id.service.ts (M8-005) — a sibling of+// Moved from packages/db/src/services/id.service.ts — a sibling of// shared/access-lookups.ts: needs @openpanel/db, so it stays out of// shared/id.ts (the database-free id helpers).//-// M10-009: Postgres comes from the caller's scope (`deps.db`), not a lazy+// Postgres comes from the caller's scope (`deps.db`), not a lazy// `import('@openpanel/db/...')` — so the requestId minted at the edge reaches-// the uniqueness probe (ADR-018, docs/TECH_DEBT.md §4). `deps` is narrowed to-// `Pick<ServiceDeps, 'db'>` because mcp's tool handlers have a fixed-// `@modelcontextprotocol/sdk` signature and only ever hold the db the route-// closed over.+// the uniqueness probe. `deps` is narrowed to `Pick<ServiceDeps, 'db'>` because+// mcp's tool handlers have a fixed `@modelcontextprotocol/sdk` signature and+// only ever hold the db the route closed over.import { slug } from '@openpanel/shared';import type { ServiceDeps } from './services';diff --git a/packages/core/test/buffer-fixtures.ts b/packages/core/test/buffer-fixtures.tsindex d04535432..2a90c9edb 100644--- a/packages/core/test/buffer-fixtures.ts+++ b/packages/core/test/buffer-fixtures.ts@@ -20,11 +20,11 @@ const silentLogger: Logger = {* `createLogger` spawns a pino transport worker thread per buffer, and these* suites build one buffer per test.*- * M10-009: `BufferDeps.ch` is the boot scope's ClickHouse client, so a suite- * that exercises a flush hands in its own fake here rather than mocking+ * `BufferDeps.ch` is the boot scope's ClickHouse client, so a suite that+ * exercises a flush hands in its own fake here rather than mocking* `@openpanel/db`'s module. `stubBufferDeps` hands in a client that throws on- * first touch — a buffer that reaches ClickHouse without one is a bug this- * stub should surface, not hide.+ * first touch — a buffer that reaches ClickHouse without one is a bug this stub+ * should surface, not hide.*/const throwingClickHouse = new Proxy({} as BufferDeps['ch'], {get() {diff --git a/packages/core/test/exports-map.test.ts b/packages/core/test/exports-map.test.tsindex 95e98a05b..330462407 100644--- a/packages/core/test/exports-map.test.ts+++ b/packages/core/test/exports-map.test.ts@@ -1,7 +1,7 @@import { expect, test } from 'bun:test';// The exports map is the only structural barrier between apps/start and a-// service (ADR-008). Widening it is silent, so it is asserted here.+// service. Widening it is silent, so it is asserted here.test('the curated barrel resolves', async () => {expect(await import('@openpanel/core')).toBeDefined();});diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.tsindex a63df05ed..8b41905c2 100644--- a/packages/core/test/request-id-end-to-end.test.ts+++ b/packages/core/test/request-id-end-to-end.test.ts@@ -1,27 +1,26 @@-// ADR-007 benchmark 3 / ADR-018 R1 — the requestId chain, end to end, on all-// three paths core actually has. One file, three sections:+// Benchmark 3 / ADR-018 R1 — the requestId chain, end to end, on all three+// paths core actually has. One file, three sections://-// 1. HTTP (P2-010's original): route log -> enqueued envelope meta -> job-// handler's logger -> the enqueue that job makes. Four hops, one id.-// 2. CHART (M10-003): a REAL `ctx.services.chart` query, observed on the-// ClickHouse call's own `query info` line. This is the hop the-// `loadChClient()` loaders failed silently — a module that reached-// @openpanel/db's client itself got a connection with no request scope,-// so the id stopped at the service boundary (docs/TECH_DEBT.md §2).-// 3. KAFKA/INGEST (M10-006): the other edge. `createIncomingEventHandler` is-// the exact function apps/api's main.ts hands the consumer, and the seam-// under test — createCtx -> incomingEvent -> ctx.buffers / ctx.db /-// ctx.services — is the real one. Nothing in this section is mocked.+// 1. HTTP (P2-010's original): route log -> enqueued envelope meta -> job+// handler's logger -> the enqueue that job makes. Four hops, one id. 2. CHART:+// a REAL `ctx.services.chart` query, observed on the ClickHouse call's own+// `query info` line. This is the hop the `loadChClient` loaders failed silently+// — a module that reached @openpanel/db's client itself got a connection with+// no request scope, so the id stopped at the service boundary. 3. KAFKA/INGEST:+// the other edge. `createIncomingEventHandler` is the exact function apps/api's+// main.ts hands the consumer, and the seam under test — createCtx ->+// incomingEvent -> ctx.buffers / ctx.db / ctx.services — is the real one.+// Nothing in this section is mocked.//-// M10-009 merged sections 2 and 3 in from their own files, so the property-// these three prove together — that no path loses the id — is one file's-// result rather than three that could drift apart.+// Merged sections 2 and 3 in from their own files, so the property these three+// prove together — that no path loses the id — is one file's result rather than+// three that could drift apart.//// Each half is already covered next to its own code — `createCtx` scoping the// producers, `wrap` carrying `meta.requestId`, `runJob` reading it back. What-// no unit test can show is that they agree, and that agreement is the-// property core's shape was chosen for: if this goes red the design is wrong,-// not this file.+// no unit test can show is that they agree, and that agreement is the property+// core's shape was chosen for: if this goes red the design is wrong, not this+// file.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { Elysia } from 'elysia';@@ -63,17 +62,16 @@ interface ProofServices {// resolve to the same file).const realServicesModule = { ...(await import('../src/services')) };-// `Services` grows with every module that lands, so this proof mocks the-// whole container with a shape of its own rather than the real one — but the-// mock is a real service: built from the SCOPED ctx, logging to that request's-// logger and enqueueing through that request's producers. A hand-rolled-// function called from the route would skip exactly the seam under test.-// M10-009: the proof's `ingest.record` is layered ON TOP of the REAL-// container rather than replacing it — sections 2 and 3 below need-// `ctx.services.chart` and `ctx.services.session` to be the real ones. The-// mock is still a real service in the sense that matters: built from the-// SCOPED ctx, logging to that request's logger and enqueueing through that-// request's producers.+// `Services` grows with every module that lands, so this proof mocks the whole+// container with a shape of its own rather than the real one — but the mock is+// a real service: built from the SCOPED ctx, logging to that request's logger+// and enqueueing through that request's producers. A hand-rolled function+// called from the route would skip exactly the seam under test. M10-009: the+// proof's `ingest.record` is layered ON TOP of the REAL container rather than+// replacing it — sections 2 and 3 below need `ctx.services.chart` and+// `ctx.services.session` to be the real ones. The mock is still a real service+// in the sense that matters: built from the SCOPED ctx, logging to that+// request's logger and enqueueing through that request's producers.const createServices = mock((deps: ServiceDeps) => ({...realServicesModule.createServices(deps),ingest: {@@ -310,7 +308,7 @@ test('a minted requestId travels the same four hops, and does not leak into the});// ===========================================================================-// Section 2 — the chart query hop (M10-003).+// Section 2 — the chart query hop.// ===========================================================================const CHART_REQUEST_ID = 'm10-003-chart-query';@@ -442,7 +440,7 @@ test('two concurrent requests do not share a requestId on their ClickHouse calls});// ===========================================================================-// Section 3 — the Kafka/ingest handler hop (M10-006).+// Section 3 — the Kafka/ingest handler hop.// ===========================================================================const INGEST_REQUEST_ID = 'adr018-kafka-1';@@ -534,8 +532,8 @@ function ingestDeps() {const eventBuffer = {add: (event: { id: string }) => eventsBuffered.push(event),- // The consumer scope reaches the buffer through this view (M18-007); it- // must still be the same buffer underneath.+ // The consumer scope reaches the buffer through this view; it must still be+ // the same buffer underneath.asRedeliverable: () => eventBuffer,};@@ -557,9 +555,9 @@ function ingestDeps() {prisma: {} as AppDeps['prisma'],db: {project: {- // M15-005: the handler reads the project through- // `project.service.ts`'s module-scope `getProjectByIdCached`, off the- // message's own scope, instead of a binding resolved at boot.+ // The handler reads the project through `project.service.ts`'s+ // module-scope `getProjectByIdCached`, off the message's own scope,+ // instead of a binding resolved at boot.findUnique: () =>Promise.resolve({ firstEventAt: new Date(), filters: [] }),updateMany: () => Promise.resolve({ count: 0 }),@@ -580,7 +578,7 @@ function ingestDeps() {const ingestBindings: IncomingEventBindings = {checkNotificationRulesForEvent: () => Promise.resolve(null),// Never a duplicate here: this suite is about the requestId, and the marker- // must not decide anything about the row either way (M21-001).+ // must not decide anything about the row either way.markDuplicateEvent: () => Promise.resolve(false),};@@ -671,13 +669,12 @@ test("the envelope's requestId reaches the handler's logger, its buffer write an]);});-// M15-004: the notification dispatch used to reach Postgres and the-// `notification` producer through the deleted compat seam's BOOT scope, so-// every job it enqueued was stamped with that scope's id no matter which-// message triggered it. It-// takes the caller's scope now, and this is the hop that proves it: the-// binding enqueues exactly what `triggerNotification` enqueues, off the deps-// it was handed, and the envelope must carry the message's own id.+// The notification dispatch used to reach Postgres and the `notification`+// producer through the deleted compat seam's BOOT scope, so every job it+// enqueued was stamped with that scope's id no matter which message triggered+// it. It takes the caller's scope now, and this is the hop that proves it: the+// binding enqueues exactly what `triggerNotification` enqueues, off the deps it+// was handed, and the envelope must carry the message's own id.test("a converted read path's own enqueue carries the message's requestId", async () => {const handleEvent = createIncomingEventHandler(ingestHarness.deps, {...ingestBindings,@@ -737,36 +734,33 @@ test('a second message is scoped to its own id, and an envelope without one stil});// ===========================================================================-// Section 4 — one request, one id, all six hops (ADR-022 A3, M15-202).+// Section 4 — one request, one id, all six hops (ADR-022 A3).// ===========================================================================//-// Sections 1-3 each prove a segment: 1 the HTTP -> job chain through a-// MOCKED service, 2 a real converted read path with no job behind it, 3 the-// Kafka edge. A3 names the property Carl actually asked for — "follow what-// has happened for a certain request, and see the entire flow" — as one-// chain, and the hops it lists are:+// Sections 1-3 each prove a segment: 1 the HTTP -> job chain through a MOCKED+// service, 2 a real converted read path with no job behind it, 3 the Kafka+// edge. A3 names the property Carl actually asked for — "follow what has+// happened for a certain request, and see the entire flow" — as one chain, and+// the hops it lists are://-// requestId minted at the edge-// -> ctx-// -> a service's bound logger-// -> producers.scope({ requestId })-// -> the { payload, meta } envelope-// -> the job's child logger+// RequestId minted at the edge -> ctx -> a service's bound logger ->+// producers.scope({ requestId }) -> the { payload, meta } envelope -> the job's+// child logger//// Nothing below is a stand-in for a hop. The read path is// `ctx.services.chart.getRetentionSeries`, a REAL converted service reaching// ClickHouse through `deps.ch`; the enqueue is// `ctx.services.cohort.enqueueCompute`, a REAL service writing onto// `ctx.queues`; the envelope is what `wrap` produces from what the recording-// producer captured; and the job is the REAL `cohortCompute` definition and-// the REAL handler off `jobs.registry.ts`, which reaches ClickHouse again —-// so the last hop is a converted read path INSIDE a job, observed on its own-// `query info` line.+// producer captured; and the job is the REAL `cohortCompute` definition and the+// REAL handler off `jobs.registry.ts`, which reaches ClickHouse again — so the+// last hop is a converted read path INSIDE a job, observed on its own `query+// info` line.//// Only the two connections are stubs, and both are the seam under test: the// ClickHouse client records what it was asked and the Postgres client answers-// one row. A `load*` loader anywhere on this path, a client that built its-// own logger, or a handler that reached past `ctx` breaks exactly one of the+// one row. A `load*` loader anywhere on this path, a client that built its own+// logger, or a handler that reached past `ctx` breaks exactly one of the// assertions below and names itself.const CHAIN_REQUEST_ID = 'adr022-a3-one-request';@@ -952,8 +946,7 @@ test('a job whose envelope carries no requestId is scoped to a fresh one, not to}const linesBefore = lines.length;- // What a scheduler enqueues: a payload with no originating request- // (ADR-018 R2).+ // What a scheduler enqueues: a payload with no originating request.await runJob(queues.cohortCompute,{diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.tsindex cdb50366c..92de56d74 100644--- a/packages/core/test/rpc-fixtures.ts+++ b/packages/core/test/rpc-fixtures.ts@@ -138,11 +138,11 @@ export function stubHttpCtx(/*** `services` with the permission ladder already granted.*- * `protectedProcedure` runs `enforceAccess` BEFORE the input parser- * (M11-001), so a test that wants to assert on a zod rejection has to get- * past the ladder first — and the real one reaches Postgres. Everything a- * procedure does after the parser is out of these tests' scope, so only the- * two lookups `enforceAccess` makes are stubbed.+ * `protectedProcedure` runs `enforceAccess` BEFORE the input parser, so a test+ * that wants to assert on a zod rejection has to get past the ladder first —+ * and the real one reaches Postgres. Everything a procedure does after the+ * parser is out of these tests' scope, so only the two lookups `enforceAccess`+ * makes are stubbed.*/export function servicesWithProjectAccess(): Services {return {diff --git a/packages/db/scripts/ch-update-sessions-with-revenue.ts b/packages/db/scripts/ch-update-sessions-with-revenue.tsindex 76ca68613..6d88325f4 100644--- a/packages/db/scripts/ch-update-sessions-with-revenue.ts+++ b/packages/db/scripts/ch-update-sessions-with-revenue.ts@@ -1,9 +1,9 @@// Local fixture script: give a couple of sessions per hour a random revenue.//-// M12-009 took it off `clix` (deleted with ADR-013 decision 21) and onto the-// `sql` tag. Both statements bind every value as a `{pN:Type}` param instead-// of splicing it into the text, which is also what removes the hand-rolled-// `'${id}'` quoting the ALTER used to do.+// Took it off `clix` (deleted with ADR-013 decision 21) and onto the `sql` tag.+// Both statements bind every value as a `{pN:Type}` param instead of splicing+// it into the text, which is also what removes the hand-rolled `'${id}'`+// quoting the ALTER used to do.import { ch, chQuery, TABLE_NAMES } from '../src/clickhouse/client';import { sql } from '../src/clickhouse/sql';diff --git a/packages/db/scripts/migrate-code.ts b/packages/db/scripts/migrate-code.tsindex c1c4fc50c..10a8b9de8 100644--- a/packages/db/scripts/migrate-code.ts+++ b/packages/db/scripts/migrate-code.ts@@ -1,12 +1,12 @@// The shell for `src/code-migrations`. It reads the environment, the runner// does the work — the same split `apps/api/src/main.ts` and `config/env.ts`-// have, and what keeps every migration file free of `process.env`-// (ADR-022 R7, which travelled with the directory in M15-204).+// have, and what keeps every migration file free of `process.env` (which+// travelled with the directory in M15-204).//-// `code-migrations` is not a conformance target (ADR-022, Carl's rulings): it-// lives in @openpanel/db, runs as a script with direct database access and no-// services, and copies the vocabulary it needs from core rather than importing-// it — isolation beats reuse.+// `code-migrations` is not a conformance target (Carl's rulings): it lives in+// @openpanel/db, runs as a script with direct database access and no services,+// and copies the vocabulary it needs from core rather than importing it —+// isolation beats reuse.import type { CodeMigrationEnv } from '../src/code-migrations/helpers';import { runCodeMigrations } from '../src/code-migrations/migrate';diff --git a/packages/db/src/clickhouse/client.ts b/packages/db/src/clickhouse/client.tsindex 0972ff9be..d3e92aab4 100644--- a/packages/db/src/clickhouse/client.ts+++ b/packages/db/src/clickhouse/client.ts@@ -325,7 +325,7 @@ export const ch = new Proxy(chTarget as unknown as ClickHouseClient, {/*** A query is either finished SQL text or a `sql` fragment carrying its own- * bound params (ADR-013 R1). Both go through the same round-robin/retry path.+ * bound params. Both go through the same round-robin/retry path.*/export type ChQueryInput = string | SqlFragment;diff --git a/packages/db/src/clickhouse/sql.clickhouse.test.ts b/packages/db/src/clickhouse/sql.clickhouse.test.tsindex 2814ab204..bfcd52f9c 100644--- a/packages/db/src/clickhouse/sql.clickhouse.test.ts+++ b/packages/db/src/clickhouse/sql.clickhouse.test.ts@@ -2,19 +2,19 @@ import { describe, expect, it } from 'bun:test';import { sql } from './sql';/**- * The ADR-013 P2 round-trip: every param type the codebase uses, bound- * through `chQuery` (so the `query_params` path is exercised through- * `withRetry` / round-robin, R1) and read back off a real local ClickHouse.+ * The ADR-013 P2 round-trip: every param type the codebase uses, bound through+ * `chQuery` (so the `query_params` path is exercised through `withRetry` /+ * round-robin, R1) and read back off a real local ClickHouse.** Payloads are hostile on purpose — single quote, double quote, backslash,- * newline, tab, and a literal `{p1:String}` — because the escaping lives in- * the driver and the parsing lives in the server, and neither is ours.+ * newline, tab, and a literal `{p1:String}` — because the escaping lives in the+ * driver and the parsing lives in the server, and neither is ours.*- * This suite runs against its own `openpanel_test` database, which it- * creates. It must never touch the local `openpanel` prod-copy: those tables- * hold hundreds of millions of rows, and a `FINAL` / `ARRAY JOIN` scan over- * them times the HTTP client out while the rest of the suite runs in- * parallel against the same node.+ * This suite runs against its own `openpanel_test` database, which it creates.+ * It must never touch the local `openpanel` prod-copy: those tables hold+ * hundreds of millions of rows, and a `FINAL` / `ARRAY JOIN` scan over them+ * times the HTTP client out while the rest of the suite runs in parallel+ * against the same node.*/const CLICKHOUSE_TEST_DATABASE = 'openpanel_test';diff --git a/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts b/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.tsindex acd5a537f..bca1517b4 100644--- a/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts+++ b/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts@@ -2,14 +2,14 @@ import { describe, expect, it } from 'bun:test';import { sql } from './sql';/**- * ADR-013 R1, the half the round-trip suite cannot reach: bound params must- * travel through `withRetry` / round-robin, so a parameterised read keeps the- * failover behaviour `chQueryWithMeta` already had for raw text.+ * R1, the half the round-trip suite cannot reach: bound params must travel+ * through `withRetry` / round-robin, so a parameterised read keeps the failover+ * behaviour `chQueryWithMeta` already had for raw text.*- * The setup is a two-node `CLICKHOUSE_URL` whose first node is dead. The- * picker starts at index 0, so every query here fails over to node 1 — if the- * params were dropped anywhere on the retry path, the second attempt would- * return a different answer or an error instead of the payload.+ * The setup is a two-node `CLICKHOUSE_URL` whose first node is dead. The picker+ * starts at index 0, so every query here fails over to node 1 — if the params+ * were dropped anywhere on the retry path, the second attempt would return a+ * different answer or an error instead of the payload.*/const CLICKHOUSE_TEST_DATABASE = 'openpanel_test';diff --git a/packages/db/src/clickhouse/sql.test.ts b/packages/db/src/clickhouse/sql.test.tsindex add927154..c57c07e91 100644--- a/packages/db/src/clickhouse/sql.test.ts+++ b/packages/db/src/clickhouse/sql.test.ts@@ -4,8 +4,8 @@ import { type SqlFragment, SqlIdentifierError, sql, toStatement } from './sql';describe('sql tag — slot typing (R1)', () => {it('is a compile-time error to interpolate a bare value', () => {// The whole safety property of ADR-013: a raw string or number can never- // reach the SQL text. If either of these ever stops erroring, injection- // has become writable again and `pnpm run typecheck` is the alarm.+ // reach the SQL text. If either of these ever stops erroring, injection has+ // become writable again and `pnpm run typecheck` is the alarm.const path = "/blog' OR '1'='1";// @ts-expect-error — a bare string is not a SqlFragment | SqlParamconst withString = sql`SELECT * FROM events WHERE path = ${path}`;@@ -248,11 +248,11 @@ describe('injection (ported from query-builder.test.ts)', () => {expect(query_params.p1).toBe('{p1:String}');});- // M12-009 completed the port: the four cases below were still only asserted- // against clix when query-builder.test.ts was deleted. Each keeps that- // test's payload; what changes is the mechanism the payload proves —- // clix asserted on the escaped literal it produced, the tag asserts the- // value never reaches the text at all.+ // Completed the port: the four cases below were still only asserted against+ // clix when query-builder.test.ts was deleted. Each keeps that test's+ // payload; what changes is the mechanism the payload proves — clix asserted+ // on the escaped literal it produced, the tag asserts the value never reaches+ // the text at all.it('binds a plain ISO date string instead of quoting it', () => {const { query, query_params } =diff --git a/packages/db/src/clickhouse/sql.ts b/packages/db/src/clickhouse/sql.tsindex 32a70e673..eed7b04ab 100644--- a/packages/db/src/clickhouse/sql.ts+++ b/packages/db/src/clickhouse/sql.ts@@ -1,34 +1,33 @@/**- * The ClickHouse `sql` tag (ADR-013).+ * The ClickHouse `sql` tag.** Two tiers, one tag:*- * 1. **Static queries** are plain SQL text — the tag is a no-op wrapper.- * 2. **Dynamic composition** builds from fragments, and every *value* binds- * as a ClickHouse-native `{name:Type}` query parameter, escaped by the- * server rather than by us.+ * 1. **Static queries** are plain SQL text — the tag is a no-op wrapper. 2.+ * **Dynamic composition** builds from fragments, and every *value* binds as a+ * ClickHouse-native `{name:Type}` query parameter, escaped by the server rather+ * than by us.** The safety property is the type of an interpolation slot: it accepts only* `SqlFragment | SqlParam`, so a bare string or number in a slot is a- * compile-time error. There is deliberately no `sql.raw()` — dynamic- * structure composes with {@link SqlBuilder.join}, and the only path from an- * untrusted string to SQL text is {@link SqlBuilder.id}, which validates and- * throws.+ * compile-time error. There is deliberately no `sql.raw` — dynamic structure+ * composes with {@link SqlBuilder.join}, and the only path from an untrusted+ * string to SQL text is {@link SqlBuilder.id}, which validates and throws.** Placeholder names are assigned at render time from a single counter, so* fragments nest and repeat without colliding (R2).*- * Exported from the package barrel (M12-009). It could not be during the clix- * coexistence window — `query-builder.ts` exported its own `SqlParam` type and- * `export *` from both was ambiguous — and that file is now deleted.+ * Exported from the package barrel. It could not be during the clix coexistence+ * window — `query-builder.ts` exported its own `SqlParam` type and `export *`+ * from both was ambiguous — and that file is now deleted.** `packages/core` still imports this module by its deep path rather than* through the barrel: the barrel also re-exports `clickhouse/client.ts` and* `prisma-client.ts`, which construct a ClickHouse client array and a* PrismaClient at module load, so a barrel import from core would acquire a* second, request-scope-less client. `.dependency-cruiser.cjs`'s- * `core-uses-ctx-not-db-internals` encodes exactly that, exempting this file- * by path and not the barrel.+ * `core-uses-ctx-not-db-internals` encodes exactly that, exempting this file by+ * path and not the barrel.*//** Auto-generated placeholders are `{p1:Type}`, `{p2:Type}`, … */diff --git a/packages/db/src/code-migrations/constants.ts b/packages/db/src/code-migrations/constants.tsindex 2e6154c20..671db4386 100644--- a/packages/db/src/code-migrations/constants.ts+++ b/packages/db/src/code-migrations/constants.ts@@ -1,18 +1,17 @@// The vocabulary these one-shot migrations need, COPIED from packages/core// rather than imported from it.//-// ADR-022, Carl's rulings: "I'd rather have code-migrations isolated from-// core, so I'd rather duplicate code for this to be isolated." A migration-// reads rows written by a past version of the app, so it must keep describing-// the shape that existed when it was written — an import of the live-// `report.constants.ts` would silently redefine what migration 7 and 9 mean-// the next time someone edits a chart segment.+// ADR-022, Carl's rulings: "I'd rather have code-migrations isolated from core,+// so I'd rather duplicate code for this to be isolated." A migration reads rows+// written by a past version of the app, so it must keep describing the shape+// that existed when it was written — an import of the live+// `report.constants.ts` would silently redefine what migration 7 and 9 mean the+// next time someone edits a chart segment.//// Sources at the time of the move (2026-09-11), for anyone diffing:-// packages/core/src/modules/report/report.constants.ts (the chart types)-// packages/core/src/modules/organization/organization.constants.ts-// (zProjectAccessGrant)-// These are frozen. Do not re-sync them with core.+// packages/core/src/modules/report/report.constants.ts (the chart types)+// packages/core/src/modules/organization/organization.constants.ts+// (zProjectAccessGrant) These are frozen. Do not re-sync them with core.import { z } from 'zod';diff --git a/packages/db/src/code-migrations/helpers.ts b/packages/db/src/code-migrations/helpers.tsindex 81404b8e6..3ddbaf2f5 100644--- a/packages/db/src/code-migrations/helpers.ts+++ b/packages/db/src/code-migrations/helpers.ts@@ -38,7 +38,7 @@ export function printBoxMessage(title: string, lines: (string | unknown)[]) {/*** The environment this script needs, read by its shell* (`packages/db/scripts/migrate-code.ts`) rather than here, so no migration- * file reads `process.env` (ADR-022 R7, which travelled with the move).+ * file reads `process.env` (which travelled with the move).*/export interface CodeMigrationEnv {clickhouseCluster: boolean;diff --git a/packages/db/src/logger.ts b/packages/db/src/logger.tsindex 786d1d33a..6f73fc6af 100644--- a/packages/db/src/logger.ts+++ b/packages/db/src/logger.ts@@ -1,11 +1,11 @@// Self-contained pino instantiation. packages/db is a leaf "stays" package// (TARGET_ARCHITECTURE §7) and must not reach into @openpanel/core just to// build a logger — that direction is backwards, since core itself depends on-// db. This is the same implementation @openpanel/core/clients/logger.ts-// carries (both descend from the pre-dissolve @openpanel/logger package,-// M4-003) — duplicated here deliberately rather than shared, because there is-// no home narrower than "the package itself" that both can reach without-// reintroducing the db <-> core cycle this file exists to remove.+// db. This is the same implementation @openpanel/core/clients/logger.ts carries+// (both descend from the pre-dissolve @openpanel/logger package) — duplicated+// here deliberately rather than shared, because there is no home narrower than+// "the package itself" that both can reach without reintroducing the db <->+// core cycle this file exists to remove.import * as HyperDX from '@hyperdx/node-opentelemetry';import pino, { type Logger as PinoLogger } from 'pino';diff --git a/packages/db/src/services/access.service.ts b/packages/db/src/services/access.service.tsindex 9c51f1f96..4160f0949 100644--- a/packages/db/src/services/access.service.ts+++ b/packages/db/src/services/access.service.ts@@ -1,13 +1,13 @@// The concrete project/organization/client access lookups live in-// @openpanel/core now (M8-005): packages/core/src/shared/access-lookups.ts.+// @openpanel/core now: packages/core/src/shared/access-lookups.ts.//// Kept here as a deep-path-only re-export (NOT part of packages/db's index.ts// barrel — that shrank to the final surface at M9-CLEANUP-001) solely because// the controller's protected `verification/contracts/auth/// group-b-project-access.mts` hard-imports this exact path-// ('packages/db/src/services/access.service.ts') to exercise ADR-011-// benchmark 2's getProjectAccess golden table. Every real importer in this-// repo now reaches these functions through `@openpanel/core` directly.+// ('packages/db/src/services/access.service.ts') to exercise ADR-011 benchmark+// 2's getProjectAccess golden table. Every real importer in this repo now+// reaches these functions through `@openpanel/core` directly.export {canWriteProject,getClientAccess,diff --git a/packages/db/src/types.ts b/packages/db/src/types.tsindex aaee03717..465e70a66 100644--- a/packages/db/src/types.ts+++ b/packages/db/src/types.ts@@ -6,9 +6,9 @@// slim-down"; three options, none picked). Taken here: option 3, "accept a// declared type-only devDependency edge" — `@openpanel/db` already depends on// `@openpanel/core` (these shims were the reason), the edge is `import type`-// only so it creates no runtime cycle, and it is the same shape as this-// repo's existing type-only `db -> queue` cycle. Revisit if a future task-// picks a different one of the three named resolutions.+// only so it creates no runtime cycle, and it is the same shape as this repo's+// existing type-only `db -> queue` cycle. Revisit if a future task picks a+// different one of the three named resolutions.import type {IClickhouseBotEvent,IClickhouseEvent,diff --git a/packages/redis/dead-letter.test.ts b/packages/redis/dead-letter.test.tsindex c39b820fd..32069f81d 100644--- a/packages/redis/dead-letter.test.ts+++ b/packages/redis/dead-letter.test.ts@@ -1,5 +1,5 @@/**- * M20-001 — the capped dead-letter list, at the Redis boundary.+ * The capped dead-letter list, at the Redis boundary.** What the consumer does with a rejection is `packages/core`'s* `consumer.test.ts`; what this file pins is the write itself: one MULTI, thediff --git a/packages/redis/dead-letter.ts b/packages/redis/dead-letter.tsindex 53ced4472..8871b0406 100644--- a/packages/redis/dead-letter.ts+++ b/packages/redis/dead-letter.ts@@ -1,26 +1,27 @@/**- * The ingest consumer's dead-letter destination: a capped Redis list (M20-001).+ * The ingest consumer's dead-letter destination: a capped Redis list.** Carl, 2026-09-14: *"For now, we can just store errors in redis and drop the* event, push it to a redis list and only keep the last N events."*** It replaces `produceDeadLetterEvent`, which produced to- * `${KAFKA_EVENTS_TOPIC}-dlq` — a topic nothing in the tree ever creates.- * Drill 08 measured that produce failing 1,592 times with 0 successes- * (`Number of partitions is invalid`), and the failure left the offset- * unresolved, which is the unbounded handler-error redelivery loop drill 02's- * re-run 2 measured at 78-79 laps per message. The Kafka producer is still- * exported from `@openpanel/core`, and the consumer's `sendToDeadLetter` seam- * is unchanged, so swapping back is one line in `apps/api`'s wiring.+ * `${KAFKA_EVENTS_TOPIC}-dlq` — a topic nothing in the tree ever creates. Drill+ * 08 measured that produce failing 1,592 times with 0 successes (`Number of+ * partitions is invalid`), and the failure left the offset unresolved, which is+ * the unbounded handler-error redelivery loop drill 02's re-run 2 measured at+ * 78-79 laps per message. The Kafka producer is still exported from+ * `@openpanel/core`, and the consumer's `sendToDeadLetter` seam is unchanged,+ * so swapping back is one line in `apps/api`'s wiring.** THE RECORD IS A DEBUGGING SAMPLE, NOT A RECOVERY MECHANISM. The list keeps* the last N and nothing more; the event itself is gone from the pipeline. The- * volume lives in `kafka_events_dead_lettered_total` / `_dead_letter_failed_total`,- * because a capped list makes 50,000 drops look exactly like 12.+ * volume lives in `kafka_events_dead_lettered_total` /+ * `_dead_letter_failed_total`, because a capped list makes 50,000 drops look+ * exactly like 12.*- * Why here and not in `packages/core`'s ingest module: the whole of it is- * Redis mechanics — one MULTI, one LPUSH, one LTRIM — and core's only export- * door is its barrel, which M20-001's scope does not cover. The input type is+ * Why here and not in `packages/core`'s ingest module: the whole of it is Redis+ * mechanics — one MULTI, one LPUSH, one LTRIM — and core's only export door is+ * its barrel, which M20-001's scope does not cover. The input type is* structural, so `DeadLetterMessage` (kafkajs `Buffer`s and `IHeaders`)* satisfies it without this package depending on kafkajs or on core.*/diff --git a/packages/redis/duplicate-marker.test.ts b/packages/redis/duplicate-marker.test.tsindex e92f8776b..f152f7996 100644--- a/packages/redis/duplicate-marker.test.ts+++ b/packages/redis/duplicate-marker.test.ts@@ -1,5 +1,5 @@/**- * M21-001 — the event-keyed duplicate marker, at the Redis boundary.+ * The event-keyed duplicate marker, at the Redis boundary.** What the ingest handler does with the answer is `packages/core`'s* `incoming-event-handler.test.ts`; what this file pins is the command: one@@ -8,9 +8,8 @@* No real Redis here: an in-memory stand-in with real `NX` and expiry* semantics. The same four answers were driven through THIS marker against the* local Redis (`redis://127.0.0.1:6379/14`) on 2026-09-14 before this file was- * written, at an 800 ms TTL — first sighting false, `PTTL` 800, second- * sighting true, a distinct id false, and the same id false again 900 ms- * later.+ * written, at an 800 ms TTL — first sighting false, `PTTL` 800, second sighting+ * true, a distinct id false, and the same id false again 900 ms later.*/import { describe, expect, it } from 'vitest';diff --git a/packages/redis/duplicate-marker.ts b/packages/redis/duplicate-marker.tsindex 902d21aa9..2ff72ae35 100644--- a/packages/redis/duplicate-marker.ts+++ b/packages/redis/duplicate-marker.ts@@ -1,5 +1,5 @@/**- * The ingest consumer's duplicate MARKER (M21-001).+ * The ingest consumer's duplicate MARKER.** Carl, 2026-09-14, on the offset watermark this replaces: *"are they purely* for logging reprocessed? Then we should remove them, i dont care. we can use@@ -14,26 +14,26 @@* in-process watermark survived: drill 08 measured 161 real duplicates and 0* `REPROCESSED` lines.*- * MARK MEANS COUNT AND LOG. IT DOES NOT MEAN DROP. This tells the caller the- * id has been seen before; the caller inserts the event either way. A false+ * MARK MEANS COUNT AND LOG. IT DOES NOT MEAN DROP. This tells the caller the id+ * has been seen before; the caller inserts the event either way. A false* positive on a suppressing check is silent data loss, and whether the events* table ever gets dedupe is Carl's decision, not this file's.** ONE round trip, `SET key NX PX`: the set and the "did it already exist"- * answer are the same command, and there is no clean seam to fold it into —- * the session buffer's own GET and Lua EVAL live in `packages/core`'s- * `buffers/`, which this change does not own.+ * answer are the same command, and there is no clean seam to fold it into — the+ * session buffer's own GET and Lua EVAL live in `packages/core`'s `buffers/`,+ * which this change does not own.*- * IT MUST BE GIVEN THE CACHE CLIENT. That one fails fast (M18-003): offline- * queue off once connected, `commandTimeout` 500 ms. `getRedisQueue()` keeps- * `maxRetriesPerRequest: null` for BullMQ and would block a handler for tens- * of seconds — which is how drill 02's consumer was evicted past its 30 s- * session timeout, and an eviction is the only reassignment M19 measured- * costing duplicate rows.+ * IT MUST BE GIVEN THE CACHE CLIENT. That one fails fast: offline queue off+ * once connected, `commandTimeout` 500 ms. `getRedisQueue` keeps+ * `maxRetriesPerRequest: null` for BullMQ and would block a handler for tens of+ * seconds — which is how drill 02's consumer was evicted past its 30 s session+ * timeout, and an eviction is the only reassignment M19 measured costing+ * duplicate rows.*- * Why here and not in `packages/core`'s ingest module: the whole of it is- * Redis mechanics, and core's only export door is its barrel, which this- * task's scope does not cover — the same reason `dead-letter.ts` lives here.+ * Why here and not in `packages/core`'s ingest module: the whole of it is Redis+ * mechanics, and core's only export door is its barrel, which this task's scope+ * does not cover — the same reason `dead-letter.ts` lives here.*//** Live key prefix. An operator has to be able to find these. */diff --git a/packages/redis/publisher.test.ts b/packages/redis/publisher.test.tsindex 273cda4ee..15287c112 100644--- a/packages/redis/publisher.test.ts+++ b/packages/redis/publisher.test.ts@@ -1,13 +1,13 @@/**- * M26-001 — F1: one subscriber leaving must not silence the others.+ * F1: one subscriber leaving must not silence the others.** `subscribeToPublishedEvent` hands every caller the SAME ioredis connection- * (`getRedisSub()`, a process-wide singleton), so before this the unsubscribe- * it returned took the channel away from the whole process. M23-003 measured- * it on the `/live` sockets: close one, every other open socket received- * nothing for 30 s. What is pinned here is the reference count — and, just as- * important, that the LAST listener leaving still sends a real UNSUBSCRIBE, so- * the fix cannot degrade into "never unsubscribe".+ * (`getRedisSub`, a process-wide singleton), so before this the unsubscribe it+ * returned took the channel away from the whole process. M23-003 measured it on+ * the `/live` sockets: close one, every other open socket received nothing for+ * 30 s. What is pinned here is the reference count — and, just as important,+ * that the LAST listener leaving still sends a real UNSUBSCRIBE, so the fix+ * cannot degrade into "never unsubscribe".** No real Redis: a stand-in for the shared connection that records the wire* commands and can push a `message` event, which is the entire surface thediff --git a/packages/redis/publisher.ts b/packages/redis/publisher.tsindex 3f3e45e50..ca53562a1 100644--- a/packages/redis/publisher.ts+++ b/packages/redis/publisher.ts@@ -44,26 +44,26 @@ export function parsePublishedEvent<Channel extends keyof IPublishChannels>(type ChannelMessageListener = (message: string) => void;/**- * Every subscriber in the process shares ONE ioredis connection- * (`getRedisSub()`, a module-level singleton). SUBSCRIBE and UNSUBSCRIBE on it- * are process-wide, so a per-subscriber UNSUBSCRIBE silences every other- * subscriber on that channel — measured by M23-003 as F1: closing one `/live`- * socket left every other open socket receiving nothing for 30 s, across- * routes and across projects, because `/live/events` and `/live/visitors` both- * ride `events:batch`.+ * Every subscriber in the process shares ONE ioredis connection (`getRedisSub`,+ * a module-level singleton). SUBSCRIBE and UNSUBSCRIBE on it are process-wide,+ * so a per-subscriber UNSUBSCRIBE silences every other subscriber on that+ * channel — measured by M23-003 as F1: closing one `/live` socket left every+ * other open socket receiving nothing for 30 s, across routes and across+ * projects, because `/live/events` and `/live/visitors` both ride+ * `events:batch`.** So the channel is reference-counted here rather than at each call site: the- * wire SUBSCRIBE happens only on 0 -> 1 and the wire UNSUBSCRIBE only on- * 1 -> 0. One `message` handler is installed on the shared connection for the- * whole process and dispatches by channel name, which also keeps the- * connection off Node's max-listeners warning as sockets accumulate.+ * wire SUBSCRIBE happens only on 0 -> 1 and the wire UNSUBSCRIBE only on 1 ->+ * 0. One `message` handler is installed on the shared connection for the whole+ * process and dispatches by channel name, which also keeps the connection off+ * Node's max-listeners warning as sockets accumulate.** RECONNECT NEEDS NO HANDLING HERE. ioredis re-issues SUBSCRIBE for every* channel it believes it holds when the connection comes back* (`ioredis/built/redis/event_handler.js:254`, gated on `autoResubscribe`,* which defaults to `true` in `redis/RedisOptions.js:45` and is not overridden- * for this client). Since the wire commands stay one-to-one with the 0 -> 1- * and 1 -> 0 edges, ioredis's own set stays exactly the set of channels with a+ * for this client). Since the wire commands stay one-to-one with the 0 -> 1 and+ * 1 -> 0 edges, ioredis's own set stays exactly the set of channels with a* non-zero count. Confirmed live against the local server on 2026-09-15:* destroying the socket under a subscribed client and publishing after the* reconnect still delivered, with no re-subscribe from here.diff --git a/packages/redis/redis.test.ts b/packages/redis/redis.test.tsindex d4c9899da..0f45e8e99 100644--- a/packages/redis/redis.test.ts+++ b/packages/redis/redis.test.ts@@ -1,11 +1,11 @@/**- * M18-003 — the CACHE client must reject promptly when Redis is unreachable.+ * The CACHE client must reject promptly when Redis is unreachable.*- * Drill 02 (rev e004e199) measured `/track` blocking 9,427 / 12,039 /- * 41,978 ms on a stopped Redis, with 10 of 20 requests never answered inside- * 30 s, because the command was queued and waited out ioredis's 20-attempt- * reconnect cycle. These tests pin the three properties that fixed it, and the- * one that must NOT change (the queue client).+ * Drill 02 (rev e004e199) measured `/track` blocking 9,427 / 12,039 / 41,978 ms+ * on a stopped Redis, with 10 of 20 requests never answered inside 30 s,+ * because the command was queued and waited out ioredis's 20-attempt reconnect+ * cycle. These tests pin the three properties that fixed it, and the one that+ * must NOT change (the queue client).** No real Redis: an unreachable port covers "never connected", and a fake RESP* server covers "connected, then gone".diff --git a/packages/redis/redis.ts b/packages/redis/redis.tsindex 2b840c55d..c0bb9ae77 100644--- a/packages/redis/redis.ts+++ b/packages/redis/redis.ts@@ -7,10 +7,10 @@ const options: RedisOptions = {};/**- * The cache client's tail bound, for the fault the offline queue cannot see:- * a server whose socket is UP and which answers nothing (a frozen or- * partitioned node). Nothing else in the request path sets a deadline there —- * `/track` never answered inside 30 s in that fault before this.+ * The cache client's tail bound, for the fault the offline queue cannot see: a+ * server whose socket is UP and which answers nothing (a frozen or partitioned+ * node). Nothing else in the request path sets a deadline there — `/track`+ * never answered inside 30 s in that fault before this.** It has to clear the heaviest LEGITIMATE command by a wide margin, or a busy* event-buffer flush would start failing as if Redis were down — and under@@ -109,27 +109,27 @@ const createRedisClient = (};/**- * The CACHE client fails fast (M18-003). Drill 02 measured `/track` blocking- * 9,427 / 12,039 / 41,978 ms on a stopped Redis, and 10 of 20 requests getting- * no answer inside 30 s, because on ioredis's defaults the command is QUEUED- * and waits out 20 reconnect attempts (backoff `min(times * 50, 2000)` ms)- * before `MaxRetriesPerRequestError`. Everything on the ingest path already- * treats these reads as optional — `device-id.ts` catches the session-buffer- * failure and mints the deterministic session id — so the wait bought nothing- * but a slower failure.+ * The CACHE client fails fast. Drill 02 measured `/track` blocking 9,427 /+ * 12,039 / 41,978 ms on a stopped Redis, and 10 of 20 requests getting no+ * answer inside 30 s, because on ioredis's defaults the command is QUEUED and+ * waits out 20 reconnect attempts (backoff `min(times * 50, 2000)` ms) before+ * `MaxRetriesPerRequestError`. Everything on the ingest path already treats+ * these reads as optional — `device-id.ts` catches the session-buffer failure+ * and mints the deterministic session id — so the wait bought nothing but a+ * slower failure.** Two mechanisms, because there are two faults:*- * - **The offline queue goes off**, so a command issued while the socket is- * known-down is rejected in microseconds rather than queued. This is what- * keeps a warm-cache `/track` at its normal latency during an outage.- * - **`commandTimeout`** bounds the case the offline queue cannot see, where- * the socket is up and the server answers nothing.+ * **The offline queue goes off**, so a command issued while the socket is+ * known-down is rejected in microseconds rather than queued. This is what keeps+ * a warm-cache `/track` at its normal latency during an outage. -+ * **`commandTimeout`** bounds the case the offline queue cannot see, where the+ * socket is up and the server answers nothing.** Reproduced and measured before/after on this box, with the API pointed at a* TCP proxy that can stop or freeze: with Redis stopped, a warm-auth `/track`- * goes from 2-of-3 requests never answered inside 30 s to 200 × 10 at p50- * 10.0 ms, and a cold-auth one from the same 30 s hang to 500 at p50 1.3 ms.+ * goes from 2-of-3 requests never answered inside 30 s to 200 × 10 at p50 10.0+ * ms, and a cold-auth one from the same 30 s hang to 500 at p50 1.3 ms.* `commandTimeout` on its own, with the queue left on, was measured as well and* is not enough: it bounds the tail but leaves that warm `/track` at 1,011 ms,* because ioredis arms the deadline before the writable check, so the queued@@ -138,10 +138,10 @@ const createRedisClient = (** THE OFFLINE QUEUE STAYS ON UNTIL THE CLIENT HAS CONNECTED ONCE. ioredis* rejects every command issued before the first connect completes when the- * queue is off — including the ones a process issues while it is still- * booting — which would make boot order decide whether a command works. A- * process that has never reached Redis therefore still falls back to- * `commandTimeout`, which is bounded; one that has connected fails instantly.+ * queue is off — including the ones a process issues while it is still booting+ * — which would make boot order decide whether a command works. A process that+ * has never reached Redis therefore still falls back to `commandTimeout`, which+ * is bounded; one that has connected fails instantly.*/export function createFailFastCacheClient(name: string,diff --git a/packages/sdks/sdk/src/index.ts b/packages/sdks/sdk/src/index.tsindex 0d135aa93..7cc6d4f5f 100644--- a/packages/sdks/sdk/src/index.ts+++ b/packages/sdks/sdk/src/index.ts@@ -1,16 +1,15 @@-// Hand-duplicated on purpose, not imported: the wire contract's source of-// truth is @openpanel/core/modules/ingest/ingest.constants.ts (ADR-008,-// "ingest owns C"), but core's package.json exports map is deliberately-// narrow (no `./*` wildcard — see packages/core/AGENTS.md) and-// rollup-plugin-dts (tsup's dts bundler) cannot inline a type that resolves-// through that map's `*` pattern: it leaves an unresolvable-// `@openpanel/core/...` reference in dist/index.d.ts, which breaks for every-// consumer since core isn't published. A plain deep import into any-// workspace-internal shim package hits the same wall one hop later, since-// those packages now just re-export core's. Keeping a literal copy here is-// what keeps this package's shipped .d.ts self-contained. The SDK wire contract-// tests (verification/contracts/sdk) exercise both sides at runtime, so a-// drift shows up as a behavioral failure even without a type-level check.+// Hand-duplicated on purpose, not imported: the wire contract's source of truth+// is @openpanel/core/modules/ingest/ingest.constants.ts ("ingest owns C"), but+// core's package.json exports map is deliberately narrow (no `./*` wildcard —+// see packages/core/AGENTS.md) and rollup-plugin-dts (tsup's dts bundler)+// cannot inline a type that resolves through that map's `*` pattern: it leaves+// an unresolvable `@openpanel/core/...` reference in dist/index.d.ts, which+// breaks for every consumer since core isn't published. A plain deep import+// into any workspace-internal shim package hits the same wall one hop later,+// since those packages now just re-export core's. Keeping a literal copy here+// is what keeps this package's shipped.d.ts self-contained. The SDK wire+// contract tests (verification/contracts/sdk) exercise both sides at runtime,+// so a drift shows up as a behavioral failure even without a type-level check.import { Api } from './api';export type ProfileId = string | number;diff --git a/packages/shared/src/date.ts b/packages/shared/src/date.tsindex 70a34cb6f..2e958fb1d 100644--- a/packages/shared/src/date.ts+++ b/packages/shared/src/date.ts@@ -1,17 +1,17 @@// 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.+// packages/db/src/services/date.service.ts — 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.+// `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+// `getDatesFromRange` and `getChartStartEndDate` left with the report// vocabulary they read (`IChartRange`, `IReportInput`) — they are// `packages/core/src/modules/report/src/chart-dates.ts` now.//-// M15-010: what was left knows nothing above it and nothing about the domain,-// so it is @openpanel/shared's (ADR-022 R21).+// What was left knows nothing above it and nothing about the domain, so it is+// @openpanel/shared's.import { DateTime } from 'luxon';export { DateTime } from 'luxon';diff --git a/packages/shared/src/id.ts b/packages/shared/src/id.tsindex 161481f50..ffd3a6392 100644--- a/packages/shared/src/id.ts+++ b/packages/shared/src/id.ts@@ -1,11 +1,10 @@-// Ported from packages/common's id.ts, then to @openpanel/shared (M15-010,-// ADR-022 R21) — apps/start had copied `shortId` into its own utils/math.ts.-// nanoid/non-secure is deliberate: these are correlation/display ids, not-// secrets.+// Ported from packages/common's id.ts, then to @openpanel/shared — apps/start+// had copied `shortId` into its own utils/math.ts. nanoid/non-secure is+// deliberate: these are correlation/display ids, not secrets.-// Ported from packages/common/server's id.ts (M4-003). Regular `nanoid`,-// not the non-secure variant above: these ids back password-reset tokens and-// invite links, so they must stay cryptographically random.+// Ported from packages/common/server's id.ts. Regular `nanoid`, not the+// non-secure variant above: these ids back password-reset tokens and invite+// links, so they must stay cryptographically random.import { nanoid as secureNanoid } from 'nanoid';import { nanoid } from 'nanoid/non-secure';diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex ef0a7908b..f10789a00 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1,12 +1,12 @@-// The isomorphic entrypoint of @openpanel/shared (ADR-022 R21).+// The isomorphic entrypoint of @openpanel/shared.//// What may live behind this file: pure functions and types with no workspace// import, no db/redis/env/logger/services and no domain vocabulary. Anything// that needs one of those stays in the package that owns it.//// Nothing reachable from here may import a `node:*` builtin or `./server` —-// this is a browser bundle's entrypoint too, and the leak would be invisible-// at the call site. The `shared-root-stays-isomorphic` cruiser rule is what+// this is a browser bundle's entrypoint too, and the leak would be invisible at+// the call site. The `shared-root-stays-isomorphic` cruiser rule is what// enforces it.export {DateTime,diff --git a/packages/shared/src/json.ts b/packages/shared/src/json.tsindex c289e1c41..b18c17923 100644--- a/packages/shared/src/json.ts+++ b/packages/shared/src/json.ts@@ -1,10 +1,10 @@-// Ported from packages/json, then to @openpanel/shared (M15-010, ADR-022-// R21): packages/redis and apps/start each carried a copy, and redis' copy-// carried the "keep in sync with packages/core" comment that is the whole-// argument for a package below both. Same semantics: getSafeJson never throws, and-// getSuperJson only hands off to superjson's parser when the payload looks-// like superjson's own `{ json, meta }` envelope — a plain JSON payload-// round-trips through JSON.parse instead.+// Ported from packages/json, then to @openpanel/shared: packages/redis and+// apps/start each carried a copy, and redis' copy carried the "keep in sync+// with packages/core" comment that is the whole argument for a package below+// both. Same semantics: getSafeJson never throws, and getSuperJson only hands+// off to superjson's parser when the payload looks like superjson's own `{+// json, meta }` envelope — a plain JSON payload round-trips through JSON.parse+// instead.import superjson from 'superjson';export function getSafeJson<T>(str: string): T | null {diff --git a/packages/shared/src/math.ts b/packages/shared/src/math.tsindex 7fa7ae240..b29f0ef7a 100644--- a/packages/shared/src/math.ts+++ b/packages/shared/src/math.ts@@ -1,13 +1,13 @@// Moved from packages/common/src/math.ts and-// packages/common/src/get-previous-metric.ts (M11-006, ADR-007 shared/ layout).+// packages/common/src/get-previous-metric.ts (ADR-007 shared/ layout).// `isFloat` does NOT come along: no importer, anywhere.//-// M15-009: `getPreviousMetric` left with the report vocabulary it returns —-// it is `packages/core/src/modules/report/src/previous-metric.ts` now.+// `getPreviousMetric` left with the report vocabulary it returns — it is+// `packages/core/src/modules/report/src/previous-metric.ts` now.//-// M15-010: what was left is generic arithmetic, so it is @openpanel/shared's-// (ADR-022 R21). apps/start had copied all six of these functions verbatim;-// that copy is deleted and the dashboard imports them from here.+// What was left is generic arithmetic, so it is @openpanel/shared's. apps/start+// had copied all six of these functions verbatim; that copy is deleted and the+// dashboard imports them from here.//// `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.diff --git a/packages/shared/src/object.ts b/packages/shared/src/object.tsindex 4fa3dc499..80e3e167c 100644--- a/packages/shared/src/object.ts+++ b/packages/shared/src/object.ts@@ -1,6 +1,6 @@-// Moved from packages/common/src/object.ts (M11-006, ADR-007 shared/ layout).-// `toDots` is the ClickHouse property flattener — its invalid-surrogate strip-// is load-bearing on the insert path.+// Moved from packages/common/src/object.ts (ADR-007 shared/ layout). `toDots`+// is the ClickHouse property flattener — its invalid-surrogate strip is+// load-bearing on the insert path.import { anyPass, assocPath, isEmpty, isNil, reject } from 'ramda';function isValidJsonString(value: string): boolean {diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex a25f364d3..008ecfc1a 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -1,7 +1,7 @@-// The Node-only entrypoint of @openpanel/shared (ADR-022 R21):-// `@openpanel/shared/server`. Everything behind it may use `node:*`.+// The Node-only entrypoint of @openpanel/shared: `@openpanel/shared/server`.+// Everything behind it may use `node:*`.//-// A web app may not import it — `no-web-to-server` in .dependency-cruiser.cjs+// A web app may not import it — `no-web-to-server` in.dependency-cruiser.cjs// forbids apps/start, apps/public and packages/sdks/* from reaching this path.export {createHash,diff --git a/packages/shared/src/slug.ts b/packages/shared/src/slug.tsindex ab122c229..1964f3020 100644--- a/packages/shared/src/slug.ts+++ b/packages/shared/src/slug.ts@@ -1,7 +1,6 @@-// Moved from packages/common/src/slug.ts (M11-006), then to-// @openpanel/shared (M15-010, ADR-022 R21) — apps/start carried a verbatim-// copy of it, which is deleted. Not to be confused with core's slug-id.ts,-// which calls this.+// Moved from packages/common/src/slug.ts, then to @openpanel/shared —+// apps/start carried a verbatim copy of it, which is deleted. Not to be+// confused with core's slug-id.ts, which calls this.import _slugify from 'slugify';const slugify = (str: string) => {diff --git a/packages/shared/src/string.ts b/packages/shared/src/string.tsindex 690d66468..c0207d959 100644--- a/packages/shared/src/string.ts+++ b/packages/shared/src/string.ts@@ -1,4 +1,4 @@-// Moved from packages/common/src/string.ts (M11-006, ADR-007 shared/ layout).+// Moved from packages/common/src/string.ts (ADR-007 shared/ layout).export function stripTrailingSlash(url: string) {return url.replace(/\/+$/, '');diff --git a/packages/shared/src/url.ts b/packages/shared/src/url.tsindex da421ec66..77b8077f0 100644--- a/packages/shared/src/url.ts+++ b/packages/shared/src/url.ts@@ -1,4 +1,4 @@-// Moved from packages/common/src/url.ts (M11-006, ADR-007 shared/ layout).+// Moved from packages/common/src/url.ts (ADR-007 shared/ layout).export function parseSearchParams(params: URLSearchParams): Record<string, string> | undefined {diff --git a/self-hosting/quiz.ts b/self-hosting/quiz.tsindex ced6b5b74..1e4f93b7e 100644--- a/self-hosting/quiz.ts+++ b/self-hosting/quiz.ts@@ -6,10 +6,9 @@ import bcrypt from 'bcrypt';import inquirer from 'inquirer';import yaml from 'js-yaml';-// Cloud runs 24 (docs/ANSWERS.md §1.1). Override by exporting-// KAFKA_EVENTS_TOPIC_PARTITIONS before running ./setup — see the footgun-// warning in redpanda/bootstrap.template.yaml before changing this after-// first boot.+// Cloud runs 24. Override by exporting KAFKA_EVENTS_TOPIC_PARTITIONS before+// running./setup — see the footgun warning in redpanda/bootstrap.template.yaml+// before changing this after first boot.const KAFKA_EVENTS_TOPIC_PARTITIONS_DEFAULT = 24;const KAFKA_EVENTS_TOPIC_PARTITIONS =process.env.KAFKA_EVENTS_TOPIC_PARTITIONS ||diff --git a/tooling/codemods/p11-codemod.ts b/tooling/codemods/p11-codemod.tsindex 2df895581..831e89d66 100644--- a/tooling/codemods/p11-codemod.ts+++ b/tooling/codemods/p11-codemod.ts@@ -1,22 +1,20 @@/**- * P11 (ADR-008): repoint importers of the four dissolving packages- * — @openpanel/validation, @openpanel/constants, @openpanel/common,- * @openpanel/json — at the targets recorded in ./p11-map.json.+ * P11: repoint importers of the four dissolving packages —+ * @openpanel/validation, @openpanel/constants, @openpanel/common,+ * @openpanel/json — at the targets recorded in./p11-map.json.** The map is the single source of truth and is the JSON block of* docs/P11_DISSOLUTION_MAP.md verbatim. A row's `to` is the default target;* `toByConsumer[<workspace>]` overrides it for one workspace.*- * Three things it does that a sed cannot:- * - one import statement fans out to several targets (packages/db/src/types.ts- * splits eight ways), so statements are regrouped by target;- * - per-symbol `type` keywords are preserved exactly as written. A `type`- * keyword can sit on a runtime binding used only in `z.infer<typeof x>`;- * dropping it promotes an erased import into a real one and changes the- * bundle (ADR-008 risk 4);- * - a named re-export (`export { X } from '@openpanel/validation'`) is- * rewritten the same way an import is — same clause grammar, same- * per-symbol targets.+ * Three things it does that a sed cannot: - one import statement fans out to+ * several targets (packages/db/src/types.ts splits eight ways), so statements+ * are regrouped by target; - per-symbol `type` keywords are preserved exactly+ * as written. A `type` keyword can sit on a runtime binding used only in+ * `z.infer<typeof x>`; dropping it promotes an erased import into a real one+ * and changes the bundle (ADR-008 risk 4); - a named re-export (`export { X }+ * from '@openpanel/validation'`) is rewritten the same way an import is — same+ * clause grammar, same per-symbol targets.** Idempotent: a rewritten specifier no longer matches DYING, so a second run* over the same files changes nothing.diff --git a/tooling/gates/conformance/cli.ts b/tooling/gates/conformance/cli.tsindex b23b33990..e788d2480 100644--- a/tooling/gates/conformance/cli.ts+++ b/tooling/gates/conformance/cli.ts@@ -1,10 +1,10 @@/*** Assembles every ADR-022 check into one report and decides --assert.*- * Output contract (docs/CONFORMANCE_GATE_SPEC.md, "Output shape"): one block per- * rule, offenders as `file:line`, a TOTAL line per rule and one overall, stable- * ordering and no timestamps in the body — so the fix wave proves a rule reached- * zero by diffing two reports.+ * Output contract (docs/CONFORMANCE_GATE_SPEC.md, "Output shape"): one block+ * per rule, offenders as `file:line`, a TOTAL line per rule and one overall,+ * stable ordering and no timestamps in the body — so the fix wave proves a rule+ * reached zero by diffing two reports.*/import { readFileSync } from 'node:fs';diff --git a/tooling/gates/conformance/conformance.constants.ts b/tooling/gates/conformance/conformance.constants.tsindex 2b90eb7b0..12e320804 100644--- a/tooling/gates/conformance/conformance.constants.ts+++ b/tooling/gates/conformance/conformance.constants.ts@@ -39,9 +39,9 @@ export const SANCTIONED_CREATE_SERVICES_SITES: readonly string[] = [/*** R6 — the asset-loader carve-out, and the reason for each entry.*- * ADR-022: "Lazy-load assets, never dependencies." Reading a file or a row on- * first use is data loading and is legal; lazily importing a sibling service or- * a db/ch/redis handle the caller was already handed is the defect the rule+ * "Lazy-load assets, never dependencies." Reading a file or a row on first use+ * is data loading and is legal; lazily importing a sibling service or a+ * db/ch/redis handle the caller was already handed is the defect the rule* exists to remove.** This is an ALLOWLIST of exact `file::function` pairs, deliberately NOT a@@ -55,7 +55,7 @@ export const ASSET_LOADER_ALLOWLIST: readonly {functionName: string;reason: string;}[] = [- // geo.ts reads a MaxMind .mmdb file from disk on first use. That is an ASSET+ // Geo.ts reads a MaxMind.mmdb file from disk on first use. That is an ASSET// load: no sibling service, no db/ch/redis handle, nothing the caller already// holds. ADR-022 names it as one of the two legitimate cases.{@@ -64,7 +64,7 @@ export const ASSET_LOADER_ALLOWLIST: readonly {reason:'reads a MaxMind .mmdb file from disk on first use - an asset, not a dependency',},- // flush-exports.ts reads an export cursor ROW on first use. Also data, and it+ // Flush-exports.ts reads an export cursor ROW on first use. Also data, and it// reads it through the db handle it was already handed rather than importing// one. ADR-022 names it as the second legitimate case.{diff --git a/tooling/gates/conformance/cruiser.ts b/tooling/gates/conformance/cruiser.tsindex b0e4835f8..c234c60f5 100644--- a/tooling/gates/conformance/cruiser.ts+++ b/tooling/gates/conformance/cruiser.ts@@ -1,10 +1,10 @@/*** R12 and R22 are delegated to dependency-cruiser, not reimplemented here.*- * M14-002 made `dependency-cruiser` a declared root devDependency, verified that- * it resolves its optional `typescript` peer (the 82-false-violation failure- * ADR-022 made R22 conditional on), and landed the layer rules in- * .dependency-cruiser.cjs. So this module runs the cruise and reports its+ * Made `dependency-cruiser` a declared root devDependency, verified that it+ * resolves its optional `typescript` peer (the 82-false-violation failure+ * ADR-022 made R22 conditional on), and landed the layer rules+ * in.dependency-cruiser.cjs. So this module runs the cruise and reports its* per-rule violation counts. ADR-022's layer-aware fallback in this gate is not* in play; a bare `../` depth grep is forbidden either way, because a module* importing `defineJob` at `../../jobs/define` is importing DOWNWARD.diff --git a/tooling/gates/conformance/rules.ts b/tooling/gates/conformance/rules.tsindex eaffde16d..db0bcaeff 100644--- a/tooling/gates/conformance/rules.ts+++ b/tooling/gates/conformance/rules.ts@@ -8,18 +8,17 @@** Where a grep would lie, the check walks the TypeScript AST:*- * R3 a factory signature can span lines, so the argument list is not on the- * `export function` line. `rg 'create[A-Za-z]+Service\(deps'` saw 28 of- * 36 on 2026-09-08.- * R5 `ReturnType<typeof create` appears once in services.ts and the match is- * a COMMENT (services.ts:154) explaining the circularity rule. The- * pattern is applied in code zero times.- * R6 `createServices(` in a comment or a string is not a call site.- * R7 `rg 'process\.env\.'` both over- and under-counts: rpc/base.ts:246 is a- * comment saying core reads no process.env, and get-client-ip.ts:83 is a- * real read written `process.env?.` that the pattern misses.- * R15 `new Redis(` inside a factory body is exactly what core is supposed to- * do; at module scope it is the violation. Only scope tells them apart.+ * R3 a factory signature can span lines, so the argument list is not on the+ * `export function` line. `rg 'create[A-Za-z]+Service\(deps'` saw 28 of 36 on+ * 2026-09-08. R5 `ReturnType<typeof create` appears once in services.ts and the+ * match is a COMMENT (services.ts:154) explaining the circularity rule. The+ * pattern is applied in code zero times. R6 `createServices(` in a comment or a+ * string is not a call site. R7 `rg 'process\.env\.'` both over- and+ * under-counts: rpc/base.ts:246 is a comment saying core reads no process.env,+ * and get-client-ip.ts:83 is a real read written `process.env?.` that the+ * pattern misses. R15 `new Redis(` inside a factory body is exactly what core+ * is supposed to do; at module scope it is the violation. Only scope tells them+ * apart.*/import { existsSync, readFileSync } from 'node:fs';@@ -506,8 +505,8 @@ export function checkResidue(files: ResidueScanInput[]): Metric[] {}// ADR-022's baseline states NEXT_PUBLIC_ for packages/core/src on its own- // (10 across 10 files); the rest of the tree is a second, wider metric. Both- // are asserted, so splitting them costs nothing and keeps the baseline+ // (10 across 10 files); the rest of the tree is a second, wider metric.+ // Both are asserted, so splitting them costs nothing and keeps the baseline// number reproducible line-for-line.if (pattern.source.includes(NEXT_PUBLIC_PREFIX)) {const inCore = offenders.filter((offender) =>diff --git a/tooling/scripts/pin-from-pnpm-lock.ts b/tooling/scripts/pin-from-pnpm-lock.tsindex 6eca298fa..24e2456ef 100644--- a/tooling/scripts/pin-from-pnpm-lock.ts+++ b/tooling/scripts/pin-from-pnpm-lock.ts@@ -1,50 +1,48 @@#!/usr/bin/env bun/**- * P13 groundwork (ADR-014): pin every declared range to the version- * `pnpm-lock.yaml` already resolved for it.+ * P13 groundwork: pin every declared range to the version `pnpm-lock.yaml`+ * already resolved for it.*- * ADR-014's stop rule ends P13 the moment a pin cannot be reproduced under- * bun, and bun 1.4.0 cannot read `pnpm-lock.yaml` — it re-resolves the whole- * graph from the declared ranges. A caret in a manifest is therefore an- * instruction to a resolver we are about to replace. Writing the resolved- * version into the manifest turns each range into a fact the next installer- * has to reproduce rather than a question it gets to answer.+ * ADR-014's stop rule ends P13 the moment a pin cannot be reproduced under bun,+ * and bun 1.4.0 cannot read `pnpm-lock.yaml` — it re-resolves the whole graph+ * from the declared ranges. A caret in a manifest is therefore an instruction+ * to a resolver we are about to replace. Writing the resolved version into the+ * manifest turns each range into a fact the next installer has to reproduce+ * rather than a question it gets to answer.*- * For every workspace importer in the lock this rewrites each- * `dependencies` / `devDependencies` / `optionalDependencies` range in that- * importer's package.json to the EXACT version the lock resolved FOR THAT- * IMPORTER, pins every `catalog:` entry in `pnpm-workspace.yaml` the same way,- * and carries the identical values into the lock's own `specifier:` fields so- * the tree stays installable with `--frozen-lockfile`.+ * For every workspace importer in the lock this rewrites each `dependencies` /+ * `devDependencies` / `optionalDependencies` range in that importer's+ * package.json to the EXACT version the lock resolved FOR THAT IMPORTER, pins+ * every `catalog:` entry in `pnpm-workspace.yaml` the same way, and carries the+ * identical values into the lock's own `specifier:` fields so the tree stays+ * installable with `--frozen-lockfile`.*- * Left alone, deliberately:- * - `workspace:` / `catalog:` / `npm:` specifiers, which name a resolution- * strategy rather than a range;- * - `peerDependencies`, which are compatibility contracts (pnpm's- * `autoInstallPeers: true` lists them under an importer's `dependencies`- * in the lock even though the manifest declares them as peers);- * - the two stale `prisma: ^5.1.1` devDeps ADR-017 rule 2 carves out by path- * (see ADR_017_RULE_2_FROZEN below);- * - every `version:` field in the lock. NOT ONE RESOLUTION MOVES.+ * Left alone, deliberately: - `workspace:` / `catalog:` / `npm:` specifiers,+ * which name a resolution strategy rather than a range; - `peerDependencies`,+ * which are compatibility contracts (pnpm's `autoInstallPeers: true` lists them+ * under an importer's `dependencies` in the lock even though the manifest+ * declares them as peers); - the two stale `prisma: ^5.1.1` devDeps ADR-017+ * rule 2 carves out by path (see ADR_017_RULE_2_FROZEN below); - every+ * `version:` field in the lock. NOT ONE RESOLUTION MOVES.*- * Why the lock's specifiers are rewritten here instead of by `pnpm install`:- * a non-frozen `pnpm install` re-resolves the whole graph and dedupes it. On- * this tree, on 2026-09-07, that pruned 142 package versions across 135- * package names and added none — `@babel/core` collapsing from four copies to- * two, `magicast` from three to two — which is real resolution movement in the- * same commit that is supposed to prove nothing moved. Rewriting the specifier+ * Why the lock's specifiers are rewritten here instead of by `pnpm install`: a+ * non-frozen `pnpm install` re-resolves the whole graph and dedupes it. On this+ * tree, on 2026-09-07, that pruned 142 package versions across 135 package+ * names and added none — `@babel/core` collapsing from four copies to two,+ * `magicast` from three to two — which is real resolution movement in the same+ * commit that is supposed to prove nothing moved. Rewriting the specifier* fields is the mechanical, resolution-preserving half of what that install* would do; `pnpm install --frozen-lockfile` then verifies the result is- * consistent. The full measurement is in- * docs/BUN_INSTALL_RECIPE.md § Why the lock is edited, not refreshed.+ * consistent. The full measurement is in docs/BUN_INSTALL_RECIPE.md § Why the+ * lock is edited, not refreshed.** Edits are surgical — only the value on a matched line is replaced — so key* order, indentation and every comment survive byte-for-byte, and nothing is* written when a file would be unchanged. That is what makes a second run a* no-op.*- * bun run tooling/scripts/pin-from-pnpm-lock.ts- * bun run tooling/scripts/pin-from-pnpm-lock.ts --check # exit 1 if stale+ * Bun run tooling/scripts/pin-from-pnpm-lock.ts bun run+ * tooling/scripts/pin-from-pnpm-lock.ts --check # exit 1 if stale*/import { write, YAML } from 'bun';@@ -69,12 +67,12 @@ const PROTOCOL_SPECIFIER = /^(workspace|catalog|npm|link|file|git|github):/;const PLAIN_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/;/**- * ADR-017 rule 2 (ACCEPTED) names these two lines by path and rules that the- * stale `prisma: ^5.1.1` devDeps "are to be **deleted, not aligned to 6.14**" —- * i.e. touching their version is itself the wrong move, and the deletion belongs- * to a CLEAN task. Pinning them to the 5.9.1 the lock resolved would be exactly- * the aligning edit the ADR forbids, so the pinner leaves the manifest entry AND- * its `specifier:` in the lock alone. Rule 3 is the general P13 pinning+ * Rule 2 (ACCEPTED) names these two lines by path and rules that the stale+ * `prisma: ^5.1.1` devDeps "are to be **deleted, not aligned to 6.14**" — i.e.+ * touching their version is itself the wrong move, and the deletion belongs to+ * a CLEAN task. Pinning them to the 5.9.1 the lock resolved would be exactly+ * the aligning edit the ADR forbids, so the pinner leaves the manifest entry+ * AND its `specifier:` in the lock alone. Rule 3 is the general P13 pinning* permission; rule 2 is a specific, named exception to it.*/const ADR_017_RULE_2_FROZEN: ReadonlySet<string> = new Set([diff --git a/tooling/scripts/write-p13-lock-snapshot.ts b/tooling/scripts/write-p13-lock-snapshot.tsindex f69cddf05..247c7db6e 100644--- a/tooling/scripts/write-p13-lock-snapshot.ts+++ b/tooling/scripts/write-p13-lock-snapshot.ts@@ -4,23 +4,22 @@** The snapshot is the reference `tooling/gates/p13-drift.sh` compares an* installed tree against. It exists as a separate committed file because- * M13-002 DELETES `pnpm-lock.yaml`: once the lock is gone there is nothing- * left to say what pnpm had resolved, and "did the installer swap move- * anything?" becomes unanswerable. This file outlives the lock.+ * M13-002 DELETES `pnpm-lock.yaml`: once the lock is gone there is nothing left+ * to say what pnpm had resolved, and "did the installer swap move anything?"+ * becomes unanswerable. This file outlives the lock.*- * Shape:- * { "<importer path>": { "<dependency>": "<exact version>" } }+ * Shape: { "<importer path>": { "<dependency>": "<exact version>" } }** Every direct dependency of every workspace importer — `dependencies`,* `devDependencies` and `optionalDependencies` alike, registry copies and* `workspace:` links alike. Links are recorded at the linked package's own* `version`, which is what a correctly-linked `node_modules/<dep>/package.json`* reports; that is deliberate, because a resolver silently preferring the- * REGISTRY copy of a workspace package over the local one is a real hazard- * here (`apps/start` depends on `@openpanel/[email protected]` from npm while the- * workspace source is 1.4.1-local) and the gate should see it.+ * REGISTRY copy of a workspace package over the local one is a real hazard here+ * (`apps/start` depends on `@openpanel/[email protected]` from npm while the workspace+ * source is 1.4.1-local) and the gate should see it.*- * bun run tooling/scripts/write-p13-lock-snapshot.ts+ * Bun run tooling/scripts/write-p13-lock-snapshot.ts*/import { file, write, YAML } from 'bun';diff --git a/vitest.workspace.ts b/vitest.workspace.tsindex 80eaaadbd..d89907da3 100644--- a/vitest.workspace.ts+++ b/vitest.workspace.ts@@ -1,17 +1,15 @@/*** The workspaces that still run on vitest.*- * M12-011 moved `packages/core`, `packages/db` and `apps/api` onto `bun test`- * (ADR-010) and gave `apps/start` its own vitest config and `test` script, so- * all four run from their own package. What is left here is the two suites- * that have never had a `test` script or a `vitest` devDependency of their own- * and only ever ran because the previous glob was `packages/*`:- * `packages/redis/cachable.test.ts` (29 tests) and- * `packages/payments/src/subscription-state.test.ts` (35 tests).+ * Moved `packages/core`, `packages/db` and `apps/api` onto `bun test` and gave+ * `apps/start` its own vitest config and `test` script, so all four run from+ * their own package. What is left here is the two suites that have never had a+ * `test` script or a `vitest` devDependency of their own and only ever ran+ * because the previous glob was `packages/*`: `packages/redis/cachable.test.ts`+ * (29 tests) and `packages/payments/src/subscription-state.test.ts` (35 tests).*- * Both are outside M12-011's scope. This is an explicit list rather than a- * glob so that a new package does not silently join the vitest side of the- * split — the direction of travel is `bun test` (see docs/TECH_DEBT.md,- * "Test split (M12-011)").+ * Both are outside M12-011's scope. This is an explicit list rather than a glob+ * so that a new package does not silently join the vitest side of the split —+ * the direction of travel is `bun test` ("Test split").*/export default ['packages/redis', 'packages/payments'];