OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
chore: trim comments in tooling, CI, Docker and scripts
Carl-Gerhard Lindesvärdf5c8ceb5f3d9
diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjsindex fb449c5a5..e90022da0 100644--- a/.dependency-cruiser.cjs+++ b/.dependency-cruiser.cjs@@ -1,129 +1,34 @@'use strict';/**- * ADR-008 (constants isomorphism) and ADR-022 R22 (layers only import downward)- * enforcement. See decisions/ADR-008-constants.md and- * decisions/ADR-022-core-conventions.md in the controller repo.- *- * The rules, in the order they appear below:- * - core-uses-ctx-not-db-internals: packages/core reaches Postgres/ClickHouse- * through ctx.db / ctx.ch, never by acquiring its own client.- * - core-no-self-barrel: a file under packages/core/src imports its siblings- * relatively, never through @openpanel/core.- * - core-layers-*: ADR-022 R22, one rule per layer boundary (see below).- * - constants-stay-isomorphic: a `*.constants.ts` file may depend on nothing- * but zod, another `*.constants.ts` file, or a type-only specifier.- * - frontend-values-only-constants: a web app (apps/start, apps/public,- * packages/sdks/*) may only VALUE-import @openpanel/core or @openpanel/db- * through a `*.constants.ts` path.- * - shared-root-stays-isomorphic: nothing reachable from @openpanel/shared's- * root entrypoint imports a node: builtin or the server/ subtree.+ * Architecture enforcement: constants stay isomorphic, layers only import downward, web bundles never reach+ * server code. Rules, in order below:+ * - core-uses-ctx-not-db-internals: packages/core reaches Postgres/ClickHouse through ctx.db / ctx.ch.+ * - core-no-self-barrel: a file under packages/core/src imports its siblings relatively, never via @openpanel/core.+ * - core-layers-*: one rule per layer boundary.+ * - constants-stay-isomorphic: a `*.constants.ts` file depends on nothing but zod, another constants file or a+ * type-only specifier.+ * - frontend-values-only-constants: a web app (apps/start, apps/public, packages/sdks/*) may only VALUE-import+ * @openpanel/core or @openpanel/db through a `*.constants.ts` path.+ * - shared-root-stays-isomorphic: nothing reachable from @openpanel/shared's root imports a node: builtin or server/.* - no-web-to-server: a web app may not import @openpanel/shared/server.*- * Both rules match by filename pattern, not by a hardcoded package.json- * "exists" check, so they hold vacuously (0 matches, exit 0) today, while- * `packages/core` does not exist yet, and start firing the moment the first- * `*.constants.ts` file (or a stray value-import of one) lands.- *- * ADR-008 Benchmark 1 ("prove dependency-cruiser resolves @openpanel/*, both- * rules must FAIL on a deliberate violation"), rerun 2026-09-01 with fixtures- * placed in `packages/trpc` (a real package that already depends on zod,- * date-fns AND @openpanel/db, so resolution is real, not the couldNotResolve- * fallback — see the two review notes below for why that distinction matters)- * plus `apps/start`:- *- * Fixture A: packages/trpc/src/__dc_fixture__/tmp.constants.ts- * import { formatISO } from 'date-fns'; // real npm package- * export const TMP_FIXTURE_TIMESTAMP = formatISO(new Date());- *- * Fixture B: apps/start/src/__dc_fixture__.ts- * import { db } from '@openpanel/db';- * export const tmpDb = db;- *- * $ pnpm run check:deps- * error frontend-values-only-constants: apps/start/src/__dc_fixture__.ts → packages/db/index.ts- * error constants-stay-isomorphic: packages/trpc/src/__dc_fixture__/tmp.constants.ts → node_modules/.pnpm/[email protected]/node_modules/date-fns/index.js- * x 2 dependency violations (2 errors, 0 warnings). 1684 modules, 6462 dependencies cruised.- * (exit 2)- *- * The node:crypto builtin case (no node_modules involved at all) was checked- * too, as a regression guard, and also fires:- *- * error constants-stay-isomorphic: packages/trpc/src/__dc_fixture__/tmp.constants.ts → crypto+ * Do NOT set `options.exclude: { path: 'node_modules' }`: it drops every npm dependency before the rules run, so+ * constants-stay-isomorphic would only catch builtins. The zod allow-list entry matches the RESOLVED path, not+ * the bare specifier, because `path` conditions match against `resolved`.*- * The allow-list side was checked in the same location: a constants file- * importing zod, a sibling `*.constants.ts`, and an `import type { ... } from- * '@openpanel/db'` together produced zero violations. All fixtures were then- * deleted (never committed) and the run went green:- *- * $ pnpm run check:deps- * ✔ no dependency violations found (1681 modules, 6460 dependencies cruised)- * (exit 0)- *- * Two things this rerun corrects from the first pass at this task, both- * caught by choosing a fixture location where resolution actually succeeds- * instead of one where it silently fails closed:- *- * 1. `options.exclude: { path: 'node_modules' }` must NOT be set (see the- * comment on `doNotFollow` below) — with it, dependency-cruiser drops- * every real npm-package dependency (zod, date-fns, …) out of- * getDependencies() before any rule runs, because they resolve through- * pnpm's `.pnpm/.../node_modules/...` store layout. constants-stay-isomorphic- * would then only ever catch node:crypto-style builtin violations, never- * the npm-package case ADR-008 Risk #6 names. The very first fixture- * attempt used `packages/common` (a package that declares neither zod- * nor @openpanel/db as a dependency), so both imports failed to resolve- * for the unrelated reason of not being installed there, fell back to- * the raw specifier string, and coincidentally still matched the- * `exclude`-broken config — hiding the bug instead of catching it.- * 2. The zod allow-list entry must match the *resolved* path- * (`(^|/)node_modules/zod/`), not the bare specifier (`^zod$`). `path`- * conditions match against `resolved`, and once zod actually resolves- * that's a real file path, never the literal string "zod" — `^zod$`- * only ever matched the couldNotResolve fallback, which is the same- * wrong-package artifact as point 1, not a legitimate isomorphic import.- *- * Resolution across the real `@openpanel/db` workspace symlink (not just the- * `packages/trpc` fixture) was also exercised for free: apps/start already- * has dozens of `import type { ... } from '@openpanel/db'` sites today, all- * type-only, and all correctly passed by `dependencyTypesNot: ['type-only']`- * — i.e. resolution AND type-only detection both work, ADR-008 risk 1 does- * not apply, Option A (deep paths + this config) stands.- *- * `check:deps` runs the DECLARED `dependency-cruiser` devDependency- * (M14-002; ADR-017's exception register reopened after P13, Carl 2026-09-08),- * replacing `tooling/scripts/check-deps.ts`, which existed only because neither- * `bunx` nor `pnpm dlx` could be relied on to put `typescript` where the tool- * looks for it. dependency-cruiser classifies an edge as `type-only` only when- * it can load the TypeScript compiler, and it resolves `typescript` — its own- * optional peer — from ITS OWN directory, an ESM lookup `NODE_PATH` cannot- * influence. Under `bunx` that failed: `depcruise --info` reported- * `typescript … -`, and the cruise returned 82 false- * `core-uses-ctx-not-db-internals` violations, every one an `import type` line- * the rule explicitly allows.- *- * Measured on this box on 2026-09-08, with the tool declared and- * `bunfig.toml`'s `linker = "isolated"` in force: `bunx --no-install depcruise- * --info` reports `✔ typescript >=2.0.0 <7.0.0 [email protected]`, and the- * cruise reproduces the runner's numbers exactly — 2700 modules, 18121- * dependencies, 0 errors. The isolated layout is WHY it works: bun's store- * lives at `node_modules/.bun/` INSIDE the repo, so node's upward walk from- * `node_modules/.bun/[email protected]/node_modules/dependency-cruiser`- * still reaches the repo root `node_modules/typescript`. A global `bunx` cache- * directory never could.+ * `check:deps` runs the declared `dependency-cruiser` devDependency, not `bunx`: it classifies an edge as+ * type-only only when it can load `typescript` from its own directory, and under `bunx` it could not, producing+ * false `core-uses-ctx-not-db-internals` violations on every `import type`. bun's isolated linker keeps the store+ * inside the repo, so the lookup reaches the root `node_modules/typescript`.*/-// ADR-022 R22 — layers only import downward. The order, lowest first:+// Layers only import downward. The order, lowest first://// shared < clients < transport infrastructure (rpc/, http/, jobs/)// < modules < services.ts < registries < index.ts//-// It is a LAYER order, not path depth: a module importing `../../jobs/define`-// is going DOWN, and must not be flagged. rpc/, http/ and jobs/ are ONE layer-// (rpc/base.ts, http/define.ts and jobs/define.ts are peers), so edges among-// them are sideways, not up. Cross-module edges are likewise sideways — every-// module is the same layer — so they are out of R22's scope; R1/R3 own those.-//-// One dependency-cruiser rule is a single from × to rectangle, and "every layer-// may import every LOWER layer" is a triangle, so R22 lands as one rule per+// It is a LAYER order, not path depth: a module importing `../../jobs/define` is going DOWN. rpc/, http/ and jobs/ are ONE+// layer, so edges among them are sideways, as are cross-module edges. A dependency-cruiser rule is one from x to+// rectangle while "every layer may import every lower layer" is a triangle, hence one rule per layer boundary.// layer boundary. All six share the `core-layers-` prefix and this comment.const R22_COMMENT ='ADR-022 R22: layers only import downward — shared < clients < transport ' +@@ -145,9 +50,7 @@ const R22_COMMENT ='macro instead of imported by it, and the two registry reads moved into the ' +'registry. A rule that fires is the only durable fix.';-// ADR-022 R12/R21 — the web tier: everything that ends up in a browser bundle.-// apps/public and packages/sdks/* joined apps/start in M15-010; before that-// only apps/start was named, so R12 was unguarded for the other two.+// The web tier: everything that ends up in a browser bundle.const FRONTENDS = '^(apps/(start|public)|packages/sdks/)';// The composition root and everything above it.@@ -288,14 +191,9 @@ module.exports = {},to: {path: COMPOSITION_AND_ABOVE,- // R8 blesses `<name>.constants.ts` as the one file that may be imported- // as a VALUE across a boundary, so a module reaching one is never a- // layering violation.+ // `<name>.constants.ts` is the one file that may be imported as a VALUE across a boundary.pathNot: '\\.constants\\.ts$',- // R3 REQUIRES this edge: every one of the 36 factories is- // `createXService(deps: ServiceDeps, services: () => Services)`, and- // both names live in services.ts. All 47 such imports in the tree today- // are `import type`, which is what keeps the edge type-only and legal.+ // Every service factory takes `(deps: ServiceDeps, services: () => Services)`, both names from services.ts: those imports must stay type-only.dependencyTypesNot: ['type-only'],},},@@ -326,11 +224,7 @@ module.exports = {from: { path: '\\.constants\\.ts$' },to: {// zod is matched by resolved path, not the raw specifier: once- // pnpm actually resolves it (package declares it as a dependency),- // `resolved` is a real file under `node_modules/(.pnpm/.../)?zod/`,- // never the bare string "zod" — `^zod$` only ever matched the- // fallback value dependency-cruiser uses when resolution fails- // entirely, which isn't the case ADR-008 needs covered here.+ // Matched by resolved path: `^zod$` only matched the fallback dependency-cruiser uses when resolution fails.pathNot: ['\\.constants\\.ts$', '(^|/)node_modules/zod/'],dependencyTypesNot: ['type-only'],},@@ -395,7 +289,7 @@ module.exports = {// Only stops the crawl from recursing INTO node_modules (so we don't// cruise zod/date-fns internals); it still leaves the edge FROM our file// TO the npm package in that file's dependency list, so rules still see- // it. Do NOT add `options.exclude` here — see header comment point 1.+ // it. Do NOT add `options.exclude` here — see the header.doNotFollow: { path: 'node_modules' },tsPreCompilationDeps: true,enhancedResolveOptions: {diff --git a/.github/smoke/docker-compose.yml b/.github/smoke/docker-compose.ymlindex 532871936..efbd3d497 100644--- a/.github/smoke/docker-compose.yml+++ b/.github/smoke/docker-compose.yml@@ -142,9 +142,7 @@ services:op-api:condition: service_healthy- # M9-003 deleted apps/worker: the worker role is the SAME image as the api,- # run as ROLE=worker (apps/api/Dockerfile's CMD picks the half). There is no- # separate worker image to resolve any more.+ # The worker role is the same image as the api, run as ROLE=worker (apps/api/Dockerfile's CMD picks the half).op-worker:image: ${OP_API_IMAGE:-openpanel-smoke-image-unset}ports:@@ -152,8 +150,7 @@ services:environment:<<: *app_envROLE: worker- # V2 serves /healthz/ready, not V1's deep /healthcheck (that one lands with- # the real clients at M9-004). Same probe the controller's boot harness uses.+ # The api serves /healthz/ready.healthcheck:test: ["CMD-SHELL", "curl -f http://localhost:3000/healthz/ready || exit 1"]interval: 5sdiff --git a/.github/smoke/smoke.sh b/.github/smoke/smoke.shindex 2c8b94fae..579347191 100755--- a/.github/smoke/smoke.sh+++ b/.github/smoke/smoke.sh@@ -1,8 +1,7 @@#!/usr/bin/env bash## Boots the app images against real Postgres/Redis/ClickHouse and asserts they-# actually serve traffic. Two images, three services: since M9-003 the worker-# is the api image run as ROLE=worker.+# actually serve traffic. Two images, three services: the worker is the api image run as ROLE=worker.## Why this exists: main-8e60 built green, pushed green, and every dashboard# route returned 500 (`r.createEffectfulFunction is not a function`) because a@@ -84,8 +83,7 @@ assert_ssr_route() {# The api container's start command runs `prisma migrate deploy` before it# boots, and `sh -c` does not stop on a failed line — so a broken migration# step is invisible: the api starts anyway and every probe stays green. That is-# exactly how the rewrite shipped an image whose start command could not find-# the Prisma CLI at all. Assert the step's own success line instead.+# exactly how an image whose start command could not find the Prisma CLI once shipped. Assert the step's own success line instead.assert_migrations_ran() {local logslogs=$(docker compose logs --no-color op-api 2>/dev/null || true)diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.ymlindex 65595e6c6..dd42504a3 100644--- a/.github/workflows/docker-build.yml+++ b/.github/workflows/docker-build.yml@@ -87,9 +87,8 @@ jobs:- name: Install bunuses: oven-sh/setup-bun@v2with:- # .bun-version is the pin's home (ADR-016 rule 5) and- # apps/api/src/config/bun-version.test.ts asserts an exact match, so read- # it rather than keeping a second copy here.+ # .bun-version is the pin's home and apps/api/src/config/bun-version.test.ts asserts an exact match, so read it+ # rather than keeping a second copy here.bun-version-file: ".bun-version"- name: Setup bun cache@@ -106,20 +105,16 @@ jobs:- name: Codegenrun: bun run codegen- # Formatting and import order only. `bun run lint` (the full rule set) still- # reports 595 errors / 45 warnings, ~328 of which need a human decision, so- # it is not a gate yet; this half is green and catches drift today.+ # Formatting and import order only. `bun run lint` (the full rule set) still reports errors that need a human+ # decision, so it is not a gate yet; this half is green and catches drift today.- name: Check formattingrun: bun run lint:format- name: Run TypeScript checksrun: bun run typecheck- # ADR-008: dependency-cruiser is the second layer keeping the dissolved- # validation/constants/common/json packages from growing back (M11-009).- # Run standalone, not via `bun run check`, so a lint error cannot mask a- # dependency-boundary break: `check` is `ultracite check && check:deps`, and- # the full rule set is not green yet (see the formatting step above).+ # dependency-cruiser keeps the dissolved validation/constants/common/json packages from growing back. Run standalone,+ # not via `bun run check`, so a lint error cannot mask a dependency-boundary break.- name: Check dependency boundariesrun: bun run check:deps@@ -135,12 +130,9 @@ jobs:CLICKHOUSE_URL: http://localhost:23123/openpanelSELF_HOSTED: "true"- # No env block, deliberately. Every workspace's test preload pins- # DATABASE_URL / CLICKHOUSE_URL / REDIS_URL itself and creates and migrates- # the isolated `openpanel_test` databases (test/bun-preload.ts,- # packages/core/test/preload.ts). Env set here would be silently overwritten,- # which is how the old 5432/8123 block came to look correct while every- # database-backed test failed.+ # No env block, deliberately. Every workspace's test preload pins DATABASE_URL / CLICKHOUSE_URL / REDIS_URL itself and+ # creates and migrates the isolated `openpanel_test` databases (test/bun-preload.ts, packages/core/test/preload.ts).+ # Env set here would be silently overwritten.- name: Run testsrun: bun run testdiff --git a/apps/api/Dockerfile b/apps/api/Dockerfileindex ee08bd466..5acdb2966 100644--- a/apps/api/Dockerfile+++ b/apps/api/Dockerfile@@ -1,30 +1,14 @@-# API image — one image, two roles (ROLE=api | worker | all).+# API image — one image, two roles (ROLE=api, worker or all).#-# Rewritten for M15-203 against the per-layer measurements in-# docs/DOCKER_SLIMMING.md (M14-203). Every cut below is one that document-# measured AND boot-tested; nothing it did not measure is attempted, and its-# "not worth it" list (§9) is treated as binding — the geo databases stay-# baked in, `netcat-openbsd` stays, the api's openssl/libssl3 security upgrade-# stays, and the base image is not up for discussion (see below).-#-# ADR-016 pins Bun exactly at 1.4.0 (floor >=1.2.23). Its declared home is-# `.bun-version` + this ARG; the file does not exist in the tree yet, so this-# ARG is the single home until it does. Keep the two in sync when it lands.+# Bun is pinned exactly; keep this ARG in sync with `.bun-version`.ARG BUN_VERSION=1.4.0-# BASE — oven/bun:${BUN_VERSION}-slim. DECIDED, not re-evaluated: Carl closed-# alpine and distroless on 2026-09-08 ("fuck it, lets keep slim"). Distroless-# has no shell and all three shipped compose files start this image with-# `sh -c "…"`; alpine is musl against a `debian-openssl-3.0.x` Prisma engine.+# BASE — oven/bun:${BUN_VERSION}-slim. Not distroless (no shell, and the compose files start this image with+# `sh -c "…"`) and not alpine (musl against a `debian-openssl-3.0.x` Prisma engine).#-# The apt set is the one the running container needs, not the one the build-# needs: `curl` backs the CMD-SHELL HEALTHCHECKs in all three compose files and-# `netcat-openbsd` backs self-hosting/coolify.yml's `nc -z` wait loops, and-# both exec *inside* the container. `ca-certificates`, `openssl` and `libssl3`-# are already present in the base — naming them buys the Debian-Security-# upgrade of libssl3t64/openssl (measured: 3.5.6 -> 3.5.7, 3,416,908 B-# compressed). DOCKER_SLIMMING.md §8 row 4 files dropping them as a security-# decision for Carl, not a size one, and recommends keeping the upgrade.+# The apt set is what the running container needs: `curl` backs the compose HEALTHCHECKs and `netcat-openbsd` backs+# self-hosting/coolify.yml's `nc -z` wait loops, both exec inside the container. `ca-certificates`, `openssl` and+# `libssl3` are already in the base; naming them pulls the Debian-Security libssl3t64/openssl upgrade.FROM oven/bun:${BUN_VERSION}-slim AS baseRUN apt-get update && \@@ -37,25 +21,18 @@ RUN apt-get update && \&& apt-get clean && \rm -rf /var/lib/apt/lists/*-# TOOLCHAIN — the full workspace, installed once WITH devDependencies, because-# codegen needs them (core's `tar` for scripts/download-geo.ts, db's `prisma`-# CLI for schema generation). Neither this stage nor `build` ships.+# TOOLCHAIN — the full workspace, installed once WITH devDependencies, because codegen needs them (core's `tar` for+# scripts/download-geo.ts, db's `prisma` CLI for schema generation). Neither this stage nor `build` ships.#-# The whole tree is copied rather than a hand-maintained list of manifests:-# a workspace install has to see every member's `package.json` anyway, Docker's-# COPY cannot glob a directory level, and the old per-package list failed-# SILENTLY when it drifted (a missing manifest omitted a package from-# node_modules and surfaced as a runtime "Cannot find module").+# The whole tree is copied rather than a list of manifests: a workspace install has to see every member's+# `package.json`, Docker's COPY cannot glob a directory level, and a hand-maintained list failed SILENTLY when it+# drifted (a missing manifest surfaced as a runtime "Cannot find module").#-# `bunfig.toml` is copied with the tree on purpose: it carries-# `[install] ignoreScripts = true` (ADR-014 amendment 2 — no dependency build-# script has ever run in an image this repo ships) and `linker = "isolated"`.-# Both install lines name `--linker=isolated` explicitly anyway, so the layout-# is a property of the command and not only of a file.+# `bunfig.toml` is copied with the tree on purpose: it carries `[install] ignoreScripts = true` and+# `linker = "isolated"`. Both install lines name `--linker=isolated` too, so the layout is a property of the command.#-# No python3/make/g++: with `ignoreScripts` nothing compiles at install time,-# and the two native addons this image needs (@node-rs/argon2, sharp) resolve-# to prebuilt packages.+# No python3/make/g++: with `ignoreScripts` nothing compiles at install time, and the native addons this image needs+# (@node-rs/argon2, sharp) resolve to prebuilt packages.FROM base AS toolchainWORKDIR /app@@ -64,9 +41,8 @@ COPY . .RUN bun install --frozen-lockfile --linker=isolated-# BUILD — the Prisma client and core's geo/ASN data. No JS build step: ADR-010-# deleted the backend bundler with the V1 boot, so the only thing this stage-# produces is generated *source* under packages/, which `prod-deps` inherits.+# BUILD — the Prisma client and core's geo/ASN data. There is no JS build step: the only output is generated+# *source* under packages/, which `prod-deps` inherits.FROM toolchain AS buildARG DATABASE_URL@@ -74,50 +50,33 @@ ENV DATABASE_URL=$DATABASE_URLRUN bun run codegen-# PROD-DEPS — the node_modules that ships, and the only place anything is-# deleted. Derived from `build` so the generated output above survives, but-# with every node_modules directory removed first: a `--production` install-# must not be a filtered view of a devDependency-laden tree, it must be an-# install that was production-only from the start.+# PROD-DEPS — the node_modules that ships, and the only place anything is deleted. Derived from `build` so the+# generated output survives, with every node_modules removed first: a `--production` install must be production-only+# from the start, not a filtered view of a devDependency-laden tree.#-# `--filter '@openpanel/api'` is the closure boundary. Verified on Bun 1.4.0:-# it follows `workspace:` edges TRANSITIVELY (api -> core -> db ->-# redis/email/payments) and installs nothing outside them. It fails visibly-# rather than silently — a filter that matches nothing leaves the app unable to-# resolve its imports, and tooling/gates/p13-images.sh boots the image and-# asserts /healthz/ready before it passes.+# `--filter '@openpanel/api'` is the closure boundary: it follows `workspace:` edges transitively (api -> core -> db ->+# redis/email/payments) and installs nothing outside them. A filter that matches nothing leaves the app unable to+# resolve its imports, which tooling/gates/p13-images.sh catches by booting the image.FROM build AS prod-depsRUN find . -maxdepth 4 -type d -name node_modules -prune -exec rm -rf {} + && \bun install --production --frozen-lockfile --linker=isolated --filter '@openpanel/api'-# TRIM — the four measured, boot-tested cuts from DOCKER_SLIMMING.md's-# "What chore C6 should implement" list. They run HERE, in a build stage, and-# never in the runtime stage: deleting a file in the final stage adds a-# whiteout and makes the image LARGER (§9.3), so the only way a removal shrinks-# anything is for the bytes never to be COPYed forward.+# TRIM — cuts that run HERE, in a build stage, never in the runtime stage: deleting a file in the final stage adds a+# whiteout and makes the image LARGER, so a removal only shrinks anything if the bytes are never COPYed forward.#-# 1. The musl-only native store entries. The base is glibc, so a package-# whose name says `musl` is dead by construction on every arch this image-# is built for; the glob is what §8 row 3 asks for instead of a list of-# content-hashed store keys, and it is arch-independent for the same-# reason (an arm64 build resolves `-linux-arm64`, never `-linuxmusl-*`).-# §2.4 proved sharp and @node-rs/argon2 still load without them.-# 2/3. apps/api/scripts (97.4% of that layer: two mock fixtures, 15.5 MB,-# whose only caller is the non-production `test:manage` script) and-# apps/api/e2e. Removed here rather than by splitting the COPY below,-# which is what keeps that COPY drift-proof.-# 4. `*.test.ts` under packages/, and packages/sdks — nothing in the api's-# closure imports an SDK (grepped 2026-09-11).+# 1. The musl-only native store entries. The base is glibc, so a package whose name says `musl` is dead on every+# arch this image is built for; the glob is arch-independent (an arm64 build resolves `-linux-arm64`).+# 2/3. apps/api/scripts (two mock fixtures, 15.5 MB, only used by the non-production `test:manage` script) and+# apps/api/e2e. Removed here rather than by splitting the COPY below, which keeps that COPY drift-proof.+# 4. `*.test.ts` under packages/, and packages/sdks: nothing in the api's closure imports an SDK.RUN find /app/node_modules/.bun -maxdepth 1 -name '*musl*' -prune -exec rm -rf {} + && \rm -rf /app/apps/api/scripts /app/apps/api/e2e && \find /app/packages -type f -name '*.test.ts' -delete && \rm -rf /app/packages/sdks-# RUNTIME — oven/bun:${BUN_VERSION}-slim, nothing but the app: the isolated-# node_modules and the source (with `build`'s generated output baked in), both-# from `prod-deps` so the store and the per-package symlinks into it come from-# one install and stay consistent.+# RUNTIME — oven/bun:${BUN_VERSION}-slim, nothing but the app: the isolated node_modules and the source (with+# `build`'s generated output), both from `prod-deps` so the store and the per-package symlinks come from one install.FROM base AS runtimeENV NODE_ENV=production@@ -133,21 +92,16 @@ WORKDIR /appCOPY --from=prod-deps --chown=bun:bun /app/package.json ./COPY --from=prod-deps --chown=bun:bun /app/node_modules ./node_modules-# Apps — src/ is the artifact now; there is no dist/.+# Apps — src/ is the artifact; there is no dist/.COPY --from=prod-deps --chown=bun:bun /app/apps/api ./apps/apiCOPY --from=prod-deps --chown=bun:bun /app/packages ./packagesCOPY --from=prod-deps --chown=bun:bun /app/tooling/typescript ./tooling/typescript-# The shipped start command is-# `cd /app/packages/db && bunx [email protected] migrate deploy`, so the schema and-# the migrations directory are load-bearing image content, not source-tree-# detail. Assert them at build time — the alternative is a self-hoster finding-# out at container start. The code migrations' entrypoint is asserted for the-# same reason: it moved to `packages/db/scripts/migrate-code.ts` in M15-204,-# and `packages/core/scripts/migrate-code.ts` — which the shipped compose files-# still name — now forwards to it, so both are load-bearing until those files-# are updated.+# The shipped start command is `cd /app/packages/db && bunx [email protected] migrate deploy`, so the schema and the+# migrations directory are load-bearing image content. Assert them at build time rather than let a self-hoster find+# out at container start. The code migrations' entrypoint is asserted too: `packages/core/scripts/migrate-code.ts`,+# which the shipped compose files name, forwards to `packages/db/scripts/migrate-code.ts`, so both are load-bearing.RUN test -f /app/packages/db/prisma/schema.prisma && \test -d /app/packages/db/prisma/migrations && \test -f /app/packages/db/scripts/migrate-code.ts && \@@ -160,8 +114,6 @@ WORKDIR /app/apps/apiEXPOSE 3000-# ROLE picks the shape: `api` (or unset) serves HTTP only, `worker` consumes-# only, `all` does both. `config/env.ts` validates it and fails boot loudly on-# an unknown value, which is why this line no longer has a case statement of-# its own.+# ROLE picks the shape: `api` (or unset) serves HTTP only, `worker` consumes only, `all` does both. `config/env.ts`+# fails boot loudly on an unknown value.CMD ["bun", "run", "src/main.ts"]diff --git a/apps/start/Dockerfile b/apps/start/Dockerfileindex 359deb7c9..4ff986c0c 100644--- a/apps/start/Dockerfile+++ b/apps/start/Dockerfile@@ -1,49 +1,20 @@-# Dashboard image.+# Dashboard image. The build runs on bun; the runtime deliberately stays Node.#-# Rewritten for M15-203 against docs/DOCKER_SLIMMING.md (M14-203) §1.2 and-# §4.2. That document measured this image layer by layer and found almost-# nothing of it is ours: 84.5% is `node:${NODE_VERSION}-slim`, of which one-# layer (the Node runtime itself) is 53%, and the application `.output` is-# 9,024,064 B — 9.5%. So the only cuts available here are the two apt ones-# below, and the base is DECIDED and stays put (§9.1, §9.2 — Carl, 2026-09-08).+# Almost nothing of this image is ours: 84.5% is `node:${NODE_VERSION}-slim` (the Node runtime alone is 53%) and the+# application `.output` is 9 MB, so the only cuts available are the two apt ones below.#-# THE TWO ROOT CAUSES THIS FILE FIXES, carried forward from M13-003 because-# both are still the reason it is shaped this way:-#-# 1. STALE COPIES OF THE DELETED `@openpanel/auth` PACKAGE. ADR-007 dissolved-# that package into `@openpanel/core` and P11 deleted its directory, so-# the COPYs that named it referenced a path that no longer exists. The-# grep gate for this file asserts that neither the old installer nor that-# path is named anywhere in it.-#-# 2. THE WORKSPACE-SUBSET INSTALL. The old base stage copied ~10 of the-# workspace's ~20 member manifests and none of `packages/core`. P11 made-# `apps/start` import `@openpanel/core/modules/*.constants`, and-# `vite-tsconfig-paths` then reads `packages/core/tsconfig.json`, whose-# `"extends": "@openpanel/tsconfig/base.json"` cannot resolve when-# `tooling/typescript` was never installed as a workspace member. The fix-# is not another manifest in the list — it is ONE FULL WORKSPACE INSTALL,-# which is the shape ADR-014 Problems §4 rules for a bun-base image-# anyway.-#-# ADR-014 scopes P13 to the INSTALLER only. The build runs on bun; the runtime-# deliberately stays Node — nothing here decides otherwise.+# The install is ONE FULL WORKSPACE INSTALL, not a list of member manifests: `apps/start` imports+# `@openpanel/core/modules/*.constants`, and `vite-tsconfig-paths` then reads `packages/core/tsconfig.json`, whose+# `"extends": "@openpanel/tsconfig/base.json"` cannot resolve unless `tooling/typescript` is installed as a workspace member.ARG BUN_VERSION=1.4.0ARG NODE_VERSION=24.19.0-# INSTALL — one full workspace install, exactly what bun.lock was resolved-# against. `bunfig.toml` rides along with the tree and carries-# `[install] ignoreScripts = true` (ADR-014 amendment 2) and-# `linker = "isolated"`; `--linker=isolated` is named here too so the layout is-# a property of the command, not only of a file.+# INSTALL — one full workspace install, exactly what bun.lock was resolved against. `bunfig.toml` rides along with the+# tree and carries `[install] ignoreScripts = true` and `linker = "isolated"`; `--linker=isolated` is named here too so+# the layout is a property of the command, not only of a file.#-# NO apt BLOCK. There used to be one here mirroring the runner's. It shipped-# nothing — the runner starts `FROM node:${NODE_VERSION}-slim`, a fresh base,-# and copies only `.output` — so it bought build time and nothing else.-# Measured (§4.2): deleting it changes the image by -74 B and the build still-# succeeds. `bun install` needs TLS and `oven/bun:${BUN_VERSION}-slim` already-# ships `ca-certificates`; nothing in `bun install` or `vite build` calls-# `curl`, `openssl` or `libssl3`.+# No apt block: the runner starts `FROM node:${NODE_VERSION}-slim` and copies only `.output`, so an apt block here+# shipped nothing. `bun install` needs TLS and `oven/bun:${BUN_VERSION}-slim` already ships `ca-certificates`.FROM oven/bun:${BUN_VERSION}-slim AS installWORKDIR /app@@ -58,10 +29,8 @@ RUN bun install --frozen-lockfile --linker=isolated# BUILD — Nitro's standalone server output. NITRO=1 selects the node-server# preset over the Cloudflare one; SELF_HOSTED=1 is read at build time.#-# No codegen step: verified on this tree (2026-09-07) that the build succeeds-# with `packages/db/src/generated` absent — every `@openpanel/db` import in-# apps/start is `import type`, and the `@openpanel/core` imports are all-# `*.constants` subpaths.+# No codegen step: the build succeeds with `packages/db/src/generated` absent, because every `@openpanel/db` import in+# apps/start is `import type` and the `@openpanel/core` imports are all `*.constants` subpaths.FROM install AS buildENV NITRO=1@@ -71,19 +40,12 @@ RUN cd apps/start && NITRO=1 SELF_HOSTED=1 bun run build# RUNNER — node:${NODE_VERSION}-slim, and only `.output`.#-# The Nitro output is standalone: it ships its own `.output/server/node_modules`-# and `.output/public` holds every asset `/login` references. So the workspace-# `node_modules` and the per-package source copies the previous image carried-# are dead weight, and dropping them is what removes the last reference to the-# deleted `@openpanel/auth` tree.+# The Nitro output is standalone: it ships its own `.output/server/node_modules` and `.output/public` holds every asset+# `/login` references, so the workspace `node_modules` and source copies are dead weight.#-# apt: `curl` for the CMD-SHELL HEALTHCHECKs, `ca-certificates` for it. The-# `openssl` and `libssl3` names that used to be here were inert (§4.2, 47 B):-# `curl` pulls libssl3 through libcurl4 and `ca-certificates` pulls openssl,-# and Node needs neither — it bundles its own OpenSSL (`ldd node` shows no-# libssl) and its own CA store. `ca-certificates` itself is 1,113,308 B and is-# KEPT: §8's dashboard row 3 files removing it as Carl's call, since it would-# break any HTTPS `curl` inside the container.+# apt: `curl` for the CMD-SHELL HEALTHCHECKs, `ca-certificates` for it. `openssl` and `libssl3` are not named: `curl`+# pulls libssl3 and `ca-certificates` pulls openssl, and Node bundles its own OpenSSL and CA store.+# `ca-certificates` is kept because removing it would break any HTTPS `curl` inside the container.FROM node:${NODE_VERSION}-slim AS runnerENV NODE_ENV=productiondiff --git a/scripts/add-internal-links.mjs b/scripts/add-internal-links.mjsindex 42a8494ab..29a4c8dab 100644--- a/scripts/add-internal-links.mjs+++ b/scripts/add-internal-links.mjs@@ -20,7 +20,6 @@ const ROOT = path.resolve(__dirname, '..');const CONTENT_DIR = path.join(ROOT, 'apps/public/content');const TODAY = '2026-02-07';-// ── Feature definitions ─────────────────────────────────────────────// Patterns are tried in order; first match wins for each feature.// Longer / more specific patterns come first to avoid partial matches.const FEATURES = [@@ -100,8 +99,6 @@ const DIRS = ['articles', 'guides', 'docs', 'pages'];// Only these dirs get the `updated` frontmatter fieldconst DIRS_WITH_UPDATED = ['articles', 'guides'];-// ── Helpers ──────────────────────────────────────────────────────────-/** Return an array of { start, end } ranges that should NOT be modified. */function getSkipZones(text) {const zones = [];@@ -173,8 +170,6 @@ function escapeRegex(s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}-// ── Core processing ──────────────────────────────────────────────────-function processFile(filePath, dir) {let content = fs.readFileSync(filePath, 'utf8');@@ -269,8 +264,6 @@ function processFile(filePath, dir) {return changes;}-// ── Walk directories ─────────────────────────────────────────────────-function walk(dir) {const entries = fs.readdirSync(dir, { withFileTypes: true });const files = [];@@ -285,8 +278,6 @@ function walk(dir) {return files;}-// ── Main ─────────────────────────────────────────────────────────────-const results = [];for (const dir of DIRS) {diff --git a/scripts/doctor.sh b/scripts/doctor.shindex 438e0c098..bd1ee33d4 100755--- a/scripts/doctor.sh+++ b/scripts/doctor.sh@@ -1,11 +1,6 @@#!/usr/bin/env bash-# Developer preflight (ADR-016 rule 5) — checks the Bun actually running on-# this machine against the version this repo pins, and fails loudly rather-# than silently drifting the way `bootstrap.sh`'s unversioned install could.-#-# NOT a gate: nothing under verification/ calls this script, and it must stay-# that way (ADR-016 rule 5 asserts the pin at three places — this is one of-# them, not the mechanism that enforces the other two).+# Developer preflight: checks the Bun actually running on this machine against the version this repo pins, and fails+# loudly rather than silently drifting. Not a CI gate.## Run from anywhere: `bash scripts/doctor.sh`.diff --git a/scripts/seed-events.mjs b/scripts/seed-events.mjsindex ad82d24c8..47bb2a86e 100644--- a/scripts/seed-events.mjs+++ b/scripts/seed-events.mjs@@ -12,10 +12,6 @@* --clientId=ID Client ID to use (required or set CLIENT_ID env var)*/-// ----------------------------------------------------------------------------// Config-// ----------------------------------------------------------------------------const args = Object.fromEntries(process.argv.slice(2).map((a) => {const [k, v] = a.replace(/^--/, '').split('=');@@ -37,10 +33,6 @@ if (!CLIENT_ID) {const TRACK_URL = `${BASE_URL}/track`;-// ----------------------------------------------------------------------------// Deterministic seeded random (mulberry32) — keeps identities stable across runs-// ----------------------------------------------------------------------------function mulberry32(seed) {return () => {seed |= 0;@@ -66,10 +58,6 @@ function randFloat(min, max, rng = eventRng) {return rng() * (max - min) + min;}-// ----------------------------------------------------------------------------// Fake data pools-// ----------------------------------------------------------------------------const FIRST_NAMES = ['Alice','Bob',@@ -174,10 +162,6 @@ function makeIP(index) {return `${a}.${b}.${c}.${d}`;}-// ----------------------------------------------------------------------------// Products & categories-// ----------------------------------------------------------------------------const PRODUCTS = [{id: 'prod_001',@@ -221,10 +205,6 @@ const CATEGORIES = ['Furniture',];-// ----------------------------------------------------------------------------// Groups (3 pre-defined companies)-// ----------------------------------------------------------------------------const GROUPS = [{id: 'org_acme',@@ -246,10 +226,6 @@ const GROUPS = [},];-// ----------------------------------------------------------------------------// Scenarios — 20 distinct user journeys-// ----------------------------------------------------------------------------/*** Each scenario returns a list of event descriptors.* screen_view events use a `path` property (origin + pathname).@@ -1123,10 +1099,6 @@ const SCENARIOS = [],];-// ----------------------------------------------------------------------------// Identity generation (deterministic by session index)-// ----------------------------------------------------------------------------function generateIdentity(sessionIndex, sessionRng) {const firstName = pick(FIRST_NAMES, sessionRng);const lastName = pick(LAST_NAMES, sessionRng);@@ -1154,10 +1126,6 @@ function getGroupForSession(sessionIndex) {return null;}-// ----------------------------------------------------------------------------// HTTP helper-// ----------------------------------------------------------------------------async function sendEvent(payload, ua, ip) {const headers = {'Content-Type': 'application/json',@@ -1182,10 +1150,6 @@ async function sendEvent(payload, ua, ip) {return res;}-// ----------------------------------------------------------------------------// Build session event list-// ----------------------------------------------------------------------------function buildSession(sessionIndex) {const sessionRng = mulberry32(sessionIndex * 9973 + 1337); // deterministic per session@@ -1200,10 +1164,6 @@ function buildSession(sessionIndex) {return { identity, group, ua, ip, events };}-// ----------------------------------------------------------------------------// Schedule events across timeline-// ----------------------------------------------------------------------------function scheduleSession(session, sessionIndex, totalSessions) {const timelineMs = TIMELINE_MINUTES * 60 * 1000;const now = Date.now();@@ -1226,10 +1186,6 @@ function scheduleSession(session, sessionIndex, totalSessions) {});}-// ----------------------------------------------------------------------------// Concurrency limiter-// ----------------------------------------------------------------------------async function withConcurrency(tasks, limit) {const results = [];const executing = [];@@ -1245,10 +1201,6 @@ async function withConcurrency(tasks, limit) {return Promise.all(results);}-// ----------------------------------------------------------------------------// Main-// ----------------------------------------------------------------------------async function main() {console.log(`\nSeeding ${SESSION_COUNT} sessions over ${TIMELINE_MINUTES} minutes`diff --git a/self-hosting/cli/src/commands/reset.ts b/self-hosting/cli/src/commands/reset.tsindex d9c2f5e16..bf75204f1 100644--- a/self-hosting/cli/src/commands/reset.ts+++ b/self-hosting/cli/src/commands/reset.ts@@ -39,8 +39,7 @@ const volumeIds = async (project: string, key: string): Promise<string[]> => {return stdout.split('\n').filter(Boolean);};-// Scoped to this install on purpose: the old script also ran host-wide-// `docker volume prune` / `image prune`, which deletes other projects' data.+// Scoped to this install on purpose: a host-wide `docker volume prune` / `image prune` deletes other projects' data.export const reset = async ({ dir, yes }: ResetFlags): Promise<number> => {if (!isInstallDir(dir)) {clackLog.error(`${dir} is not an OpenPanel install.`);diff --git a/test/bun-preload.ts b/test/bun-preload.tsindex 55cd3e926..d0469e16c 100644--- a/test/bun-preload.ts+++ b/test/bun-preload.ts@@ -1,29 +1,15 @@/*** `bun test` preload for `packages/db` and `apps/api`.*- * Two jobs, in this order:+ * 1. Pin the infrastructure URLs at the ISOLATED test databases (`test/databases.ts`): no test may reach the+ * application's own `openpanel` databases, where fixture teardown would mutate real data.+ * 2. Bootstrap those databases and load the shared fixture, tearing it down when the file's tests finish.*- * 1. **Pin the infrastructure URLs at the ISOLATED test databases.** This is- * a safety property, not a convenience: no test may reach the- * application's own `openpanel` databases, which on this box hold a copy- * of production — fixture teardown there mutates the dataset the- * migration goldens are diffed against, and a delete against a 318M-row- * table does not finish inside a test timeout. `test/databases.ts` is the- * single source of truth for the strings.- * 2. **Bootstrap those databases and load the shared fixture**, tearing it- * down again when the file's tests finish.+ * `preload` runs once per test FILE under `--isolate`; neither `globalThis` nor `process.env` survives between files,+ * so everything here is idempotent and setup/teardown are paired around one file's tests.*- * `preload` runs once per test FILE under `--isolate`, strictly sequential- * within one process — neither `globalThis` nor `process.env` survives- * between files, so there is no in-process channel to dedupe through.- * Everything here is therefore written to be idempotent and is serialised by- * that sequencing: `bootstrapTestDatabases` is idempotent by construction,- * and setup/teardown are paired around a single file's tests so no file can- * observe another's teardown.- *- * The imports below are deliberately dynamic and deliberately below the env- * pins: `packages/db`'s ClickHouse module constructs its clients at import- * time, so a static import would capture the pre-pin `CLICKHOUSE_URL`.+ * The imports below are deliberately dynamic and below the env pins: `packages/db`'s ClickHouse module constructs its+ * clients at import time, so a static import would capture the pre-pin `CLICKHOUSE_URL`.*/import { afterAll } from 'bun:test';diff --git a/test/databases.ts b/test/databases.tsindex 7397cfee0..a97778521 100644--- a/test/databases.ts+++ b/test/databases.ts@@ -1,16 +1,7 @@/**- * Connection details for the suite's ISOLATED databases.- *- * Tests get their own Postgres and ClickHouse databases, never the ones the- * application uses. On this box the application databases hold a copy of- * production, which breaks tests twice over: fixture teardown issues- * `DELETE FROM events WHERE project_id = ...`, which mutates the dataset the- * migration goldens are diffed against, and a lightweight delete against a- * 318M-row table does not finish inside a test timeout.- *- * Every test connection string is derived from here — test/bun-preload.ts- * pins the worker env at these values and test/bootstrap-databases.ts- * creates and migrates them. Nothing in test/ may hard-code a database name.+ * Connection details for the suite's ISOLATED databases: tests never touch the application's own databases, whose+ * fixture teardown (`DELETE FROM events WHERE project_id = ...`) would mutate real data and, on a large table, outlast a+ * test timeout. Every test connection string derives from here; nothing in test/ may hard-code a database name.*/const POSTGRES_ORIGIN = 'postgresql://postgres:postgres@localhost:23432';@@ -34,9 +25,5 @@ export const POSTGRES_MAINTENANCE_URL = postgresUrl();export const TEST_CLICKHOUSE_URL = clickhouseUrl(TEST_CLICKHOUSE_DATABASE);-/**- * Redis is deliberately NOT isolated — unchanged from the previous pin. It- * holds no prod copy and no golden, so it carries neither hazard this module- * exists to remove.- */+/** Redis is deliberately NOT isolated: it holds no production copy, so it carries neither hazard this module removes. */export const TEST_REDIS_URL = 'redis://localhost:23379';diff --git a/test/fixtures.ts b/test/fixtures.tsindex 5f7529c03..52773f73f 100644--- a/test/fixtures.ts+++ b/test/fixtures.ts@@ -33,10 +33,6 @@ function getDb() {return new PrismaClient({ datasources: { db: { url } } });}-// ----------------------------------------------------------------------------// Well-known fixture IDs — import these in tests instead of hard-coding strings-// ----------------------------------------------------------------------------export const FIXTURE = {profiles: {alice: 'profile-alice',@@ -64,10 +60,6 @@ export const FIXTURE = {},} as const;-// ----------------------------------------------------------------------------// Internal helpers-// ----------------------------------------------------------------------------type ChClient = ReturnType<typeof createClient>;function getClient() {@@ -387,10 +379,6 @@ async function deleteFixtures(client: ChClient, projectId: string) {]);}-// ----------------------------------------------------------------------------// Public API-// ----------------------------------------------------------------------------export async function setupPostgresFixtures(projectId: string,orgId: stringdiff --git a/test/retention-fixtures.ts b/test/retention-fixtures.tsindex 6dc28d412..8d5c2ddad 100644--- a/test/retention-fixtures.ts+++ b/test/retention-fixtures.ts@@ -36,10 +36,6 @@import { createClient } from '../packages/db/src/clickhouse/client';import { TEST_CLICKHOUSE_URL } from './databases';-// ----------------------------------------------------------------------------// Well-known ids + absolute dates-// ----------------------------------------------------------------------------export const RETENTION_FIXTURE = {users: {ru1: 'retention-ru1',@@ -110,10 +106,6 @@ export const RETENTION_BLUEPRINT = {],} as const;-// ----------------------------------------------------------------------------// Builders-// ----------------------------------------------------------------------------type ChClient = ReturnType<typeof createClient>;function getClient(): ChClient {@@ -173,7 +165,6 @@ function buildEvents(projectId: string) {const se = { country: 'SE' };return [- // --- DAY scenario: app_open (self-retention) ---buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d0), us),buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d1), us),buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d2), us),@@ -184,11 +175,9 @@ function buildEvents(projectId: string) {buildEvent(projectId, users.ru4, 'app_open', dayAt(day.d2), us),buildEvent(projectId, users.ru5, 'app_open', dayAt(day.d1), us),- // --- DAY scenario: purchase (cross-event retention) ---buildEvent(projectId, users.ru1, 'purchase', dayAt(day.d1), us),buildEvent(projectId, users.ru2, 'purchase', dayAt(day.d2), us),- // --- WEEK scenario: app_open crossing the 2024->2025 boundary ---// 2024-12-30 (Mon) falls in the Sunday-aligned week starting 2024-12-29.buildEvent(projectId, users.wu1, 'app_open', '2024-12-30 12:00:00'),buildEvent(projectId, users.wu1, 'app_open', '2025-01-06 12:00:00'),@@ -196,10 +185,6 @@ function buildEvents(projectId: string) {];}-// ----------------------------------------------------------------------------// Public API-// ----------------------------------------------------------------------------function buildCohortMembers(projectId: string) {return RETENTION_FIXTURE.cohort.members.map((profileId) => ({project_id: projectId,diff --git a/tooling/gates/conformance.sh b/tooling/gates/conformance.shindex 0bacc1a9a..e4c673386 100755--- a/tooling/gates/conformance.sh+++ b/tooling/gates/conformance.sh@@ -1,72 +1,16 @@#!/usr/bin/env bash#-# ADR-022 conformance gate — does the tree still have the SHAPE the standard-# describes?+# Conformance gate: does the tree still have the shape the architecture rules describe?#-# --report per-rule counts and every offender as file:line, one block per-# rule ending in a TOTAL, plus one overall TOTAL. Always exits 0.-# --assert exits 1 if any ASSERTED rule is above its target, printing only-# those rules and their offenders. Exits 0 when the tree is-# conformant. `--assert` exiting 0 is the M14 gate.-# --selftest runs the gate's own bun:test suite — the two miscount traps and-# the R6 asset-loader allowlist. Exits 1 if a test fails.+# --report per-rule counts and every offender as file:line, plus a TOTAL. Always exits 0.+# --assert exits 1 if any asserted rule is above its target, printing only those rules.+# --selftest runs the gate's own bun:test suite.#-# WHY THIS GATE EXISTS-#-# Every other gate in this plan proves BEHAVIOUR: goldens 137/137, the routing-# golden 217/217, the session e2e 29/29, the wire contracts 67/67, the P13 drift-# gate 0/416. Not one of them proves shape. Each of ADR-022's rules can be broken-# while all of that stays green, which is exactly how the tree arrived at 36-# factories with no composition root, 172 process.env reads in a package whose-# app calls itself "the sole reader", and a 2,104-line v1-compat.ts. A rule with-# no check is advice.-#-# WHY IT WALKS THE AST INSTEAD OF GREPPING-#-# Both of these were measured on 2026-09-08 against packages/core/src, and both-# make a naive gate lie:-#-# 1. `rg 'export function create[A-Za-z]+Service\(deps'` finds 28 factories.-# There are 36 — eight signatures span lines, so the argument list is not on-# the `export function` line. A gate that greps for the opening paren and-# the first parameter together silently passes the eight it cannot see.-#-# 2. `rg -o 'ReturnType<typeof create' packages/core/src/services.ts` matches-# once, and the match is a COMMENT at services.ts:154 explaining why-# `ReturnType<typeof createServices>` is circular. The pattern is applied in-# code ZERO times. A grep scores that comment as one compliant member.-#-# A third turned up while building the gate, in the same family: R7's baseline-# was measured with `rg 'process\.env\.'`, which counts a comment at-# rpc/base.ts:246 saying core reads no process.env, and misses a real read at-# shared/get-client-ip.ts:83 written `process.env?.`. The two errors cancel in-# the occurrence count (172 either way) and do not in the file count. The report-# prints the reconciliation rather than quietly picking one.-#-# A check that cannot tell code from a comment about code is not a check, so-# every count used as evidence walks the TypeScript AST. `typescript` is already-# a declared dependency.-#-# WHAT IS DELEGATED-#-# R22 the layer rules M14-002 landed in .dependency-cruiser.cjs. This gate-# reports their violation counts; it does not reimplement them. ADR-022's-# grep fallback is not in play — M14-002's peer-resolution verification-# passed. A bare `../` depth grep is forbidden either way: a module-# importing `defineJob` at `../../jobs/define` is importing DOWNWARD, and-# a depth check flags every well-formed module in the tree.-# R12 the existing `frontend-values-only-constants` cruiser rule.-#-# WHAT IS REPORTED BUT NOT ASSERTED-#-# R1, R2, R4, R9, R11, R13, R16, R17, R18, R19. They are review rules: passing-# them is a judgement a document makes, not a number. `--report` prints whatever-# is measurable as a hint for the reviewer. R20 is deferred by Carl (2026-09-08)-# and is absent from this gate entirely — do not add it.-#-# The report body carries no timestamps and orders everything by file then line,-# so two runs diff cleanly. That is the property the fix wave needs to prove a-# rule reached zero.+# The analyzer walks the TypeScript AST instead of grepping: a grep scores a comment about a pattern as a+# compliant use, and misses signatures that span lines. The layer rules (R22) and `frontend-values-only-constants`+# (R12) are delegated to .dependency-cruiser.cjs; this gate only reports their violation counts.+# R1, R2, R4, R9, R11, R13, R16-R19 are review rules: reported as a hint, not asserted.+# The report carries no timestamps and orders by file then line, so two runs diff cleanly.set -uo pipefail@@ -90,8 +34,7 @@ require_analyzer() {echo "FAIL: bun is not on PATH; the analyzer runs under bun (ADR-010)." >&2exit 2}- # R12 and R22 are delegated. A delegated check that silently reports zero- # because its tool is absent is worse than no check, so say so up front.+ # A delegated check that silently reports zero because its tool is absent is worse than no check.[[ -x "$CRUISER_BINARY" ]] || {echo "WARN: $CRUISER_BINARY is missing — R12 and R22 will report UNAVAILABLE" >&2echo " and --assert will fail on them. Run \`bun install\`." >&2diff --git a/tooling/gates/conformance/cli.ts b/tooling/gates/conformance/cli.tsindex 5bedbd39a..b869db915 100644--- a/tooling/gates/conformance/cli.ts+++ b/tooling/gates/conformance/cli.ts@@ -1,5 +1,5 @@/**- * Assembles every ADR-022 check into one report and decides --assert.+ * Assembles every conformance check into one report and decides --assert.** Output contract: one block per rule, offenders as `file:line`, a TOTAL* line per rule and one overall, stable ordering and no timestamps in the@@ -71,8 +71,6 @@ const SEPARATOR_WIDTH = 80;const heavy = '='.repeat(SEPARATOR_WIDTH);const light = '-'.repeat(SEPARATOR_WIDTH);-// --- collection ----------------------------------------------------------------interface Tree {repoRoot: string;core: ParsedSource[];@@ -271,8 +269,6 @@ function collectRouters(tree: Tree) {return routers.sort((a, b) => a.routerKey.localeCompare(b.routerKey));}-// --- rules ---------------------------------------------------------------------const reviewOnly = (label: string, hint: string): Metric => ({label,count: 0,@@ -545,13 +541,10 @@ function buildRules(tree: Tree): RuleBlock[] {? "M14-002 landed these rules and verified cruiser resolves its typescript peer, so R22 is the cruiser rule, not ADR-022's grep fallback. A bare ../ depth grep is forbidden: a module importing defineJob at ../../jobs/define is importing DOWNWARD.": undefined,},- // R20 (test shapes) is deferred by Carl, 2026-09-08, and is deliberately- // absent from this gate. Do not add it.+ // R20 (test shapes) is deliberately absent from this gate.];}-// --- formatting ----------------------------------------------------------------const offenderLine = (offender: Offender): string =>offender.line > 0? ` ${offender.file}:${offender.line} ${offender.detail}`@@ -738,8 +731,6 @@ export function renderAssert(rules: RuleBlock[]): {return { output: lines.join('\n'), failed: true };}-// --- entrypoint ----------------------------------------------------------------/*** `conformance.sh --report | grep -q 36` closes the pipe on the first match and* the remaining ~700 lines land on a dead fd. Without this the gate prints andiff --git a/tooling/gates/conformance/rules.ts b/tooling/gates/conformance/rules.tsindex 734628cb4..3eaa301c3 100644--- a/tooling/gates/conformance/rules.ts+++ b/tooling/gates/conformance/rules.ts@@ -71,8 +71,6 @@ const sorted = (offenders: Offender[]): Offender[] =>const isUnder = (path: string, roots: readonly string[]): boolean =>roots.some((root) => path === root || path.startsWith(root));-// --- R3 ------------------------------------------------------------------------const typeText = (node: ts.TypeNode | undefined): string =>node ? node.getText().replace(/\s+/g, ' ') : '<untyped>';@@ -148,8 +146,6 @@ export function checkFactorySignatures(sources: ParsedSource[]): Metric {};}-// --- R5 ------------------------------------------------------------------------/** R5a — no hand-written `export interface XService` outside services.ts. */export function checkServiceInterfaces(sources: ParsedSource[]): Metric {const offenders: Offender[] = [];@@ -245,8 +241,6 @@ export function checkServicesMembers(sources: ParsedSource[]): Metric {};}-// --- R6 ------------------------------------------------------------------------/** R6a — `createServices(` only at the sanctioned construction sites. */export function checkCreateServicesCallSites(sources: ParsedSource[]): Metric {const offenders: Offender[] = [];@@ -340,8 +334,6 @@ export function checkDependencyLoaders(sources: ParsedSource[]): Metric {};}-// --- R7 ------------------------------------------------------------------------const isProcessEnv = (node: ts.Node): boolean =>ts.isPropertyAccessExpression(node) &&ts.isIdentifier(node.expression) &&@@ -414,8 +406,6 @@ export function checkEnvReads(sources: ParsedSource[]): Metric[] {];}-// --- R10 -----------------------------------------------------------------------/** R10 — the access checks live in the auth service and the builders only. */export function checkAccessChecks(sources: ParsedSource[]): Metric {const offenders: Offender[] = [];@@ -445,8 +435,6 @@ export function checkAccessChecks(sources: ParsedSource[]): Metric {};}-// --- R14 -----------------------------------------------------------------------export interface ResidueScanInput {path: string;text: string;@@ -525,8 +513,6 @@ export function checkResidue(files: ResidueScanInput[]): Metric[] {return metrics;}-// --- R15 -----------------------------------------------------------------------/*** The name a `new` expression actually constructs, however it is qualified.*@@ -597,8 +583,6 @@ export function checkModuleScopeConstruction(sources: ParsedSource[]): Metric {};}-// --- R21 -----------------------------------------------------------------------const utilKey = (path: string): string | undefined => {if (!UTIL_DIRECTORY_PATTERNS.some((pattern) => pattern.test(path))) {return undefined;@@ -691,8 +675,6 @@ export function checkSharedPackageIsolation(repoRoot: string): Metric {};}-// --- reported-only hints -------------------------------------------------------/** R1 — a module's root files carry the `<name>.` prefix and stop at `src/`. */export function checkModuleLayout(modulePaths: string[],diff --git a/tooling/gates/p13-images.sh b/tooling/gates/p13-images.shindex e121be0b1..a6e4ef1d4 100755--- a/tooling/gates/p13-images.sh+++ b/tooling/gates/p13-images.sh@@ -1,58 +1,17 @@#!/usr/bin/env bash#-# P13 image gate (ADR-014, M13-003) — do BOTH images build on `bun install`,-# and does what they build actually BOOT?+# Image gate: do both images build on `bun install`, and does what they build actually boot?+# A green build is not enough (a build once pushed green while every dashboard route returned 500), so this+# starts each image and asserts /healthz/ready = 200 on the api and a server-rendered /login on the dashboard+# (HTTP 200, an `<html`, at least 1000 bytes), then checks the container logs for module-resolution errors.#-# ADR-014's own gate line is "all Dockerfiles build", and `.github/smoke/smoke.sh:6-11`-# is the repo's record of why that is not enough: main-8e60 built green, pushed-# green, and every dashboard route returned 500. So this gate does the same two-# things that script does — start the image and assert a real server-rendered-# page — rather than stopping at a successful build.+# Uses the isolated `openpanel_test` databases. The repo `.env` is sourced only for ENCRYPTION_KEY and+# COOKIE_SECRET; everything else the containers get is explicit, so a developer's `.env` cannot leak in.+# `--env-file` is not used: `.env` contains `DATABASE_URL_DIRECT="$DATABASE_URL"`, which docker does not expand.#-# What it does:-# 1. builds apps/api/Dockerfile (with a dummy DATABASE_URL build arg — the-# build stage's `bun run codegen` only needs the variable to exist, it-# never connects) and apps/start/Dockerfile;-# 2. runs the api image with `--network host` against this box's already-# running Postgres/ClickHouse/Redis/Redpanda and asserts /healthz/ready = 200;-# 3. runs the dashboard image the same way and asserts smoke.sh's-# assert_ssr_route conditions for /login — HTTP 200, an `<html`, at least-# 1000 bytes — plus assert_no_server_errors on the container log;-# 4. stops and removes both containers, always;-# 5. prunes the build cache.-#-# The prune also runs BETWEEN the two builds. Measured on this box on-# 2026-09-07: one from-scratch build leaves ~6GB of cache and the box had 12GB-# free, so building both without an intermediate prune fills the disk. The two-# builds share no cache anyway — they start from different base layers.-#-# DATABASES: the isolated `openpanel_test` Postgres and ClickHouse, never the-# prod-copy `openpanel` ones — both containers are read-only against them in-# practice (a session lookup and a readiness probe), but the rule is the rule.-#-# ENVIRONMENT: the repo `.env` is sourced into this shell for the two values a-# gate must not invent — ENCRYPTION_KEY and COOKIE_SECRET — and every other-# variable the containers get is written out explicitly below, so the api's-# database URLs and ports cannot be inherited from a developer's `.env`-# (which pins API_PORT=3333 and points CLICKHOUSE_URL at the prod copy).-# `--env-file` is deliberately not used: `.env` contains-# `DATABASE_URL_DIRECT="$DATABASE_URL"`, a shell expansion docker does not-# perform.-#-# DISK is the operational risk here: two from-scratch workspace installs-# produce several GB of build cache on a box that has ~15G free, so the prune-# runs on success, on failure and on an interrupt. It is a-# `docker builder prune -f --all` — build cache only; it does not touch images-# or the containers already running on this box.-#-# `--all` is not decoration. Measured on this box on 2026-09-07, immediately-# after a full gate run: a plain `docker builder prune -f` reclaimed **0B** and-# left **22.91GB** of cache (buildkit's default policy keeps recent records);-# `docker builder prune -af` on the same state reclaimed **20.89GB** and took-# the disk from 3.4G to 23G free. Without `--all` this gate fills the box in-# two or three runs, which is the exact failure it is supposed to prevent.-# Nothing else on this box builds images, so discarding all cache costs only-# rebuild time — one from-scratch build of either image is ~1.5-3 min.+# Disk is the operational risk: a from-scratch build leaves ~6GB of cache, so the cache is pruned between the+# builds and on exit (success, failure or interrupt). `docker builder prune -f --all` is deliberate: without+# `--all`, buildkit's default policy kept 22GB of cache and reclaimed 0B.## bash tooling/gates/p13-images.sh@@ -88,8 +47,6 @@ readonly READY_POLL_INTERVAL_SECONDS=2FAILED=0-# --- lifecycle ----------------------------------------------------------------remove_container() {local name="$1"docker rm -f "$name" >/dev/null 2>&1 || true@@ -141,8 +98,6 @@ wait_ready() {echo " $name ready at $url (${waited}s)"}-# --- assertions ---------------------------------------------------------------assert_ssr_route() {local path="$1" status bytes@@ -183,8 +138,6 @@ assert_no_server_errors() {echo " $name log clean"}-# --- run ----------------------------------------------------------------------mkdir -p "$RUN_DIR"command -v docker >/dev/null || die 'docker is not available'diff --git a/tooling/publish/publish.ts b/tooling/publish/publish.tsindex 2c957b88e..92ebb3754 100644--- a/tooling/publish/publish.ts+++ b/tooling/publish/publish.ts@@ -10,7 +10,6 @@ import { generateReadme } from './generate-readme';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);-// Typesinterface PackageJson {name: string;version: string;@@ -35,7 +34,6 @@ interface PublishConfig {clear: boolean;}-// Utility functionsconst workspacePath = (relativePath: string) =>resolve(__dirname, '../../', relativePath);@@ -76,7 +74,6 @@ const getNextVersion = (version: string, type: ReleaseType): string => {: nextVersion;};-// Core functionsconst loadPackages = (releaseType: ReleaseType): Record<string, PackageInfo> => {@@ -336,7 +333,6 @@ const restoreAndUpdateLocal = (};function main() {- // Main executionconst args = arg({'--name': String,'--publish': Boolean,diff --git a/tooling/release/src/next-version.ts b/tooling/release/src/next-version.tsindex 91df4817e..2ce1dab70 100644--- a/tooling/release/src/next-version.ts+++ b/tooling/release/src/next-version.ts@@ -4,8 +4,7 @@ import { git, gitOrNull, lines } from './git';export type Bump = 'patch' | 'minor' | 'major';-// v3 is the first release numbered this way. Anything computed below it (the-// baseline tag is v2.3.0) is lifted to it, so v3 code can never ship as 2.3.x.+// v3 is the first release numbered this way: anything computed below it (the baseline tag is v2.3.0) is lifted to it.export const MINIMUM_VERSION = '3.0.0';export const TAG_PREFIX = 'v';const TAG_PATTERN = 'v[0-9]*';diff --git a/tooling/scripts/typecheck-workspaces.ts b/tooling/scripts/typecheck-workspaces.tsindex ebb193cd9..5ffc9b92a 100644--- a/tooling/scripts/typecheck-workspaces.ts+++ b/tooling/scripts/typecheck-workspaces.ts@@ -1,13 +1,7 @@/**- * `typecheck` across every workspace package that declares one.- *- * pnpm's `-r --no-bail` typechecked all of them and reported every failure.- * `bun run --filter <pattern> typecheck` has no `--no-bail` equivalent, so the- * "keep going and report all of them" half is done here by construction: a- * failing package is recorded and the run continues. A gate that stops at the- * first failure silently narrows to "the first package that fails".- *- * The root package is skipped — its own `typecheck` is this script.+ * `typecheck` across every workspace package that declares one. `bun run --filter` has no `--no-bail` equivalent, so a+ * failing package is recorded and the run continues; stopping at the first failure would silently narrow the gate.+ * The root package is skipped: its own `typecheck` is this script.*/import { spawn } from 'node:child_process';