Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

docs: delete the rewrite scaffolding, add a clean-code skill

Carl-Gerhard Lindesvärdd59a972022f8
diff --git a/.claude/skills/clean-code/SKILL.md b/.claude/skills/clean-code/SKILL.md
new file mode 100644
index 000000000..03cd97004
--- /dev/null
+++ b/.claude/skills/clean-code/SKILL.md
@@ -0,0 +1,108 @@
+---
+name: clean-code
+description: Coding standards for this repo - concise, direct, no over-engineering, and no comments that carry no knowledge. Use when writing or reviewing any code here, and whenever adding a comment.
+allowed-tools: Read, Write, Edit, Grep, Glob, Bash
+---
+
+# Clean code
+
+Adapted from `davila7/claude-code-templates` (MIT). The comment rules below are
+this repo's own, derived from what a 2026-09-28 cleanup actually found.
+
+`AGENTS.md` and `packages/core/AGENTS.md` are the binding contract. Where this
+file and either of those disagree, **they win.**
+
+## Core principles
+
+| Principle | Rule |
+|---|---|
+| **SRP** | One responsibility per function. But see the size note below. |
+| **DRY** | At the narrowest level that fits — the module first. Never invent a cross-module abstraction for two call sites. |
+| **KISS** | The simplest thing that works. |
+| **YAGNI** | No abstraction, parameter or hook for a need that does not exist yet. |
+| **Boy Scout** | Leave what you touch cleaner — inside the task's scope only. |
+
+## Naming
+
+| Element | Convention |
+|---|---|
+| Variables | Reveal intent: `userCount`, not `n`. No abbreviations unless universal. |
+| Functions | Verb + noun: `getUserById()`, not `user()`. |
+| Booleans | Question form: `isActive`, `hasPermission`, `canEdit`. |
+| Constants | `SCREAMING_SNAKE`, at the top of the file or in the module's `<name>.constants.ts`. Never a magic number inline. |
+
+**If you need a comment to explain a name, rename it.**
+
+## Function size — read this before splitting anything
+
+`packages/core/AGENTS.md` is explicit: *"a coherent 100-line function beats
+twenty five-line fragments. Split where a reader benefits, not to satisfy a
+metric."*
+
+So: no line limit. Split when a reader benefits. Keep arguments few, prefer an
+options object over four positionals, use guard clauses and early returns, and
+avoid nesting past two levels.
+
+## Comments — the part that actually goes wrong here
+
+Comment the **why**, briefly: an invariant, a non-obvious side effect, a
+constraint that bit someone, a reason the obvious spelling is wrong. Never
+narrate what the code does.
+
+These five shapes are banned. Each one was found in bulk in this repo and
+deleted:
+
+| Banned | Why | Instead |
+|---|---|---|
+| **Restating a rule from `AGENTS.md`** — `// Isomorphic by the AGENTS.md rule: zod and nothing else.` | True of every file of that name, machine-enforced by the `constants-stay-isomorphic` cruiser rule, and visible from the imports. Zero knowledge. | Nothing. Delete it. |
+| **Citing a document the repo does not contain** — `// Cluster note (docs/ENVIRONMENT.md): …` | 479 `ADR-nnn` and ~90 doc links pointed into a checkout that never ships. An unresolvable citation reads as authority it cannot back. | State the fact itself, with no citation. |
+| **Provenance** — `// Moved from packages/db/src/services/x.service.ts` | Says nothing about the file you have open, and rots the moment the path moves. | Nothing. `git log` knows. |
+| **Referring to a system that no longer exists** — `// exactly as V1 does`, `// V1's twin` | Justifies current behaviour by a reference point the reader cannot check. | State the rule the code follows. |
+| **Task ids** — `// M10-005:`, `// P11:` | Meaningless outside the tracker that issued them. | Nothing. |
+
+A comment that survives those five says something a careful reader could not
+have got from the code. That is the bar.
+
+## Anti-patterns
+
+| Don't | Do |
+|---|---|
+| Comment every line | Delete the obvious ones |
+| Helper for a one-liner | Inline it |
+| Factory for two objects | Construct them directly |
+| A `utils.ts` holding one function | Put it where it is used |
+| Deep nesting | Guard clauses |
+| Magic numbers | Named constants |
+| God functions | Split by responsibility, not by line count |
+| `any` | `unknown`, then narrow |
+| `as` assertions | Narrowing |
+| `console.log` / `debugger` left behind | Remove before finishing |
+
+## Before editing a file
+
+| Ask | Because |
+|---|---|
+| What imports this? | They may break — `grep -rn "from '.*<name>'"` |
+| What does it import? | An interface change ripples |
+| What tests cover it? | Run them, not the whole suite |
+| Is it on a package's public surface? | `packages/core/src/index.ts` and the `exports` map are contracts |
+
+Edit the file and every dependent in the same change. Never leave a broken
+import or a half-applied rename.
+
+## Before saying it is done
+
+Run what the change warrants, from `AGENTS.md`'s verification table — not the
+whole suite for a one-line fix, and always the full one for a query or ingest
+change:
+
+```bash
+bun run typecheck # always
+npx ultracite fix <files you changed> # always; they must come out clean
+bun test --isolate # in packages/core, for backend changes
+bunx vitest run # in apps/start, for dashboard changes
+bun run check:deps # if you touched a package boundary
+```
+
+Report what you ran and what you saw. A screenshot or a query result is
+evidence; "should work" is not.
diff --git a/AGENTS.md b/AGENTS.md
index 4c94fe449..0557aa249 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -166,7 +166,9 @@ disable rules to make a check pass. Generated and vendored files are excluded in
`<name>.constants.ts`.
- Names reveal purpose; no abbreviations unless universal.
- Comments say *why*, briefly. Never narrate what the code does. If a function needs
- a comment to explain what it does, split it.
+ a comment to explain what it does, split it. A comment that restates a rule from
+ this file, cites a document the repo does not contain, records where the code used
+ to live, or refers to V1 carries no knowledge — see `.claude/skills/clean-code`.
- Single responsibility, early returns, no nested ternaries, extract conditions into
named booleans.
- DRY at the narrowest level that fits: the module first, `packages/core/src/shared/`
@@ -188,7 +190,3 @@ verified, with a message that says what and why. Never push, never add
remotes, never rewrite history that is not yours. `WORKTREE.md`, `.seed.json` and
`.worktree-*` are gitignored — keep them that way.
-## Ralph
-
-If `/home/deploy/rewrite-openpanel` exists you are the autonomous rewrite loop:
-`CLAUDE.ralph.md` overrides this file.
diff --git a/CLAUDE.ralph.md b/CLAUDE.ralph.md
deleted file mode 100644
index d04d5c843..000000000
--- a/CLAUDE.ralph.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# OpenPanel V2 — autonomous rewrite
-
-This repository is being rewritten by an autonomous loop. Read this before doing
-anything.
-
-## Safety
-
-Your world is exactly two directories: this repository and
-`/home/deploy/rewrite-openpanel` (the controller). Do not read, list, or modify
-anything else on this machine.
-
-Never use production credentials — production does not exist on this machine,
-and nothing here should reach it. Local Postgres / ClickHouse / Redis only.
-
-## Environment
-
-- **No docker.** `bun run dock:up` will fail. Postgres (5432), Redis (6379) and
- ClickHouse (8123) are already running on localhost, started by another user.
- Do not try to start, stop or install them.
-- **No sudo.** Anything needing root is a human task. Say so; do not attempt it.
-- Writes are confined to this repo and `/home/deploy/rewrite-openpanel`. Every
- other path on the box is read-only to you.
-
-## Commands
-
-```bash
-bun install
-bun run codegen # prisma client; needs .env
-bun run typecheck
-bun run check # ultracite + check:deps
-bun run test
-```
-
-`typecheck` and `test` fail until `.env` exists and `bun run codegen` has run.
-If a task depends on them and they are not ready, report `BLOCKED` rather than
-inventing a workaround.
-
-## ClickHouse
-
-Never commit ClickHouse SQL you have not executed. Run it against the local
-server (`http://127.0.0.1:8123`, database `openpanel`) and report timing and row
-count. When replacing a query, diff the old and new result sets on the same data.
-
-Local is a single node; production is 2 shards x 2 replicas. Before editing any
-query against a `Distributed` table read
-`/home/deploy/rewrite-openpanel/docs/ENVIRONMENT.md` - a plain `IN (subquery)` on a
-distributed table silently returns per-shard results.
-
-## Architecture
-
-Architecture decisions live in `/home/deploy/rewrite-openpanel/decisions`.
-**Accepted ADRs are binding.** If you need a decision no accepted ADR covers,
-stop and say `BLOCKED: needs ADR — <question>`. Do not decide it yourself.
-
-The target architecture is `/home/deploy/rewrite-openpanel/docs/TARGET_ARCHITECTURE.md`.
-The documented behaviour of the system you are replacing is in
-`/home/deploy/rewrite-openpanel/docs/current/`. Read the relevant document before
-changing that area — it exists so you do not have to rediscover it.
-
-## Ralph
-
-Do not modify:
-
-```
-/home/deploy/rewrite-openpanel/plan/tasks.json
-/home/deploy/rewrite-openpanel/state
-/home/deploy/rewrite-openpanel/verification
-```
-
-The orchestrator owns task state and owns the definition of "passing".
-
-## Git
-
-Do not commit. The orchestrator manages commits and the `rewrite/v2` branch.
-There are no push credentials on this machine, by design - all commits are local
-and a human pushes them later. Never try to add a remote or authenticate to one.
-
-## Code style
-
-- **Formatting and linting: ultracite** (the Biome preset) — but **only ever on
- the files you changed**, named explicitly (`npx ultracite fix <files...>` or
- `biome check --write <files...>`). NEVER run it bare or on `.`: the repo has
- never been bulk-formatted, so an unscoped run rewrites thousands of files,
- buries your real diff, and fails the task. (This is why format-on-save hooks
- are disabled here.) Do not hand-format against it, and do not disable its
- rules to make a task pass.
-
-- **Constants over magic numbers** — named, descriptive, at the top of the file
- or in the module's `<name>.constants.ts`.
-- **Meaningful names** — reveal purpose; no abbreviations unless universal.
-- **Smart comments** — never narrate what code does; comment only the why, and
- keep it very short. APIs, non-obvious side effects and invariants excepted.
-- **Single responsibility** — small, focused functions; if it needs a comment
- to explain what it does, split it.
-- **DRY** — single sources of truth, shared at the narrowest level that fits:
- inside the module first; `core/shared/` when several backend modules need it;
- a **dedicated package** when anything beyond the backend (frontend, SDKs,
- other apps) needs it — core is not a grab-bag for cross-app code. Exception,
- by accepted decision: module `*.constants.ts` files are consumed by the
- frontend via deep paths into core, not via a package. Never invent a
- cross-module abstraction just to deduplicate two call sites.
-- **Clean structure & encapsulation** — related code together, implementation
- hidden, nested conditionals extracted into well-named functions.
-- **Leave the code you touch cleaner than you found it — inside the task's
- scope only.** Refactoring outside scope is a task of its own; propose it,
- don't do it. Same for technical debt you notice: record it, move on.
-
-## Scope
-
-Do exactly the assigned task. Do not opportunistically refactor, upgrade
-dependencies, or fix unrelated things you notice along the way.
diff --git a/ISSUES.md b/ISSUES.md
index 4da07de25..ca1894da7 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -58,6 +58,41 @@ bug.** Core suite 1830 pass, 12 skip, 0 fail.
realtime empty states.
- **Test debt** — untouched.
+### Carried over from `docs/TECH_DEBT.md` (deleted 2026-09-28)
+
+That file was a dated log of work that landed, not a to-do list. Four of its
+"known debt" items had already been fixed by the time it was read (the tracked
+`package-lock.json`, the inert `rolldown` override, the unused `jiti`
+devDependencies, and `verification/golden/queue-keys/`, whose directory is
+gone). These are what was left, each re-checked against the tree on 2026-09-28:
+
+- **`tooling/gates/conformance/rules.test.ts` runs in no suite.** The root
+ `test` script is core + db + api + seed + start + `vitest run`; `tooling/` is
+ in neither list, so the conformance gate's own regression tests only run by
+ hand (`cd tooling/gates/conformance && bun test` → 19 pass, 0 fail). Wiring
+ it in is one entry in the root `package.json`.
+- **The conformance R14 residue scan does not reach `packages/`.**
+ `tooling/gates/conformance/cli.ts` builds `residueFiles` from `packages/core`,
+ `apps/api` and `apps/start` only, so the one surviving `NEXT_PUBLIC_`
+ reference outside `apps/public` —
+ `packages/payments/src/polar.ts:63`'s `process.env.NEXT_PUBLIC_DASHBOARD_URL`
+ — is invisible to the rule whose label says "elsewhere outside
+ `apps/public/`". Widening the scan changes what that gate asserts, so it is a
+ decision, not a fix.
+
+### Found while cleaning comments (2026-09-28)
+
+- **`notification.constants.ts` duplicates three schemas from
+ `report.constants.ts`.** `zChartEvent`, `zChartEventFilter` and
+ `zChartEventSegment` are local copies whose operator and value-type enums are
+ inlined as literal tuples rather than derived from `operators` /
+ `filterValueTypes`. Verified on 2026-09-28: both enum sets are identical
+ (15 operators, 5 value types) and `report.constants.ts` does not import
+ `notification.constants.ts`, so there is no cycle — the copies can be
+ collapsed onto the report module's. The file's own TODO asked for exactly
+ this once `report.constants.ts` existed, which it now does. Left as a
+ refactor rather than done inside a comment pass.
+
Everything else below is still open.
---
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 574f497cc..aec7e24d6 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -195,7 +195,7 @@ function buildDeps(): AppDeps {
// 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).
+ // instead of importing them.
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.
diff --git a/docs/BUN_INSTALL_RECIPE.md b/docs/BUN_INSTALL_RECIPE.md
deleted file mode 100644
index 17c207fc8..000000000
--- a/docs/BUN_INSTALL_RECIPE.md
+++ /dev/null
@@ -1,840 +0,0 @@
-# BUN_INSTALL_RECIPE
-
-How `pnpm install` becomes `bun install` in M13-002, what each line of
-`pnpm-workspace.yaml` turns into, and what the swap is forbidden from doing.
-
-**Status: a recipe, not a decision.** ADR-014 (ACCEPTED) is the decision, and
-its stop rule governs everything here:
-
-> **any pin that cannot be reproduced ends P13 and the repo stays on pnpm.**
-
-Nothing in this file may be read as permission to make a pin reproduce by
-changing what it pins. ADR-017 rule 3 says the same thing from the other side —
-P13 lockfile churn is not an upgrade, and the installer swap must not carry a
-declared-range change of its own.
-
-Written for M13-001 (2026-09-07), against `pnpm-workspace.yaml` at the commit
-that pinned every direct dependency to its resolved version. Numbers are
-labelled with who measured them and when; the operator's throwaway-worktree
-survey of a bare `bun install` is labelled as such, because this task did not
-run `bun install` against this tree.
-
----
-
-## 0. What M13-001 already did, and why it matters here
-
-Every direct dependency of every workspace importer that declares a version
-range now names an **exact** version, except the two lines ADR-017 rule 2
-forbids this task from touching. Audited on the pinned tree, 2026-09-07, across
-the lock's 20 importers:
-
-| | count |
-|---|---:|
-| declared ranges, now exact | **306** |
-| still a range — the ADR-017 rule 2 carve-out, below | **2** |
-| `workspace:` / `catalog:` specifiers, untouched by design | 99 |
-| peers auto-installed by pnpm, left as peer ranges by design | 9 |
-
-`tooling/scripts/pin-from-pnpm-lock.ts` did 263 of those rewrites (253 in 20
-`package.json` files plus the 10 `catalog:` entries — the other 53 were already
-exact), taking every value from what `pnpm-lock.yaml` had already resolved.
-**Not one `version:` line in the lock moved**; only its 263 matching
-`specifier:` fields were relabelled, and `pnpm install --frozen-lockfile` is
-green on the result. The lock is edited rather than regenerated on purpose —
-see *Why the lock is edited, not refreshed* below for the measurement.
-
-### The two dependencies that stay a range
-
-`packages/redis/package.json` and `packages/sdks/_info/package.json` each carry
-a stale `prisma: ^5.1.1` devDep, a whole major behind the `@prisma/client` /
-`prisma` 6.14.0 that `packages/db` actually uses. **ADR-017 rule 2 (ACCEPTED)
-names those two lines by path** and rules that they "are to be **deleted, not
-aligned to 6.14**" — the ruling is that touching their version at all is the
-wrong move, and the deletion belongs to a separate CLEAN task. Rule 3 is the
-general P13 pinning permission; rule 2 is a specific, named exception to it, and
-a binding ADR outranks the mechanical "pin everything".
-
-So `pin-from-pnpm-lock.ts` carries an explicit, commented exclusion list
-(`ADR_017_RULE_2_FROZEN`) for exactly those two entries, and leaves both the
-manifest line and its `specifier:` in the lock at `^5.1.1`. `pnpm-lock.yaml`
-still resolves both to `[email protected]`, and
-`tooling/gates/p13-lock-snapshot.json` records `5.9.1` for them — the snapshot
-is a record of **resolutions**, not of declared ranges, so the drift gate still
-holds these two to an exact installed version.
-
-**What M13-002 must know:** these are the only two direct dependencies whose
-declared range bun gets to resolve itself. Bun re-resolving `^5.1.1` to a newer
-5.x (or the whole `prisma` 5 line vanishing) shows up in `p13-drift.sh` as
-drift, not as a silent change. If the CLEAN task deletes them before the swap,
-the exclusion list and this section become dead and should go with them; until
-then, do not "fix" them in a P13 commit.
-
-That is the precondition for everything below. Bun 1.4.0 **cannot read
-`pnpm-lock.yaml`** (operator survey, 2026-09-07) — it re-resolves the whole
-graph from the declared ranges — so under carets the swap is an uncontrolled
-upgrade of the entire tree (see *Known drift hazards*). A
-manifest full of exact versions turns the swap into something a resolver has to
-*reproduce* rather than *decide*, and `tooling/gates/p13-drift.sh` is what
-checks that it did.
-
-`tooling/gates/p13-lock-snapshot.json` (416 direct dependencies across 20
-workspace packages) is the reference, kept as its own committed file precisely
-because M13-002 deletes `pnpm-lock.yaml`.
-
----
-
-## Why the lock is edited, not refreshed
-
-`pin-from-pnpm-lock.ts` writes the manifests, `pnpm-workspace.yaml`'s catalog
-**and** the matching `specifier:` lines of `pnpm-lock.yaml`. It does not run
-`pnpm install` to have pnpm regenerate the lock, and M13-002 must not either.
-
-The reason is that a non-frozen `pnpm install` does not merely relabel the
-specifiers — it re-resolves the whole graph and dedupes it, which moves the
-baseline in the same commit that is supposed to prove nothing moved.
-
-**Measured on this box, 2026-09-07**, on the pinned tree, with the manifests
-already pinned and only the lock rolled back to `HEAD`'s:
-
-```bash
-# from the pinned working tree
-cp pnpm-lock.yaml /tmp/lock.pinned.yaml
-git show HEAD:pnpm-lock.yaml > pnpm-lock.yaml
-pnpm install --lockfile-only # 24.6s, pnpm 11.23.0
-cp pnpm-lock.yaml /tmp/lock.refreshed.yaml
-cp /tmp/lock.pinned.yaml pnpm-lock.yaml # baseline restored
-```
-
-Comparing `/tmp/lock.refreshed.yaml` against the committed (edited) lock:
-
-| | |
-|---|---:|
-| `packages:` entries, edited lock | 3608 |
-| `packages:` entries, refreshed lock | 3466 |
-| package versions **pruned** by the refresh | **142** |
-| package versions **added** by the refresh | **0** |
-| distinct package names that lost a duplicate copy | 135 |
-| package names that disappeared entirely | 0 |
-| changed lines in the lock diff | 3643 |
-| of those, `specifier:` lines | **0** |
-| importer `version:` lines that changed | 6 |
-| direct dependencies whose resolved version changed | **0** |
-
-Counted with:
-
-```bash
-count() { awk '/^packages:/{f=1;next} /^[a-z]/{f=0} f && /^ [^ ]/{n++} END{print n+0}' "$1"; }
-count /tmp/lock.refreshed.yaml
-diff -u /tmp/lock.pinned.yaml /tmp/lock.refreshed.yaml | grep -cE '^[-+]'
-```
-
-The 142 prunes are duplicate copies collapsing: every pruned name still has a
-surviving copy, and consumers get re-pointed at it. Concretely, `@babel/core`
-goes from four copies (7.24.5, 7.28.3, 7.28.5, 7.29.0) to two, `magicast` from
-three (0.3.5, 0.5.1, 0.5.3) to two, `semver` from nine to six. That is why the
-6 changed importer `version:` lines are peer-resolution **suffix** changes only
-`…(@babel/[email protected]…)` — with the base version identical in all six, which is
-why the snapshot generated from the refreshed lock is byte-identical to the
-committed one.
-
-So the refresh moves no direct dependency, but it does move 142 transitive
-resolutions. ADR-014's stop rule is "any pin that cannot be **reproduced**",
-and M13-002 measures bun's tree against the pnpm tree; re-deduping the pnpm
-tree first means measuring against a baseline nobody ever ran, built or
-shipped. Rewriting the `specifier:` fields is the mechanical,
-resolution-preserving half of what that install would have done.
-
-**The three proofs that the edit is legitimate**, all verification commands of
-M13-001:
-
-```bash
-# 1. the lock diff against HEAD touches specifier: lines and nothing else
-git diff -U0 -- pnpm-lock.yaml | grep -E '^[-+]' | grep -vE '^(\+\+\+|---)|specifier:' # prints nothing
-
-# 2. pnpm itself accepts the edited lock as consistent with the manifests
-pnpm install --frozen-lockfile # green
-
-# 3. the installed tree still matches what pnpm had resolved
-bash tooling/gates/p13-drift.sh --assert # exit 0
-```
-
-A fourth, not required but worth knowing: on the edited lock a plain
-`pnpm install --lockfile-only` reports `Already up to date` and rewrites
-nothing, so the hand-edited lock is a fixpoint of pnpm's own resolver rather
-than a file pnpm merely tolerates.
-
----
-
-## 1. Translation table: `pnpm-workspace.yaml` → root `package.json`
-
-Every block of the file is accounted for. Bun has no workspace file; the three
-things it does read all live in the root `package.json`.
-
-| `pnpm-workspace.yaml` block | Lines | Becomes | Notes |
-|---|---|---|---|
-| `packages:` (`apps/*`, `packages/**`, `tooling/*`) | 1–4 | `workspaces.packages: ["apps/*", "packages/**", "tooling/*"]` | Must resolve to the **same 20 importers**. `packages/**` is the one to check: `packages/sdks/*` are members only if bun expands `**` the way pnpm does. If it does not, write the globs out (`packages/*`, `packages/sdks/*`) rather than dropping a member. The check is `bun pm ls` against the 20 keys of `p13-lock-snapshot.json` |
-| `patchedDependencies: { nuqs }` | 7–8 | **deleted** | ADR-014 decision 17. `patches/` and the lock's `patchedDependencies` hash go with it. `bun patch` exists and we deliberately do not use it |
-| `allowUnusedPatches: true` | 10–17 | **deleted** | Its cause dies with the patch: it existed only because the api image installed a workspace subset in which `nuqs` was absent |
-| `verifyDepsBeforeRun: false` | 19–38 | **no bun analogue — dropped** | ADR-014 *Tradeoffs*: this is a pnpm-11 behaviour toggle, not a setting to port. Its cause — `apps/start/Dockerfile` installing ~10 of its 18 importers and then `COPY packages` — **remains**. Whether bun re-resolves in that situation is an empirical question, and `tooling/gates/p13-ssr.sh` is the thing that answers it |
-| `overrides:` (6 entries) | 40–72 | `overrides` in the root `package.json` | Five translate one-for-one; one cannot be expressed — see §1.1 |
-| `catalog:` (10 entries) | 75–85 | `workspaces.catalog` | All ten are now exact (M13-001), so the catalog is a version map, not a range map. Importers keep writing `catalog:` |
-| `allowBuilds:` (12 entries, **all `false`**) | 87–117 | **`trustedDependencies` omitted entirely** | ADR-014 amendment 2. Writing the twelve names in would *invert* the policy. See §2, which is where the real work is |
-
-`workspaces` must therefore be the **object** form, because the array form has
-nowhere to put the catalog:
-
-```jsonc
-"workspaces": {
- "packages": ["apps/*", "packages/**", "tooling/*"],
- "catalog": {
- "zod": "4.3.6",
- "react": "19.2.3",
- "@types/react": "19.2.7",
- "react-dom": "19.2.3",
- "@types/react-dom": "19.2.3",
- "@types/node": "24.10.1",
- "typescript": "5.9.3",
- "pino": "10.3.1",
- "pino-pretty": "13.1.3",
- "@hyperdx/node-opentelemetry": "0.10.3"
- }
-},
-"overrides": {
- "rolldown": "1.0.0-beta.43",
- "esm-env": "npm:esm-env-runtime@^0.1.0",
- "seroval": "1.3.2",
- "seroval-plugins": "1.3.2",
- "embla-carousel": "8.0.0-rc22"
-}
-```
-
-### 1.1 The one row bun cannot express: `"@nuxt/vite-builder>seroval": 1.4.0`
-
-pnpm's `parent>child` override syntax scopes an override to one parent. **Bun's
-`overrides` has no such form** — an override key is a package name, full stop.
-So the exemption that keeps `@nuxt/vite-builder` on `[email protected]` while the
-dashboard graph stays on `1.3.2` has no direct translation.
-
-**Recorded as moot, to be re-proven, not assumed.** In the operator's
-2026-09-07 survey the Nuxt SDK built under the **global `seroval: 1.3.2` pin**,
-with no per-parent exemption. That is consistent with what
-`pnpm-workspace.yaml:60-64` itself says about the row: `@nuxt/vite-builder`
-"only imports `serialize`, which exists in both, so 1.3.2 would very likely
-work" — the exemption was written so a *future* nuxt bump needing a real 1.4
-API would fail loudly in the Nuxt SDK build rather than be silently held back.
-
-So the recipe is: **drop the row, keep the global `seroval`/`seroval-plugins`
-1.3.2 pins, and let the Nuxt SDK build be the proof.** The moment
-`packages/sdks/nuxt` fails to build, the row was not moot after all and — per
-the stop rule — that is an unreproducible pin, not an invitation to bump nuxt.
-
-The two seroval pins themselves are the highest-stakes rows in the whole file:
-they are what stands between the dashboard and `r.createEffectfulFunction is
-not a function` on every SSR route. `tooling/gates/p13-ssr.sh` exists for them.
-
----
-
-## 2. Lifecycle scripts: what pnpm actually ran, and what bun would
-
-### The evidence
-
-**pnpm runs no dependency build script at all.** `allowBuilds` is twelve
-entries and every one is `false`. Measured on this box on 2026-09-07: a
-`pnpm install` on this tree printed exactly two lifecycle scripts, and both are
-**workspace-own** `postinstall`s, not dependency ones:
-
-```
-apps/testbed postinstall$ node scripts/copy-op1.mjs
-apps/public postinstall$ fumadocs-mdx
-```
-
-**Bun's default is not "run nothing".** Bun ships a built-in trusted list, and
-it is large. Measured on this box on 2026-09-07 with `bun pm default-trusted`
-(Bun 1.4.0): **367 packages**, of which **8 of the 12 `allowBuilds: false`
-entries are on it** —
-
-| on bun's default-trusted list | not on it |
-|---|---|
-| `@prisma/client`, `@prisma/engines`, `prisma`, `esbuild`, `msgpackr-extract`, `sharp`, `simple-git-hooks`, `workerd` | `@biomejs/biome`, `@parcel/watcher`, `@tailwindcss/oxide`, `protobufjs` |
-
-A bare `bun install` therefore runs install scripts for eight packages whose
-scripts have **never run** in any image this repo has ever shipped. That is
-precisely the inversion ADR-014 amendment 2 forbids, and the repo already has
-the scar: flipping `allowBuilds` to `true` during the pnpm 11 bump made
-`sharp`'s install script attempt a node-gyp compile under
-`npm_config_build_from_source=true` and broke the dashboard build
-(`pnpm-workspace.yaml:98-103`, reverted in `4e715348`).
-
-**And one of the eight fails outright.** In the operator's 2026-09-07 survey,
-`simple-git-hooks`'s `postinstall` — which assumes a hoisted layout and walks
-up to find `.git` — crashed under `bun install --linker=isolated`, the layout
-ADR-014 amendment 1 makes the default attempt.
-
-### The policy M13-002 uses
-
-**`--ignore-scripts` on every install command**, not a `trustedDependencies`
-array.
-
-- It reproduces pnpm's *actual behaviour* (nothing ran) rather than a
- hand-maintained approximation of it.
-- `trustedDependencies` is an allow-list layered on top of a 367-entry default;
- omitting it does **not** get you "nothing", it gets you those 367. The only
- formulation whose meaning does not depend on what a future bun release adds
- to its default list is the flag.
-- It is one word per install command, greppable, and identical in the
- Dockerfiles, in CI and on a laptop — which is what makes "did a script run?"
- answerable from the command line rather than from a list.
-- ADR-014 amendment 2 already says the field is omitted entirely. This is the
- same ruling stated as a positive: omit the field **and** pass the flag.
-
-**The two workspace-own `postinstall`s must still run**, because they are build
-steps the tree depends on (`apps/public`'s `fumadocs-mdx` generates the MDX
-index; `apps/testbed`'s copies `op1.js` into `public/`). `--ignore-scripts`
-suppresses them too, so every install site gains an explicit follow-up:
-
-```bash
-bun install --linker=isolated --frozen-lockfile --ignore-scripts
-bun run --filter public postinstall
-bun run --filter testbed postinstall
-```
-
-Naming them is a feature: it makes the set of scripts this repo runs a list in
-one file rather than a property of a resolver's defaults.
-
-> **Superseded in part by M13-002.** The policy is right; the *home* is not the
-> command line. The gates and `verification/full.sh` run a bare
-> `bun install --frozen-lockfile` with no flags of ours, so the flag would be
-> off exactly where it matters. Both settings live in the root `bunfig.toml`
-> instead (`[install] ignoreScripts = true` and `linker = "isolated"`), which
-> makes every install command — flagged or bare — obey them. The two
-> workspace-own `postinstall`s are now invoked by the scripts that need their
-> output, and `bun run postinstall:workspaces` runs both explicitly. See
-> *Lifecycle scripts: `bunfig.toml`, not a flag* below.
-
----
-
-## 3. Every `package.json` script that shells out to `pnpm`
-
-Measured 2026-09-07: **25 scripts across 5 manifests** — root, `apps/api`,
-`apps/start`, `packages/core`, `packages/db`. Verified on Bun 1.4.0 on this
-box: `bun run <script> <args…>` forwards trailing arguments to the script body
-exactly as `pnpm <script> <args…>` does, so every `pnpm with-env X` becomes
-`bun run with-env X` with no change to `with-env` itself; and `bun run` takes
-`-F, --filter=<pattern>` — "Run a script in all workspace packages matching the
-pattern" — which is what replaces `pnpm -r --filter`.
-
-### `package.json` (root)
-
-| script | today | bun |
-|---|---|---|
-| `test` | `pnpm --filter @openpanel/core run test && pnpm --filter @openpanel/db run test && pnpm --filter @openpanel/api run test && pnpm --filter start run test && vitest run` | `bun run --filter @openpanel/core test && bun run --filter @openpanel/db test && bun run --filter @openpanel/api test && bun run --filter start test && vitest run` |
-| `gen:bots` | `pnpm -r --filter core gen:bots` | `bun run --filter core gen:bots` |
-| `gen:referrers` | `pnpm -r --filter core gen:referrers` | `bun run --filter core gen:referrers` |
-| `db:codegen` | `pnpm -r --filter db run codegen` | `bun run --filter db codegen` |
-| `codegen` | `pnpm -r --filter db --filter core run codegen` | `bun run --filter db codegen && bun run --filter core codegen` — bun takes one `--filter` pattern per run; keep the **db-then-core order**, core's codegen reads db's generated client |
-| `migrate` | `pnpm -r --filter db run migrate` | `bun run --filter db migrate` |
-| `migrate:deploy` | `pnpm -r --filter db run migrate:deploy` | `bun run --filter db migrate:deploy` |
-| `dev` | `pnpm --filter api run testing & pnpm --filter start run dev & wait` | `bun run --filter api testing & bun run --filter start dev & wait` |
-| `dev:public` | `pnpm -r --filter public dev` | `bun run --filter public dev` |
-| `typecheck` | `pnpm -r --no-bail typecheck` | `bun run --filter '*' typecheck` — **behaviour gap:** `--no-bail` makes pnpm typecheck every workspace and report all failures. Bun has no `--no-bail`. If it stops at the first failure, the script must keep going by construction (a loop over the workspace list, collecting exit codes) or the gate silently narrows to "the first package that fails" |
-| `check:workspace` | `pnpm dlx sherif@latest` | `bunx sherif@<pinned>` — pin it while touching it (ADR-014 benchmark item 13; it is unpinned today) |
-| `check:deps` | `NODE_PATH=$PWD/node_modules pnpm dlx --package [email protected] depcruise …` | ~~`bunx --package [email protected] depcruise …`~~ — **the one row this translation gets wrong.** `bunx` cannot give dependency-cruiser TypeScript, so every `import type` edge stops being `type-only` and the gate returns 82 false errors. M13-002 replaced it with `bun tooling/scripts/check-deps.ts`; **M14-002 then deleted that runner** in favour of a declared `dependency-cruiser` devDependency, whose peer *does* resolve under `linker = "isolated"` — so `check:deps` is now a plain `depcruise …`. See *`check:deps` is the one script that is not a `bunx`* below |
-| `check` | `ultracite check && pnpm run check:deps` | `ultracite check && bun run check:deps` |
-
-### `apps/api/package.json`
-
-| script | today | bun |
-|---|---|---|
-| `testing` | `API_PORT=3333 pnpm dev` | `API_PORT=3333 bun run dev` |
-
-### `apps/start/package.json`
-
-| script | today | bun |
-|---|---|---|
-| `dev` | `pnpm with-env vite dev --port 3000` | `bun run with-env vite dev --port 3000` |
-| `build` | `pnpm with-env vite build` | `bun run with-env vite build` |
-| `start_deprecated` | `pnpm with-env node .output/server/index.mjs` | `bun run with-env node .output/server/index.mjs` |
-| `deploy` | `pnpm build && npx wrangler deploy` | `bun run build && bunx wrangler deploy` |
-
-`apps/start`'s `build` is the one the SSR gate drives, so it is the one that
-must be right first.
-
-### `packages/core/package.json`
-
-| script | today | bun |
-|---|---|---|
-| `migrate:deploy:code` | `pnpm with-env jiti ./src/code-migrations/migrate.ts` | `bun run with-env bun ./src/code-migrations/migrate.ts` — ADR-019 row 7b already replaces `jiti` with bun as the TS runner |
-
-> **Superseded, M15-204:** `code-migrations` left core for `@openpanel/db`
-> (ADR-022, Carl's rulings), so `packages/core` no longer declares
-> `migrate:deploy:code` at all and `packages/db`'s own entry below runs
-> `bun run with-env bun ./scripts/migrate-code.ts` directly instead of
-> filtering back to core. The rows are kept as the P13 record.
-
-### `packages/db/package.json`
-
-| script | today | bun |
-|---|---|---|
-| `codegen` | `pnpm with-env prisma generate && jiti prisma/prisma-json-types.ts` | `bun run with-env prisma generate && bun prisma/prisma-json-types.ts` |
-| `migrate` | `pnpm with-env prisma migrate dev` | `bun run with-env prisma migrate dev` |
-| `migrate:deploy:db` | `pnpm with-env prisma migrate deploy` | `bun run with-env prisma migrate deploy` |
-| `migrate:deploy:code` | `pnpm --filter @openpanel/core run migrate:deploy:code` | `bun run --filter @openpanel/core migrate:deploy:code` |
-| `migrate:deploy` | `pnpm migrate:deploy:db && pnpm migrate:deploy:code` | `bun run migrate:deploy:db && bun run migrate:deploy:code` |
-| `duplicate-events` | `pnpm with-env jiti ./scripts/find-duplicate-events.ts` | `bun run with-env bun ./scripts/find-duplicate-events.ts` |
-
-**Out of this file's scope but in the same release** (ADR-014 *Migration
-impact*): the shipped self-hosting templates —
-`self-hosting/docker-compose.template.yml`, `self-hosting/coolify.yml` and
-`.github/smoke/docker-compose.yml` — invoke `pnpm` **inside the api image** at
-container start. They must change in the same release as the image, or
-self-hosters' containers fail at boot.
-
----
-
-## 4. The SSR gate procedure
-
-`tooling/gates/p13-ssr.sh`. It is **green under pnpm today** — that is the
-baseline the swap is measured against — and M13-002 runs it **unchanged**. The
-only installer-specific thing in it is which binary runs the workspace's own
-`build` script, detected the way `verification/full.sh` detects it: a committed
-`bun.lock` means bun installed the tree.
-
-```bash
-bash tooling/gates/p13-ssr.sh
-```
-
-What it does, in `apps/start/Dockerfile`'s order:
-
-1. **Builds** `apps/start` with `NITRO=1 SELF_HOSTED=1` through the package's
- own `build` script (which goes through `with-env`, i.e. the repo `.env`).
-2. **Reproduces the runner stage's `esm-env` shim** and its
- `BROWSER=false / NODE=true / DEV=false` assertion. The standalone Nitro
- output ships `esm-env-runtime` under the `esm-env` override, so `esm-env`
- has to be made resolvable inside the SSR bundle; without it,
- `@number-flow/react` is a hard `ERR_MODULE_NOT_FOUND` at first render. This
- is the `overrides` row whose failure mode is invisible until a page renders.
-3. **Boots `apps/api` (`ROLE=api`) and then `.output/server/index.mjs`**, each
- on a free port, with the `app_env` block from
- `.github/smoke/docker-compose.yml` pointed at this box's already-running
- services and at the api it just started. Databases are the **isolated
- `openpanel_test` Postgres and ClickHouse**, never the prod-copy `openpanel`
- ones; both asserted routes read no analytics, so the cost is one session
- lookup.
-4. **Asserts exactly what `.github/smoke/smoke.sh`'s `assert_ssr_route`
- asserts** — HTTP 200, an `<html` in the body, at least 1000 bytes — for
- **`/login`** and **`/onboarding`**.
-5. **Greps the dashboard log** for
- `is not a function|Cannot find (module|package)|ERR_MODULE_NOT_FOUND|ERR_PACKAGE_PATH_NOT_EXPORTED`
- and fails on any hit — `assert_no_server_errors`, so an SSR failure
- swallowed into a 200 still shows up.
-
-It always kills the two servers it started, on success, on failure and on an
-interrupt. Logs land in `/tmp/openpanel-p13-ssr/` (`P13_SSR_RUN_DIR` to move
-them).
-
-**Why `/onboarding` is the second route.** ADR-014's gate wants "`/login` plus
-one dashboard route", and every route past `/login` needs a session the smoke
-stack has never seeded. `/onboarding` is the create-an-account page and renders
-**without** a session by construction: its `beforeLoad` redirects only when a
-session *exists*, and its loader is a no-op unless an `inviteId` search param is
-present, so an anonymous request needs no seeded row. It also sits under the
-`_public` layout rather than `/login`'s `_login` one, so the two assertions
-cover two different server-rendered subtrees instead of the same layout twice.
-
-**Run it with `tooling/gates/p13-drift.sh --assert`**, not instead of it. The
-drift gate answers "did anything move?" and the SSR gate answers "does it still
-work?" — main-8e60 was green on the second question's cheaper cousin (the
-build) and red on the real one.
-
----
-
-## Known drift hazards
-
-**The installer swap is not an upgrade.** Everything in this section is what
-happens when it is allowed to become one.
-
-### What a bare `bun install` did to this tree
-
-Operator survey, throwaway worktree, 2026-09-07 — **before** M13-001 pinned the
-manifests, i.e. against the carets that were there:
-
-| Workspace | direct deps | re-resolved to a **newer** version |
-|---|---:|---:|
-| `apps/start` | 165 | **86** |
-| `packages/core` | 67 | **27** |
-| `apps/public` | 43 | **9** |
-
-Named examples: `prisma` 6.14 → **6.19**, `@clickhouse/client` 1.18 → **1.23**,
-`nuqs` 2.5.2 → **2.10.1**. (The per-workspace direct-dependency counts are this
-task's own measurement, from `tooling/gates/p13-lock-snapshot.json`.)
-
-Two things then broke, both downstream of that re-resolve, neither of them in
-the installer:
-
-- **`apps/api` failed to boot**: `Export named 'Unsafe' not found` from
- `@sinclair/[email protected]` — a transitive of the Elysia stack that a
- different resolution paired with a copy expecting a different export surface.
-- **`apps/public` failed to build**: `activeAnimations` missing from
- `motion-dom`, and `renderTranslation` missing from `fumadocs-core/i18n` — the
- same shape of failure, twice, in a workspace that is not even part of the
- backend rewrite.
-
-Note what these have in common with the seroval incident
-(`pnpm-workspace.yaml:19-37`): a resolver picked a *newer, in-range* version of
-a package nobody edited, and the failure surfaced somewhere that looks like
-application code. `prisma` 6.14 → 6.19 also crosses ADR-017 row 3
-(**REFUSED** — 6.14.0 already carries both preview features) and ADR-012, which
-pins `@prisma/adapter-pg` to `6.14.0` *because it matches the client exactly*.
-A silent 6.19 breaks a decision, not just a build.
-
-### The rule that follows
-
-> **Drift is fixed by exact pins and `overrides` that cite the breakage — never
-> by editing code to fit a newer dependency.**
-
-Concretely, when M13-002 hits a version that moved:
-
-1. **Pin it back**, using `tooling/gates/p13-lock-snapshot.json` as the source
- of truth for what it was. `tooling/gates/p13-drift.sh --assert` is the check.
-2. If a **transitive** moved, add an `overrides` entry and **write the
- breakage into a comment next to it**, the way every row in
- `pnpm-workspace.yaml` does today. An override with no recorded symptom is
- the next person's mystery.
-3. If neither works, **stop.** ADR-014's stop rule is not a last resort to be
- argued around — it is the decision. The repo stays on pnpm and the backend
- rewrite loses nothing, because Bun has run a pnpm-built `node_modules` since
- P3.
-
-What is **never** the fix:
-
-- changing application source so it compiles against a newer dependency (that
- is the upgrade the swap is not allowed to be, and it makes the swap
- unrevertible);
-- bumping a declared range to "whatever bun picked" (ADR-017 rule 3: the
- lockfile swap must not carry a declared-range change in the same commit);
-- relaxing a gate. `--linker=hoisted` instead of `isolated` is allowed *only*
- with a recorded reason and a re-run of the full gate (ADR-014 amendment 1),
- because a hoisted layout resolves phantom dependencies by accident and turns
- an install-time failure into a container-time one.
-
-### Two smaller hazards worth naming
-
-- **Workspace-vs-registry linking.** `apps/start` depends on
- `@openpanel/[email protected]` **from npm** while `packages/sdks/web` is
- `1.4.1-local`; `apps/public` likewise takes `@openpanel/[email protected]` from
- npm. If bun's workspace-linking default differs from pnpm's, the dashboard
- silently starts running a different copy of its own tracking SDK. Both are in
- the snapshot at their registry versions, so `p13-drift.sh` sees the flip.
-- **`bun install` re-resolving inside a Docker build stage.** This is the
- main-8e60 mechanism in a new costume: `apps/start/Dockerfile` installs a
- subset, then `COPY packages`, then builds. `--frozen-lockfile` on every
- install command is what makes that re-resolve an error instead of a silent
- rewrite — and it is the successor to `verifyDepsBeforeRun: false`, which has
- no bun analogue.
-
----
-
-# M13-002 — the swap, as executed
-
-Everything below was executed on this box on **2026-09-07**, by the M13-002
-implement task, on Bun **1.4.0** and pnpm **11.23.0**. Every number is from a
-run recorded here; nothing is carried over from the M13-001 survey.
-
-The stop rule did **not** fire. Every gate ADR-014 names is green under the bun
-tree, `verification/full.sh` included. One of them — the SDK dist gate — needed
-a one-line controller fix first, for a reason worth knowing before you write any
-script against this tree; see *pnpm can no longer run a script inside this tree*
-below.
-
-## What bun's `overrides` actually do — measured, not assumed
-
-Four properties, each established by installing this tree and reading the
-result. They are what the table in the next section is built on, and three of
-them are counter-intuitive enough to be worth writing down.
-
-1. **Overrides apply to `peerDependencies`.** Nine of the eleven initial drift
- rows were peers pnpm auto-installed and bun resolved differently; six were
- fixed by a plain `"<name>": "<version>"` override.
-2. **A `name@spec` key matches when the *requested* range is a SUBSET of the
- key's range.** Key `prisma@^5.1.1` matched the two `^5.1.1` devDeps and left
- `packages/db`'s `prisma: 6.14.0` alone. Key `next@^12.0.0` did **not** match
- a request of `^12.0.0 || … || ^16.0.0` (the union is not a subset of
- `^12.0.0`), while a key spelled as that whole union **did** match a request
- of `16.0.7`. So the key must be a superset of the request; it is not an
- intersection test.
-3. **Two keys that both match one request cancel — for the whole package
- name.** With `[email protected]` and `next@^12.0.0 || … || ^16.0.0` both present,
- *neither* applied to *either* importer. This is why §"the three exact pins"
- below could not be an override.
-4. **A new override is only honoured on a fresh resolve.** Adding an override
- and re-running `bun install` against an existing `bun.lock` left already-
- locked peers at their old versions; `nuxt`, `expo-application` and
- `react-native` only moved after `rm bun.lock`. Anyone adding a row here must
- delete the lockfile, not amend it.
-
-Two forms were tried and do **not** work on Bun 1.4.0: `overrides` declared in a
-workspace member's own `package.json` (silently ignored — verified against
-`packages/sdks/nextjs`), and yarn-style path keys in `resolutions`
-(`"@openpanel/nextjs/next"` — silently ignored).
-
-## Overrides
-
-Every row, with the breakage it fixes. Rows 1–5 are carried over from
-`pnpm-workspace.yaml`; rows 6–15 are new in M13-002 and each cites the failure
-it was added for. The one pnpm row that is **not** here is
-`"@nuxt/vite-builder>seroval": 1.4.0` — see §1.1 above; it is dropped because
-bun cannot express a parent-scoped override, and it is proven moot by
-`cd packages/sdks/nuxt && bun run build` succeeding under the global
-`seroval: 1.3.2` pin (run 2026-09-07, `✔ Build succeeded for nuxt`, 4.14 kB).
-
-| # | Override | Breakage it fixes |
-|---|---|---|
-| 1 | `rolldown: 1.0.0-beta.43` | Carried from pnpm. **Now inert** — no package in `bun.lock` requests `rolldown` (tsdown was deleted in M12). Kept because ADR-017 rules the register frozen: "the `rolldown` override … stays on purpose" |
-| 2 | `esm-env: npm:esm-env-runtime@^0.1.0` | Carried. Resolves to `[email protected]`. Without it `@number-flow/react`'s `import "esm-env"` is `ERR_MODULE_NOT_FOUND` at first SSR render. Proven by `p13-ssr.sh`'s in-bundle assertion (`BROWSER=false, NODE=true, DEV=false`) |
-| 3 | `seroval: 1.3.2` | Carried. The dashboard pin. `bun.lock` contains exactly one `[email protected]` and one `[email protected]` — no 1.4.x anywhere. Proven by `p13-ssr.sh` (`/login` 152348 bytes, `/onboarding` 156301 bytes, dashboard log clean) |
-| 4 | `seroval-plugins: 1.3.2` | Carried, same failure as row 3 |
-| 5 | `embla-carousel: 8.0.0-rc22` | Carried. `AutoplayType` vs `CreatePluginType`; the failure mode is `apps/start` failing to typecheck. Proven by `start` PASS in `bun run typecheck` |
-| 6 | `express: 4.19.2` | `packages/sdks/express`'s peer `express: ^4.17.0 \|\| ^5.0.0` resolved to **5.2.1**; the snapshot has 4.19.2. Drift row |
-| 7 | `prisma@^5.1.1: 5.9.1` | The two ADR-017 rule 2 carve-out devDeps (`packages/redis`, `packages/sdks/_info`) resolved to **5.22.0**; the snapshot has 5.9.1. Spec-scoped so `packages/db`'s `prisma: 6.14.0` is untouched — the declared `^5.1.1` ranges are **not** edited, which is what rule 2 forbids |
-| 8 | `h3: 1.15.4` | `packages/sdks/nuxt`'s peer `h3: ^1.0.0` resolved to **1.15.11**. Drift row |
-| 9 | `nuxt: 4.2.2` | `packages/sdks/nuxt`'s peer `nuxt: ^3.0.0 \|\| ^4.0.0` resolved to **4.5.2**. Drift row |
-| 10 | `react-native: 0.73.6` | `packages/sdks/react-native`'s peer `react-native: *` resolved to **0.87.1**. Drift row |
-| 11 | `expo-application: 5.3.1` | Same package's peer `5 - 7` resolved to **7.0.8**. Drift row |
-| 12 | `expo-constants: 15.4.5` | Same package's peer `14 - 18` resolved to **18.0.14**. Drift row |
-| 13 | `framer-motion@^12.40.0: 12.40.0` | With `motion`'s `framer-motion: ^12.40.0` free, bun took **12.43.0**, which requests `motion-dom: ^12.43.0` and drags row 14's single copy forward. pnpm resolved this edge to 12.40.0 |
-| 14 | `motion-dom@^12.23.23: 12.40.0` | **`cd apps/public && bun run build` failed**: `Attempted import error: 'activeAnimations' is not exported from 'motion-dom'`, from `[email protected]/dist/es/projection/node/create-projection-node.mjs`, traced through `HTMLProjectionNode.mjs` → `use-instant-layout-transition.mjs` → `src/components/navbar.tsx`; `Build failed because of webpack errors`. pnpm carried four `motion-dom` copies (11.18.1 / 12.23.23 / 12.38.0 / 12.40.0); bun collapses the whole 12.x line onto one, and it chose 12.43.0. Measured on this box: `activeAnimations` is exported by 12.23.23, 12.38.0 and 12.40.0 and **absent** in 12.43.0, so 12.40.0 is the one version that satisfies every 12.x requester here. Subset matching (property 2) makes the single `^12.23.23` key cover `^12.38.0` and `^12.40.0` too |
-| 15 | `lucide-react@^1.7.0: 0.555.0` | **`apps/public` failed to typecheck** with a ~40-line `fumadocs-core` structural mismatch ending in `Types have separate declarations of a private property 'flattenPathToFullPath'`, between `[email protected]+3b8a98ceba1412f0` and `[email protected]+18a2f888045eb88b`. Same version, two peer-hashed copies, differing in exactly one entry: which `lucide-react` filled `fumadocs-core`'s **optional** peer `lucide-react: "*"` — `0.555.0` (apps/public's own pin) for apps/public + `fumadocs-mdx`, `1.42.0` for `fumadocs-ui` + `fumadocs-openapi`. pnpm resolved that optional peer to 0.555.0 for *every* consumer and produced ONE `fumadocs-core`; bun resolves it per scope. Forcing the `^1.7.0` requesters onto the same 0.555.0 collapses the two instances. **Residual risk, stated:** `fumadocs-ui`/`fumadocs-openapi` now run a lucide-react a major below what they declare. The webpack build is the check — it reports every unresolved named import (that is how row 14 was found) and reported none for lucide-react across 242 generated pages |
-| 16 | `vue: 3.5.25` | **`packages/sdks/nuxt` failed to typecheck**: `src/runtime/plugin.client.ts(11,16): error TS2664: Invalid module name in augmentation, module '@vue/runtime-core' cannot be found.` `[email protected]` resolved `vue` to **3.5.42** under bun (pnpm: 3.5.25), which put `@vue/[email protected]` in the tree beside the `3.5.25` the package declares as a devDep, and the augmentation resolved to neither. Pinning `vue` back to pnpm's 3.5.25 leaves exactly one `@vue/runtime-core` |
-
-## The three exact pins, and why they are not overrides
-
-`packages/sdks/nextjs` gains three **devDependencies** at exact versions:
-
-```jsonc
-"next": "15.0.3", "react": "19.1.1", "react-dom": "19.1.1"
-```
-
-Its `peerDependencies` are **not** touched — the published contract is byte
-identical. These three are the versions pnpm's `auto-install-peers` put in
-`packages/sdks/nextjs/node_modules`, and they are already recorded as such in
-`tooling/gates/p13-lock-snapshot.json`. Bun instead deduped them onto
-`apps/public`'s `next: 16.0.7` and the catalog's `react`/`react-dom: 19.2.3`.
-
-An override cannot express this. The only `name@spec` key that matches the
-peer's request (`^12.0.0 || ^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0`) is a
-superset of it, and every such superset also matches `apps/public`'s `16.0.7`
-(property 2) — measured: the union key moved `apps/public` to 15.0.3 and
-`apps/testbed` to react 19.1.1, trading three drift rows for three others.
-Adding a second, narrower key to exempt them cancels both (property 3). A
-workspace-level `overrides` block and a yarn path key are both ignored.
-
-So the mechanism is the other one the task allows: an **exact pin**, declaring
-in the manifest what pnpm did implicitly. It is the smallest change that makes
-`p13-drift.sh --assert` exit 0, and it is worth flagging to a reviewer as the
-one row in this swap that adds declarations rather than constraining
-resolution.
-
-## `packageManager` is removed, not repointed to bun
-
-The field is **deleted** from the root `package.json` rather than rewritten to
-
-`packageManager` is corepack's field, and corepack shims npm/pnpm/yarn — it has
-never installed or dispatched bun. Leaving `[email protected]` there after the swap
-would be a lie a `corepack enable` would act on; writing `[email protected]` would name
-a value nothing on this box reads, and ADR-016 rule 5 is explicit that *"an
-unasserted exact pin is worse than a range, because it reads as a guarantee and
-is not one"*. Bun's version pin already has a home a build actually reads —
-`apps/api/Dockerfile:4`'s `ARG BUN_VERSION=1.4.0`, feeding
-`oven/bun:${BUN_VERSION}-slim` — so a second copy in `package.json` would add a
-drift site and no enforcement. (ADR-016 also names a `.bun-version` file; that
-file does not exist in this tree. Creating it is outside M13-002's scope —
-recorded in `docs/TECH_DEBT.md`.)
-
-`bunx [email protected]` (`check:workspace`) notices: its `root-package-manager-field`
-rule wants the field present. That is the only row the deletion adds — sherif
-goes from **25 issues (19 errors)** at `HEAD` to **26 (20)** here, both measured
-on 2026-09-07 with the same pinned sherif. The other 19 are pre-existing
-declared-range facts ADR-017 freezes, so this script was already red and is not
-a gate anything passes today.
-
-**Update, M13-005:** once the other 19 pre-existing issues were cleaned up,
-`sherif exits 0` became a real, load-bearing acceptance criterion rather than
-an already-red script — so `root-package-manager-field` needed an actual
-answer instead of a deferral. The reasoning above (`packageManager` is
-corepack's field; corepack never runs bun; Bun does not enforce it, ADR-016
-Problem 2) still stands and `packageManager` itself is still not written. What
-M13-005 adds is `devEngines.packageManager`:
-
-```json
-"devEngines": {
- "packageManager": { "name": "bun", "version": ">=1.4.0", "onFail": "warn" }
-}
-```
-
-`devEngines` is a different field from `packageManager` — no corepack shim
-reads it, so it cannot "lie" to one. And it carries a **range**
-(`>=1.4.0`, byte-identical to `engines.bun`), not an exact pin, so it does not
-trip ADR-016 rule 5's actual objection ("an unasserted *exact* pin is worse
-than a range"). It is one more unenforced assertion alongside the three rule 5
-already names (`scripts/doctor.sh`, `scripts/bootstrap.sh`, `main.ts`'s boot
-log) — sherif's rule only checks the field's presence, not that anything acts
-on it, so this closes the gate without adding a value a future bump has to
-remember to keep in sync with anything exact.
-
-## `check:deps` is the one script that is not a `bunx`
-
-`pnpm dlx X` -> `bunx X` is right everywhere except here, and it is worth
-knowing why before someone "simplifies" it back.
-
-dependency-cruiser only tags an edge `type-only` when it can load the
-TypeScript compiler, and `type-only` is exactly what
-`.dependency-cruiser.cjs`'s `core-uses-ctx-not-db-internals` exempts
-(`dependencyTypesNot: ['type-only']`). It resolves `typescript` — its own
-*optional peer* — from its own directory, an ESM lookup that `NODE_PATH` cannot
-influence at all. `pnpm dlx` satisfied that by accident: pnpm auto-installs
-optional peers, so the dlx sandbox contained TypeScript next to the cruiser.
-
-Measured on this box on 2026-09-07, same tree, same config, `depcruise --info`
-plus the full cruise over `apps/start packages`:
-
-| runner | `typescript` found | result |
-|---|---|---|
-| `pnpm dlx --package [email protected]` | `[email protected]` | `no dependency violations found (2703 modules, 18121 dependencies)` |
-| `bunx --package [email protected]` | `-` | **82 errors** (2695 modules, 17845 dependencies) |
-| `npx --yes --package [email protected]` | `-` | 82 errors |
-| `npx --yes -p [email protected] -p [email protected]` | `-` | 82 errors |
-
-All 82 are `import type` lines the rule allows. The failure is silent and it is
-the wrong direction — a gate that goes red on correct code. It is also **not**
-caused by the installer: `bunx` produces the same 82 on a pnpm-installed tree
-(verified by restoring `HEAD` and re-running).
-
-So, through P13, `check:deps` was `bun tooling/scripts/check-deps.ts`, which
-installed `[email protected]` and `[email protected]` **together,
-hoisted**, into `node_modules/.cache/depcruise` and ran the tool from there. It
-reproduced `pnpm dlx`'s numbers exactly (`2703 modules, 18121 dependencies`,
-zero violations).
-
-**Superseded by M14-002 (2026-09-08).** The runner is deleted and `check:deps`
-is now a plain `depcruise` against a **declared** root devDependency
-(`"dependency-cruiser": "18.2.0"`), which ADR-017's register — reopened after
-P13 by Carl — permits. The row above still holds for `bunx`: what changed is
-that a *declared* dependency is not a `bunx` one. Under `linker = "isolated"`
-bun's store is `node_modules/.bun/` **inside the repo**, so node's upward walk
-from the cruiser's real directory still finds the repo root's
-`node_modules/typescript`; a global `bunx` cache directory is outside the repo
-and never could. Measured 2026-09-08: `bunx --no-install depcruise --info`
-reports `✔ typescript … [email protected]`, and the cruise reproduces the
-runner's numbers on the same tree (2700 modules, 18121 dependencies, 0 errors).
-No hoist exception was needed. Full detail in `docs/TECH_DEBT.md`.
-
-## Lifecycle scripts: `bunfig.toml`, not a flag
-
-The recipe's §2 policy is `--ignore-scripts` on every install command. **That is
-not sufficient**, because the gates and `verification/full.sh` run a *bare*
-`bun install --frozen-lockfile` with no flags of ours. The policy therefore
-lives in the root `bunfig.toml`:
-
-```toml
-[install]
-ignoreScripts = true
-linker = "isolated"
-```
-
-Both keys were verified to be honoured on Bun 1.4.0 before being relied on —
-unknown keys in `bunfig.toml` are *silently ignored* (the same trap
-`packages/core/bunfig.toml` records for `[test] isolate`), so "it is in the
-file" is not evidence:
-
-- `ignoreScripts`: a scratch package depending on `[email protected]`
- (default-trusted) fails its postinstall under `--linker=isolated` with a bare
- `bun install`; with `[install] ignoreScripts = true` the same install exits 0
- and runs nothing. Identical to passing `--ignore-scripts`.
-- `linker`: a scratch install with only `[install] linker = "isolated"` produced
- `node_modules/.bun/`, the isolated layout.
-
-`trustedDependencies` is absent, per ADR-014 amendment 2. Note for the record
-that `bun pm ls --trusted` is **not** empty on this tree — it prints
-`[email protected]`, because that package is on bun's 367-entry default
-list. ADR-014's benchmark item 6 asked for that command to be empty; the
-honest reading is that the list is not the enforcement point and never was.
-`ignoreScripts` is, and the observable fact it asked for — no dependency build
-script runs — holds: a full install prints no lifecycle script output, and
-`sharp`, `prisma`, `esbuild`, `msgpackr-extract` and `workerd` are all
-installed with their install scripts unrun, exactly as under pnpm.
-
-The two **workspace-own** postinstalls that pnpm did run (`apps/public`'s
-`fumadocs-mdx`, `apps/testbed`'s `node scripts/copy-op1.mjs`) are suppressed by
-the same setting, and both generate gitignored build inputs. Each is now
-invoked by the script that needs its output (`apps/public`'s `build` /
-`preview` / `deploy`, which already did this in `typecheck`; `apps/testbed`'s
-`build` / `dev`), so a package is buildable straight after an install with no
-follow-up step to remember. `bun run postinstall:workspaces` runs both
-explicitly for anyone who wants the pnpm-era behaviour back.
-
-## `jiti` is gone from every script (ADR-019 row 7b)
-
-`apps/api` invoked `jiti` in three scripts and **never declared it** — pnpm's
-layout happened to make the binary reachable. Under `--linker=isolated` it is
-not: `bun run e2e:sessions` fails with `Error: spawn jiti ENOENT`. That is the
-phantom dependency the isolated layout exists to surface, and ADR-019 row 7b
-(**ADOPT**, P12) already rules the fix: `jiti X.ts` → `bun X.ts`. Applied to
-`apps/api`'s `test:manage` / `e2e:sessions` / `e2e:sessions:stress` and to
-`tooling/publish`'s `publish`, alongside the `packages/db` and `packages/core`
-entries the recipe's §3 table already listed.
-
-The `jiti` **devDependency** in `packages/core` and `packages/db` stays
-declared. Deleting it is ADR-017 rule 2's separate CLEAN task, and removing it
-here would make `p13-drift.sh` report it `missing`.
-
-## `typecheck` and the missing `--no-bail`
-
-`pnpm -r --no-bail typecheck` had no bun equivalent (recipe §3 flagged it).
-Root `typecheck` is now `bun tooling/scripts/typecheck-workspaces.ts`, which
-expands the same three workspace globs, runs every package that declares a
-`typecheck` script (17 of them) at CPU-count concurrency, prints each result,
-and exits 1 listing every failure — the "keep going by construction" the recipe
-asked for.
-
-## pnpm can no longer run a script inside this tree — and one gate needed that
-
-Recorded because it cost two blocked attempts and it will surprise the next
-person: after this swap, **any** invocation of `pnpm run <script>` inside this
-repo fails before it does any work. pnpm 11 verifies `node_modules` against the
-workspace before running a script and re-installs on mismatch — that is what
-`pnpm-workspace.yaml`'s `verifyDepsBeforeRun: false` suppressed, and that file
-is deleted. The implicit install then dies on
-
-```
-[ERR_PNPM_CATALOG_ENTRY_NOT_FOUND_FOR_SPEC] No catalog entry '@types/node' was found for catalog 'default'
-```
-
-because `catalog:` now resolves from the root `package.json`'s `workspaces.catalog`,
-which pnpm does not read.
-
-`verification/contracts/sdk/dist-gate.sh` shelled out to a hardcoded
-`pnpm run build` and was the sole failing item in `verification/full.sh` for
-exactly this reason. It is a **controller** file — out of this task's scope —
-and the operator has since given it the same `bun.lock` detection
-`full.sh:12-19` carries. Both now pass on this tree:
-
-```
-verification/contracts/sdk/dist-gate.sh → DIST GATE: all 5 checked package(s) clean (rc=0, 2026-09-07)
-verification/full.sh → FULL: green (rc=0, 2026-09-07)
-```
-
-Three repo-side workarounds were tried during the blocked attempts and all
-three are dead ends; they are listed so nobody re-spends them:
-
-| attempt | result |
-|---|---|
-| `.npmrc` (`verify-deps-before-run=false`, via `NPM_CONFIG_USERCONFIG`) | ignored — the implicit `pnpm install` still fired |
-| env var `npm_config_verify_deps_before_run=false` | ignored — `pnpm config get verify-deps-before-run` prints `undefined` |
-| a per-SDK `pnpm-workspace.yaml` in each package directory | works, and is rejected: it re-introduces pnpm config to a repo that just removed it, to satisfy a stale line in a protected script |
-
-The rule that generalises: a script that wants to build or run something in
-this tree invokes `bun`, not `pnpm`. Every caller inside the repo now does. The
-three Dockerfiles still name `pnpm-lock.yaml` (M13-003) and CI still installs
-pnpm (M13-004); both fail this way until they are converted.
diff --git a/docs/MIGRATIONS_FRESH_INSTALL.md b/docs/MIGRATIONS_FRESH_INSTALL.md
deleted file mode 100644
index 49bb5e92c..000000000
--- a/docs/MIGRATIONS_FRESH_INSTALL.md
+++ /dev/null
@@ -1,326 +0,0 @@
-# A fresh install's migrations, measured
-
-**Task M16-004. All numbers below come from runs executed on this box on
-2026-09-12 between 19:50 and 20:00 UTC**, against the local Postgres (5432) and
-ClickHouse (8123), on scratch databases that were dropped afterwards.
-
-Carl's scope (2026-09-12): *"Only thing I want here is our existing migrations
-will work in a similar fashion"*, narrowed to *"I don't feel worried about 2.
-Just try number 1 on new databases is good enough here."* So this is
-**fresh databases only** — upgrade-in-place is deliberately not exercised.
-
-## Verdict, first
-
-| Question | Answer |
-|---|---|
-| Does a brand-new install migrate cleanly, end to end? | **Yes.** Every Prisma migration and every code-migration applied, first try, no errors. |
-| Is the sequence idempotent on a second boot? | **Yes** — and also when the ledger is empty but the tables already exist (extra test below). |
-| Is the `3-init-ch` failure report real? | **The failure is real and reproduces byte for byte — but it is an artifact of the harness M15-203 used, not of a fresh install.** Neither the original explanation nor the operator's hypothesis is the cause. See [`3-init-ch`](#deliverable-2--the-3-init-ch-verdict). |
-| Anything genuinely broken found? | One real hazard, **not** on the first boot: if the *first* boot is interrupted part-way through `3-init-ch`, the *next* boot takes the self-hosting upgrade path on what is really a fresh install. Reported, not fixed — see [Why nothing was fixed](#why-nothing-was-fixed). |
-
-## The shipped command, verified not assumed
-
-`self-hosting/docker-compose.template.yml:152`, `self-hosting/coolify.yml:132`
-and `.github/smoke/docker-compose.yml:85` all run the same two lines in the api
-container's start command, before `bun run start`:
-
-```sh
-cd /app/packages/db && bunx [email protected] migrate deploy
-cd /app/packages/core && bun scripts/migrate-code.ts
-```
-
-`packages/core/scripts/migrate-code.ts` is a one-line forwarder to
-`@openpanel/db/scripts/migrate-code`, which reads the environment and calls
-`runCodeMigrations` (`packages/db/src/code-migrations/migrate.ts`). Both were
-run exactly as written.
-
-## The surface is 153 + 24, not 154 + 27
-
-The task text says 154 Prisma migrations and 27 code-migrations. Measured:
-
-```console
-$ find packages/db/prisma/migrations -mindepth 1 -maxdepth 1 -type d | wc -l
-153
-$ ls packages/db/src/code-migrations/*.ts | grep -E "/[0-9]+-" | wc -l
-24
-```
-
-`ls packages/db/prisma/migrations | wc -l` returns 154 because it counts
-`migration_lock.toml`, which is not a migration. Prisma agrees: *"153 migrations
-found in prisma/migrations"*. The 24 code-migrations are files `1`…`22` with two
-`20-` and two `21-` files. The runner's own plan box lists exactly those 24.
-
-## Reproducing it safely
-
-**The local ClickHouse holds the prod-copy dataset every golden test replays
-against. Read this section before running anything.**
-
-Pointing `CLICKHOUSE_URL` at a scratch database is **not** isolation, for two
-reasons that are easy to miss:
-
-1. `getExistingTables()` (`packages/db/src/clickhouse/migration.ts:174-187`)
- asks `SELECT name FROM system.tables WHERE database = 'openpanel'` — the
- database name is a **literal**, not the one in `CLICKHOUSE_URL`. A run
- pointed at a scratch database still reads the real `openpanel`.
-2. `4-add-sessions.ts:111-114` writes `INSERT INTO openpanel.sessions ... FROM
- openpanel.events` — fully qualified. A run pointed at a scratch database
- would still **write** to the real `openpanel`.
-
-So the drill puts a proxy between the migrations and ClickHouse
-(`docs/migrations-fresh-install/ch-scratch-proxy.ts`) which rewrites every
-`openpanel` token — in the URL and in the SQL — to the scratch database name,
-and refuses outright any request that still names `openpanel` or
-`openpanel_test`. That is also what makes the run *faithful*: the migration's
-own hardcoded database name resolves to the empty scratch database, which is
-what it would find on a real fresh install.
-
-```bash
-# run 1 + run 2, on scratch databases, with the proxy
-bash docs/migrations-fresh-install/fresh-install-drill.sh rewrite
-
-# M15-203's setup: only CLICKHOUSE_URL points at a scratch database
-bash docs/migrations-fresh-install/fresh-install-drill.sh guard
-
-# drops ONLY the scratch databases (refuses openpanel / openpanel_test / postgres)
-bash docs/migrations-fresh-install/fresh-install-teardown.sh
-```
-
-The drill creates `openpanel_m16_004` in both Postgres and ClickHouse
-(`SCRATCH_DB` overrides the name), prints the protected databases' table counts
-before and after, and dies if something is already listening on the proxy port —
-a stale proxy would silently serve the run against the wrong database.
-
-The migrations write a `<migration>.sql` dump next to each migration file
-(`writeSqlDump`, `helpers.ts:79-92`). Those files are **untracked and not
-gitignored**, so `fresh-install-teardown.sh` removes them
-(`rm -f packages/db/src/code-migrations/*.sql`) along with the databases. They are also how M15-203's report came to cite a `3-init-ch.sql` that
-does not exist in the repo: it is generated by the failing run itself.
-
-## Deliverable 1 — what actually happened
-
-`bash docs/migrations-fresh-install/fresh-install-drill.sh rewrite`, 2026-09-12
-19:54:44 UTC, whole drill **7.8 s wall clock** (`time`):
-
-| Step | Result | Time |
-|---|---|---|
-| RUN 1 `bunx [email protected] migrate deploy` | `153 migrations found` → **"All migrations have been successfully applied."** | 3 s |
-| RUN 1 `bun scripts/migrate-code.ts` | all **24** ran, **"Migrations finished"**, exit 0 | 2 s |
-| RUN 2 `bunx [email protected] migrate deploy` | **"No pending migrations to apply."** | 2 s |
-| RUN 2 `bun scripts/migrate-code.ts` | 24 × **"✅ Already Migrated ✅"**, **"Migrations finished"** | 0 s |
-
-**There was no first failure. All 177 applied cleanly** (153 Prisma + 24
-code-migrations).
-
-State after each run, read from the scratch databases themselves:
-
-```
-_prisma_migrations finished: 153
-__code_migrations rows: 24
-clickhouse tables: 33 (25 tables/MVs + 8 .inner_id MV storage tables)
-```
-
-identical after run 2.
-
-The config the run reported: `isClustered: false`, `isSelfHosting: true`
-(`SELF_HOSTED=true`, which is what `self-hosting/.env.template:2`,
-`self-hosting/coolify.yml` and `.github/smoke/docker-compose.yml` all set — so
-it is the path every self-hoster takes).
-
-### The fresh schema against the live one
-
-```console
-$ diff <live openpanel tables> <fresh scratch tables>
-17a18,19
-> profile_event_property_summary_mv
-> profile_event_summary_mv
-```
-
-A fresh install produces **exactly the live prod-copy table set plus two MVs**.
-That is expected, not drift: migration 20's header says the pre-20 summary MVs
-"are left in place and keep receiving inserts. Once the new ones are verified,
-dropping them is a one-line follow-up migration" — so a fresh install carries
-both generations, and the prod copy simply does not have the older pair.
-
-The dated tables (`events_20251123`, `sessions_20251123`, `profiles_20260504`)
-are created by a *fresh* run too — they are the rename-swap halves of
-`8-order-keys` and `16-restructure-profiles`, not leftovers.
-
-## Deliverable 2 — the `3-init-ch` verdict
-
-**The failure reproduces exactly, and it is a property of the harness, not of a
-fresh install.**
-
-Reproduced with `fresh-install-drill.sh guard` (2026-09-12 19:51 UTC), which is
-M15-203's setup — `CLICKHOUSE_URL` pointed at a scratch database and nothing
-else:
-
-```
-Failed on query RENAME TABLE cohort_events_mv TO cohort_events_mv_tmp
-error: Table `openpanel_m16_004`.`cohort_events_mv` doesn't exist.
- type: "UNKNOWN_TABLE",
- code: "60"
-```
-
-Character for character M15-203's error, with only the scratch database's name
-different (theirs said `openpanel_m15_203`). The proxy log shows why, in one
-pair of lines — the request is routed at the scratch database while the SQL asks
-about `openpanel`:
-
-```
-[POST] /?query_id=...&database=openpanel_m16_004
-SELECT name FROM system.tables WHERE database = 'openpanel'
-FORMAT JSONEachRow
-[POST] /?query_id=...&database=openpanel_m16_004
-RENAME TABLE cohort_events_mv TO cohort_events_mv_tmp
-```
-
-`getExistingTables()` answered with the **prod copy's 23 tables** (the local
-`openpanel`, alphabetically first `cohort_events_mv`), so
-`isSelfHostingOld = existingTables.length !== 0 && isSelfHosting` was true, and
-the rename block emitted a rename for every one of them — against a database
-where none of them exist.
-
-Three explanations, judged against that evidence:
-
-1. **M15-203's stated mechanism — "the migration opens with `RENAME TABLE
- cohort_events_mv TO cohort_events_mv_tmp`, so it cannot run against an empty
- ClickHouse": WRONG.** In the fresh run the same migration's first statement
- is `CREATE DATABASE IF NOT EXISTS openpanel` and it emits **zero** renames
- (`grep -c RENAME` over the run's ClickHouse traffic: the only 6 renames in
- the whole 24-migration sequence are the deliberate table swaps in
- `8-order-keys` and `16-restructure-profiles`). The generated
- `3-init-ch.sql`'s first line after a fresh run is `CREATE DATABASE IF NOT
- EXISTS openpanel;`.
-2. **The operator's hypothesis — "migrations 1 and 2 run first and CREATE
- tables, so by migration 3 `existingTables.length !== 0` is true": WRONG, and
- disprovable by reading the two files.** `1-settings.ts` is three lines and a
- no-op (`// Deprecate migration`); `2-accounts.ts` only touches Postgres, and
- on a fresh install it returns immediately (`No users found, skipping
- migration`). Neither creates a ClickHouse table. In the fresh run, migration
- 3 saw an empty `existingTables` and took no rename path.
-3. **What actually happened: the hardcoded database name in
- `getExistingTables()`.** On a real fresh install the target database *is*
- `openpanel`, so the literal matches and the answer is empty. On a box where
- `openpanel` already holds data and the run is aimed elsewhere — which is
- exactly how you would try to test a fresh install without endangering the
- prod copy — the answer comes from the wrong database, and the upgrade path
- fires. The report was an artifact of the only safe-looking way to run the
- test.
-
-**So: the `3-init-ch` box is not a fresh-install bug, and M15-203's conclusion
-("a fresh self-host install is left partially migrated") does not follow from
-it.** A fresh install with `SELF_HOSTED=true` completes all 24 migrations.
-
-### But there is a real hazard next door: the retry
-
-`3-init-ch` is not safely retryable on a self-hosted install. The ledger row in
-`__code_migrations` is written **after** the migration finishes
-(`migrate.ts:96-108`), so if the first boot dies part-way through it — disk
-full, ClickHouse restart, container killed — the tables it already created stay
-and the ledger row does not. On the next boot `existingTables.length !== 0` is
-true, `isSelfHosting` is true, and the upgrade path runs on what is really a
-fresh install. The shipped start command makes this easy to reach: it is one
-`sh -c` without `set -e`, so a failed migration still lets `bun run start`
-execute, and the operator sees a booting api.
-
-Demonstrated directly (2026-09-12 19:57 UTC), on fresh scratch databases:
-
-```console
-# boot 1, interrupted: migration 3 runs, its ledger row is never written
-$ bun scripts/migrate-code.ts 3-init-ch.ts --no-record
-Migrations finished # 13 ClickHouse tables created, 0 ledger rows
-
-# boot 2: the retry
-$ bun scripts/migrate-code.ts
-Migrations finished # exit 0 — and:
-9 _tmp tables now exist (every table migration 3 created, renamed aside)
-0 INSERT statements ran (migration 3's two data-move branches need a V1
- marker table; the renamed tables were empty anyway)
-```
-
-and the operator is told to delete them:
-
-```
-│ ⚠️ Please run the following command to clean up unused tables:
-│ docker compose exec -it op-ch clickhouse-client --query "DROP TABLE IF EXISTS openpanel.cohort_events_mv_tmp"
-│ ...
-```
-
-On a fresh install those tables are empty, so nothing is lost — the cost is 9
-orphaned tables and a frightening message. The same path on a populated
-database is what makes it worth recording: with the ledger cleared and the
-scratch database fully migrated, a re-run renamed **all 25** tables aside,
-created 25 empty ones, moved nothing out of them (migration 3's two
-data-move branches need `events_replicated` or `events_v2`, and neither exists
-on a V2 install), and still exited 0.
-
-## Deliverable 3 — idempotency
-
-The second run of the whole sequence changed nothing and errored nowhere:
-
-```
-========== RUN 2 (idempotency) — prisma migrate deploy ==========
-153 migrations found in prisma/migrations
-No pending migrations to apply.
-========== RUN 2 (idempotency) — code migrations ==========
-│ ✅ Already Migrated ✅ (× 24)
-Migrations finished
-========== state after run 2 (ok) ==========
-[{"applied":153}] [{"code_migrations":24}] 33 clickhouse tables
-```
-
-Counts identical to run 1; 0 s of ClickHouse work.
-
-Note **why** it is idempotent: the code-migration half is skipped wholesale by
-the `__code_migrations` ledger, so the second boot executes no ClickHouse SQL at
-all. That is a property of the ledger, not of the SQL. The stronger property was
-tested separately — ledger deleted, all 24 replayed against the already-migrated
-scratch database — and **all 24 succeeded** (exit 0, "Migrations finished"), at
-the cost of the rename shuffle described above. Both properties hold; only the
-first one is what a normal second boot exercises.
-
-## Why nothing was fixed
-
-The fresh-install path works, so there is nothing to fix there. The retry hazard
-is real, but the obvious fix is not safe, and the task's own constraint is that
-a fix which breaks upgrades is worse than the bug:
-
-- The narrow fix would be to fire the rename only when a **V1 marker** table
- exists — `events_v2`, `events_replicated` or one of the `*_distributed` names
- the migration already probes — rather than on any table at all. That works for
- a non-clustered install.
-- It does **not** work clustered. With `isClustered`, `createTable` creates
- `events_replicated` *itself* (`migration.ts:103-115`), so a fresh clustered
- install that retries would match the marker anyway — and would additionally
- match `isSelfHostingPostCluster`, which tries to move data out of
- `events_replicated_tmp`.
-- A very old self-host with plain `events` (no `_v2`, no `_replicated`) matches
- no marker, so the marker fix would silently change its behaviour from
- "rename aside, create new" to "keep the old table, schema and all".
-- Making the retry safe properly needs a persistent "V2 init already started
- here" marker, which is a new mechanism and a new place to put it — a decision,
- not a patch.
-
-`getExistingTables()` lives in `packages/db/src/clickhouse/migration.ts`, which
-is outside this task's scope (`packages/db/src/code-migrations/**`, `docs/**`)
-in any case.
-
-## Still unknown
-
-- **Non-default ClickHouse database names are not supported and nothing says
- so.** `getExistingTables()` and `4-add-sessions.ts` hardcode `openpanel`, and
- `3-init-ch.ts` hardcodes `CREATE DATABASE IF NOT EXISTS openpanel`. A
- self-hoster who points `CLICKHOUSE_URL` at a differently-named database gets a
- half-populated `openpanel` alongside it. Pre-existing V1 behaviour; not
- measured beyond noticing it.
-- **Clustered fresh install.** Everything here ran `isClustered: false`. The
- clustered path creates different tables and has the sharper version of the
- retry hazard; it needs a real cluster to test.
-- **This was not run inside the api image.** The commands are the shipped ones
- and were run from the same repo layout the image ships, but `bunx
- [email protected]` fetching the CLI at container start (and the registry reach
- that needs) is covered by `.github/smoke`, not by this drill.
-- **The `.sql` dumps are untracked and not gitignored.** Adding
- `packages/db/src/code-migrations/.gitignore` would stop a future run dirtying
- the tree and stop the next reader citing a generated file as source, as
- M15-203 did. Not done here: it is not this task's change to make.
diff --git a/docs/OPS_DEPLOY_MIGRATION.md b/docs/OPS_DEPLOY_MIGRATION.md
index a9151e1ca..1a2bb3249 100644
--- a/docs/OPS_DEPLOY_MIGRATION.md
+++ b/docs/OPS_DEPLOY_MIGRATION.md
@@ -223,10 +223,9 @@ $ curl -s http://127.0.0.1:3333/healthz/ready
replacement) was also exercised directly and shut down cleanly on `SIGTERM`
("Graceful shutdown completed").
-## M10-008: closure-scoped install (TECH_DEBT §5d)
+## Closure-scoped install
-TECH_DEBT §5d, sourced from M9-006's own "real lever left on the table" note,
-claimed the `prod-deps` stage's workspace-root `pnpm install --frozen-lockfile
+An earlier note claimed the `prod-deps` stage's workspace-root `pnpm install --frozen-lockfile
--prod` installed all 23 workspace projects' production dependencies —
`next`, `react-email`, `@polar-sh/sdk`, `effect`, `mathjs`, ~1.1GB total —
because it runs at the repo root regardless of which `package.json` files were
@@ -238,7 +237,7 @@ selectively `COPY`'d.
and `apps/public` are never copied in, so pnpm's workspace glob simply cannot
see them, confirmed via `Scope: all 14 workspace projects` in the install log
and by reproducing the exact stage in a scratch directory). Every package named
-in TECH_DEBT §5d is a genuine transitive **production** dependency already
+in that note is a genuine transitive **production** dependency already
inside `@openpanel/api`'s real closure, not workspace leakage:
| Package | `pnpm why` chain |
@@ -311,13 +310,10 @@ snapshotter reports compressed content size, per M9-006); uncompressed via
**Verdict: no measurable size change (−4,372 bytes, noise).** This is the
correct, honestly-reported result given the `pnpm why` findings above — the
image was already scoped to `@openpanel/api`'s real closure before this task,
-so there was no apps/start/apps/public dependency bloat to remove. TECH_DEBT
-§5d's premise was wrong; this task's value is making the closure boundary an
+so there was no apps/start/apps/public dependency bloat to remove. That
+premise was wrong; this task's value is making the closure boundary an
explicit property of the install command instead of an implicit consequence of
the manifest list, which is a correctness/robustness improvement, not a size
-one. `docs/TECH_DEBT.md` §5d should be corrected to reflect this the next time
-it's touched — not done here, out of this task's scope (register the finding,
-don't edit the register's narrative text as a side effect of closing it).
### Boot proof (2026-09-06, this attempt, against `openpanel-v2:closure`)
@@ -416,5 +412,4 @@ Full run, 2026-09-07: **PASSED in 3m16s**, `/login` 152348 bytes, both container
logs clean, 7.8G free after the final prune.
**Sizes and the one known break** (the shipped compose templates' `prisma
-migrate deploy` line, pre-existing): `docs/TECH_DEBT.md` → *M13-003 image
sizes*.
diff --git a/docs/OPS_P11_DASHBOARD_CHECK.md b/docs/OPS_P11_DASHBOARD_CHECK.md
deleted file mode 100644
index 368ac4d3a..000000000
--- a/docs/OPS_P11_DASHBOARD_CHECK.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# Dashboard human check-list — P11 dissolution (M11-009)
-
-> This box has no browser. `curl http://127.0.0.1:4173/login` proves the SPA
-> shell boots and serves HTML (the automated boot gate); it cannot prove a
-> chart renders or a form validates. That half is this checklist — run it by
-> hand against `bun run build && bun run preview` (or `bun run dev`) in a real
-> browser after any change that touches `@openpanel/core`'s
-> `*.constants.ts` files or `apps/start/src/utils/{math,slug,super-json,
-> union-omit}.ts` — the P11 dissolution's actual runtime surface.
-
-A pass is: no red error overlay, no blank panel where a chart should be, no
-console error mentioning `validation`, `constants`, `common` or `json`
-(the four deleted packages), and every listed control accepts valid input and
-rejects invalid input with a visible message.
-
-## 1. Sign-in (`/login`)
-
-- [ ] Page renders the email/password form, no console errors.
-- [ ] Submitting an empty form shows a validation message under each empty
- field (uses `zSignInEmail` from `auth.constants.ts`) — nothing is sent.
-- [ ] Submitting a malformed email shows a validation message.
-- [ ] Signing in with a valid seeded user redirects to `/<organizationId>`.
-
-## 2. Organization overview (`/:organizationId`)
-
-- [ ] The project list renders.
-- [ ] Any per-project metric tiles render numbers, not `NaN` or blank
- (exercises `round`/`average`/`sum` from `apps/start/src/utils/math.ts`).
-
-## 3. Project overview (`/:organizationId/:projectId`)
-
-- [ ] The overview line chart renders a line, with an x-axis labelled by the
- selected interval (exercises `intervals`/`timeWindows` from
- `report.constants.ts`).
-- [ ] Switching the time-window picker (e.g. 24h → 7d → 30d) redraws the
- chart and updates the interval shown on the x-axis.
-- [ ] The weekly-trends / previous-period comparison tile shows a %
- change, not `NaN%` (exercises `getPreviousMetric`).
-
-## 4. Report builder (`/:organizationId/:projectId/insights` → new report)
-
-- [ ] Adding an event to the report opens the event picker and lists events.
-- [ ] Adding a filter to an event opens the filter builder; the operator
- dropdown is populated (exercises `operators`/`getOperatorsForType`
- from `report.constants.ts`) and choosing an operator that needs a
- value (e.g. "is one of") requires one before the filter can be saved.
-- [ ] Switching chart type (line / bar / pie / funnel) redraws without a
- crash for at least: line, bar, funnel.
-- [ ] Changing the breakdown dimension redraws the chart with a new legend.
-- [ ] Saving the report and reloading the page preserves the chart config.
-
-## 5. Cohort builder (`/:organizationId/:projectId/cohorts` → new cohort)
-
-- [ ] The event/property criteria builder renders and accepts at least one
- criterion (exercises `cohort.constants.ts`).
-- [ ] Saving with zero criteria is rejected with a visible message.
-
-## 6. Project settings → filters (`/:organizationId/:projectId/settings`)
-
-- [ ] The IP/profile-id filter forms accept a value and show it in the list
- after saving (exercises `project.constants.ts`).
-
-## 7. Notification rule (`/:organizationId/:projectId/notifications` → new rule)
-
-- [ ] The rule-condition form renders and a rule can be saved with at least
- one condition (exercises `notification.constants.ts`).
-
-## 8. Onboarding (`/onboarding` with a fresh org, or `/steps/onboarding/:projectId`)
-
-- [ ] The project-creation step's type dropdown lists the project types
- (exercises `ProjectTypeNames` from `project.constants.ts`).
-
-## What a fail looks like
-
-- A blank panel where a chart should be, or a chart that never stops
- showing its loading state.
-- A red React error overlay (dev) or a blank white page (prod build).
-- A dropdown with zero options where the sections above say it should be
- populated.
-- A form that submits despite an empty required field, or one that never
- accepts valid input.
-- Any browser console error whose message names `@openpanel/validation`,
- `@openpanel/constants`, `@openpanel/common` or `@openpanel/json` — those
- four packages are deleted; such an error means a stray reference survived
- the codemod.
diff --git a/docs/RPC_PROCEDURE_SET_EQUIVALENCE.md b/docs/RPC_PROCEDURE_SET_EQUIVALENCE.md
deleted file mode 100644
index cd869985f..000000000
--- a/docs/RPC_PROCEDURE_SET_EQUIVALENCE.md
+++ /dev/null
@@ -1,686 +0,0 @@
-# tRPC procedure-set equivalence: `@openpanel/core` vs `@openpanel/trpc`
-
-Evidence for M11-001, produced 2026-09-06 on branch `rewrite/v2` at `04b211e3`.
-
-> **Status: the swap is done.** Sections 1-3 below are attempts 1 and 2's
-> findings, kept verbatim because they are what the fix was measured against.
-> The work and its re-run are in *M11-001 attempt 3* at the end of this file;
-> read that for the current state.
-
-At the time attempts 1 and 2 were written, `apps/api/src/main.ts:95` still
-mounted `@openpanel/trpc`'s `appRouter`. Core's
-`rpc.router.ts` has been typechecked since P2-009 but has never served a
-request. This file records the comparison that must pass before the mount is
-swapped.
-
-## Method
-
-A throwaway script (`packages/core/procedure-diff.tmp.ts`, since deleted)
-imported both routers and printed `Object.keys(router._def.procedures).sort()`
-— tRPC 11.17.0 keys that record by dotted procedure path, so it is the full
-flat procedure set of each router.
-
-```bash
-cd packages/core && bun run procedure-diff.tmp.ts
-```
-
-The process computes both lists in under a second and then does not exit: the
-`@openpanel/trpc` import graph opens two Redis connections at import time
-(`ss -tnp` showed two ESTAB sockets to `:6379` held by the bun pid). The lists
-were written to disk with `Bun.write` before that point and diffed separately.
-
-## Result — the diff is NOT empty
-
-```
-core(@openpanel/core): 217 procedures across 29 routers
-trpc(@openpanel/trpc): 216 procedures across 28 routers
-
-$ diff procedure-paths-trpc.txt procedure-paths-core.txt
-97a98
-> health.live
-```
-
-One line. Core is a **strict superset**: every one of the 216 procedures
-`@openpanel/trpc` serves today exists in core under the identical path, and
-core adds exactly one, `health.live`.
-
-`health.live` is not drift. It was added by P2-009 (`61ccc7cb`) as core's own
-scaffold proof and its source comment says so explicitly:
-
-> The one procedure `rpc.router.ts` mounts before the first real module lands
-> (ADR-007 decision 19) — proves the tRPC surface composes end to end. No V1
-> router named `health` exists.
-
-`apps/start` never references `health.*`, so mounting it adds a procedure no
-client calls rather than changing one any client does.
-
-M11-001 attempt 2's acceptance criterion expects **exactly this diff** and
-forbids deleting `health.live` to force it empty. Reproduced on 2026-09-06 at
-`04b211e3`, byte-identical to attempt 1's result. The procedure sets are
-equivalent; the mount swap is blocked by the routing golden below, not by this.
-
-## Per-router coverage by existing automated checks
-
-The three checks named in the task cover the tRPC surface as follows.
-
-- **session-e2e** (`apps/api/e2e/session-e2e.ts`) issues **zero** tRPC
- requests. It drives `POST /track` and asserts ClickHouse and Redis state. Its
- 29/29 pass says nothing about any procedure.
-- **golden REST suite** (`verification/golden/`, 137 cases: 112 `insights`,
- 25 `export`) is REST-only. It will **not** catch a tRPC regression.
-- **auth contract suite** (`verification/contracts/auth/`) is the only check
- that issues tRPC requests: 11 procedures across 7 routers. It asserts
- authorization outcomes (401/403/200), not response shape.
-
-| # | Router | Procs | Covered by | Procedures exercised |
-|---|---|---:|---|---|
-| 1 | auth | 15 | **nothing** | — |
-| 2 | chart | 12 | auth contract suite (1/12) | `chart.aggregate` |
-| 3 | chat | 1 | **nothing** | — |
-| 4 | client | 4 | **nothing** | — |
-| 5 | cohort | 13 | auth contract suite (1/13) | `cohort.refresh` |
-| 6 | conversation | 4 | auth contract suite (2/4) | `conversation.get`, `conversation.rename` |
-| 7 | dashboard | 5 | auth contract suite (3/5) | `dashboard.create`, `dashboard.list`, `dashboard.delete` |
-| 8 | email | 3 | **nothing** | — |
-| 9 | event | 12 | **nothing** | — |
-| 10 | group | 14 | **nothing** | — |
-| 11 | gsc | 14 | **nothing** | — |
-| 12 | health | 1 | **nothing** | — (core-only; see diff above) |
-| 13 | import | 5 | auth contract suite (1/5) | `import.delete` |
-| 14 | insight | 3 | **nothing** | — |
-| 15 | integration | 8 | **nothing** | — |
-| 16 | notification | 4 | **nothing** | — |
-| 17 | onboarding | 2 | **nothing** | — |
-| 18 | organization | 13 | auth contract suite (1/13) | `organization.list` |
-| 19 | overview | 13 | **nothing** | — |
-| 20 | profile | 9 | **nothing** | — |
-| 21 | project | 7 | **nothing** | — |
-| 22 | realtime | 6 | **nothing** | — |
-| 23 | reference | 5 | **nothing** | — |
-| 24 | report | 10 | auth contract suite (2/10) | `report.get`, `report.update` |
-| 25 | session | 4 | **nothing** | — |
-| 26 | share | 10 | **nothing** | — |
-| 27 | subscription | 9 | **nothing** | — |
-| 28 | user | 5 | **nothing** | — |
-| 29 | widget | 6 | **nothing** | — |
-
-**11 of 217 procedures (5%) are exercised over HTTP by any of the three
-checks. 22 of 29 routers have no end-to-end coverage at all.**
-
-Not counted above, because the task named three specific checks and these are
-not them: 21 `packages/core/src/modules/*/*.rpc.test.ts` files run under
-`bun test`. They are in-process unit tests over mocked deps — they prove a
-procedure's logic, not that it is reachable through the mounted router, the
-Elysia lifecycle, the session macro or superjson.
-
-## Consequence
-
-The mount swap is a change whose blast radius is 217 procedures against 11
-procedures of end-to-end coverage. That gap is a real finding independent of
-the `health.live` diff, and it is why the task asked for this table.
-
----
-
-# The tRPC routing golden (M11-001 attempt 2, 2026-09-06)
-
-`apps/api/e2e/trpc-routing-golden.ts` is the gate the mount swap must pass, and
-it exists because of the 11/217 coverage gap measured above. It enumerates the
-mounted router's procedures, issues one **unauthenticated** request per path
-through `/trpc/<path>` (GET `?input=` for queries, POST for mutations,
-superjson `{}`), and records `{type, status, tRPC error code}` per path. A 404
-or `NOT_FOUND` is a routing failure and exits non-zero; 400/401/403 are passes —
-they prove the procedure resolved and its validation/auth ran.
-
-The router specifier is read out of `apps/api/src/main.ts`'s `appRouter` import,
-so the same committed script measures both sides of the swap with no flag.
-
-## Both runs, harness up (`verification/harness start`), local box, 2026-09-06
-
-```
-$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-before.json
-mounted router: @openpanel/trpc
-probing 216 procedures across 28 routers at http://127.0.0.1:3333
- 4 200 ok
- 17 400 BAD_REQUEST
- 195 401 UNAUTHORIZED
-trpc-routing-golden: 216/216 reachable, 0 routing failure(s) exit 0
-
-$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json
-mounted router: @openpanel/core
-probing 217 procedures across 29 routers at http://127.0.0.1:3333
- 5 200 ok
- 193 400 BAD_REQUEST
- 19 401 UNAUTHORIZED
-trpc-routing-golden: 217/217 reachable, 0 routing failure(s) exit 0
-```
-
-**Reachability passes on both sides**: every one of core's 217 procedures
-resolves through the real Elysia lifecycle and the tRPC fetch mount. Nothing is
-unroutable, and `health.live` is the only path present on one side only.
-
-## The maps are NOT identical — 176 of 216 shared paths answer differently
-
-```
-only in AFTER: ['health.live']
-only in BEFORE: []
-changed: 176 # all of them 401 UNAUTHORIZED -> 400 BAD_REQUEST
- auth.totpDisable: 401 UNAUTHORIZED -> 400 BAD_REQUEST
- chart.aggregate: 401 UNAUTHORIZED -> 400 BAD_REQUEST
- client.list: 401 UNAUTHORIZED -> 400 BAD_REQUEST
- ...
-```
-
-Cause: V1's routers are built on `packages/trpc/src/trpc.ts:142`'s
-`protectedProcedure = procedure.use(enforceUserIsAuthed).use(enforceAccess)…`,
-so authentication runs **before** input parsing and an anonymous caller gets
-`UNAUTHORIZED` whatever it sends. Core's ported routers use the bare
-`procedure` and do their auth **inside the handler** — `rpc/base.ts:90` says the
-middleware stack "lands with auth (P6)", and it never did. Input parsing
-therefore precedes authentication, and an anonymous caller with a malformed
-input gets `BAD_REQUEST`.
-
-## The consequence the golden's empty input hides — 3 procedures lose authorization
-
-Ordering alone would be a contract detail. But because the check moved from a
-middleware to per-handler code, a procedure can simply not have one. Probing
-**queries only** (no mutations, no side effects) with a plausible input,
-unauthenticated, on the same box and the same harness, 2026-09-06:
-
-```
-$ bun run authprobe.tmp.ts # throwaway, deleted; input {projectId, organizationId}
-mounted: @openpanel/trpc queries: 133 mounted: @openpanel/core queries: 134
- 2 200 ok 6 200 ok
- 9 400 BAD_REQUEST 70 400 BAD_REQUEST
- 122 401 UNAUTHORIZED 57 401 UNAUTHORIZED
- 1 500 INTERNAL_SERVER_ERROR
-
-401/other -> 200 (authorization LOST): client.list, subscription.getCurrent, subscription.usage
-401 UNAUTHORIZED -> 400 BAD_REQUEST: 61
-identical: 68 / 133 shared query paths
-core-only 500: subscription.products (trpc: 401 UNAUTHORIZED)
-```
-
-What the three return to a caller with no cookie and no credential:
-
-| Procedure | trpc | core | Body |
-|---|---|---|---|
-| `client.list` | 401 | **200** | `array of {createdAt,id,ignoreCorsAndSecret,name,organizationId,projectId,secret,type,updatedAt}` — the project's ingestion clients, `secret` included (ADR-011 already flags that field as the scrypt hash) |
-| `subscription.usage` | 401 | **200** | `array[31] of {count, day}` — 31 days of per-day event volume for any projectId |
-| `subscription.getCurrent` | 401 | **200** | `null` for an org with no subscription; not gated either way |
-
-`client.list`'s source comment is the whole story
-(`modules/client/client.rpc.ts:31`):
-
-> Ported verbatim: V1's `client.list` reads by projectId with no access check of
-> its own (packages/trpc/src/routers/client.ts).
-
-True of the *handler body*, and wrong about the procedure: V1's `client.list` is
-a `protectedProcedure`, so `enforceUserIsAuthed` + `enforceAccess` gated it on
-the `projectId` in the input. Dropping the stack dropped the check.
-
-`auth.session`, `onboarding.skipOnboardingCheck` and `health.live` also answer
-200 on core; the first two answer 200 on trpc too and are legitimately public.
-
-## Verdict (attempt 2 — SUPERSEDED by attempt 3 below, which did the work)
-
-The swap is **not** blocked by reachability, by the procedure set, or by
-anything `health.live` does. It is blocked because mounting core today would
-publish three authenticated read endpoints to anonymous callers and change the
-error precedence of 176 more. The fix is the P6 work `rpc/base.ts:90` defers:
-port `publicProcedure` / `protectedProcedure` / `protectedProcedureWithoutAccess`
-(and with them `enforceUserIsAuthed`, `enforceAccess`, `loggerMiddleware`,
-`sessionScopeMiddleware`) into core and rebuild the 29 routers on them. That
-restores auth-before-validation by construction and makes the missing check
-impossible rather than per-handler. It is a wave, not a line, and it is not
-M11-001's to do.
-
-Re-run this golden after that work: the diff should then be `health.live` only.
-
----
-
-# M11-001 attempt 3: the port landed, and the swap is live
-
-Produced 2026-09-06 on branch `rewrite/v2` on top of `04b211e3`. Attempt 2's
-two artefacts above (`apps/api/e2e/trpc-routing-golden.ts` and everything up to
-its verdict) are unchanged; this section records the work that verdict named as
-the fix, and the re-run of its own gate.
-
-## What landed
-
-`packages/trpc/src/trpc.ts:35-155`'s four middlewares are now in
-`packages/core/src/rpc/base.ts`, with their logic unchanged:
-
-| Middleware | Change on the port |
-|---|---|
-| `enforceUserIsAuthed` | none, except `console.error` → `ctx.logger.error` (core has a request-scoped logger; CLAUDE.md bans `console`). Same branch, same messages. |
-| `enforceAccess` | the two lookups come through `ctx.services.auth.requireProjectAccess` / `.getOrganizationAccess` instead of `packages/trpc/src/access.ts`'s direct imports. M10-002 bound the ladder there once. Everything else — `runWithAlsSession` first, `getRawInput()` before the demo-mode ban, top-level `has('projectId')` / `has('organizationId')` only, `needsWrite = type === 'mutation' && !meta?.readOnlyMutation` — is character-for-character V1's. |
-| `loggerMiddleware` | none. |
-| `sessionScopeMiddleware` | none. |
-
-and the three builders compose them in V1's order (`trpc.ts:141-155`):
-
-```ts
-publicProcedure = procedure.use(logger).use(sessionScope);
-protectedProcedure = procedure.use(enforceUserIsAuthed)
- .use(enforceAccess)
- .use(logger).use(sessionScope);
-protectedProcedureWithoutAccess = procedure.use(enforceUserIsAuthed)
- .use(logger).use(sessionScope);
-```
-
-`rpc/base.ts:90`'s "they land with auth (P6)" comment is gone; what replaces it
-says why the stack is a stack — authentication before input parsing, a check
-that cannot be forgotten, and the raw-input rule ADR-011 invariant 2 states.
-
-`apps/api/src/main.ts` imports `appRouter` from `@openpanel/core` (biome folded
-it into the existing core block at line 36). `packages/trpc` is untouched and
-still typechecks and tests green — it builds on the same `procedure`.
-
-## The rebuild: every procedure on its V1 twin's builder
-
-Derived per procedure, not per file: both routers were parsed for the
-top-level `name: builder` entries of their `createTRPCRouter({...})` object
-(comments and string literals blanked first, so a `//` line cannot be mistaken
-for an entry). 216 V1 procedures, 217 core procedures, and every shared name
-now carries the same builder.
-
-`chartProcedure` and `overviewProcedure` are V1's own share-aware builders —
-both are `publicProcedure` plus one middleware — and core now has them in the
-same shape rather than as per-handler calls. That is load-bearing for the
-golden: their access decision has to run before the input parser, or a
-`chartProcedure` path answers `BAD_REQUEST` where V1 answers `UNAUTHORIZED`.
-`chart.rpc.ts`'s `resolveShareableReport` helper is gone; the resolved report
-rides on `ctx.report`, exactly as in V1.
-
-| Router | Procs | public | protected | withoutAccess | share-aware |
-|---|---:|---:|---:|---:|---:|
-| auth | 15 | 10 | 5 | 0 | 0 |
-| chart | 12 | 0 | 7 | 0 | 5 |
-| chat | 1 | 0 | 1 | 0 | 0 |
-| client | 4 | 0 | 4 | 0 | 0 |
-| cohort | 13 | 0 | 13 | 0 | 0 |
-| conversation | 4 | 0 | 4 | 0 | 0 |
-| dashboard | 5 | 0 | 5 | 0 | 0 |
-| email | 3 | 1 | 2 | 0 | 0 |
-| event | 12 | 0 | 12 | 0 | 0 |
-| group | 14 | 0 | 14 | 0 | 0 |
-| gsc | 14 | 0 | 14 | 0 | 0 |
-| health | 1 | 1 | 0 | 0 | 0 |
-| import | 5 | 0 | 5 | 0 | 0 |
-| insight | 3 | 0 | 3 | 0 | 0 |
-| integration | 8 | 0 | 8 | 0 | 0 |
-| notification | 4 | 0 | 4 | 0 | 0 |
-| onboarding | 2 | 1 | 1 | 0 | 0 |
-| organization | 13 | 1 | 11 | 1 | 0 |
-| overview | 13 | 0 | 1 | 0 | 12 |
-| profile | 9 | 0 | 9 | 0 | 0 |
-| project | 7 | 0 | 7 | 0 | 0 |
-| realtime | 6 | 0 | 6 | 0 | 0 |
-| reference | 5 | 1 | 4 | 0 | 0 |
-| report | 10 | 0 | 10 | 0 | 0 |
-| session | 4 | 0 | 4 | 0 | 0 |
-| share | 10 | 4 | 6 | 0 | 0 |
-| subscription | 9 | 0 | 9 | 0 | 0 |
-| user | 5 | 0 | 5 | 0 | 0 |
-| widget | 6 | 3 | 3 | 0 | 0 |
-| **total** | **217** | **22** | **177** | **1** | **17** |
-
-`health.live` is core-only (P2-009) and is `publicProcedure`.
-
-**No in-handler check was removed.** ADR-011 counts 58 of them and the auth
-contract suite's group C tests 14; every one still runs, now behind the
-builder's check rather than instead of it.
-
-<details>
-<summary>All 217 procedures: path → V1 builder → core builder</summary>
-
-| Procedure | V1 builder | core builder |
-|---|---|---|
-| `chat.models` | `protectedProcedure` | `protectedProcedure` |
-| `auth.signOut` | `publicProcedure` | `publicProcedure` |
-| `auth.signInOAuth` | `publicProcedure` | `publicProcedure` |
-| `auth.signUpEmail` | `publicProcedure` | `publicProcedure` |
-| `auth.signInEmail` | `publicProcedure` | `publicProcedure` |
-| `auth.signInTotp` | `publicProcedure` | `publicProcedure` |
-| `auth.totpStatus` | `protectedProcedure` | `protectedProcedure` |
-| `auth.totpSetup` | `protectedProcedure` | `protectedProcedure` |
-| `auth.totpEnable` | `protectedProcedure` | `protectedProcedure` |
-| `auth.totpDisable` | `protectedProcedure` | `protectedProcedure` |
-| `auth.totpRegenerateRecoveryCodes` | `protectedProcedure` | `protectedProcedure` |
-| `auth.resetPassword` | `publicProcedure` | `publicProcedure` |
-| `auth.requestResetPassword` | `publicProcedure` | `publicProcedure` |
-| `auth.session` | `publicProcedure` | `publicProcedure` |
-| `auth.extendSession` | `publicProcedure` | `publicProcedure` |
-| `auth.signInShare` | `publicProcedure` | `publicProcedure` |
-| `chart.projectCard` | `protectedProcedure` | `protectedProcedure` |
-| `chart.events` | `protectedProcedure` | `protectedProcedure` |
-| `chart.properties` | `protectedProcedure` | `protectedProcedure` |
-| `chart.values` | `protectedProcedure` | `protectedProcedure` |
-| `chart.funnel` | `chartProcedure` | `chartProcedure` |
-| `chart.conversion` | `chartProcedure` | `chartProcedure` |
-| `chart.sankey` | `protectedProcedure` | `protectedProcedure` |
-| `chart.chart` | `chartProcedure` | `chartProcedure` |
-| `chart.aggregate` | `chartProcedure` | `chartProcedure` |
-| `chart.cohort` | `chartProcedure` | `chartProcedure` |
-| `chart.getProfiles` | `protectedProcedure` | `protectedProcedure` |
-| `chart.getFunnelProfiles` | `protectedProcedure` | `protectedProcedure` |
-| `client.list` | `protectedProcedure` | `protectedProcedure` |
-| `client.update` | `protectedProcedure` | `protectedProcedure` |
-| `client.create` | `protectedProcedure` | `protectedProcedure` |
-| `client.remove` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.list` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.get` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.create` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.update` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.delete` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.listProfiles` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.mostEvents` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.eventsPerDay` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.popularRoutes` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.getCount` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.preview` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.exportProfiles` | `protectedProcedure` | `protectedProcedure` |
-| `cohort.refresh` | `protectedProcedure` | `protectedProcedure` |
-| `conversation.list` | `protectedProcedure` | `protectedProcedure` |
-| `conversation.get` | `protectedProcedure` | `protectedProcedure` |
-| `conversation.rename` | `protectedProcedure` | `protectedProcedure` |
-| `conversation.delete` | `protectedProcedure` | `protectedProcedure` |
-| `dashboard.list` | `protectedProcedure` | `protectedProcedure` |
-| `dashboard.byId` | `protectedProcedure` | `protectedProcedure` |
-| `dashboard.create` | `protectedProcedure` | `protectedProcedure` |
-| `dashboard.update` | `protectedProcedure` | `protectedProcedure` |
-| `dashboard.delete` | `protectedProcedure` | `protectedProcedure` |
-| `email.unsubscribe` | `publicProcedure` | `publicProcedure` |
-| `email.getPreferences` | `protectedProcedure` | `protectedProcedure` |
-| `email.updatePreferences` | `protectedProcedure` | `protectedProcedure` |
-| `event.updateEventMeta` | `protectedProcedure` | `protectedProcedure` |
-| `event.byId` | `protectedProcedure` | `protectedProcedure` |
-| `event.details` | `protectedProcedure` | `protectedProcedure` |
-| `event.events` | `protectedProcedure` | `protectedProcedure` |
-| `event.conversionNames` | `protectedProcedure` | `protectedProcedure` |
-| `event.conversions` | `protectedProcedure` | `protectedProcedure` |
-| `event.bots` | `protectedProcedure` | `protectedProcedure` |
-| `event.pages` | `protectedProcedure` | `protectedProcedure` |
-| `event.pagesTimeseries` | `protectedProcedure` | `protectedProcedure` |
-| `event.previousPages` | `protectedProcedure` | `protectedProcedure` |
-| `event.pageTimeseries` | `protectedProcedure` | `protectedProcedure` |
-| `event.origin` | `protectedProcedure` | `protectedProcedure` |
-| `group.list` | `protectedProcedure` | `protectedProcedure` |
-| `group.byId` | `protectedProcedure` | `protectedProcedure` |
-| `group.create` | `protectedProcedure` | `protectedProcedure` |
-| `group.update` | `protectedProcedure` | `protectedProcedure` |
-| `group.delete` | `protectedProcedure` | `protectedProcedure` |
-| `group.types` | `protectedProcedure` | `protectedProcedure` |
-| `group.metrics` | `protectedProcedure` | `protectedProcedure` |
-| `group.activity` | `protectedProcedure` | `protectedProcedure` |
-| `group.memberGrowth` | `protectedProcedure` | `protectedProcedure` |
-| `group.listProfiles` | `protectedProcedure` | `protectedProcedure` |
-| `group.mostEvents` | `protectedProcedure` | `protectedProcedure` |
-| `group.popularRoutes` | `protectedProcedure` | `protectedProcedure` |
-| `group.properties` | `protectedProcedure` | `protectedProcedure` |
-| `group.listByIds` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getConnection` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.initiateOAuth` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getSites` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.selectSite` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.disconnect` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getOverview` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getPages` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getPageDetails` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getQueryDetails` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getQueries` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getSearchEngines` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getAiEngines` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getPreviousOverview` | `protectedProcedure` | `protectedProcedure` |
-| `gsc.getCannibalization` | `protectedProcedure` | `protectedProcedure` |
-| `health.live` | `— (core-only)` | `publicProcedure` |
-| `import.list` | `protectedProcedure` | `protectedProcedure` |
-| `import.get` | `protectedProcedure` | `protectedProcedure` |
-| `import.create` | `protectedProcedure` | `protectedProcedure` |
-| `import.delete` | `protectedProcedure` | `protectedProcedure` |
-| `import.retry` | `protectedProcedure` | `protectedProcedure` |
-| `insight.list` | `protectedProcedure` | `protectedProcedure` |
-| `insight.listAll` | `protectedProcedure` | `protectedProcedure` |
-| `insight.explain` | `protectedProcedure` | `protectedProcedure` |
-| `integration.get` | `protectedProcedure` | `protectedProcedure` |
-| `integration.list` | `protectedProcedure` | `protectedProcedure` |
-| `integration.createOrUpdateSlack` | `protectedProcedure` | `protectedProcedure` |
-| `integration.createOrUpdate` | `protectedProcedure` | `protectedProcedure` |
-| `integration.createOrUpdateExport` | `protectedProcedure` | `protectedProcedure` |
-| `integration.testConnection` | `protectedProcedure` | `protectedProcedure` |
-| `integration.testExportConnection` | `protectedProcedure` | `protectedProcedure` |
-| `integration.delete` | `protectedProcedure` | `protectedProcedure` |
-| `notification.list` | `protectedProcedure` | `protectedProcedure` |
-| `notification.rules` | `protectedProcedure` | `protectedProcedure` |
-| `notification.createOrUpdateRule` | `protectedProcedure` | `protectedProcedure` |
-| `notification.deleteRule` | `protectedProcedure` | `protectedProcedure` |
-| `onboarding.skipOnboardingCheck` | `publicProcedure` | `publicProcedure` |
-| `onboarding.project` | `protectedProcedure` | `protectedProcedure` |
-| `organization.get` | `protectedProcedure` | `protectedProcedure` |
-| `organization.list` | `protectedProcedure` | `protectedProcedure` |
-| `organization.myAccess` | `protectedProcedureWithoutAccess` | `protectedProcedureWithoutAccess` |
-| `organization.update` | `protectedProcedure` | `protectedProcedure` |
-| `organization.delete` | `protectedProcedure` | `protectedProcedure` |
-| `organization.cancelDeletion` | `protectedProcedure` | `protectedProcedure` |
-| `organization.inviteUser` | `protectedProcedure` | `protectedProcedure` |
-| `organization.revokeInvite` | `protectedProcedure` | `protectedProcedure` |
-| `organization.removeMember` | `protectedProcedure` | `protectedProcedure` |
-| `organization.updateMemberAccess` | `protectedProcedure` | `protectedProcedure` |
-| `organization.members` | `protectedProcedure` | `protectedProcedure` |
-| `organization.invitations` | `protectedProcedure` | `protectedProcedure` |
-| `organization.getInvite` | `publicProcedure` | `publicProcedure` |
-| `overview.liveVisitors` | `overviewProcedure` | `overviewProcedure` |
-| `overview.liveData` | `overviewProcedure` | `overviewProcedure` |
-| `overview.stats` | `overviewProcedure` | `overviewProcedure` |
-| `overview.getReferrerSpikes` | `overviewProcedure` | `overviewProcedure` |
-| `overview.topPages` | `overviewProcedure` | `overviewProcedure` |
-| `overview.topGeneric` | `overviewProcedure` | `overviewProcedure` |
-| `overview.topGenericSeries` | `overviewProcedure` | `overviewProcedure` |
-| `overview.userJourney` | `overviewProcedure` | `overviewProcedure` |
-| `overview.topEvents` | `overviewProcedure` | `overviewProcedure` |
-| `overview.topConversions` | `overviewProcedure` | `overviewProcedure` |
-| `overview.topLinkOut` | `overviewProcedure` | `overviewProcedure` |
-| `overview.runFilterCommand` | `protectedProcedure` | `protectedProcedure` |
-| `overview.map` | `overviewProcedure` | `overviewProcedure` |
-| `profile.byId` | `protectedProcedure` | `protectedProcedure` |
-| `profile.metrics` | `protectedProcedure` | `protectedProcedure` |
-| `profile.activity` | `protectedProcedure` | `protectedProcedure` |
-| `profile.mostEvents` | `protectedProcedure` | `protectedProcedure` |
-| `profile.popularRoutes` | `protectedProcedure` | `protectedProcedure` |
-| `profile.properties` | `protectedProcedure` | `protectedProcedure` |
-| `profile.list` | `protectedProcedure` | `protectedProcedure` |
-| `profile.powerUsers` | `protectedProcedure` | `protectedProcedure` |
-| `profile.values` | `protectedProcedure` | `protectedProcedure` |
-| `project.getProjectWithClients` | `protectedProcedure` | `protectedProcedure` |
-| `project.activationStatus` | `protectedProcedure` | `protectedProcedure` |
-| `project.list` | `protectedProcedure` | `protectedProcedure` |
-| `project.update` | `protectedProcedure` | `protectedProcedure` |
-| `project.create` | `protectedProcedure` | `protectedProcedure` |
-| `project.delete` | `protectedProcedure` | `protectedProcedure` |
-| `project.cancelDeletion` | `protectedProcedure` | `protectedProcedure` |
-| `realtime.coordinates` | `protectedProcedure` | `protectedProcedure` |
-| `realtime.mapBadgeDetails` | `protectedProcedure` | `protectedProcedure` |
-| `realtime.activeSessions` | `protectedProcedure` | `protectedProcedure` |
-| `realtime.paths` | `protectedProcedure` | `protectedProcedure` |
-| `realtime.referrals` | `protectedProcedure` | `protectedProcedure` |
-| `realtime.geo` | `protectedProcedure` | `protectedProcedure` |
-| `reference.getReferences` | `protectedProcedure` | `protectedProcedure` |
-| `reference.create` | `protectedProcedure` | `protectedProcedure` |
-| `reference.update` | `protectedProcedure` | `protectedProcedure` |
-| `reference.delete` | `protectedProcedure` | `protectedProcedure` |
-| `reference.getChartReferences` | `publicProcedure` | `publicProcedure` |
-| `report.list` | `protectedProcedure` | `protectedProcedure` |
-| `report.create` | `protectedProcedure` | `protectedProcedure` |
-| `report.update` | `protectedProcedure` | `protectedProcedure` |
-| `report.move` | `protectedProcedure` | `protectedProcedure` |
-| `report.delete` | `protectedProcedure` | `protectedProcedure` |
-| `report.duplicate` | `protectedProcedure` | `protectedProcedure` |
-| `report.get` | `protectedProcedure` | `protectedProcedure` |
-| `report.updateLayout` | `protectedProcedure` | `protectedProcedure` |
-| `report.getLayouts` | `protectedProcedure` | `protectedProcedure` |
-| `report.resetLayout` | `protectedProcedure` | `protectedProcedure` |
-| `session.list` | `protectedProcedure` | `protectedProcedure` |
-| `session.distinctValues` | `protectedProcedure` | `protectedProcedure` |
-| `session.byId` | `protectedProcedure` | `protectedProcedure` |
-| `session.replayChunksFrom` | `protectedProcedure` | `protectedProcedure` |
-| `share.overview` | `publicProcedure` | `publicProcedure` |
-| `share.overviewSettings` | `protectedProcedure` | `protectedProcedure` |
-| `share.createOverview` | `protectedProcedure` | `protectedProcedure` |
-| `share.dashboard` | `publicProcedure` | `publicProcedure` |
-| `share.dashboardSettings` | `protectedProcedure` | `protectedProcedure` |
-| `share.createDashboard` | `protectedProcedure` | `protectedProcedure` |
-| `share.dashboardReports` | `publicProcedure` | `publicProcedure` |
-| `share.report` | `publicProcedure` | `publicProcedure` |
-| `share.reportSettings` | `protectedProcedure` | `protectedProcedure` |
-| `share.createReport` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.getCurrent` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.checkout` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.products` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.usage` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.cancelSubscription` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.pauseSubscription` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.resumeSubscription` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.applySaveDiscount` | `protectedProcedure` | `protectedProcedure` |
-| `subscription.portal` | `protectedProcedure` | `protectedProcedure` |
-| `user.deletionBlockers` | `protectedProcedure` | `protectedProcedure` |
-| `user.delete` | `protectedProcedure` | `protectedProcedure` |
-| `user.update` | `protectedProcedure` | `protectedProcedure` |
-| `user.debugPostCookie` | `protectedProcedure` | `protectedProcedure` |
-| `user.debugGetCookie` | `protectedProcedure` | `protectedProcedure` |
-| `widget.get` | `protectedProcedure` | `protectedProcedure` |
-| `widget.toggle` | `protectedProcedure` | `protectedProcedure` |
-| `widget.updateOptions` | `protectedProcedure` | `protectedProcedure` |
-| `widget.counter` | `publicProcedure` | `publicProcedure` |
-| `widget.badge` | `publicProcedure` | `publicProcedure` |
-| `widget.realtimeData` | `publicProcedure` | `publicProcedure` |
-
-</details>
-
-## PROOF 1 — the routing golden, before and after
-
-Both runs on this box, 2026-09-06, `verification/harness start` up, the same
-harness process restarted between them so no in-process cache crossed the swap.
-`main.ts` was temporarily pointed back at `@openpanel/trpc` for the BEFORE run
-and restored for the AFTER run; the golden reads the specifier out of `main.ts`
-itself, so neither run needed a flag.
-
-```
-$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-before.json
-mounted router: @openpanel/trpc
-probing 216 procedures across 28 routers at http://127.0.0.1:3333
- 4 200 ok
- 17 400 BAD_REQUEST
- 195 401 UNAUTHORIZED
-trpc-routing-golden: 216/216 reachable, 0 routing failure(s) exit 0
-
-$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json
-mounted router: @openpanel/core
-probing 217 procedures across 29 routers at http://127.0.0.1:3333
- 5 200 ok
- 17 400 BAD_REQUEST
- 195 401 UNAUTHORIZED
-trpc-routing-golden: 217/217 reachable, 0 routing failure(s) exit 0
-```
-
-The diff of the two maps:
-
-```
-only in AFTER : ['health.live']
-only in BEFORE: []
-changed : 0
-
-shared paths identical: 216 / 216
- AFTER-only health.live {'type': 'query', 'status': 200, 'code': None}
-```
-
-**Empty except `health.live`.** Attempt 2's 176 differing paths, its three
-401 → 200 and its one 401 → 500 are all gone, and the per-status tallies now
-match on both sides (17 `BAD_REQUEST`, 195 `UNAUTHORIZED`, plus the 4 public
-200s and core's fifth, `health.live`).
-
-## PROOF 3 — the three holes, and the 500
-
-The golden probes with an empty input, which is what let three missing checks
-hide behind a zod rejection in attempt 2. Repeating that attempt's own
-plausible-input probe — every **query** procedure, unauthenticated, input
-`{projectId: 'proj_1', organizationId: 'org_1'}` — on both mounts, same box,
-same day:
-
-```
-mounted: @openpanel/trpc queries: 133 mounted: @openpanel/core queries: 134
- 2 200 ok 3 200 ok
- 9 400 BAD_REQUEST 9 400 BAD_REQUEST
- 122 401 UNAUTHORIZED 122 401 UNAUTHORIZED
-
-changed: 0
-identical: 133 / 133 shared query paths
-core-only: health.live
-```
-
-Attempt 2 measured 68/133 identical here. It is now 133/133, and the third
-core `200` is `health.live`, not a leaked endpoint.
-
-The four named procedures, requested with no cookie and no credential:
-
-```
---- GET /trpc/client.list?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
-HTTP 401
-{"error":{"json":{"message":"Not authenticated","code":-32001,
- "data":{"code":"UNAUTHORIZED","httpStatus":401,
- "stack":"TRPCError: Not authenticated\n at packages/core/src/rpc/base.ts:129:15 ...
-
---- GET /trpc/subscription.getCurrent?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
-HTTP 401 code UNAUTHORIZED message "Not authenticated"
-
---- GET /trpc/subscription.usage?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
-HTTP 401 code UNAUTHORIZED message "Not authenticated"
-
---- GET /trpc/subscription.products?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
-HTTP 401 code UNAUTHORIZED message "Not authenticated"
-```
-
-`@openpanel/trpc` answers all four identically (`401 UNAUTHORIZED`,
-`"Not authenticated"`, thrown at `packages/trpc/src/trpc.ts:38` rather than
-`packages/core/src/rpc/base.ts:129`). `client.list` no longer returns the
-project's ingestion clients — `secret` column included — to an anonymous
-caller, and `subscription.products` no longer 500s.
-
-## PROOF 2 — the auth contract suite, run against CORE
-
-`verification/contracts/auth/run.sh` re-seeds, restarts the harness and targets
-:3333, so with core mounted it tests core. Zero edits to `verification/`.
-
-```
-group (a) per-surface negative: 24 passed, 0 failed
-group (b) getProjectAccess golden table: 17 passed, 0 failed
-group (c) in-handler checks: 14 passed, 0 failed
-group (d) enforceAccess shape triggers: 9 passed, 0 failed
-group (e) cross-project share isolation: 7 passed, 0 failed
-AUTH CONTRACTS: all 5 groups green
-```
-
-Group (d) is the one that could only ever have passed on the ported stack: it
-asserts that a nested `projectId` does **not** trigger `enforceAccess` while a
-top-level one does, that `readOnlyMutation` downgrades the demanded level to
-read, and that the `organizationId` branch checks membership and not role.
-
-## Verdict
-
-The procedure-set diff is still exactly one line, `> health.live`. The routing
-golden's diff is now empty except that same line. The plausible-input probe is
-133/133 identical. All five auth-contract groups are green against core's
-mount. **`apps/api` serves `@openpanel/core`'s router.**
-
-Coverage is no longer 11/217: the routing golden reaches every procedure over
-HTTP, and the 217 answers are pinned to V1's on the committed
-`/tmp/trpc-routing-{before,after}.json` protocol. What it does not assert is
-response *shape* — that is still the golden REST suite's job for `/insights`
-and `/export`, and nothing's job for the other 27 routers.
-
-Two V1 middlewares did **not** move with this task and are named here so they
-are not assumed present: `rateLimitMiddleware` (10 `auth.*` procedures and
-`organization.getInvite`) and `cacheMiddleware` (chart's 60s/300s and
-overview's per-range TTLs). Both are already factories in `rpc/base.ts`
-(`createRateLimitMiddleware`, `createCacheMiddleware`) awaiting a Redis handle
-at the mount; wiring them is not in M11-001's scope and neither is visible to
-any gate this task runs.
diff --git a/docs/SQL_MIGRATION_RECIPE.md b/docs/SQL_MIGRATION_RECIPE.md
deleted file mode 100644
index 3dcfb40a6..000000000
--- a/docs/SQL_MIGRATION_RECIPE.md
+++ /dev/null
@@ -1,631 +0,0 @@
-# SQL migration recipe — `sqlstring` / clix → the `sql` tag
-
-The eight P12 conversion tasks after this one share one procedure, written here
-so it is not re-derived eight times. ADR-013 decision 21 is the target:
-`sqlstring` = 0, clix = 0, no builder, all three definer files deleted.
-
-The gate is `tooling/gates/p12-grep-gates.sh`. Run `--report` before and after
-every conversion; the wave is finished when `--assert` exits 0.
-
-## Baseline 448fa219a68bcc6929b6a11276fbcb414511e8f9
-
-`bash tooling/gates/p12-grep-gates.sh --report`, run 2026-09-07 on this box.
-Reproduced verbatim. This commit adds only `tooling/gates/` and `docs/`, neither
-of which the gate scans, so the table is byte-identical at the parent and at
-this commit.
-
-```
- sqlstring clix sql-builder file
-----------------------------------------------------------------------------
- 1 0 0 apps/start/package.json
- 2 0 0 packages/core/package.json
- 3 0 0 packages/core/src/buffers/group-buffer.ts
- 3 0 0 packages/core/src/buffers/profile-backfill-buffer.ts
- 2 0 0 packages/core/src/buffers/profile-buffer.ts
- 13 0 0 packages/core/src/modules/chart/src/field-resolution.ts
- 2 0 0 packages/core/src/modules/chart/src/filter-cast.ts
- 53 0 0 packages/core/src/modules/chart/src/filter-where.ts
- 13 0 0 packages/core/src/modules/chart/src/table-filter-where.ts
- 49 0 0 packages/core/src/modules/cohort/cohort.service.ts
- 0 13 0 packages/core/src/modules/insight/src/cached-clix.ts
- 0 2 0 packages/core/src/modules/insight/src/engine.ts
- 0 11 0 packages/core/src/modules/insight/src/legacy-scan.ts
- 0 5 0 packages/core/src/modules/insight/src/modules/devices.module.ts
- 0 5 0 packages/core/src/modules/insight/src/modules/entry-pages.module.ts
- 0 5 0 packages/core/src/modules/insight/src/modules/geo.module.ts
- 0 5 0 packages/core/src/modules/insight/src/modules/page-trends.module.ts
- 0 5 0 packages/core/src/modules/insight/src/modules/referrers.module.ts
- 0 4 0 packages/core/src/modules/insight/src/referrer-spikes.ts
- 0 1 0 packages/core/src/modules/insight/src/types.ts
- 0 2 0 packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
- 10 0 5 packages/core/src/modules/organization/organization.service.ts
- 2 0 0 packages/core/src/modules/profile/src/profile.sql.ts
- 2 2 0 packages/core/src/modules/project/project.service.ts
- 8 7 0 packages/core/src/modules/realtime/realtime.service.ts
- 0 7 0 packages/core/src/modules/widget/widget.rpc.ts
- 0 2 0 packages/core/src/v1-compat.ts
- 0 1 1 packages/db/index.ts
- 2 0 0 packages/db/package.json
- 3 0 0 packages/db/src/clickhouse/client.ts
-----------------------------------------------------------------------------
- 168 77 6 TOTAL
-```
-
-Read the totals as three separate deletions:
-
-- **`sqlstring` 168** — 6 files hold 133 of them: `filter-where.ts` (53),
- `cohort.service.ts` (49), `table-filter-where.ts` (13), `field-resolution.ts`
- (13), `organization.service.ts` (10), `realtime.service.ts` (8). Every one is
- `escape()`; there is no `format()` and no `escapeId()` in the tree.
-- **clix 77** — the insight modules (5 × 5 through `createCachedClix`),
- `legacy-scan.ts` (11), `cached-clix.ts` (13, the wrapper itself),
- `realtime.service.ts` (7), `widget.rpc.ts` (7), `referrer-spikes.ts` (4),
- `property-values.ts` (2), `project.service.ts` (2), `engine.ts` (2),
- `types.ts` (1), `v1-compat.ts` (2), `packages/db/index.ts` (1).
-- **sql-builder 6** — `organization.service.ts` (5 sites) plus the
- `packages/db/index.ts` re-export.
-
-The three files that DEFINE the builders are excluded from the scan and checked
-separately by `--assert`: `packages/db/src/clickhouse/query-builder.ts`, its
-`.test.ts`, and `packages/db/src/sql-builder.ts`. `packages/db/index.ts` still
-re-exports the first and third with a comment saying they are dead per ADR-013
-and blocked on exactly this conversion; that line is the last one to go.
-
-Comment-only mentions do not count. `funnel.sql.ts`, `retention.sql.ts`,
-`compiled.ts`, `mcp/src/tools/shared.ts`, `event|profile|session/src/filter-clauses.ts`
-and `overview-raw-where.sql.test.ts` all name `sqlstring` or `clix` in prose and
-score 0 — that is correct, and it is what makes 0 reachable without editing
-history.
-
-## The `sql` tag as it is
-
-`packages/db/src/clickhouse/sql.ts`. Every exported member, with the line it is
-defined on:
-
-| Export | Line | What it is |
-|---|---|---|
-| `sql` (the tag) | 261 (`tag` at 258) | `` sql`…${slot}…` `` → `SqlFragment`. Slots are typed `SqlFragment \| SqlParam`, so a bare string or number in a slot is a **compile-time error**. There is deliberately no `sql.raw()`. |
-| `sql.empty` | 262 (`EMPTY_FRAGMENT` 206) | A fragment that renders to nothing. The identity element for conditionals — `cond ? sql\`…\` : sql.empty`. |
-| `sql.param(type, value)` | 264 (`param` 162) | Escape hatch for a ClickHouse type with no shortcut. `sql.param('Int64', -1)`, `sql.param('DateTime', …)`. |
-| `sql.string(v)` | 265 | `{pN:String}` |
-| `sql.uint64(v)` | 266 | `{pN:UInt64}` — `number \| bigint \| string` |
-| `sql.float64(v)` | 267 | `{pN:Float64}` |
-| `sql.date(v)` | 268 (`toClickhouseDate` 200) | `{pN:Date}`. A `Date` is truncated to `YYYY-MM-DD` **in JS** — ClickHouse rejects a unix timestamp for `Date`, and the driver would send one. |
-| `sql.dateTime64(v, precision = 3)` | 269 | `{pN:DateTime64(3)}` |
-| `sql.uuid(v)` | 273 | `{pN:UUID}` |
-| `sql.bool(v)` | 274 | `{pN:Bool}` |
-| `sql.array(itemType, values)` | 275 | `{pN:Array(<itemType>)}` |
-| `sql.map(keyType, valueType, v)` | 277 | `{pN:Map(<k>,<v>)}`; accepts a `Map` or a plain object |
-| `sql.nullable(innerType, v)` | 284 | `{pN:Nullable(<inner>)}` — the only correct binding for a value that may be `null` |
-| `sql.identifier(name)` | 286 | `{pN:Identifier}`, bound server-side. Positional limits below. |
-| `sql.id(name, allowed?)` | 288 (`assertSafeIdentifier` 166) | Validated identifier **inlined as text**, for positions `{x:Identifier}` cannot reach. Throws `SqlIdentifierError`; never falls back to interpolation (ADR-013 R3). Pass `allowed` wherever the call site has a closed column set. |
-| `sql.join(fragments, separator?)` | 293 | Composes fragments. `separator` is a closed union (`SQL_JOIN_SEPARATORS`, line 151): `', '`, `' AND '`, `' OR '`, `' UNION ALL '`, `' '`, `'\n'`. Empty input → `sql.empty`. |
-| `SqlFragment` (class) | 87 | `strings` + `slots`; `new SqlFragment([text], [])` is the one text bridge (see `compiledText` below). |
-| `SqlFragment#toStatement()` | 92 | `{ query, query_params }`. Placeholder names are assigned **here**, from one counter, which is why nesting and reuse never collide (ADR-013 R2). |
-| `toStatement(query)` | 132 | Accepts `string \| SqlFragment`, so `chQuery` has one code path. |
-| `isSqlFragment(v)` | 110 | Type guard. |
-| `SqlIdentifierError` | 138 | What `sql.id` throws. |
-| `SqlParam` / `SqlParamValue` / `SqlParamType` / `SqlSlot` / `SqlStatement` / `SqlJoinSeparator` | 61 / 46 / 58 / 68 / 71 / 159 | Types. |
-
-`{name:Identifier}` does not work everywhere. The measured matrix is a comment
-in `packages/db/src/clickhouse/sql.clickhouse.test.ts:241-269` (ClickHouse
-26.1.3.52, 2026-09-02) — SELECT / alias / function argument / WHERE / GROUP BY /
-ORDER BY / FROM / JOIN / FROM-inside-a-CTE all work; a qualified
-`'alias.column'` in ONE param and a `SETTINGS` value both FAIL. Do not re-derive
-it; read it.
-
-## Idiom mapping
-
-`v` is the V1 value. `n` is a column name. Every V2 form below composes; none of
-them is a special case.
-
-| # | V1 | V2 | Note |
-|---|---|---|---|
-| 1 | `` `${n} = ${sqlstring.escape(v)}` `` | ``sql`${sql.id(n, ALLOWED)} = ${sql.string(v)}` `` | The default. `escape` produces `'…'`; the tag produces `{p1:String}` + a param. |
-| 2 | `` `${n} = ${sqlstring.escape(String(v).trim())}` `` on a numeric column | ``sql`${col} = ${sql.uint64(v)}` `` **only if** the column is unsigned and the V1 text had no `toFloat64` wrapper | See "numbers" below. When V1 wrote `toFloat64(${n}) > toFloat64('5')`, keep the wrapper and bind `sql.string(v)` — the cast is the behaviour. |
-| 3 | `` `${n} > ${sqlstring.escape(v)}` `` where `v` may be negative | ``sql`${col} > ${sql.param('Int64', v)}` `` | `sql.uint64(-1)` throws `BAD_QUERY_PARAMETER` (code 457) at the server. Measured 2026-09-07. |
-| 4 | fractional | `sql.float64(v)` | |
-| 5 | `` `toDateTime('${d}')` `` / `` toDateTime(${sqlstring.escape(d)}) `` | ``sql`toDateTime(${sql.string(d)})` `` | **Keep `toDateTime(...)` and bind the string.** This is what every landed M7 conversion did (`chart.sql.ts`, `funnel.sql.ts`, `retention.sql.ts`). Do not "improve" it to `sql.dateTime64` — that changes the emitted expression and its parse rules. |
-| 6 | `toDate('${d}')` on a calendar day | `sql.date(d)` where the expression is genuinely a `Date` column comparison; otherwise `toDate(${sql.string(d)})` | `sql.date` truncates a JS `Date` to `YYYY-MM-DD` in JS (line 200). |
-| 7 | `sqlstring.escape(true)` → `true` | `sql.bool(v)` → `{p:Bool}` | |
-| 8 | `sqlstring.escape(null)` → **`NULL`** | `sql.nullable('String', v)` | `sql.string(null as any)` sends `null`, which ClickHouse parses as **`''`** for `String`. Measured 2026-09-07: `SELECT {p1:String}` with `p1=null` returns `""`, while `{p1:Nullable(String)}` returns `null` and `isNull()` = 1. Getting this wrong turns `IS NULL` into `= ''` silently. |
-| 9 | `` `${n} IN (${v.map(escape).join(', ')})` `` | ``sql`${col} IN ${sql.array('String', v)}` `` | **Drop the parentheses.** `IN {p:Array(String)}` and `IN ({p:Array(String)})` both work (measured), but the array form is the idiom in every landed conversion. |
-| 10 | `IN ()` on an empty list | `IN ${sql.array('String', [])}` | Both return 0 rows; ClickHouse accepts a literal `IN ()`. Measured 2026-09-07. An empty array is a legal param — it does not need a `sql.empty` guard for correctness, only for readability. |
-| 11 | `` `${n} LIKE ${sqlstring.escape(`%${v}%`)}` `` | ``sql`${col} LIKE ${sql.string(`%${v}%`)}` `` | **Build the `%` in JS, on the value, exactly as V1 did.** Do not move `%` into the SQL text as `'%' \|\| {p}`; that is a different expression. |
-| 12 | `%` / `_` inside `v` | unchanged | Neither `sqlstring.escape` nor a bound param escapes LIKE metacharacters. A user value of `a%b` is a wildcard on both sides. Preserve the defect; do not fix it during a conversion. |
-| 13 | `` `${n} = ${escape(v)}` `` where `n` came from user input | ``sql`${sql.id(n, ALLOWED)} = …` `` — **`sql.id` only** | Never `compiledText(n)`, never a template hole. `sql.id` throws on anything that is not a bare or once-qualified identifier (≤64 chars, `[A-Za-z_][A-Za-z0-9_]*`). Pass the closed set as `allowed` whenever one exists — `EVENT_TOP_LEVEL_COLUMNS`, `PROFILE_COLUMNS`, `SESSION_LIST_COLUMNS` are already used this way. |
-| 14 | a dynamic column list joined with `', '` | `sql.join(cols.map((c) => sql.id(c, ALLOWED)))` | Default separator is `', '`. For a WHERE conjunction use `sql.join(parts, ' AND ')`; for a disjunction `' OR '`. |
-| 15 | a nested builder / sub-select spliced as text | a nested `SqlFragment` in a slot | Nesting is free: names are assigned once at `toStatement()`, depth-first, from one counter. Three levels deep is tested (`sql.test.ts`, "auto-named params (R2)"). |
-| 16 | `properties[${escape(k)}]` | ``sql`properties[${sql.string(k)}]` `` | A map **key** is a value, not an identifier. |
-
-### Numbers: which ClickHouse type, and why
-
-There is no "the number type". Pick by the column and by what V1 emitted:
-
-- **`UInt64`** (`sql.uint64`) for counts, limits, offsets, `range(n)` bounds and
- `INTERVAL n` operands — anything that cannot be negative. This is 50 of the 55
- numeric bindings already in core (`retention.sql.ts:97,202,233,243`,
- `sankey.sql.ts:115,175,192`, `chart.sql.ts:620`). It **throws at the server**
- on a negative value (measured: `Value -1 cannot be parsed as UInt64 … code
- 457`), which is the point — a limit that went negative is a bug, not a row.
-- **`Int64`** via `sql.param('Int64', v)` when the value is a signed offset or a
- user-supplied comparand that may be negative. There is no `sql.int64`
- shortcut; `sql.param` is the sanctioned form (line 264).
-- **`Float64`** (`sql.float64`) for fractional values —
- `event.sql.ts:167` and `session.sql.ts:124` bind a lookback in days this way.
-- **`String`** when V1 wrapped the value in a cast. `filter-where.ts:489` emits
- ``toFloat64(${name}) > toFloat64('5')`` — a *quoted* comparand fed to
- `toFloat64`. The V2 form is
- ``sql`toFloat64(${col}) > toFloat64(${sql.string(v)})` ``. Binding `Float64`
- there deletes the cast and changes the comparison for a non-numeric input,
- which is exactly the kind of silent drift the per-query proof exists to catch.
-
-One precision note, measured: `sql.uint64('9007199254740993')` binds correctly
-but comes back through `format: 'JSON'` as `9007199254740992`. That is the
-JSON response, not the parameter. If a converted query returns an id above 2^53,
-compare it as a string.
-
-### The `compiledText` seam
-
-`packages/core/src/modules/chart/src/compiled.ts` is the ONE place the chart
-module splices pre-compiled SQL text into a fragment:
-
-- `compiledText(text)` (line 14) — `new SqlFragment([text], [])`. Not a
- `sql.raw()`: it is a named export in one file, so the conversion's endpoint is
- "this file has no callers left", which is a grep.
-- `compiledTextWithProfileRefs(text, keys)` (line 23) — the same, after running
- `rewriteProfilePropertyRefs`.
-
-**What crosses it today:** the output of `field-resolution.ts` and
-`filter-where.ts` — V1's field resolver and filter compiler, both of which still
-render `sqlstring`-escaped text. ADR-013 left the shared compilers alone ("two
-behaviours, not two builders"), so M7 bridged them rather than rewriting them.
-Those two files are 66 of the baseline's 168 `sqlstring` lines.
-
-**Why it disappears:** once `getEventFiltersWhereClause` and the field resolver
-return `SqlFragment` instead of `string`, their output is already a fragment and
-there is nothing to bridge. Every caller that today writes
-`compiledText(getEventFiltersWhereClause(...))` writes the fragment directly.
-`compiled.ts` is then deleted whole, and with it the last legitimate
-`new SqlFragment([text], [])` in core. The conversion order therefore matters:
-**convert the compilers, then delete the seam** — not the other way round.
-
-## clix to sql
-
-A clix chain is a fragment sum. `packages/db/src/clickhouse/query-builder.ts`
-defines the methods being replaced (`select`/`from` 117, `where` 150,
-`groupBy` 205, `orderBy` 237, `limit` 246, `offset` 253, `having` 211,
-`with` 266, joins 297-345, `settings` 261, `toSQL` 570, `execute` 552).
-
-```ts
-// V1
-const rows = await clix(ch, timezone)
- .select<Row>(['name', 'count() as count'])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', projectId)
- .where('created_at', '>=', clix.datetime(start))
- .groupBy(['name'])
- .orderBy('count', 'DESC')
- .limit(10)
- .execute();
-
-// V2
-const statement = sql`
- SELECT ${sql.join([sql.id('name'), sql`count() as count`])}
- FROM ${sql.id(TABLE_NAMES.events)}
- WHERE project_id = ${sql.string(projectId)}
- AND created_at >= toDateTime(${sql.string(start)})
- GROUP BY name
- ORDER BY count DESC
- LIMIT ${sql.uint64(10)}
-`;
-const rows = await chQuery<Row>(deps, statement, { session_timezone: timezone });
-```
-
-Rules that fall out of the shape:
-
-- **Clause order becomes textual, so write the whole statement.** clix let
- `.where()` calls accumulate in any order; a fragment does not. Collect the
- conditions into an array and `sql.join(conditions, ' AND ')`, with
- `sql.empty` for the absent ones — that is what `event.sql.ts`,
- `profile.sql.ts` and `group.sql.ts` do.
-- **`.if()` / `.endIf()` has no successor and needs none.** clix's `_skipNext`
- (`query-builder.ts:578-589`) silently swallows the next clause when an
- `endIf()` is missing. A ternary into `sql.empty` cannot.
-- **`.rawWhere()` / `.rawJoin()` / `.rawHaving()` / `clix.exp()` are already raw
- text** — those are the easy ones. They become the literal parts of a template,
- with any value in them pulled out into a param.
-- **`.settings({ session_timezone })` does not become SQL text.** A `SETTINGS`
- value cannot be a bound param (matrix, above), and clix itself had already
- moved it to `clickhouse_settings` (`query-builder.ts:556` is the commented-out
- text form, `:562` the live one). Pass it as `chQuery`'s settings argument.
-- **`.execute()` becomes `chQuery(deps, statement, settings)`** — one code path
- for `string` and `SqlFragment` via `toStatement` (sql.ts:132), keeping
- `withRetry` and round-robin (ADR-013 R1).
-
-### `createCachedClix`
-
-`packages/core/src/modules/insight/src/cached-clix.ts` wraps `clix` so that
-`execute()` memoises on `sha256(query.toSQL() + '|' + timezone)` into a
-caller-supplied `Map` (lines 22-55). It is used by the five insight modules
-(`devices`, `entry-pages`, `geo`, `page-trends`, `referrers`) plus `engine.ts`,
-which is 27 of the baseline's 77 clix lines.
-
-The replacement keys on the **rendered statement plus its params**, because two
-statements with identical text and different params are different queries — the
-whole point of binding:
-
-```ts
-// modules/insight/src/cached-query.ts (the shape; write it in the task that needs it)
-export function createStatementCache(cache?: Map<string, unknown>) {
- return async function run<T>(
- deps: ServiceDeps,
- fragment: SqlFragment,
- settings?: ClickHouseSettings
- ): Promise<T[]> {
- const { query, query_params } = fragment.toStatement();
- if (!cache) {
- return chQuery<T>(deps, fragment, settings);
- }
- const key = createHash('sha256')
- .update(`${query}|${JSON.stringify(query_params)}|${settings?.session_timezone ?? 'UTC'}`)
- .digest('hex');
- const hit = cache.get(key);
- if (hit !== undefined) {
- return hit as T[];
- }
- const rows = await chQuery<T>(deps, fragment, settings);
- cache.set(key, rows);
- return rows;
- };
-}
-```
-
-Three things that must hold, and are worth asserting in the task's test:
-
-1. **`query_params` is serialized deterministically.** `toStatement` assigns
- `p1, p2, …` in render order from one counter, so the same fragment always
- produces the same names in the same order and `JSON.stringify` is stable. Do
- not sort the keys — two fragments that differ only in param *order* are
- different queries.
-2. **The timezone stays in the key.** clix folded it in (`|${queryTimezone}`,
- line 35) and it defaulted to `'UTC'` (line 24). Keep both, including the
- default, or a cache built under one project's timezone serves another's.
-3. **The cache is per-request, not global** — `createCachedClix` takes the `Map`
- from its caller and that does not change. A module-level cache would be a
- cross-tenant read.
-
-## Traps
-
-Every one of these is a way to write a conversion that typechecks, passes
-locally, and is wrong.
-
-### 1. Date-shaped substrings — clix re-quoted them, binding cannot
-
-clix's `escapeDate` regex-replaced any `\d{4}-\d{2}-\d{2}` substring **anywhere**
-in a SELECT expression or JOIN condition with a quoted literal; `clix.exp()`
-existed to opt out. A bound param does not do this, and that is a **behaviour
-change per conversion, not a bug fix to celebrate silently**.
-
-Evidence: `packages/db/src/clickhouse/sql.test.ts:221-250`, the
-`describe('injection (ported from query-builder.test.ts)')` block — in
-particular the case at `:236` named "leaves a path containing a date substring
-intact (the escapeDate bug)", asserting
-`/blog/2024-03-17-supabase-activity-scheduler` arrives at
-`query_params.p1` verbatim.
-
-Consequence for a conversion: if a V1 expression relied on `escapeDate` to quote
-something for it, the V2 text must quote it explicitly. The side-by-side proof
-is what surfaces this — the two texts will differ visibly.
-
-### 2. `IN` vs `GLOBAL IN` — never rewritten, in either direction
-
-Read `/home/deploy/rewrite-openpanel/docs/ENVIRONMENT.md` before touching any
-query on a `Distributed` table. On one node the two are **indistinguishable**;
-production Cloud is 2 shards × 2 replicas, where a plain `IN (subquery)` runs
-per-shard against that shard's local data and silently returns wrong answers.
-`docs/ENVIRONMENT.md` calls it "the single most dangerous edit in this repo".
-
-**The rule for this wave: a conversion changes the binding of values and nothing
-about the distribution semantics.** If V1 wrote `IN`, V2 writes `IN`. If V1 wrote
-`GLOBAL IN`, V2 writes `GLOBAL IN`. Whether a given site *should* be `GLOBAL IN`
-is a separate, pre-existing question — `retention.sql.ts:14` and
-`sankey.sql.ts:14-16` are the precedent: the M7 conversions recorded the question
-in a comment and did not answer it. Do the same.
-
-The tag does not obstruct either form — `sql.test.ts:143` and
-`sql.clickhouse.test.ts:393,410` pin `GLOBAL IN`, `GLOBAL JOIN`, `PREWHERE`,
-`FINAL`, `LIMIT BY`, `WITH FILL`, `ARRAY JOIN` and a trailing `SETTINGS` clause
-(ADR-013 R4). `packages/db/src/clickhouse/client.ts:118` sets
-`distributed_product_mode: 'allow'` globally, which is what keeps today's plain
-joins from erroring.
-
-### 3. `session_timezone` — clix always sent `'UTC'`
-
-`clix(client, timezone)` defaults to `'UTC'` when no timezone is passed
-(`query-builder.ts:696-697`) and sends it as
-`clickhouse_settings.session_timezone` (`:562`). Almost every clix call site
-passes no timezone, so almost every clix query ran under `session_timezone =
-'UTC'` — including queries whose date expressions would otherwise have used the
-server default.
-
-A converted query that just drops the setting changes every `toStartOfDay`,
-`toDate` and `toDateTime` in it. The landed conversions pin it explicitly:
-
-```ts
-// clix always sent `session_timezone: 'UTC'`; the two queries converted from
-// clix keep sending it so their result sets stay identical.
-const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;
-```
-
-— `packages/core/src/modules/session/session.service.ts:178-180`, and the
-byte-identical comment at `event.service.ts:94-96` and
-`profile.service.ts:66-68`. Copy that constant into any module you convert off
-clix. (`chart/src/run-query.ts:21` documents the other half: where a real
-project timezone was passed, it still travels as `session_timezone`.)
-
-Also, from the identifier matrix: a `SETTINGS` value **cannot** be a bound
-param, of any type. It goes through `chQuery`'s settings argument or nowhere.
-
-### 4. `rewriteProfilePropertyRefs` ran over finished text
-
-`packages/core/src/modules/chart/src/field-resolution.ts:457-467` rewrites
-`profile.properties['<key>']` → `` `profile.properties.<key>` `` by string
-`split`/`join` over the **whole finished query**. V1 could do that because
-everything was text.
-
-The reason it survives the conversion at all is stated at
-`compiled.ts:18-22`: bound params were never matched by it — an escaped literal
-cannot contain `['`, so the rewrite only ever hit generated column expressions,
-never values. That is why applying it per compiled piece before splicing
-(`compiledTextWithProfileRefs`, line 23) is provably the same rewrite.
-
-**The trap:** it is a textual pass. If a conversion moves a
-`profile.properties['x']` reference out of `field-resolution.ts`'s output and
-into a `sql` template's literal part, the rewrite will still match it — and if a
-conversion moves one into a *param*, it will silently stop matching. When
-converting the field resolver, the rewrite must be applied to the fragment's
-literal parts or folded into the resolver itself; it cannot be left as a pass
-over `toStatement().query`, because by then the params are gone and the CTE
-column names would no longer line up.
-
-### 5. Nullable columns and `null` values
-
-`sqlstring.escape(null)` produces the SQL keyword `NULL`. `sql.string(v)` with
-`v === null` produces `{p:String}` bound to `null`, which ClickHouse parses as
-the **empty string**. Measured 2026-09-07 against local ClickHouse 26.1.3.52:
-
-```
-SELECT {p1:String} AS v p1=null -> [{"v":""}]
-SELECT {p1:Nullable(String)} AS v p1=null -> [{"v":null}] isNull() = 1
-```
-
-So: any value whose type is `T | null | undefined` binds through
-`sql.nullable('T', v)`, not `sql.string`. If the V1 branch tested for null
-before escaping and emitted `IS NULL` / `= ''` instead (as `filter-where.ts:420-425`
-does for `isNull`/`isNotNull`), keep that branch — do not collapse it into a
-nullable param.
-
-### 6. Empty arrays
-
-`sql.array('String', [])` renders `{p:Array(String)}` bound to `[]`. Measured:
-ClickHouse accepts it and `n IN {p:Array(String)}` returns 0 rows, matching
-V1's literal `IN ()`, which it also accepts and which also returns 0. So an
-empty list is not a correctness hazard — but it is a *semantic* one wherever V1
-had an early return. `filter-where.ts:67-69` returns without emitting a clause
-when `cohortIds.length === 0`; converting that to `IN ${sql.array('String', [])}`
-would turn "no filter" into "match nothing". Preserve the guard.
-
-## Side-by-side proof
-
-M7 produced ten `*.proof.md` files by one method. This is that method, written
-as a procedure. It is not optional: `CLAUDE.md` requires that a replaced query
-be run against local ClickHouse with the old and new result sets shown side by
-side, and "looks equivalent" is explicitly not evidence.
-
-### Procedure
-
-1. **Get the PRE-change file.** `git show HEAD:<path> > /tmp/v1-<name>.ts`, or
- `git worktree add /tmp/v1 HEAD` if the V1 code needs its imports to resolve.
- Import V1 and V2 **side by side in one process** — that is what makes "the
- same inputs" checkable rather than asserted. Do not retype the V1 text by
- hand; generate it by calling the V1 function.
-2. **Execute both through one `@clickhouse/client`**, `format: 'JSON'`, the same
- `session_timezone` for both (trap 3 — if V1 appended
- `SETTINGS session_timezone = '<tz>'` to its text, pass that same value as
- `clickhouse_settings.session_timezone` for both sides). V1 goes as `query`;
- V2 goes as `query` + `query_params`.
-3. **Compare `data` row for row and `meta` column for column.** Compare as
- **sets** where V1 has no total `ORDER BY` — `ORDER BY date ASC WITH FILL`
- leaves rows sharing a `date` in arbitrary order, and three V1-vs-V1 runs of
- the same case produced three different orders. State in the proof which cases
- were compared as sets and why. Never sort away a difference you have not
- explained.
-4. **Record row counts on both sides, for every case.** A case that returns
- **zero rows proves nothing** — it proves the two texts are both syntactically
- valid. Every case in a proof needs a non-zero row count, or an explicit note
- saying which fixture would have produced one and why it does not exist here
- (the `chart.sql.proof.md` cohort cases are the precedent: `cohort_members` is
- empty in the prod-copy, so those cases are stated as 0-row statement
- equivalence with positive-row coverage moved to `openpanel_test`).
-5. **A difference is either fixed or explained as a V1 defect reproduced
- identically.** `IDENTICAL ERROR` — both sides failing with the same ClickHouse
- error — is a passing case and must be listed. A difference you cannot explain
- is a failed conversion.
-6. **Reproducibility.** Every statement in the proof must be runnable with
- `curl 'http://127.0.0.1:8123/?database=openpanel'`, binding V2's params as
- `param_pN=`. Write the params out.
-
-### Proof-file template
-
-Save as `<module>/src/<name>.sql.proof.md`. The four header lines are mandatory.
-
-````markdown
-# <name>.sql.ts — V1 → V2 result-set proof (<TASK-ID>)
-
-<One paragraph: which V1 file and commit sha, how both sides were executed,
-what was compared (`data` + `meta`), and which cases were compared as sets
-because V1 has no total ORDER BY.>
-
-- **Date**: YYYY-MM-DD.
-- **Data**: local prod-copy `openpanel` (<N> events). Projects: <ids and their
- timezones>. Name every fixture that is empty here, and say where its
- positive-row coverage lives instead.
-- **Machine**: single-node ClickHouse <version> on a <N>-vCPU box — timings are
- directional only; production is 2 shards × 2 replicas
- (`docs/ENVIRONMENT.md`). <One sentence on whether the statements contain
- `IN (subquery)` on a Distributed table, and that no `IN`/`GLOBAL IN` was
- changed.>
-- **Verdict**: N cases, all IDENTICAL.
- <or: N cases, all IDENTICAL; M of the N are IDENTICAL ERROR — V1 defects
- reproduced byte-for-byte, listed below, not fixed here.>
-
-## <case name>
-
-**statement** — IDENTICAL; rows V1/V2 = <n>/<n>; rows_read V1/V2 = <n>/<n>;
-wall V1/V2 = <n> ms / <n> ms; clickhouse_settings: session_timezone=<tz> (both).
-
-```sql
--- V1
-<text>
--- V2
-<text>
--- V2 params: {"p1": …}
-```
-````
-
-`rows_read` differing between the two sides is normal and is a perf note, not a
-semantic one: ClickHouse's index analysis treats a bound `{p:String}` differently
-from an inline literal for a `created_at` range. Record it; do not chase it.
-
-## Worked example
-
-One real `sqlstring.escape()` site, converted and executed. Documentation only —
-`git diff --stat` for this task shows `tooling/gates/` and `docs/` and nothing
-else.
-
-**Site:** `packages/core/src/modules/chart/src/filter-where.ts:439-446`, the
-`contains` branch for a top-level column:
-
-```ts
-case 'contains': {
- where[id] = `(${value
- .map(
- (val) =>
- `${name} LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
- )
- .join(' OR ')})`;
- break;
-}
-```
-
-**V2** — idiom 11 for the `%` wrapping, idiom 13 for the column, idiom 14 for
-the disjunction:
-
-```ts
-const where = sql`(${sql.join(
- value.map(
- (val) =>
- sql`${sql.id(name, [...EVENT_TOP_LEVEL_COLUMNS])} LIKE ${sql.string(`%${String(val).trim()}%`)}`
- ),
- ' OR '
-)})`;
-```
-
-**Inputs** — `filter = { name: 'path', operator: 'contains', value: ['/blog', "o'brien-%_"] }`,
-`projectId = 'secure-privacy'`, window `2026-07-01 00:00:00` … `2026-07-08 00:00:00`.
-The second value carries a quote (the escaping case) and a `%` and a `_` (the
-LIKE-metacharacter case, trap idiom 12).
-
-V1 text, produced by calling the real `getEventFiltersWhereClause`:
-
-```sql
-(path LIKE '%/blog%' OR path LIKE '%o\'brien-%_%')
-```
-
-V2 fragment, rendered:
-
-```sql
-(path LIKE {p1:String} OR path LIKE {p2:String})
--- params: {"p1":"%/blog%","p2":"%o'brien-%_%"}
-```
-
-Spliced into the same surrounding count, both sides were executed against local
-prod-copy `openpanel` through one `@clickhouse/client` with
-`session_timezone: 'UTC'`, `format: 'JSON'`:
-
-```sql
--- V1
-SELECT count() AS c, uniq(profile_id) AS u FROM events e
-WHERE project_id = 'secure-privacy'
- AND created_at >= toDateTime('2026-07-01 00:00:00')
- AND created_at < toDateTime('2026-07-08 00:00:00')
- AND (path LIKE '%/blog%' OR path LIKE '%o\'brien-%_%')
-
--- V2
-SELECT count() AS c, uniq(profile_id) AS u FROM events e
-WHERE project_id = {p1:String}
- AND created_at >= toDateTime({p2:String})
- AND created_at < toDateTime({p3:String})
- AND (path LIKE {p4:String} OR path LIKE {p5:String})
--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"%/blog%","p5":"%o'brien-%_%"}
-```
-
-**statement** — IDENTICAL; rows V1/V2 = 1/1; matched events V1/V2 = **60795/60795**;
-distinct profiles V1/V2 = **19723/19723**; `meta` V1/V2 =
-`[{"name":"c","type":"UInt64"},{"name":"u","type":"UInt64"}]` on both sides;
-rows_read V1/V2 = 90057/90057; wall V1/V2 = 33 ms / 31 ms; clickhouse_settings:
-`session_timezone=UTC` (both).
-
-- **Date**: 2026-09-07. **Data**: local prod-copy `openpanel`, 319,850,223 events.
-- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are
- directional only; production is 2 shards × 2 replicas. The statement contains
- no `IN (subquery)`, so no `IN`/`GLOBAL IN` question arises.
-- **Verdict**: 1 case, IDENTICAL.
-
-Reproduce either side with `curl`:
-
-```bash
-curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \
- --data-binary "SELECT count() AS c, uniq(profile_id) AS u FROM events e WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path LIKE '%/blog%' OR path LIKE '%o\\'brien-%_%')"
-
-curl -s -G 'http://127.0.0.1:8123/' \
- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \
- --data-urlencode 'default_format=JSONCompact' \
- --data-urlencode 'param_p1=secure-privacy' \
- --data-urlencode 'param_p2=2026-07-01 00:00:00' \
- --data-urlencode 'param_p3=2026-07-08 00:00:00' \
- --data-urlencode 'param_p4=%/blog%' \
- --data-urlencode "param_p5=%o'brien-%_%" \
- --data-urlencode "query=SELECT count() AS c, uniq(profile_id) AS u FROM events e WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (path LIKE {p4:String} OR path LIKE {p5:String})"
-```
-
-Both return `[[60795, 19723]]`.
-
-Two things this one case already demonstrates, and which the eight conversion
-tasks should expect:
-
-- The quote in `o'brien` is handled on both sides — V1 by `sqlstring`'s
- backslash escape, V2 by never putting the value in the text at all.
-- The `%` and `_` inside that value are LIKE wildcards on **both** sides. That
- is trap 12: the conversion preserves the defect. `%o'brien-%_%` matches
- nothing here, so its contribution to the count is zero on both sides — which
- is why the case pairs it with `/blog`, whose 60,795 matching rows are what
- makes the proof mean something.
-
-## Checklist per conversion task
-
-1. `bash tooling/gates/p12-grep-gates.sh --report | tail -3` — record the before.
-2. Convert. Values become params; identifiers become `sql.id`/`sql.identifier`;
- structure becomes `sql.join`. No `IN`/`GLOBAL IN` change. Keep
- `CLIX_SESSION_TIMEZONE` where clix implied it.
-3. Write the proof file from the template. Every case has a non-zero row count
- or a stated reason.
-4. `bash tooling/gates/p12-grep-gates.sh --report | tail -3` — the numbers went
- down, and nothing else moved.
-5. `bun run typecheck` and `cd packages/core && bun test`.
-6. When all three totals reach 0, delete `query-builder.ts`,
- `query-builder.test.ts`, `sql-builder.ts` and their `packages/db/index.ts`
- re-exports, drop `sqlstring` and `@types/sqlstring` from the three manifests,
- add `sql.ts` to the barrel (the comment at `sql.ts:21-23` says it joins then),
- and `--assert` exits 0.
diff --git a/docs/TECH_DEBT.md b/docs/TECH_DEBT.md
deleted file mode 100644
index 31fcf17fc..000000000
--- a/docs/TECH_DEBT.md
+++ /dev/null
@@ -1,2248 +0,0 @@
-# Tech debt register — dependency-cruiser baseline log
-
-The full remediation narrative (why `packages/core` ended up bypassing
-`ctx.db`/`ctx.ch` and importing its own barrel) lives in the controller repo
-at `docs/TECH_DEBT.md` — that is the source of truth for sections 1-5 (the
-"Deliberate", "Drift", "Planned remediation" and Carl's 2026-09-05 review).
-This file is the in-repo log of the dependency-cruiser rule that enforces
-that remediation (`docs/TECH_DEBT.md` §4 step 4, §5a), so the numbers below
-are re-measurable from this repo without controller access.
-
-## Re-measured
-
-### 2026-09-05 — M10-001, dependency-cruiser rules landed at `warn`
-
-Ran by: ralph (M10-001 implement task).
-Command: `pnpm run check:deps` (`.dependency-cruiser.cjs`), each new rule set
-to `severity: 'error'` in isolation for the count, then both reset to `warn`
-before commit.
-
-Scope of both rules: every file under `packages/core/src/**` (production and
-test files alike — the rule text in `.dependency-cruiser.cjs` does not carve
-tests out; see the note below on why some of these are expected to persist).
-
-| Rule | Violations (error, isolated run) | Breakdown |
-|---|---:|---|
-| `core-uses-ctx-not-db-internals` | **161** | 83 dynamic (`import('@openpanel/db/...')`) + 78 static (`from '@openpanel/db/...'`) edges, via `--output-type json`'s `dependencyTypes`/`dynamic` fields |
-| `core-no-self-barrel` | **96** | value-imports of `packages/core/src/index.ts` (the `"."` export target for the bare `@openpanel/core` specifier) from a sibling file under `packages/core/src/**` |
-
-Both were confirmed to fire with a real count (not vacuous): the same run
-with both rules reset to `warn` exits `0` (`x 257 dependency violations (0
-errors, 257 warnings)`), and the two ADR-008 rules
-(`constants-stay-isomorphic`, `frontend-values-only-constants`) reported 0
-violations throughout, at their unchanged `error` severity.
-
-**Numbers vs. the controller doc's 2026-09-05 measurement (`grep`-based, 63
-dynamic + 80 static, non-test files only):** roughly consistent. The
-difference is methodology, not drift — the grep baseline excluded test
-files and dependency-cruiser here does not, and a handful of test files use
-the ADR-010 `mock.module('@openpanel/db/...')` idiom (dynamic `import()` of
-the *mocked* specifier inside `beforeAll`), which is the sanctioned test
-pattern, not the production-code drift `core-uses-ctx-not-db-internals`
-exists to catch. Restricting the JSON breakdown to non-test files alone
-gives 57 dynamic + 75 static, closer to the controller doc's figures.
-Deciding whether the rule itself should exclude test files (and how
-`M10-009`'s flip to `error` treats the legitimate mock-module imports) is
-left to a later M10 task — this task only proves the rule fires and records
-the baseline, per its acceptance criteria.
-
-`context.ts`'s `typeof import('@openpanel/db/...')` type queries
-(`Db`/`ClickHouseClient`) do **not** count: verified via
-`--output-type json` that dependency-cruiser tags them `['undetermined',
-'type-import']`, a genuinely type-level reference distinct from the
-`'type-only'` tag `import type {...}` statements get. `dependencyTypesNot`
-on `core-uses-ctx-not-db-internals` exempts both tags, so no per-file
-exception entry was needed for `context.ts`.
-
-### 2026-09-05 — M10-001 fix, `core-uses-ctx-not-db-internals` re-measured (161 → 167)
-
-Ran by: ralph (M10-001 rework, after the independent reviewer rejected the
-first attempt above).
-
-The first attempt's blanket `dependencyTypesNot: ['type-only', 'type-import']`
-was wrong: it exempted the `'type-import'` tag package-wide instead of naming
-`context.ts` in the rule's exception list, and that hid a real composition
-seam. `packages/core/src/buffers/clickhouse.ts` has a `typeof import(...)`
-type query (line 8, genuinely type-only on its own) *and* a real runtime
-`import(...)` dynamic import of the same resolved module (line 13, the
-deliberate lazy-load-to-keep-`bun-test`-offline pattern). Confirmed with an
-isolated probe file mirroring that exact structure, via `--output-type json`:
-dependency-cruiser merges the two references between the same pair of files
-into **one** edge and the merge drops the `'dynamic-import'` tag entirely,
-leaving only `['undetermined', 'type-import']` — indistinguishable, by tag
-alone, from `context.ts`'s pure type queries. The same merge silently hid the
-identical pattern in five test files that use the ADR-010
-`mock.module('@openpanel/db/...')` idiom (a `typeof import(...)` alias
-declared once, then `await import(...)`'d for real inside `beforeAll`):
-`chart.service.test.ts`, `chart.sql.test.ts`, `funnel.sql.test.ts`,
-`overview.sql.test.ts`, `pages.sql.test.ts` (all under
-`packages/core/src/modules/chart|overview/`).
-
-Fix: `dependencyTypesNot` on the rule's `to` now reads `['type-only']` only,
-matching the idiom the other three rules in this file already use.
-`context.ts` is excluded by `pathNot` on the rule's `from` instead — named
-explicitly, as the acceptance criteria requires — since it is the one file
-under `packages/core/src/**` that references `@openpanel/db` exclusively
-through type queries with no accompanying value import to merge with.
-
-Command: `pnpm run check:deps` (`.dependency-cruiser.cjs`), `core-uses-ctx-not-db-internals`
-set to `severity: 'error'` in isolation (`core-no-self-barrel` left at `warn`).
-
-| Rule | Violations (error, isolated run) | Breakdown |
-|---|---:|---|
-| `core-uses-ctx-not-db-internals` | **167** (was 161) | 83 dynamic (`dependencyTypes` includes `'dynamic-import'`) + 78 static (plain `import`/`esm`) + **6 newly caught** merged edges tagged `['undetermined', 'type-import']` that are real value imports (`buffers/clickhouse.ts` + the 5 test files above), via `--output-type json`'s `dependencyTypes` field |
-| `core-no-self-barrel` | **96** (unchanged) | not touched by this fix |
-
-Diffed the violation edge list (`(from, to)` pairs) between the old rule
-config and the fixed one: exactly those 6 edges were added, zero were
-removed or changed — the fix is strictly additive detection, not a
-re-classification of the existing 161.
-
-Both rules reset to `warn` after measuring: `pnpm run check:deps` exits `0`
-(`x 263 dependency violations (0 errors, 263 warnings)`). The two ADR-008
-rules still report 0 violations at their unchanged `error` severity.
-`pnpm run typecheck` and `cd packages/core && bun test --isolate` (1447
-pass, 0 fail) both pass unaffected — this task only changes the lint config
-and this doc, not any source file.
-
-### 2026-09-05 — M10-002, the 22 `modules/*/src/access.ts` copies deleted, ladder bound once via a lazy memoized helper
-
-Ran by: ralph (M10-002 implement task, docs/TECH_DEBT.md §5b). Reset three
-times on review before this attempt; the operator rewrote criteria 1-2 to
-explicitly authorize what earlier attempts got blocked or FAILed on:
-`integration.service.ts` / `subscription.service.ts` reaching the shared
-binding directly, because both are called with a bare `userId` (no `ctx`) by
-`packages/trpc`'s still-live V1 delegate routers — the exemption expires when
-`packages/trpc` dies at P10.
-
-Before, proof the 22 were byte-identical copies (via git history — the files
-are gone from the working tree by the time this entry is written):
-
-```
-$ git ls-tree -r HEAD --name-only | grep -E '^packages/core/src/modules/[^/]+/src/access\.ts$' \
- | while read -r f; do git show "HEAD:$f" | head -n1; done | sort | uniq -c
- 22 // Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-```
-
-**The binding.** `modules/auth/auth.service.ts` exports one `getAccessChecks()`:
-a module-level `let accessChecksPromise`, populated the first time anything
-calls it, via `Promise.all([import('../../shared/access-lookups'),
-import('../project/project.service')])` feeding the four lookups into
-`shared/access.ts`'s `createAccessChecks(...)` — exactly once, ever. Nothing
-runs at module-import time, and nothing runs at `createAuthService(deps)`
-construction time either, which matters because `createAuthService` is NOT a
-process-lifetime singleton: `context.ts`'s `installLazyServices` calls
-`createServices(deps)` (hence `createAuthService(deps)`) fresh on the first
-`ctx.services` read of every request. `createAuthService` spreads the
-resolved checks into `AuthService`'s `requireProjectAccess` /
-`requireOrganizationAdmin` / `requireProjectAdmin`, plus three raw lookups
-(`getProjectAccess` / `getOrganizationAccess` / `getClientAccess`, each its
-own `import('../../shared/access-lookups')` — cheap after the first call,
-since the module resolves from Bun's own import cache). Every rpc/route/
-handler that HAS a `ctx` now calls `ctx.services.auth.<check>`.
-
-**The two authorized exceptions.** `integration.service.ts` (4 call sites)
-and `subscription.service.ts` (6 — 10 total, matching the earlier attempt's
-"unmemoized across its 10 call sites" diagnosis) import `getAccessChecks`
-directly from `../auth/auth.service`. `integration.service.ts`'s org-wide
-read branch also imports `getOrganizationAccess` directly from the sibling
-`shared/access-lookups.ts` — a raw lookup, not part of the `require*` ladder,
-so it never goes through `getAccessChecks()`. Neither import touches
-`@openpanel/core`'s own barrel.
-
-**Why this is not the earlier module-scope attempt that hung.** An earlier
-attempt bound `createAccessChecks(...)` at module scope in `auth.service.ts`
-(a top-level `const accessChecks = createAccessChecks({...})`, with static
-imports of `access-lookups.ts` / `project.service.ts`) and hung
-`cd packages/core && bun test` for 30 minutes. This attempt never calls
-`createAccessChecks` anywhere except inside `getAccessChecks()`'s own lazily-
-invoked body, and both its inputs are reached by dynamic `import()`, not a
-static top-level import — see the timing table below for proof the bare suite
-now exits on its own.
-
-**Fixed, not worked around: a real pre-existing test leak this task's own
-hard gate exposed.** Bare `bun test` shares one module registry across every
-file (no `--isolate`); `src/context.test.ts`, `src/http/context.test.ts` and
-`test/request-id-end-to-end.test.ts` each `mock.module('./services' /
-'../services' / '../src/services', ...)` with a stub `createServices`
-returning `{}` (no `.auth`) and never restored it. Nothing else in the suite
-read `ctx.services.auth` before this task, so the leak was invisible; this
-task adds ~20 more rpc files that do, and `group.rpc.test.ts` /
-`realtime.rpc.test.ts` / `realtime.routes.test.ts` started failing with
-`undefined is not an object (evaluating 'ctx.services.auth.requireProjectAccess')`
-— whichever context test's stub ran first, still installed. Fixed by
-snapshotting each real module BEFORE its `mock.module` call and restoring to
-that snapshot in `afterAll` (the snapshot-before-mock idiom — a live
-re-`import` during restore just reads the already-mocked registry entry back).
-The new `auth.service.access.test.ts` has the same hazard one level deeper:
-`getAccessChecks()`'s `accessChecksPromise` is a true process-lifetime memo,
-so its `afterAll` also calls a new test-only `resetAccessChecksForTests()`
-alongside restoring its two mocked modules, or its fakes would answer every
-later file's real access checks for the rest of the run.
-
-**Test that binds fake `AccessLookups`.** `auth.service.access.test.ts` mocks
-`../../shared/access-lookups` and `../project/project.service` (spreading the
-real modules, overriding only the four lookups) and exercises
-`createAuthService(...)` directly: fail-closed ordering (no access throws
-before the write-level check runs), the exact messages (`'You do not have
-access to this project'`, `'You have read-only access to this project'`,
-`'Only organization admins can do this'`, and a caller-supplied override),
-the write/admin level set, and `requireProjectAdmin`'s project→org
-resolution. `shared/access.ts` itself is untouched by this task.
-
-**Deletion proof:**
-```
-$ find packages/core/src/modules -name access.ts | wc -l
-0
-```
-
-**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at
-their landed `warn` severity):
-
-| Rule | Before (M10-001) | After (M10-002) | Delta |
-|---|---:|---:|---:|
-| `core-uses-ctx-not-db-internals` | 167 | 167 | 0 |
-| `core-no-self-barrel` | 96 | 74 | −22, exactly the 22 deleted files |
-
-`core-uses-ctx-not-db-internals` counts VALUE imports of `packages/db/**`;
-all 22 deleted files imported `@openpanel/core` (the self-barrel) and
-`shared/access.ts` — never `@openpanel/db` directly — so this task's
-mechanism (deleting self-barrel copies) has zero edges of that kind to
-remove. `core-no-self-barrel` counts value-imports of
-`packages/core/src/index.ts`, which is exactly what every deleted file did
-once, for its own `createAccessChecks` binding; −22 is the 22 files, one edge
-each. `pnpm run check:deps` exits `0`
-(`x 241 dependency violations (0 errors, 241 warnings)`).
-
-**`pnpm run typecheck`** — all 25 workspaces, `Done`.
-
-**`cd packages/core && bun test`** (bare, no `--isolate` — the hard gate):
-```
- 1455 pass
- 0 fail
-Ran 1467 tests across 148 files. [10.73s]
-
-real 0m10.797s
-user 0m8.005s
-sys 0m1.878s
-```
-The process exited on its own; `real` tracks `user`+`sys`, not a multi-minute
-stall on an idle handle. `cd packages/core && bun test --isolate` (the
-configured suite) is also green — 1455 pass, 0 fail, `real 1m45.680s`.
-
-### 2026-09-05 — M10-002 correction: the previous "third call site" fix is reverted — it was out of scope, not authorized
-
-The independent reviewer REJECTED the attempt written up in the correction
-section that used to be here (Attempt 2): it touched 14 files under
-`packages/trpc/**` plus deleted `packages/trpc/src/access.test.ts`, none of
-which are in this task's declared scope (`packages/core/**`, `apps/api/**`,
-`docs/**`). The reviewer was right — CLAUDE.md's Scope section is explicit
-("Refactoring outside scope is a task of its own; propose it, don't do it")
-and self-justifying the change in the report instead of stopping is exactly
-the failure pattern the review exists to catch. That diff is reverted in
-full (`git checkout HEAD -- packages/trpc/`); `packages/trpc/src/access.ts`,
-its three ladder exports, its twelve router call sites and
-`packages/trpc/src/access.test.ts` are back to their pre-task state,
-byte-identical to `HEAD`.
-
-**What that leaves.** `packages/trpc/src/access.ts` does have its own
-top-level `const checks = createAccessChecks({...})` — pre-existing, from
-M4-002 (`packages/trpc` rebase onto core's `CoreContext`) and untouched by
-every M10-002 wave since, not something this task introduced or could
-authorize itself. It is wired live through `apps/api/src/main.ts`
-(`enforceAccess` middleware in `packages/trpc/src/trpc.ts`, plus fifteen V1
-router files). So criterion 1's "called from exactly ONE place in the
-codebase," read literally against the *whole repo*, is not met:
-
-```
-$ grep -rn "createAccessChecks(" --include="*.ts" packages apps | grep -v '\.test\.ts'
-packages/core/src/modules/auth/auth.service.ts:148: createAccessChecks({
-packages/trpc/src/access.ts:22:const checks = createAccessChecks({
-```
-
-Everything this task's scope can reach is consistent with the criterion:
-inside `packages/core/**`, `createAccessChecks` is called from exactly one
-place (`auth.service.ts`'s `getAccessChecks()`, memoized, lazy — see the
-2026-09-05 M10-002 entry above for the mechanism, unchanged by this
-correction). `packages/trpc/src/access.ts`'s copy is a second, independent
-binding of the same ladder to the same lookups, but it lives entirely
-outside `packages/core`, is unreachable from anything this task is allowed
-to edit, and predates this task by five waves (M4-002 → M9-CLEANUP-001).
-Fixing it requires editing `packages/trpc/**`, which is out of scope; per
-CLAUDE.md this is recorded as a follow-up, not done here. It is low-risk
-debt on its own terms: `packages/trpc` is V1's whole surface and is deleted
-entire at P10 (docs/TECH_DEBT.md's other P10 entries), taking this second
-call site with it — the exemption for integration.service.ts /
-subscription.service.ts calling `getAccessChecks()` directly already carries
-the identical "expires at P10" note for the same reason.
-
-**Follow-up (new, not this task):** collapse `packages/trpc/src/access.ts`'s
-`createAccessChecks({...})` into a call through core's `getAccessChecks()`
-(or delete the file once its callers move to `ctx.services.auth`, as
-Attempt 2 did) — scoped to `packages/trpc/**`, proposed here rather than
-done, per CLAUDE.md's Scope section.
-
-Re-verified after the revert: `pnpm run typecheck` — all 25 workspaces,
-`Done`, including `packages/trpc` (its `access.ts` still resolves
-`createAccessChecks`, `canWriteProject`, `getOrganizationAccess`,
-`getProjectAccess`, `getProjectById` off `@openpanel/core`'s barrel, which
-this task doesn't remove). `cd packages/core && bun test` (bare): 1455 pass,
-0 fail, `Ran 1467 tests across 148 files. [13.56s]`, `real 0m13.635s` —
-process exited on its own. `pnpm run check:deps`:
-`core-uses-ctx-not-db-internals` 167, `core-no-self-barrel` 74 — unchanged
-from the M10-002 entry above; this rule only cruises `packages/core/**`, and
-the revert touched nothing there.
-
-### 2026-09-05 — M10-003, the read path (chart+4, report, dashboard, export, share, reference) onto `createXService(deps)`
-
-Ran by: ralph (M10-003 implement task, docs/TECH_DEBT.md §4 steps 1/2/5 and
-§5a).
-
-**Shape.** Ten modules now expose exactly one
-`createXService(deps: ServiceDeps): XService`, registered in `services.ts`'s
-`Services` interface and `createServices`. Their implementation functions take
-`deps` as the first parameter and the factory binds it; every service method
-carries an explicit return type (`ReturnType<typeof fn>` /
-`Parameters<typeof fn>[1]` where the shape is a Prisma payload), for the
-ts7022/ts7023 reason `services.ts` documents.
-
-**The four chart sub-services FOLD INTO `ChartService`** rather than becoming
-four more `Services` members. They are sibling files of `modules/chart/`, not
-modules — ADR-007's map is one service per module, `chart.service.ts` is
-already the dispatcher every caller goes through (`getFunnelChart` /
-`getConversionChart` / `getSankeyChart` / `getRetentionChart`), and four keys
-named after files would claim four modules that do not exist.
-
-**Loaders deleted.** In those ten modules there is now no
-`import('@openpanel/db...')` at all, and `loadChClient()` / `loadDb()` /
-`loadCore()` / `loadReportsService()` / `loadIdService()` /
-`loadDateService()` / `loadOrganizationService()` / `loadAccessService()` /
-`loadDashboardService()` are gone. ClickHouse is `deps.ch` and Postgres is
-`deps.db`.
-
-- `chart/src/run-query.ts` runs `deps.ch.query(...)` — `chQuery`'s own
- transport (`withRetry(client => client.query(...))`) — and reproduces
- `chQuery`'s Int-meta coercion, the same shape `modules/overview/src/run-query.ts`
- has shipped since M7-005. It logs `'query info'` on `deps.logger`, which is
- the request-scoped child, so the ClickHouse call now carries the requestId.
-- `chart/src/table-filter-where.ts` stopped statically importing
- `@openpanel/db/src/clickhouse/client` (a module that builds a ClickHouse
- client and a pino logger at import time) for `formatClickhouseDate` and
- `TABLE_NAMES`; both are local — the module's own `./dates.formatClickhouseDate`
- (byte-identical to packages/db's non-`skipTime` branch) and
- `./field-resolution.CHART_TABLE`, which already carried all four physical
- table names (`events`, `profiles`, `groups`, `cohort_members`).
-- `export/export.routes.ts`'s `/insights/:projectId/live` reads
- `ctx.buffers.event` instead of `loadDbBuffers()`.
-
-**Section 2's duplicate is unwired.** `chart.service.ts` (and
-`conversion.service.ts`, `funnel.service.ts`, `engine/normalize.ts`) reached
-`mergeGlobalFilters` / `onlyReportEvents` through `import('@openpanel/core')`.
-They now import them from `modules/report/src/series.ts`. The two helpers moved
-there, out of `report.service.ts`, because `report.service.ts` imports the
-chart engine and `chart/funnel.service.ts` imports them — a static import back
-would have closed a real `report.service -> chart/funnel.service ->
-report.service` cycle. `src/series.ts` imports nothing but a zod-derived type,
-so both sides stay eager and neither needs a loader.
-
-**One genuine cycle kept lazy, both ends named.**
-`modules/auth/auth.service.ts`'s `loadShare()`:
-`../share/share.service` statically imports this file's `hashPassword`, and
-`signInToShare` needs share's three lookups — `auth.service.ts <->
-share.service.ts`. It is not a `@openpanel/db` loader; the share lookups take
-`deps` like everything else.
-
-**What is still a value import of `@openpanel/db` in these modules, and why.**
-Seven files in `modules/chart/src/` value-import `sql` / `SqlFragment` /
-`toStatement` from `@openpanel/db/src/clickhouse/sql` (`chart.sql.ts`,
-`funnel.sql.ts`, `conversion.sql.ts`, `sankey.sql.ts`, `retention.sql.ts`,
-`compiled.ts`, `run-query.ts`). That is ADR-013's SQL tag, which ADR-007's
-"`packages/db` — the final surface" keeps in `packages/db` by name ("**new**
-`clickhouse/sql.ts`"), and `packages/db/**` is outside this task's scope globs,
-so it cannot be moved here. It carries no client, no connection and no request
-scope — it is a compile-time template tag — so it is not a place the requestId
-chain can end. Nine more core files outside this task's modules
-(`overview`, `profile`, `group`, `session`, `event`, `mcp`) import it the same
-way; a decision on whether `core-uses-ctx-not-db-internals` should exempt
-`clickhouse/sql.ts` (or whether the tag moves) belongs to M10-009's flip to
-`error`, not here. Prisma ROW TYPES stay as `import type` (erased at runtime),
-which is what keeps `bun test` offline.
-
-**`v1-compat.ts` — the seam this wave needed and could not avoid.**
-`apps/api/src/main.ts` still mounts `@openpanel/trpc`'s `appRouter`, not core's
-`rpc.router.ts`, so V1's 28 routers are the LIVE `/trpc` surface; they call
-core's modules as bare barrel exports and have no `Ctx` to hand a
-`ServiceDeps`. `packages/trpc/**` is outside this task's scope globs (the
-reviewer rejected M10-002 attempt 2 for editing it), and the mcp/assistant tool
-runtimes are in the same position. So `packages/core/src/v1-compat.ts` holds
-one registration point — `setV1CompatServices(deps)`, called once from
-`main.ts` right after `AppDeps` is built — and the ~60 bare wrappers the barrel
-exports for those callers. Everything that HAS a `Ctx` (core's own rpc files,
-`export.routes.ts`, `overview.rpc.ts`) uses `ctx.services.*` and keeps the
-request-scoped logger. One file, one grep, deleted whole when `packages/trpc`
-dies at P10. Its `signInToShare` wrapper preserves V1's 2-argument spelling;
-core's own `auth.rpc.ts` passes `ctx`.
-
-A process that never builds `AppDeps` falls back to the same singletons the
-deleted `loadDb()` / `loadChClient()` loaders reached, built lazily on first
-use (so importing `@openpanel/core` still constructs no database and
-`bun test` still runs offline), with packages/db's own `createLogger` — the
-pino logger that already writes `chQuery`'s `query info` line — so those
-callers behave exactly as they did before this wave. That fallback is not
-theoretical: the root `pnpm test` run caught
-`packages/trpc/src/routers/share.test.ts` calling `shareRouter` procedures
-directly with no boot, and `packages/trpc/**` is outside this task's scope.
-Its three lazy `import('@openpanel/db/...')` edges are the +3 in the table
-below; `main.ts` always registers before `buildHttpApp`, so a running server
-never reaches it.
-
-**requestId proven through this path.** New sibling test
-`packages/core/test/request-id-chart-query.test.ts` — the existing
-`request-id-end-to-end.test.ts` mocks the whole `Services` container, so it
-cannot show this hop. The new file uses a REAL `createServices`: an Elysia
-route under `requestLogging(deps)` calls
-`ctx.services.chart.getRetentionSeries({ projectId })` with a recording
-`deps.ch`, and asserts
-
-```ts
- // The query really ran through `deps.ch` — a silent miss would leave the
- // logger assertion below trivially true (AGENTS.md).
- expect(queries).toHaveLength(1);
- expect(queries[0]?.query).toContain('FROM events');
-
- const bindingOf = (message: string) =>
- lines.find((line) => line.message === message)?.bindings.requestId;
-
- // The ClickHouse call's own log line, and the route's, carry ONE requestId.
- expect(bindingOf('query info')).toBe(SUPPLIED_REQUEST_ID);
- expect(bindingOf('request done')).toBe(SUPPLIED_REQUEST_ID);
-```
-
-plus a second case proving two concurrent requests do not share one
-(`expect(queryLineIds.sort()).toEqual(['req-a', 'req-b'])`).
-
-**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at
-their landed `warn` severity):
-
-| Rule | Before (M10-002) | After (M10-003) | Delta |
-|---|---:|---:|---:|
-| `core-uses-ctx-not-db-internals` | 167 | **160** | **−7** |
-| `core-no-self-barrel` | 74 | **62** | **−12** |
-
-The ten modules themselves shed 10 edges; `v1-compat.ts`'s lazy fallback adds
-3 back, in one file with a stated death date, for a net −7. Exit `0`,
-`x 222 dependency violations (0 errors, 222 warnings). 1991 modules, 8035
-dependencies cruised.` (was 241.)
-
-**Verification, all run by ralph on 2026-09-05:**
-
-- `pnpm run typecheck` — all 25 workspaces, `Done` (`packages/trpc` included:
- the barrel's V1 spellings are unchanged).
-- `cd packages/core && bun test` (bare, no `--isolate`): **1457 pass, 12 skip,
- 0 fail**, `Ran 1469 tests across 149 files. [31.02s]`.
-- `pnpm test` (root vitest, what `full.sh` runs): **13 files, 205/205 passed**.
-- `pnpm run check:deps` — the table above.
-- `controller:verification/harness start` — api :3333, worker :9999 ready in 3s.
-- `cd apps/api && timeout 900 pnpm run e2e:sessions` — **29/29 checks passed**.
-- `controller:verification/golden/compare.sh`:
- `passed: 137/137` / `OK: zero diffs` (`golden: http://127.0.0.1:3333 @
- 2026-09-05T07:59:27Z`; no `stale:` skips — same UTC day as the capture).
-- `controller:verification/harness stop`.
-- `controller:verification/full.sh` — `FULL: green (1 documented pre-existing
- exception(s) - see BLOCKED-KNOWN above)`, exit `0`. The one exception is
- `contracts/sdk/run.sh`'s `dist-gate.sh` on the documented pre-P11 state
- (web/nextjs/react-native/express leak `@openpanel/*`, sdk is clean); every
- other stage is `OK`, including `pnpm test`, `golden/compare.sh`
- (`passed: 137/137`, zero diffs) and `contracts/auth/run.sh`.
-
-### 2026-09-06 — M10-004, the account path (auth, client, project, user, subscription, salt, conversation, assistant, mcp) onto `createXService(deps)`
-
-Ran by: ralph (M10-004 implement task, docs/TECH_DEBT.md §4 steps 1/2/5 and
-§5a, continuing M10-003).
-
-**Shape.** All nine modules now expose exactly one
-`createXService(deps: ServiceDeps): XService`, registered in `services.ts`.
-`auth.service.ts` already had `createAuthService` from M10-002 (bound to the
-access ladder, independent of `deps`) — this wave finishes it: every OTHER
-lazy `@openpanel/db` load in the file (sign-up/sign-in/TOTP/reset-password/
-OAuth-callback) now takes `deps` too, and `./src/login-session.ts` /
-`./src/registration.ts` reach Postgres as `deps.db` with no lazy loader left.
-`assistant` and `mcp` needed a factory for the first time; both were a bag of
-loosely-related exports, not a services-shaped file, before this wave.
-
-**Two modules that were never going to fit the mechanical pattern.**
-
-- **`assistant.service.ts`** re-exported `chatApp`/`chatRunContext` as
- eager `export ... from './src/app'` / `'./src/run-context'` — a static
- re-export, which means importing this file AT ALL constructs the whole
- Better Agent app (one `defineAgent` per whitelisted chat model). Registering
- `createAssistantService` in `services.ts` would have made that run at
- PROCESS BOOT (services.ts's own module evaluation) instead of on the first
- real chat/filter-command request. Fixed by moving the lazy-loader index.ts
- used to hide this (`loadAssistant()`/`getChatApp()`/`getChatRunContext()`)
- INTO `assistant.service.ts` itself, so the file is cheap to import
- regardless of who imports it; index.ts's own copy of that mechanism is
- deleted, replaced by a plain re-export now that it's safe. `deps` goes
- unused in the factory — nothing here touches Postgres directly.
-- **`mcp.service.ts`** statically imported `./src/auth` (fine, fixed below)
- and `./src/server` (`registerAllTools`, ~20 tool files, several importing
- `@openpanel/core` for cross-module functions) — reached only via a dynamic
- `loadMcp()` in index.ts before this wave, for exactly the reason
- `assistant`'s TDZ hazard note already named for this file. `./src/server`
- stays behind a lazy loader inside `mcp.service.ts`; `./src/auth` is a plain
- import again because its own `@openpanel/core` reach (below) is now lazy
- too, so nothing static is left to protect against. `handleStatelessMcpRequest`
- /`extractToken` keep their exact bare signature — both are called directly
- by their own tests with no `deps` argument, a hard contract this wave does
- not touch — so `McpService`'s two methods are thin, deps-ignoring binds.
-
-**Bare hot-path callers with no `Ctx` to give a `deps` — the pattern this wave
-generalizes from `v1-compat.ts`'s v1-compat seam to core's OWN internals.**
-`getProjectByIdCached`/`getClientByIdCached` (ingest's `/track` auth,
-`http/client-auth.ts`'s `/export`+`/import`+`/manage` tier, MCP's token auth)
-and `getSalts` (ingest's device-id resolution) all have their L1 LRU cache
-built INSIDE their `createXService(deps)` closure now, which only stays a
-cross-request singleton through the v1-compat seam (`registered`, built once
-at boot) — not through `ctx.services`, which is one Ctx per request. Every one
-of these callers has no `Ctx`/`ServiceDeps` of its own, so they reach the
-cache through `v1-compat.ts` (`compatDb()`/`compatCh()` for the couple of
-third-party-signature callers — `@better-agent/core`'s `ConversationStore`,
-`@modelcontextprotocol/sdk`'s tool handlers — that can't carry a wrapped
-service method at all). `getClientByIdCached`/`getProjectByIdCached` also
-gained a `clearClientByIdCache`/`clearProjectByIdCache` service method, since
-the LRU's `.clear()` isn't part of the plain `(id) => Promise<...>` shape
-`ServiceDeps`-free callers expect.
-
-One of these (`ingest/src/incoming-event-handler.ts`) carried a **stale
-constraint**: a comment mandating a *static* import of `project.service.ts`
-"so a dynamic edge into project.service doesn't become its own rolldown chunk
-... external in apps/worker's bundle". `apps/worker` no longer exists (M9) and
-`apps/api` ships with no bundler at all (`apps/api/package.json` has no
-`build` script — ADR-010) — the constraint the comment protected against is
-gone, so the file now uses the same "GENUINE CYCLE, kept lazy" dynamic import
-as everywhere else in this wave.
-
-**Correction (post-review): there is no "no import-time cost" exception to
-acceptance criterion 2.** The first pass through this wave left four plain,
-top-level value imports of `@openpanel/db` standing — `subscription.service.ts`
-and mcp's `dashboard-management.ts` each imported `Prisma` (for the
-`Prisma.DbNull` sentinel), and mcp's `analytics/property-values.ts` imported
-`TABLE_NAMES`/`clix` — and this section originally excused all four, plus
-`project.service.ts`'s two still-`clix` functions, as "scoped exceptions"
-under ADR-013. That was wrong on the acceptance criterion's own terms: ADR-013
-grants time to convert ClickHouse query BODIES to the `sql` tag (one query per
-P7 task, diffed); it says nothing about the criterion's separate,
-unconditional "no `@openpanel/db` import in these nine modules" rule, and a
-gap no ADR actually covers is `BLOCKED`, not self-exempted (CLAUDE.md). Fixed
-by extending the v1-compat seam instead of arguing the rule away:
-
-- `v1-compat.ts` gained `compatPrisma()` (the `Prisma` namespace — a value,
- not a client, but still `@openpanel/db`) and `compatChHelpers()` (`clix`,
- `TABLE_NAMES`, `chQuery`, `convertClickhouseDateToJs` — the query-building
- helpers that ADR-013 leaves in place beside `deps.ch`, the actual client).
- Both are lazy, same as `compatDb`/`compatCh`.
-- `subscription.service.ts` and `project.service.ts` reach them through a
- local `loadCompatPrisma`/`loadChHelpers` lazy loader (GENUINE CYCLE: both
- are statically imported by `services.ts`, which `v1-compat.ts` statically
- imports back for `createServices`). mcp's `dashboard-management.ts` and
- `analytics/property-values.ts` reach them via `./shared`'s
- `loadCompatPrisma`/`loadCompatChHelpers` (no cycle — mcp's tool tree is
- already behind `mcp.service.ts`'s own lazy loader).
-- `project.service.ts`'s `getLastEventPerProject` also had an actual bug this
- surfaced: it built its own ClickHouse client from `@openpanel/db` instead of
- using the `deps.ch` already sitting unused in its (underscore-prefixed)
- `_deps` parameter. Now it does.
-- `dashboard-management.ts`'s `reportData()` helper takes the resolved
- `DbNull` sentinel as an `unknown` parameter rather than importing `Prisma`
- for its type — the same shape `notification.service.ts`'s `isValidPayload`
- already uses for the identical sentinel-comparison problem.
-
-No query TEXT changed; only which module reaches the query-building helpers
-did.
-
-**`v1-compat.ts` grew, not just from this wave's nine modules.** Fixing the
-above meant every OTHER core module that reached one of these nine bare (no
-`deps`) also needed its import repointed at `v1-compat.ts`:
-`shared/access-lookups.ts` (`getProjectById`), `onboarding.service.ts`
-(`getUserById`), `dashboard.service.ts` (`getProjectById` — this one already
-had `deps` in scope, so it's a straight parameter pass, no new v1-compat
-wrapper), `export.service.ts`'s `resolveInsightsProjectId` (~35 call sites in
-`export.routes.ts`, none carrying `deps`), `session/src/usage.ts` and
-`organization/src/wind-down.ts`/`misc/src/data-health.ts` (`getLastEventPerProject`,
-zero-arg shape preserved). None of these files are in this task's scope
-globs by name; all of them needed a one-line import-target fix to keep
-compiling once their target's signature gained `deps` — the same category of
-necessary wiring M10-003's `auth.rpc.ts`/`chart.rpc.ts` touch-ups were.
-
-**Test-isolation hazard found and fixed, not just avoided.** Two tests
-(`mcp/src/tools/dashboard-management.test.ts`,
-`mcp/src/tools/analytics/page-performance.test.ts`) mock
-`@openpanel/db/src/prisma-client` / `.../clickhouse/client` directly and rely
-on `v1-compat.ts`'s fallback to pick the mock up — but that fallback is a
-process-lifetime memoized singleton (`v1-compat.ts`'s own `fallback` promise),
-so under a bare (non-`--isolate`) `bun test` run an EARLIER file that already
-resolved it (against ITS OWN mock, or the real db) leaves it wrong for every
-later file. Both now call `resetV1CompatServicesForTests()` in `beforeAll`
-(before importing the subject) and `afterAll` (so they don't do the same
-thing to files after them) — this is the reset the memoized-singleton pattern
-already existed for, just not previously needed by anything reaching the
-fallback through a *different* module's mock.
-
-**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at
-their landed `warn` severity):
-
-| Rule | Before (M10-003) | After (M10-004) | Delta |
-|---|---:|---:|---:|
-| `core-uses-ctx-not-db-internals` | 160 | **135** | **−25** |
-| `core-no-self-barrel` | 62 | **59** | **−3** |
-
-Exit `0` either way (`warn`, not `error`):
-`x 194 dependency violations (0 errors, 194 warnings). 1991 modules, 8036
-dependencies cruised.` (was 222.) The residual `core-uses-ctx-not-db-internals`
-hits inside this wave's nine modules are all `.test.ts` files that mock
-`@openpanel/db` directly (`mcp/src/tools/dashboard-management.test.ts`,
-`mcp/src/tools/analytics/{profiles,page-performance}.test.ts`,
-`mcp/mcp.service.test.ts` — pre-existing pattern, unrelated to this wave);
-none of the nine modules' `*.service.ts`/`*.rpc.ts`/`*.routes.ts` files import
-`@openpanel/db` as a value any more (`import type` for a handful of Prisma
-model types is not a value import — it is erased, so it carries no
-import-time cost and is not what this rule or the acceptance criterion
-target). The residual `core-no-self-barrel` hits inside `mcp`/`assistant` are
-entirely the ~40 untouched tool files reaching `@openpanel/core` for
-cross-module functions — real, but out of this wave's scope (fixing them
-means rewriting every tool file's imports to relative paths, not wiring a
-service factory).
-
-**Verification, all run by ralph on 2026-09-06:**
-
-- `pnpm run typecheck` — all 25 workspaces, `Done`.
-- `cd packages/core && bun test --isolate`: **1457 pass, 12 skip, 0 fail**,
- `Ran 1469 tests across 149 files. [100.93s]`.
-- `cd packages/core && bun test` (bare, no `--isolate`): **1457 pass, 12 skip,
- 0 fail**, `Ran 1469 tests across 149 files. [34.00s]`.
-- `pnpm run check:deps` — the table above.
-
-### 2026-09-06 — M10-005, the runtime path (event, profile, group, misc, overview+pages, realtime) onto `createXService(deps)`
-
-Ran by: ralph (M10-005 implement task, docs/TECH_DEBT.md §4 steps 1/2/5 and
-§5a, continuing M10-003/M10-004).
-
-**Shape.** `createEventService`, `createProfileService`, `createGroupService`
-and `createMiscService` take `deps` (no longer `_deps`) and bind functions that
-use it. `OverviewService` and `PagesService` are no longer classes: their
-methods are module-scope functions taking `ServiceDeps` first and otherwise the
-same arguments, bound by `createOverviewService(deps)` /
-`createPagesService(deps)` under their old method names.
-`createRealtimeService(deps)` is new. All three are registered in `services.ts`
-as `services.overview`, `services.pages` and `services.realtime`.
-
-**Pages is REGISTERED, not folded in.** Both `OverviewService` and
-`PagesService` expose a `getTopPages`, and they are different queries with
-different inputs — one over `events` scoped by a search string, one over
-`sessions` scoped by chart filters. Folding them into one service would have
-had to rename one of them, which is a call-site contract this wave does not
-change. `services.pages` is its own entry; `pages.service.ts` keeps its own
-file.
-
-**Every lazy `@openpanel/db` import inside those modules is gone.** So is the
-`loadDbBuffers()` hop in all three of this wave's modules that used it: the
-buffers are `deps.buffers.event` / `.bot` / `.profile` (M8-001), which is the
-exact drift this wave was chartered to remove. `misc/src/data-health.ts` no
-longer imports `@openpanel/db/src/prisma-client` either — it takes `deps` and
-calls `project.service.ts`'s `getLastEventPerProject(deps)` directly.
-
-**Two new files in `shared/`, both because six modules needed the same thing.**
-
-- `shared/ch-query.ts` — `chQuery` / `chQueryWithMeta` over `deps.ch` and
- `deps.logger`. `deps.ch.query` IS `withRetry(client => client.query(...))`,
- the same transport `@openpanel/db`'s `chQuery` uses, and the Int-meta
- coercion is copied verbatim, so result sets are identical (proof below). 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. The gain is the `query info` line now carrying the
- request's id (ADR-018 R1). `overview/src/run-query.ts` is now a three-line
- wrapper over it (`timezone` is mandatory there, optional here).
-- `shared/cacheable-per-deps.ts` — `cacheable` for a function that needs
- `ServiceDeps`. `cacheable` keys on EVERY argument through a recursive
- `stringify`, so passing `deps` would serialize the whole Prisma client into
- the Redis key. `deps` is not cache identity anyway, so the cacheable is built
- once per `deps` in a `WeakMap` and the key stays byte-identical —
- `cachable:getEventMetas:<projectId>`, `cachable:getProfiles:<args>`,
- `cachable:getProfilePropertyKeys:<projectId>`. **The explicit `name` is the
- load-bearing part**: `cacheable(fn, ttl)` derives the prefix from `fn.name`,
- and an inline arrow silently drops it.
- **Stated cost:** `createCtx` builds a fresh deps object per request, so the
- L1 LRU inside `cacheable` is now per scope rather than per process. The
- shared L2 Redis cache — the one that actually saves the query — is
- unchanged, so a repeat call costs one Redis GET where it used to cost none.
- Boot-scoped callers (the v1-compat seam, job handlers) keep a process-lived
- L1.
-
-**What is deliberately still lazy in these modules, and why.**
-`event.service.ts` keeps `loadCache()` (`@openpanel/redis`'s `getCache` — core
-tests that partially mock that package with no `getCache` reach this module
-through the barrel), `loadFilterCompiler()` and `loadSessionService()` (a real
-core-internal cycle, documented in place; a second dynamic edge on that loop
-panics rolldown). None of them reach `@openpanel/db`. `realtime` and `misc`
-keep ONE hop each into `v1-compat.ts`'s `compatChHelpers()` for `TABLE_NAMES`
-/ `clix` / `formatClickhouseDate` — the pure helpers that live beside the
-client, not the client, which is `deps.ch` in both. That is the same seam
-`project.service.ts` uses since M10-004 and it exists because ADR-013 converts
-the analytics read path one query per P7 task: those statements are still raw
-strings and clix builders, not `sql` fragments. `compatChHelpers()` gained
-`formatClickhouseDate` and `toNullIfDefaultMinDate` for this.
-`profile/src/dates.ts` and `group/src/dates.ts` gained their own
-`toNullIfDefaultMinDate` instead — module-local, matching the five existing
-`src/dates.ts` copies, because two modules is not "several".
-
-**Blast radius outside the six modules, all forced by a signature change.**
-`ingest.service.ts` (`IngestTransport` gains `deps`; `checkIngestBot` gains a
-`ServiceDeps` first parameter, because `createBotEvent` needs the bot buffer),
-`ingest/src/incoming-event-handler.ts` and `session/src/session-end.ts` (their
-`load*Deps` builders take `deps` and bind `createEvent` to it),
-`session.jobs.ts`, `apps/api/src/main.ts` (one `bootServiceDeps(deps)` helper,
-extracted from the literal `setV1CompatServices` already built),
-`chart.service.ts`, `export.routes.ts`, `overview.rpc.ts`, `event.rpc.ts`,
-`group.rpc.ts`, `profile.rpc.ts`, `profile.routes.ts`, `realtime.rpc.ts`,
-`realtime.routes.ts`, `misc.routes.ts`, `mcp`'s `page-performance.ts`. Three
-callers that genuinely have no scope of their own reach the bare v1-compat
-spellings, exactly as `loadWindDownDeps` already did for
-`getLastEventPerProject`: `cohort.service.ts`'s `listCohortMemberProfiles`,
-`session.service.ts`'s `getSessionList`, and
-`organization/src/win-back-highlight.ts`. Converting those three modules is
-their own task.
-
-`v1-compat.ts` gained 88 bare wrappers plus `overviewService` / `pagesService`
-as plain objects of wrappers (`packages/trpc`'s overview router calls
-`overviewService.getMetrics.bind(overviewService)`; `bind` on a plain function
-is a no-op, so the call site reads identically). `index.ts` now exports those
-spellings instead of the raw deps-taking functions, same as M10-003/M10-004
-did for their waves.
-
-**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at
-their landed `warn` severity):
-
-| Rule | Before (M10-004) | After (M10-005) | Delta |
-|---|---:|---:|---:|
-| `core-uses-ctx-not-db-internals` | 135 | **123** | **−12** |
-| `core-no-self-barrel` | 59 | **56** | **−3** |
-
-Exit `0` either way (`warn`, not `error`):
-`x 179 dependency violations (0 errors, 179 warnings). 1993 modules, 8050
-dependencies cruised.` (was 194.) Thirteen edges removed, one added:
-
-```
-REMOVED modules/event/event.service.ts -> db/src/clickhouse/client.ts
-REMOVED modules/event/event.service.ts -> db/src/prisma-client.ts
-REMOVED modules/group/group.service.ts -> db/src/clickhouse/client.ts
-REMOVED modules/misc/misc.service.ts -> db/src/clickhouse/client.ts
-REMOVED modules/misc/src/data-health.ts -> db/src/prisma-client.ts
-REMOVED modules/overview/src/run-query.ts -> db/src/clickhouse/client.ts
-REMOVED modules/overview/src/run-query.ts -> db/src/clickhouse/sql.ts
-REMOVED modules/profile/profile.service.ts -> db/src/clickhouse/client.ts
-REMOVED modules/realtime/realtime.service.ts -> db/src/clickhouse/client.ts
-REMOVED modules/realtime/realtime.service.ts -> db/src/clickhouse/query-builder.ts
-REMOVED modules/mcp/.../page-performance.test.ts -> db/src/clickhouse/client.ts
-REMOVED modules/mcp/.../profiles.test.ts -> db/src/clickhouse/client.ts
-REMOVED modules/realtime/realtime.service.test.ts -> db/src/clickhouse/client.ts
-ADDED shared/ch-query.ts -> db/src/clickhouse/sql.ts
-```
-
-The one added edge is ADR-013's `sql` tag, which ADR-007 keeps in
-`packages/db` by name: a compile-time template tag, no client, no request
-scope — the same residual `chart.service.ts`'s header already records. The
-`*.sql.ts` files in these modules keep theirs for the same reason.
-
-**ClickHouse — old vs new transport, same data, same day.** No SQL TEXT
-changed in this wave; what moved is which client executes it. Run by ralph on
-2026-09-06 against the local single node (`http://localhost:8123/openpanel`,
-the prod copy, read-only), calling `@openpanel/db`'s `chQuery` and core's new
-`chQuery(deps, …)` back to back on each statement and comparing the serialized
-result sets:
-
-```
-getStats/projects rows old=1864 new=1864 identical=true old=1332.6ms new=1309.1ms
-getStats/last24h rows old=1 new=1 identical=true old=6.9ms new=5.6ms
-runPingCron rows old=1 new=1 identical=true old=3.3ms new=3.1ms
-event.topOrigins rows old=2 new=2 identical=true old=59.7ms new=41.9ms
-profile.propertyKeys rows old=6 new=6 identical=true old=10.1ms new=6.3ms
-group.types rows old=0 new=0 identical=true old=3.8ms new=3.6ms
-```
-
-`single-node` numbers, valid for the self-host topology (docs/ENVIRONMENT.md).
-No `Distributed`-table construct was added, removed or reordered — no `IN`
-became a `GLOBAL IN` or vice versa — so the cluster topology is unaffected by
-this wave.
-
-**Verification, all run by ralph on 2026-09-06:**
-
-- `pnpm run typecheck` — all 25 workspaces, `Done`.
-- `cd packages/core && bun test` (bare): **1457 pass, 12 skip, 0 fail**,
- `Ran 1469 tests across 149 files. [31.14s]`.
-- `cd packages/core && bun test --isolate`: **1457 pass, 12 skip, 0 fail**,
- `Ran 1469 tests across 149 files. [102.80s]`.
-- `pnpm run check:deps` — the table above.
-- `verification/harness start` → `cd apps/api && pnpm run e2e:sessions`:
- **29/29 checks passed** (profile, group and event flushes are all on that
- path).
-- `verification/golden/compare.sh`: **`passed: 131/137`, 0 diffs in the 131
- validated**; the other 6 are the calendar-stale clock-anchored cases the
- harness itself skips (`captured on 2026-09-05, replayed on 2026-09-06` —
- `export-events-no-dates`, `insights-overview-range-30d`,
- `insights-retention-cohort`, and the three
- `insights-pages-performance-*`). Re-capturing is an operator/verify task,
- not an implement one. **137/137 was not reachable on 2026-09-06** — see the
- task report.
-- `verification/harness stop`, then `verification/full.sh`.
-
-**Left for later, named not fixed.**
-
-- `getEventMetasCached`, `getProfilesCached` and `getProfilePropertyKeysCached`
- keep V1's Redis key because `cacheablePerDeps` takes an explicit `name`.
- **M10-004's `getClientByIdCached` (client.service.ts) and
- `getProjectByIdCached` (project.service.ts) do NOT**: both were converted to
- `cacheable((id) => …, ttl)` with an inline arrow, whose `fn.name` is `''`, so
- their prefix is `cachable:` for both. That is a cache-key change (a cold
- window) AND a potential cross-function collision — `cachable::<id>` is the
- same key for a client id and a project id. Out of this task's scope; needs
- its own fix, which is one `cacheable(NAME, …)` argument each.
-- `session/src/session-end.ts` still lazy-loads `chQuery` from
- `@openpanel/db/src/clickhouse/client`, and `ingest/src/incoming-event-handler.ts`
- still reaches `sessionBuffer` through `loadDbBuffers()`. Both are the
- `session`/`ingest` modules' own conversion, not this wave's.
-
-### 2026-09-06 — M10-009, both rules flipped to `error` at 0 violations
-
-Ran by: ralph (M10-009). This closes §4 steps 3, 4 and 5 of the controller's
-`docs/TECH_DEBT.md`.
-
-#### The rules now fire
-
-| Rule | Severity | Violations |
-|---|---|---:|
-| `core-uses-ctx-not-db-internals` | `error` | **0** |
-| `core-no-self-barrel` | `error` | **0** |
-
-```
-$ pnpm run check:deps
-✔ no dependency violations found (1998 modules, 8070 dependencies cruised)
-```
-
-Four exemptions carry the rule, each named in `.dependency-cruiser.cjs` with
-its reason — not a widened `dependencyTypesNot`, which would swallow real
-value imports (see the M10-001 entry above for the merge that proved it):
-
-- **from `packages/core/src/context.ts`** — `typeof import('@openpanel/db/…')`
- type queries, tagged `['undetermined','type-import']` rather than
- `'type-only'`.
-- **from `packages/core/src/v1-compat.ts`** — THE declared composition seam
- (§4 step 4's own wording). Deleted whole with `packages/trpc` at P10.
-- **from `packages/core/src/code-migrations/**`** — one-shot CLI scripts run by
- `migrate.ts` outside the app; no request, no `Ctx` to lose.
-- **from `*.test.ts`** — a test has no request, and the `grep` measurement
- below is itself defined as `| grep -v .test.ts`.
-- **to** `clickhouse/sql.ts`, `clickhouse/query-builder.ts` and
- `sql-builder.ts` — the three `packages/db` modules that build query TEXT and
- hold no client (`clix(client, tz)` takes the client as an argument).
- `prisma-client.ts`, `clickhouse/client.ts`, `logger.ts` and the barrel are
- NOT exempt: those are where a second client comes from.
-
-#### Re-measured — `@openpanel/db` reached from `packages/core/src`
-
-Non-test files, 2026-09-06:
-
-| Measurement | Count | Where the remainder is |
-|---|---:|---|
-| `grep -rn "import('@openpanel/db" packages/core/src --include=*.ts \| grep -v .test.ts \| wc -l` | **22** | 7 prose comments, 9 `typeof import()` type queries (2 in `context.ts`, 7 in `v1-compat.ts`), **6 runtime imports, all in `v1-compat.ts`** |
-| …of those, outside `v1-compat.ts` / `context.ts` | **0** | — |
-| `grep -rn "from '@openpanel/db" packages/core/src --include=*.ts \| grep -v .test.ts \| wc -l` | **77** | 20 `import type`, 34 in `code-migrations/**`, 23 value imports of the query-text builders |
-| …value imports of a **client-bearing** module (`prisma-client`, `clickhouse/client`, the barrel) outside `code-migrations/**` | **0** | — |
-
-The controller's 2026-09-05 baseline was 63 dynamic + 80 static value imports;
-both drift numbers are now 0 outside the two seams the rule names. The 23 that
-remain are `sql`/`clix`/`createSqlBuilder` — pure text, no client, so a
-requestId cannot be lost through them (ADR-013 fixes the `sql` tag at that
-path by name).
-
-What made the last of them go: the buffers took the boot scope's client as
-`BufferDeps.ch` (`apps/api/src/main.ts` hands in the same `ch` every service
-gets as `deps.ch`), `buffers/clickhouse.ts`'s `loadClickHouse()` seam was
-deleted, and `shared/ch-tables.ts` / `shared/ch-dates.ts` hold core's own copy
-of the table map and the date helpers — policed against `@openpanel/db`'s
-originals by `ch-tables.parity.test.ts` and `ch-dates.parity.test.ts`, so the
-copies cannot drift silently.
-
-The violations that were still standing after M10-006 (118 + 56 = 174 edges)
-were closed here, in two groups:
-
-- `core-uses-ctx-not-db-internals` — 41 files (production plus the tests that
- mocked what they imported). The buffers (8) via
- `BufferDeps.ch` + `shared/ch-tables.ts` / `shared/ch-dates.ts`; the
- still-unconverted service functions in `cohort`, `gsc`, `import`, `insight`,
- `integration`, `notification`, `onboarding`, `organization`, `project`,
- `session` and `widget` onto `deps.db` / `deps.ch`; `shared/slug-id.ts` and
- `shared/access-lookups.ts` onto the v1-compat seam (their `cacheable`
- signatures cannot take a leading `deps`).
-- `core-no-self-barrel` — 60 files stopped importing `@openpanel/core` from
- inside `packages/core`: 26 under `modules/mcp/**`, 13 under
- `modules/assistant/**`, 7 under `modules/import/**`, and one or two each in
- `cohort`, `gsc`, `insight`, `notification`, `onboarding`, `organization`,
- `overview` and `session`. Each now imports the sibling module by relative
- path, or `../../v1-compat` where the caller has no `Ctx` (mcp's and the chat
- agent's tool handlers have a third-party-fixed signature).
-
-No genuine cycle needed a per-file exception: the two lazy edges that remain
-(`base-buffer.ts` → `v1-compat`, `shared/access-lookups.ts` → `v1-compat`)
-both point AT the declared seam, and each names the cycle in a comment above
-the loader.
-
-#### `services.ts` registers every `*.service.ts`
-
-```
-$ ls packages/core/src/modules/*/*.service.ts | wc -l
-36
-$ grep -rh "^export function create[A-Za-z]*Service" packages/core/src/modules/*/*.service.ts | wc -l
-36
-$ grep -cE "^ [a-z]+: create[A-Za-z]*Service\(" packages/core/src/services.ts
-36
-$ grep -rn "export class .*Service" packages/core/src --include=*.ts | wc -l
-0
-$ grep -rn "_deps" packages/core/src --include=*.ts | grep -v ".test.ts" | wc -l
-1
-```
-
-The four chart sub-modules (`conversion`, `funnel`, `retention`, `sankey`) got
-their own keys in this task — `chart` still composes them for the facade its
-own callers use, and both bind the same stateless closures. Three factories
-that genuinely need nothing (`createAuthService`, `createAssistantService`,
-`createMcpService`) now say so on the signature instead of ignoring a `_deps`
-argument; their reasons are on each factory.
-
-The one `_deps` left is `http/client-auth.ts`'s `authenticateClient(_deps:
-AppDeps, …)`: its single lookup is `getClientByIdCached`, a `cacheable` whose
-key is derived from the call's arguments, so it cannot take a leading `deps`
-(same constraint as `shared/access-lookups.ts`). Named, not fixed.
-
-#### §4 step 3 — `bun test` wall time, before and after the wave
-
-`cd packages/core && time bun test`, same box, 2 runs each. Baseline is the
-parent of M10-001 (`49a6388e`) measured in a `git worktree`, never a checkout
-of the working tree.
-
-| Tree | Run 1 | Run 2 | Tests |
-|---|---:|---:|---|
-| `49a6388e` (parent of M10-001) | **11.739s** | **14.521s** | 1447 pass, 12 skip, 0 fail — 1459 across 147 files |
-| HEAD (M10-009) | **14.330s** | **13.202s** | 1466 pass, 12 skip, 0 fail — 1478 across 151 files |
-
-No target was set and none is claimed: 13.1s mean before, 13.8s mean after,
-with a 2.8s spread inside the baseline pair alone — the difference is inside
-the noise of this box, while the suite grew by 19 tests and 4 files. The lazy
-`import('@openpanel/db/…')` pattern was justified by test cost; removing it
-cost nothing measurable.
-
-#### §4 step 5 — the requestId proof, on all three paths
-
-`packages/core/test/request-id-end-to-end.test.ts` (M10-009 merged
-`request-id-chart-query.test.ts` and `request-id-ingest.test.ts` into it, so
-the three paths cannot drift into three files that disagree):
-
-```
-✓ one requestId spans the route log, the enqueue, the job and its follow-up enqueue
-✓ a minted requestId travels the same four hops, and does not leak into the next request
-✓ a chart query made through a request-scoped ctx logs the request's own requestId
-✓ two concurrent requests do not share a requestId on their ClickHouse calls
-✓ the envelope's requestId reaches the handler's logger, its buffer write and the session_end it enqueues
-✓ a second message is scoped to its own id, and an envelope without one still gets scoped
-```
-
-HTTP → job (P2-010's original), chart query (M10-003) and Kafka/ingest handler
-(M10-006), in one file.
-
-#### A test-isolation bug this task had to fix to go green
-
-`cd packages/core && bun test` (bare, one shared module registry) failed 6
-chart-integration assertions with `deps.db.project.findUniqueOrThrow is not a
-function`, intermittently — only when the 5-minute Redis cache behind
-`getOrganizationByProjectIdCached` was cold. Cause: `v1-compat.ts` MEMOIZES
-its fallback `ServiceDeps`, so a file that resolves it while a
-`mock.module('@openpanel/db/src/prisma-client', …)` is installed pins the
-mocked client for every later FILE in the process — restoring the module
-registry in `afterAll` does not undo it. Reproduced deterministically with
-`bun test src/modules/mcp/mcp.service.test.ts src/modules/chart/chart.service.test.ts`
-(6 fail before, 0 after). Fixed at the leak: the four files that mock
-`prisma-client` now also call `resetV1CompatServicesForTests()` in `afterAll`
-(the idiom `mcp/src/tools/dashboard-management.test.ts` already used), and
-`import/import.service.test.ts` dropped its `@openpanel/db/src/clickhouse/client`
-module mock entirely — the subject takes `deps.ch` now, so the mock only
-existed to leak.
-
-**Verification, all run by ralph on 2026-09-06:**
-
-- `pnpm run check:deps` — 0 violations, both rules at `error`.
-- `pnpm run typecheck` — all 25 workspaces, `Done`.
-- `cd packages/core && bun test` (bare): **1466 pass, 12 skip, 0 fail**,
- `Ran 1478 tests across 151 files.`, twice.
-- `verification/harness start` → `cd apps/api && pnpm run e2e:sessions`:
- **29/29 checks passed**.
-- `verification/golden/compare.sh`: **`passed: 131/137`, 0 diffs in the 131
- validated**; the other 6 are the calendar-stale clock-anchored cases the
- harness skips itself (`captured on 2026-09-05, replayed on 2026-09-06`) —
- the same six M10-003 and M10-005 recorded. **137/137 is not reachable on a
- day that is not the capture day**; re-capturing is a verify task, not an
- implement one.
-- `verification/harness stop`, then `verification/full.sh` — green, with the
- documented pre-P11 `contracts/sdk/dist-gate.sh` exception.
-
-### 2026-09-06 — M11-003, `packages/queue`'s Kafka transport and notification dispatch move into core; `queues.ts` / `buffers.ts` do NOT (out of scope)
-
-Ran by: ralph (M11-003 implement task).
-
-**Survey, before the move** — every import of `@openpanel/queue` outside
-`packages/queue` (`grep -rnE "from '@openpanel/queue" --include=*.ts`):
-
-| File | Symbols |
-|---|---|
-| `apps/api/src/main.ts` | `assertKafkaConfigured`, `createKafkaEventsConsumer`, `KAFKA_EVENTS_TOPIC`, `KAFKA_HANDLER_MAX_ATTEMPTS`, `KAFKA_HANDLER_RETRY_INITIAL_MS`, `KAFKA_HANDLER_RETRY_MAX_MS`, `KAFKA_PARTITIONS_CONCURRENT`, `kafkaLogger`, `produceDeadLetterEvent`, `produceIncomingEvent` (10, from the barrel) + `checkNotificationRulesForEvent` (deep, `@openpanel/queue/src/notification-dispatch`) |
-| `apps/api/e2e/lag-monitor.ts` | `createKafkaAdmin`, `disconnectKafka`, `KAFKA_BROKERS`, `KAFKA_CONSUMER_GROUP`, `KAFKA_EVENTS_TOPIC`, `sampleConsumerGroupLag` |
-| `apps/api/e2e/legacy-job-proof.ts` | `produceIncomingEvent` |
-| `packages/core/src/modules/session/session.jobs.ts` | `checkNotificationRulesForSessionEnd` (lazy `import('@openpanel/queue/src/notification-dispatch')`) |
-| `packages/core/src/buffers/lazy-db-buffers.ts` | the buffer singletons (lazy `import('@openpanel/queue/src/buffers')`), reached only by `modules/widget/widget.rpc.ts` |
-| `packages/db/scripts/check-sessions.ts` | `sessionsQueue` |
-| `packages/db/scripts/drain-old-session-jobs.ts` | `sessionsQueue` |
-| `packages/db/scripts/migrate-sessions.ts` | `sessionsQueue`, `EventsQueuePayloadCreateSessionEnd` |
-| `packages/trpc/src/routers/cohort.ts` | `cohortComputeQueue` |
-| `packages/trpc/src/routers/gsc.ts` | `gscQueue` |
-| `packages/trpc/src/routers/import.ts` | `importQueue` |
-| `packages/trpc/src/routers/overview.ts` | `eventBuffer` (deep, `@openpanel/queue/src/buffers`) |
-| `packages/trpc/src/routers/widget.ts` | `eventBuffer` (deep, `@openpanel/queue/src/buffers`) |
-
-**What moved.** `src/kafka.ts` → `packages/core/src/modules/ingest/src/kafka.ts`
-and `src/notification-dispatch.ts` →
-`packages/core/src/modules/notification/src/notification-dispatch.ts`. Both are
-the same file: `diff` against `HEAD` shows only repointed imports, plus two
-edits with reasons —
-
-- `DeadLetterMessage` was declared twice (once in `kafka.ts`, once in
- `consumer.ts`, structurally identical by design); now that they are siblings
- `kafka.ts` imports the consumer's.
-- `produceIncomingEvent`'s parameter changed from
- `EventsQueuePayloadIncomingEvent['payload']` to core's own
- `IncomingEventPayload`. The wire format is unchanged: a temporary
- `[A] extends [B] ? [B] extends [A]` assertion compiled clean in both
- directions against `@openpanel/queue`'s type.
-- `triggerNotification` enqueues through core's registry
- (`queues.notification.sendNotification`) rather than a second
- `new Queue('notification')` — same Redis key, same job name, same
- `{payload, meta}` envelope (`golden/queue-keys/check.sh` still matches the
- V1 goldens), and it became `async` because the registry producer is.
-
-Every Kafka constant is byte-identical after the move — topic
-(`process.env.KAFKA_EVENTS_TOPIC || 'events'`), DLQ
-(`|| \`${KAFKA_EVENTS_TOPIC}-dlq\``), group
-(`|| 'openpanel-events'`), and the 15 `Number.parseInt` bounds — verified by
-`diff -u` of the two files' bodies.
-
-**The `AppDeps.produceIncomingEvent` injection is retired.** It existed only
-because `@openpanel/queue` imports `@openpanel/core` for its logger, so core
-could not import the producer back (`context.ts`'s own comment). With
-`kafka.ts` in core, `ingest.routes.ts` imports the sibling directly. The
-producer stays an *argument* to `ingest.service.ts` — that seam is now about
-letting a test assert what was produced without a broker, not about a package
-cycle, and `ingest.service.test.ts` / `legacy-event.test.ts` still use it.
-
-**`buffers/lazy-db-buffers.ts` is deleted**; its one core caller
-(`widget.rpc.ts`'s `loadEventBuffer`) reads `ctx.buffers.event`.
-
-**The three orphan `packages/db/scripts` are deleted** — `check-sessions.ts`,
-`drain-old-session-jobs.ts`, `migrate-sessions.ts`, all V1 session-migration
-tooling. `grep -rn 'check-sessions\|drain-old-session-jobs\|migrate-sessions'`
-over `*.json`/`*.ts`/`*.md`/`*.sh` returns nothing outside the files
-themselves; `packages/db/package.json`'s only `scripts/*` entry is
-`duplicate-events` → `find-duplicate-events.ts`, untouched.
-
-**NOT done, and why — `packages/queue/src/queues.ts` and `src/buffers.ts` stay.**
-The task asked for both to be deleted. They cannot be, inside this task's
-declared scope (`packages/core/**`, `packages/queue/**`,
-`packages/db/scripts/**`, `apps/api/**`, `docs/**`): five
-`packages/trpc/src/routers/*` files import them (the last five rows of the
-survey above), and `packages/trpc/**` is not in scope. Deleting the two files
-without touching those routers fails `pnpm run typecheck`; touching them is
-the out-of-scope edit. **This needs either a scope extension to
-`packages/trpc/src/routers/{cohort,gsc,import,overview,widget}.ts` or a
-follow-up task**, and it is not a mechanical repoint — the three queue call
-sites become `ctx.services.cohort.enqueueCompute` / `ctx.queues.gsc...` /
-`ctx.services.import.enqueue`, which changes `import.ts`'s `jobId` handling
-and `cohort.ts`'s procedure signatures. `packages/queue/index.ts` no longer
-re-exports `./src/kafka`; what remains behind the barrel is exactly what trpc
-still consumes.
-
-Also still declared, unused: `@openpanel/queue` in `apps/api/package.json`,
-`packages/core/package.json` and `packages/db/package.json` — no file in any
-of the three imports it any more. Removing the manifest entries belongs with
-M11-004's deletion of the package.
-
-**Verification, all run by ralph on 2026-09-06:**
-
-- `pnpm run typecheck` — all 25 workspaces, `Done`.
-- `pnpm test` — 13 files, **205 passed**.
-- `cd packages/core && bun test` (bare) — **1466 pass, 12 skip, 0 fail**,
- `Ran 1478 tests across 151 files. [12.59s]`, `real 0m12.652s`, and it
- EXITS: moving `kafka.ts` into core constructs no Kafka client at import
- time (`getKafka()` is lazy; only `assertKafkaConfigured` reads
- `KAFKA_BROKERS`, and nothing calls it at module scope).
-- `pnpm run check:deps` — `no dependency violations found (2321 modules,
- 10072 dependencies cruised)`, both rules still at `error`.
-- `bash apps/api/e2e/boot-proof.sh` — all checks passed, all three ROLEs.
-- `verification/golden/queue-keys/check.sh` — `OK - 7x2 queue keys and 20
- scheduler ids derived from the V2 registry match the V1 goldens`.
-- `verification/harness start` → `cd apps/api && pnpm run e2e:sessions`:
- **29/29 checks passed** (Kafka produce → consume is the path under test) →
- `pnpm run e2e:legacy-jobs`: **all checks passed** → `harness stop`.
-- `verification/full.sh` — `FULL: green`.
-
-One incidental find, recorded not fixed: `usage.ts`'s static
-`import { getOrganizationBillingEventsCount } from '../../../v1-compat'` had
-to become part of the existing lazy `loadProjectService()` call. `jobs.registry.ts`
-reaches this file (`session.jobs.ts` → `session-end` → `usage`), and that one
-static edge pulls `services.ts` and all 36 services into the registry's import
-graph, which builds a ClickHouse client at import time — `queue-keys/check.sh`
-fails outright without the change (confirmed by reverting the file alone and
-re-running it).
-
-### 2026-09-06 — M11-008, `dist-gate.sh`'s internal-vs-published fix confirmed green — no source change needed
-
-Ran by: ralph (M11-008 implement task).
-
-The operator's fix to `contracts/sdk/dist-gate.sh` (deriving its
-workspace-internal package list from `packages/*/package.json` names instead
-of grepping any `@openpanel/`) needed no corresponding code change here: the
-three preconditions it depends on were already satisfied by M11-007's
-codemod. Re-verified from scratch rather than trusted:
-
-- `grep -rn @openpanel/common packages/sdks` — empty. `express/get-client-ip.ts`
- carries its own inlined `getClientIpFromHeaders` (header comment explains
- why), `express/package.json` has no `@openpanel/common` dependency, and
- `express/tsup.config.ts` has no `noExternal` entry.
-- `packages/sdks/sdk/src/index.ts` still hand-duplicates the wire constants
- rather than importing `@openpanel/core/modules/ingest/ingest.constants` —
- its header comment's reasoning (core's package.json exports map has no
- `./*` wildcard; `rollup-plugin-dts` can't inline a type through it) still
- holds, so this task kept that approach rather than retargeting.
-- `dist-gate.sh` standalone: `DIST GATE: all 5 checked package(s) clean`
- (express/nextjs/react-native/sdk/web PASS; astro/`_info` SKIP no build
- script; nuxt SKIPs no `dist/index.d.ts`).
-
-**Verification, all re-run by ralph on 2026-09-06:**
-
-- `pnpm run typecheck` — 23 workspace projects, all `Done`.
-- `contracts/sdk/dist-gate.sh` — `DIST GATE: all 5 checked package(s) clean`.
-- `contracts/sdk/run.sh` — `SDK WIRE CONTRACTS: all green` (67 assertions:
- node 37, web 10, legacy-event 20, plus the dist gate), 37.0s.
-- `verification/full.sh` — `FULL: green`, exit `0`, no `BLOCKED-KNOWN` line:
- the fingerprint this task exists to retire didn't fire because
- `contracts/sdk/run.sh` now fully succeeds. This supersedes the
- `dist-gate.sh` pre-P11 exception recorded in the M10-003 and M10-009
- entries above (both `full.sh` runs there carried it; this one doesn't).
-
-Working tree change is this entry alone — every acceptance criterion for
-M11-008 was already met by the source tree M11-007 left behind.
-
-**Debt noticed, not fixed (outside this task's scope — the gate only
-inspects built `.d.ts`, not manifests):** `packages/sdks/sdk/package.json`
-still declares `@openpanel/validation` as a `devDependency`; nothing in the
-package imports it — the wire-constant types were inlined into `src/index.ts`
-in a pre-rewrite commit (`fix(sdk): inline validation types in dts...`) and
-the manifest entry never followed. Safe to delete whenever that
-`package.json` is next touched.
-
-### 2026-09-07 — M12-009, ADR-013 decision 21 closed: the builders are deleted and `sqlstring` is out of the repo
-
-**RESOLVED: the "clix coexistence" exception.** ADR-013's P8 deletion had been
-deferred since M7 and was last restated by `M9-CLEANUP-001` in
-`packages/db/index.ts`:
-
-> `clix` (query-builder.ts) and `createSqlBuilder` (sql-builder.ts) are dead
-> per ADR-013, but 7 live call sites across @openpanel/core still import them
-> directly and have not been converted onto the `sql` tag yet — see
-> M9-CLEANUP-001's report. Deleting these two ahead of that conversion is
-> BLOCKED, not done.
-
-M12-002..008 emptied that import graph; M12-009 deleted the three files
-(`git rm`), took the barrel comment with them, and removed `sqlstring` /
-`@types/sqlstring` from every workspace that declared it (`packages/db`,
-`packages/core`, `apps/start` — `apps/api` had already lost its copy). Both
-sections of this register that cite `query-builder.ts` / `sql-builder.ts` as
-exempt targets of `core-uses-ctx-not-db-internals` are now describing paths
-that do not exist; `packages/db/src/clickhouse/sql.ts` is the only one left,
-and it is also the one the rule keeps exempt.
-
-**Final `bash tooling/gates/p12-grep-gates.sh --report`, ralph 2026-09-07:**
-
-```
- sqlstring clix sql-builder file
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
- 0 0 0 TOTAL
-```
-
-`--assert` exits `0`: `OK: sqlstring = 0, clix = 0, sql-builder = 0; all three
-definer files are gone.`
-
-**The leftovers M12-008 disclosed, converted here.** The gate read
-`sqlstring 16 / clix 1 / sql-builder 1` on clean `30d236fa` (measured by
-stashing this task's tree and re-running `--report`), spread over eight files:
-`apps/start/package.json` 1, `packages/core/package.json` 2, `group-buffer.ts`
-3, `profile-backfill-buffer.ts` 3, `profile-buffer.ts` 2,
-`packages/db/package.json` 2, `packages/db/src/clickhouse/client.ts` 3, and
-`packages/db/index.ts` 1 clix + 1 sql-builder. The gate does not scan
-`packages/db/scripts/`, but the two scripts there imported `clix` and
-`sqlstring` and had to convert too — removing the dependency removes the module
-they import.
-
-Every changed statement was executed against local ClickHouse in **both** forms
-through the same `@clickhouse/client` — V1 as `query`, V2 as `query` +
-`query_params` — on the same data. **8 statements, all IDENTICAL.** Full SQL,
-params, row counts and timings: `packages/core/src/buffers/buffers.sql.proof.md`
-and `packages/db/scripts/scripts.sql.proof.md`.
-
-| Site | Statement | Rows | old → new |
-|---|---|---:|---|
-| `core/src/buffers/group-buffer.ts:84` | `SELECT … FROM groups FINAL` | 1 | 33ms → 8ms |
-| `core/src/buffers/profile-buffer.ts:222` | batch fetch, no date filter | 2 | 20ms → 20ms |
-| `core/src/buffers/profile-buffer.ts:222` | batch fetch, 2-day filter | 0 | 9ms → 8ms |
-| `core/src/buffers/profile-backfill-buffer.ts:96` | lightweight `UPDATE … CASE` | 3 read back | 7ms → 6ms |
-| `db/scripts/ch-update-sessions-with-revenue.ts:45` | `SELECT id FROM sessions` | 2 | 5ms → 5ms |
-| `db/scripts/ch-update-sessions-with-revenue.ts:79` | `ALTER TABLE … UPDATE multiIf` | 4 read back | 11ms → 14ms |
-| `db/scripts/ch-copy-from-remote.ts:95` | `SELECT * FROM remote(…)` | 2 | 7ms → 9ms |
-| `db/scripts/ch-copy-from-remote.ts:97` | `INSERT … SELECT * FROM remote(…)` | 3 → 5 | 9ms → 9ms |
-
-Reads ran against the local prod-copy `openpanel`; the two mutations and the
-`INSERT` ran against a throwaway `m12009_scratch` database, dropped afterwards
-— never against `openpanel` or `openpanel_test`. `remote()` accepts bound
-params (`{p:String}` for the host and credentials, `{p:Identifier}` for the
-database and table), verified before the conversion was written, which is what
-takes the remote password out of the query text the script logs. No `IN` was
-converted to `GLOBAL IN` or back: every `IN` touched takes a literal set, not
-a subquery, so `docs/ENVIRONMENT.md`'s distributed-`IN` trap does not apply.
-
-Timings are single-node and directional only (ClickHouse 26.1.3.52, 4 vCPU);
-production is 2 shards × 2 replicas.
-
-`packages/db/src/clickhouse/client.ts`'s `toDate(str, interval?)` was deleted
-rather than converted: it existed only to `sqlstring.escape` a date-shaped
-string into query text, it had zero importers in the repo, and keeping it
-would have kept a manual-escaping helper alive that ADR-013 forbids.
-
-**`packages/db/src/clickhouse/sql.ts` joined the barrel**, as its own header
-promised. `packages/core` still reaches it by its deep path in all 55 files:
-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 acquires a second, request-scope-less client —
-which is exactly what `.dependency-cruiser.cjs`'s
-`core-uses-ctx-not-db-internals` forbids (its comment: "prisma-client.ts,
-clickhouse/client.ts, logger.ts **and the barrel** are NOT exempt"). Nothing
-outside `packages/core` imported the deep path.
-
-**Debt noticed, not fixed (outside this task's scope — the file is at the repo
-root, not under any of this task's scope globs):** `.dependency-cruiser.cjs`'s
-`core-uses-ctx-not-db-internals` still exempts
-`^packages/db/src/clickhouse/query-builder\.ts$` and
-`^packages/db/src/sql-builder\.ts$` in its `to.pathNot`, and its comment still
-explains both. They are dead regex branches now — harmless (nothing can match
-them), but the next task that touches that file should delete both lines and
-the two sentences describing them.
-
-#### `packages/core/src/modules/chart/src/compiled.ts` — kept, with its caller census
-
-M12-003 kept `compiled.ts` and its reviewer checked the reason: neither filter
-compiler (`filter-where.ts`, `table-filter-where.ts`) nor the field resolver
-(`field-resolution.ts`'s `getSelectPropertyKey`) returns anything that crosses
-`compiledText` any more — they all return `SqlFragment`s — so what is left are
-the chart builders splicing a name they generated themselves.
-`compiledTextWithProfileRefs` was deleted outright at that time. That still
-holds at M12-009: `compiled.ts` has **29 `compiledText(` splice sites on 27
-lines across 8 files**, so it
-is NOT deleted, and this is the census the M12-009 criterion asks for.
-
-`compiledText` stays a named export in one file rather than a `sql.raw()`
-scattered across the module precisely so this census is a grep:
-
-```
-$ grep -rn "compiledText(" packages/core/src --include=*.ts | grep -v '/compiled.ts:'
-```
-
-| file:line | what it splices | where the text comes from |
-|---|---|---|
-| `chart/src/chart.sql.ts:175` | a CTE name in `WITH <name> AS (…)` | keys of the `ctes` record the builder itself assembles — the profile CTE name and `` `cohort-<id>` `` (below) |
-| `chart/src/chart.sql.ts:274` | the `"profile.<field>"` CTE alias | `field`, validated on the same line by `sql.id(field, PROFILE_CTE_FIELDS)` against a closed column set (`id`,
-`properties`, plus `PROFILE_CTE_SCALAR_FIELDS`) |
-| `chart/src/chart.sql.ts:340` | `` `cohort-<id>` `` as a JOIN target | `cohortId`, through `assertCohortId` (below) |
-| `chart/src/chart.sql.ts:434` | `label_<n>` breakdown alias | `\`label_${index + 1}\`` — a loop index |
-| `chart/src/chart.sql.ts:435` | the same `label_<n>` as a GROUP BY key | same |
-| `chart/src/chart.sql.ts:469` | the aggregate keyword (`sum`/`avg`/`max`/`min`) | `MATH_FUNCTION_BY_SEGMENT[event.segment]` — a 4-entry literal `Record` at `chart.sql.ts:58`; an unknown segment yields `undefined`, not the input |
-| `chart/src/chart.sql.ts:580` | `label_<n>` in a window `PARTITION BY` | a loop index |
-| `chart/src/funnel.sql.ts:78` | `, 'strict_increase'` — the `windowFunnel` mode | `STRICT_INCREASE_MODE`, a file constant; the only branch is an env flag |
-| `chart/src/funnel.sql.ts:188` | `b_<index>` breakdown alias | a loop index |
-| `chart/src/funnel.sql.ts:307` | `b_<index>` as a GROUP BY key | a loop index |
-| `chart/src/funnel.sql.ts:366` | `b_<index>` in SELECT and GROUP BY | a loop index |
-| `chart/src/funnel.sql.ts:391` | `trim(ifNull(toString(b_<n>), ''))` | a loop index inside a fixed template; the compared VALUE beside it binds as `sql.string` |
-| `chart/src/conversion.sql.ts:117` | `b_<index>` outer-select alias | a loop index |
-| `chart/conversion.service.ts:137` | `b_<index>` alias | a loop index |
-| `chart/src/retention.sql.ts:170` | `toDate` / `toStartOfWeek` / `toStartOfMonth` | `SQL_START_OF[interval]`, a 5-entry `Record` keyed by the `IRetentionInterval` union |
-| `chart/src/retention.sql.ts:171` | the `dateDiff` / `INTERVAL` unit | `SQL_INTERVAL[interval]`, same shape |
-| `chart/src/retention.sql.ts:172` | `>=` vs `=` | `COUNT_CRITERIA[criteria]`, keyed by the `IRetentionCriteria` union |
-| `chart/src/retention.sql.ts:200` | `interval_<n>_users` alias | `String(index)` over `range(0..diffInterval)` |
-| `chart/src/retention.sql.ts:206` | `interval_<n>_users` / `_user_count` | same |
-| `chart/src/sankey.sql.ts:28` | the `arrayFilter(…) as events_deduped` expression | a file-level constant, no interpolation |
-| `chart/src/sankey.sql.ts:38` | the `if(arrayFirstIndex(…))` truncation | a file-level constant, no interpolation |
-| `chart/src/sankey.sql.ts:48` | the `arrayJoin(arrayMap(…))` transition subselect | a file-level constant, no interpolation |
-| `chart/src/sankey.sql.ts:187` | `arraySlice(events, start_index, …)` | a file-level constant, no interpolation |
-| `chart/src/sankey.sql.ts:201` (×2) | the base CTE name | `transitionsFrom`'s two callers pass the string literals `'session_paths_base'` and `'between_sessions'` |
-| `overview/src/overview.sql.ts:115` | the `WITH FILL … STEP toInterval<Unit>(1)` step | `toIntervalStep(interval)`, a `switch` over the `IInterval` union that throws on anything else |
-| `chart/src/field-resolution.ts:203` | `` `cohort-<id>` `` CTE name | `cohortId` — see below |
-| `chart/src/field-resolution.ts:505` | `` `profile.properties.<key>` `` CTE alias | `key` — see below |
-
-**Nothing above is a value, and nothing above is a compiler's output.** Every
-row is an alias, a CTE name, a SQL keyword or a static expression. The two
-compilers' and the resolver's outputs reach the statement as `SqlFragment`s and
-never pass through `compiledText`.
-
-**Two rows are name-shaped text derived from a user-chosen NAME, and are
-flagged rather than buried** — they are the same two M12-003's reviewer read,
-and both are guarded so that `compiledText` receives only a validated
-identifier, never the raw input:
-
-- **`` `cohort-<id>` ``** (`field-resolution.ts:203`, `chart.sql.ts:340`,
- and the `ctes` key at `chart.sql.ts:175`). `cohortId` comes from a saved
- report's breakdown config. `chart.sql.ts:119`'s `assertCohortId` tests it
- against `/^[A-Za-z0-9_-]+$/` and **throws `ChartCohortIdError`** otherwise —
- it never falls back to inlining, which is what ADR-013 R3 requires of an
- identifier path. The name needs the text seam because a dash makes `sql.id`
- reject it and `{x:Identifier}` is not accepted in a `WITH … AS` position.
- `field-resolution.ts:202`'s `getCohortCteName` has no in-repo caller today
- beyond the two barrel re-exports (`chart.service.ts:133`, `index.ts:338`);
- `chart.sql.ts` builds the same name behind `assertCohortId` itself.
-- **`` `profile.properties.<key>` ``** (`field-resolution.ts:505`). `key` is
- the tail of a `profile.properties.<key>` field reference in the chart config.
- `collectProfilePropertyKeys` (`field-resolution.ts:465`, guard at `:484`)
- **rejects any key
- containing a backtick or a backslash** — the only two characters that are
- special inside a backtick-quoted ClickHouse identifier — and such keys are
- simply not narrowed: the full `properties` Map stays selected and their refs
- keep the Map access. The alias has three dot-separated parts, so `sql.id`
- cannot express it. The key's *value* twin on the same line binds normally
- (`properties[${sql.string(k)}]`).
-
-Both are the identifier tier of ADR-013, implemented as a guard local to the
-call site rather than through `sql.id`, because `sql.id`'s grammar (bare or
-once-qualified, no dashes, no backticks) cannot spell either name. **If a
-future task widens `sql.id` to accept a backtick-quoted, multi-part name,
-these two rows and `compiled.ts` with them can go.** That is the standing exit
-condition; recorded here, not done in M12-009 (out of its scope).
-
-## Root scripts (M12-010)
-
-Every `--filter <name>` in the root `package.json` verified against the
-workspace it selects and the script that workspace actually exports.
-`gen:bots` pointed at `api`, which has no such script — the generator has
-always lived in `core`; fixed to match `gen:referrers`, which was already
-correct. `dev` assumed a `testing` script existed on every dev-facing
-workspace (a V1-era convention); only `apps/api` still has one, so
-`pnpm -r --parallel testing` silently ran nothing but the API. Fixed to start
-`apps/api` and `apps/start`'s dashboard explicitly, on non-colliding ports
-(both default to 3000) — verified with a real 10s boot (Kafka consumer joined,
-7 BullMQ workers started, cron upserted, Vite ready) and a clean `SIGTERM`
-shutdown, 2026-09-07.
-
-| Script | Target workspace(s) | Target script | Exists |
-|---|---|---|---|
-| `gen:bots` | `core` | `gen:bots` | yes |
-| `gen:referrers` | `core` | `gen:referrers` | yes |
-| `dev` | `api` (testing), `start` (dev) | `testing`, `dev` | yes |
-| `dev:public` | `public` | `dev` | yes |
-| `db:codegen` | `db` | `codegen` | yes |
-| `codegen` | `db`, `core` | `codegen` (both) | yes |
-| `migrate` | `db` | `migrate` | yes |
-| `migrate:deploy` | `db` | `migrate:deploy` | yes |
-
-`typecheck`, `check`, `check:workspace`, `check:deps` and `fix` run across the
-whole workspace (`pnpm -r` / no filter) and name no specific package, so they
-are not in this table.
-
-## Test split (M12-011)
-
-Measured on this box (4 cores, local Postgres/ClickHouse/Redis) by the agent
-implementing M12-011, on 2026-09-07, at HEAD `bcf07cbc` with a clean tree.
-Every number below is from a run recorded in this section — none is inherited.
-
-### BEFORE
-
-**`pnpm test`** (`vitest run`, root `vitest.workspace.ts` = `['packages/*','apps/*','!apps/start']`):
-**7 files, 178 tests, 178 passed, 0 failed, 0 skipped — 10.19s.**
-
-| Workspace | Files | Tests | Runner |
-|---|---:|---:|---|
-| `@openpanel/db` | 4 | 101 | vitest (own `vitest.config.ts` → `vitest.shared.ts`) |
-| `@openpanel/api` | 1 | 13 | vitest (own `vitest.config.ts` → `vitest.shared.ts`) |
-| `@openpanel/redis` | 1 | 29 | vitest, **root config only** — no per-package config, no `test` script, no `vitest` devDependency |
-| `@openpanel/payments` | 1 | 35 | vitest, **root config only** — same |
-| **total** | **7** | **178** | |
-
-The task survey recorded db (5 files) and api (1) as "the only vitest suites
-left". That is wrong in both directions: db has **4** test files, not 5, and
-`packages/redis` + `packages/payments` are two more vitest suites, 64 tests
-between them, which only ever run because the root workspace globs `packages/*`
-and the root manifest carries the `vitest` devDependency. Neither is inside
-M12-011's scope globs. See *The redis/payments constraint* below.
-
-**`cd packages/core && bun test`** (bare, as the verification list spells it —
-the package's own script is `bun test --isolate`):
-**154 files, 1487 tests, 1475 pass / 12 skip / 0 fail — 45.82s.**
-
-**`apps/start`**: `src/utils/math.test.ts`, **1 file, 2 tests, run by nothing.**
-Measured, not assumed, in both directions:
-
-- `pnpm --filter start test` → prints nothing, **exit 0** (pnpm treats a missing
- script in a filtered run as a no-op, so this reads green while testing zero).
-- `cd apps/start && pnpm run test` → `[ERR_PNPM_NO_SCRIPT] Missing script: test`,
- exit 1.
-- the root workspace file negates `apps/start`, so `pnpm test` never sees it.
-
-### AFTER
-
-Same box, same day, tree as this task leaves it. `pnpm test` is now a chain of
-five `&&`-joined legs (root `package.json`); it exited **0**.
-
-| Suite | Runner | Files | Tests | Result | Wall |
-|---|---|---:|---:|---|---:|
-| `@openpanel/core` | `bun test --isolate` | 154 | 1487 | 1475 pass / 12 skip / 0 fail | 88.12s |
-| `@openpanel/db` | `bun test --isolate` | 4 | 101 | 101 pass / 0 fail | 10.47s |
-| `@openpanel/api` | `bun test --isolate` | 1 | 13 | 13 pass / 0 fail | 4.40s |
-| `apps/start` | `vitest run` (own config) | 1 | 2 | 2 pass | 1.22s |
-| `redis` + `payments` | root `vitest run` | 2 | 64 | 64 pass | 0.44s |
-| **`pnpm test` total** | | **162** | **1667** | **RC 0** | |
-
-Per suite, before → after. Nothing shrank:
-
-| Suite | Files before → after | Tests before → after |
-|---|---|---|
-| `@openpanel/db` | 4 → 4 | 101 → 101 |
-| `@openpanel/api` | 1 → 1 | 13 → 13 |
-| `@openpanel/redis` | 1 → 1 | 29 → 29 |
-| `@openpanel/payments` | 1 → 1 | 35 → 35 |
-| `@openpanel/core` | 154 → 154 | 1487 → 1487 (now **inside** `pnpm test`; before, only reachable by `cd`) |
-| `apps/start` | 0 running → 1 | 0 running → 2 |
-| **`pnpm test`** | **7 → 162** | **178 → 1667** |
-
-The two `+` deltas are the point of the task: `packages/core`'s 1487 tests and
-`apps/start`'s 2 were both invisible to `pnpm test` (and therefore to
-`full.sh`) and now are not. No test was weakened, skipped or deleted — the
-per-suite rows are equal everywhere else.
-
-Standalone, as the verification list spells them:
-
-| Command | Result | Wall |
-|---|---|---:|
-| `pnpm install --frozen-lockfile` | up to date, RC 0 | 0.4s |
-| `cd packages/db && bun test` (bare) | 4 files, 101 pass / 0 fail / 0 skip | 2.74s |
-| `cd apps/api && bun test` (bare) | 1 file, 13 pass / 0 fail | 3.77s |
-| `cd apps/start && pnpm run test` | 1 file, 2 pass | 1.22s |
-| `cd packages/core && bun test` (bare) | 154 files, 1475 pass / 12 skip / 0 fail | 47.34s |
-| `pnpm run typecheck` | 17 passes, 0 fails, RC 0 | |
-| `verification/full.sh` | **FULL: green**, RC 0, zero `FAIL:`, zero `BLOCKED`, goldens `137/137` | |
-
-### What the preload had to do that `globalSetup` did not
-
-`bunfig.toml`'s `[test] preload` has no once-per-run mode. Measured on Bun
-1.4.0 in `packages/db` (4 test files): bare `bun test` → **1** preload;
-`bun test --isolate` → **4** preloads, all in **one pid**, strictly sequential;
-`bun test --parallel=4` → 4 preloads across 3 pids. Under `--isolate` neither
-`globalThis` nor `process.env` survives from one preload to the next, so there
-is no in-process channel to dedupe through — the only workable shape is the one
-the ADR-010 note asked for: idempotent, and serialised by that sequencing.
-`test/bun-preload.ts` is therefore run per file, and each run costs (measured
-once, warm): import 333ms, `bootstrapTestDatabases` 1190ms, fixture load
-1102ms, teardown 1045ms. That is where `packages/db`'s 2.7s bare run becomes
-10.5s under `--isolate`.
-
-Two things the move surfaced, neither of them a weakened test:
-
-- **`pinTestDatabases()` is called twice**, at preload and again inside the
- `afterAll` teardown — exactly as `test/global-setup.ts` called it in both
- `setup` and `teardown`. vitest ran teardown in the parent process, which no
- test could reach; bun runs it in the test file's own realm, *after*
- `sql.round-robin.clickhouse.test.ts` has deliberately repointed
- `CLICKHOUSE_URL` at a dead node. Without the re-pin the teardown's
- `DELETE FROM ...` goes to `127.0.0.1:1` and the hook fails.
-- **`sql.round-robin.clickhouse.test.ts` now restores `CLICKHOUSE_URL`** after
- the client module has read it. Under a bare `bun test` all four files share
- one global, and the dead-node-first URL leaked into
- `sql.clickhouse.test.ts`'s reachability probe: **22 of its tests silently
- skipped** (`79 pass / 22 skip`) before the restore, 101/101 after. This is one
- of the three coupling hazards ADR-010 named when it chose `--isolate`; the
- restore makes both modes agree.
-
-### bun:test types the assertion, vitest did not
-
-Two edits were type-level only; no assertion changed.
-
-- `bun-types` (`1.4.0`, pinned as core pins it) joins `packages/db` and
- `apps/api` devDependencies, and each `tsconfig.json` names it in `types`
- (`bun:test` is declared nowhere else). ADR-017 row 7 authorises this addition.
-- bun's `expect` has an `(actual?: never) => Matchers<undefined>` overload,
- which makes the argument position a **contextual inference site**.
- `sql.clickhouse.test.ts`'s local `value<T>()` helper, called bare, therefore
- resolved `T` to `never` and every `toBe` below it failed to compile; it now
- returns `unknown`. And `expect(config.ROLE).toBe(role)` in `env.test.ts`
- needs `as const` on the literal array, because bun's `toBe(expected: T)` is
- typed where vitest's was `any`.
-
-### The redis/payments constraint — read this before deleting more vitest
-
-The task's removal criterion is conditional: the root vitest artefacts go
-"when nothing there uses them any more". Two suites still do.
-`packages/redis/cachable.test.ts` and
-`packages/payments/src/subscription-state.test.ts` have **no `test` script and
-no `vitest` devDependency of their own** — they ran only because the root
-workspace globbed `packages/*` and the root manifest carried `vitest`. Neither
-package is inside M12-011's scope globs, so converting them was not this task's
-to do. Deleting the root `vitest` devDependency and `vitest.workspace.ts`
-anyway would have dropped 64 passing tests out of `pnpm test`, which the
-before/after table above exists to prevent.
-
-So: `vitest.config.ts`, `vitest.shared.ts`, `test/global-setup.ts`,
-`test/test-setup.ts`, `packages/core/vitest.config.ts`,
-`packages/db/vitest.config.ts` and `apps/api/vitest.config.ts` are **deleted**,
-and `apps/api`'s `vitest ^1.0.0` devDependency with them.
-`vitest.workspace.ts` survives, rewritten from a glob to the explicit list
-`['packages/redis', 'packages/payments']`, and the root `vitest` devDependency
-survives to run it. **Next step, when someone owns those two packages:** port
-both to `bun:test`, delete `vitest.workspace.ts` and the root `vitest`
-devDependency, and drop the last `&& vitest run` from the root `test` script.
-
-Also left alone, out of scope: `CLAUDE.md:31` and `.claude/CLAUDE.md:25` still
-describe `pnpm test` as "vitest run — packages/* and apps/* (excluding
-apps/start, packages/core)", which this task made false.
-
-## M13-002 — pnpm → `bun install --linker=isolated` (2026-09-07)
-
-The installer swap (ADR-014, P13). `pnpm-workspace.yaml`, `pnpm-lock.yaml` and
-`patches/` are gone; `bun.lock` is committed; every `package.json` script is off
-pnpm. The stop rule did not fire. Full reasoning, the overrides table and the
-measured bun-override semantics are in `docs/BUN_INSTALL_RECIPE.md`
-(*M13-002 — the swap, as executed*).
-
-### Install wall time and `node_modules` size
-
-Both installers measured on this box on **2026-09-07** by the M13-002 implement
-task, on the **same tree** (the manifests were already pinned by M13-001), and
-in the same way: all 20 workspace `node_modules` directories removed first, the
-installer's own global cache left warm, timed with `/usr/bin/time -f %e`. The
-pnpm side was measured by stashing the swap so the tree was exactly `HEAD`
-(`pnpm-workspace.yaml` + `pnpm-lock.yaml` + `patches/` present, root
-`packageManager: [email protected]`), then restored. pnpm self-selected **11.23.0**
-from that field; the binary otherwise on PATH here is 11.24.0. Size is
-`du -csh` over those same 20 directories.
-
-| | pnpm 11.23.0 | Bun 1.4.0 |
-|---|---:|---:|
-| install, cold `node_modules` + warm global cache | `pnpm install --frozen-lockfile` — **8.60s**, **8.09s** (two runs) | `bun install --frozen-lockfile` — **2.89s**, **2.66s** (two runs) |
-| install, warm (no-op re-run) | **0.43s** | **0.14s** |
-| `node_modules`, all 20 directories | **3.0G** | **3.9G** |
-| files under `node_modules` | 212 145 | 197 975 |
-| packages | `resolved 3313, reused 3184, downloaded 0, added 3313` | `3002 packages installed` (3053 installs / 3429 packages per `--frozen-lockfile`) |
-| global cache backing it | `~/.local/share/pnpm/store` — 9.4G | `~/.bun/install/cache` — 5.7G |
-
-Bun installs this tree **~3× faster** cold (2.66-2.89s vs 8.09-8.60s) and leaves
-a **~30% larger** `node_modules` from **7% fewer files**.
-
-The size figure is the honest one to quote but it is not a
-like-for-like disk claim: both installers hardlink from their own global cache,
-`du` charges each inode to whichever tree it walks first, and the two caches are
-different sizes. Nothing here has been measured *inside an image* — that is
-M13-003's number, and it is the one that matters for deployment.
-
-### `p13-drift.sh --report`, final
-
-```
-workspace package dependency snapshot installed
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
-TOTAL: 0 drifted of 416 direct dependencies across 20 workspace packages
-```
-
-Zero, against `tooling/gates/p13-lock-snapshot.json` — the record of what pnpm
-had resolved, and the only such record left now that `pnpm-lock.yaml` is
-deleted. A bare `bun install` on the pinned tree started at **11 drifted**: nine
-`peerDependencies` pnpm auto-installed and bun resolved differently, plus the
-two ADR-017 rule 2 `prisma: ^5.1.1` carve-outs. Six peers and both prisma rows
-were closed with `overrides`; the last three (`packages/sdks/nextjs`'s `next`,
-`react`, `react-dom`) with exact devDependency pins, because bun's override key
-space cannot scope a version to one importer — see the recipe.
-
-### Known debt this swap leaves behind
-
-- **pnpm cannot run a script inside this tree any more, and one controller gate
- had to learn that.** Two earlier M13-002 attempts blocked on
- `verification/contracts/sdk/dist-gate.sh`, which shelled out to a hardcoded
- `pnpm run build`: with `pnpm-workspace.yaml` gone, pnpm 11 fires an implicit
- install inside each SDK directory (the `verifyDepsBeforeRun: false` that
- suppressed it died with that file) and dies on
- `ERR_PNPM_CATALOG_ENTRY_NOT_FOUND_FOR_SPEC`, because `catalog:` now resolves
- from the root `package.json`, where pnpm does not look. The operator fixed the
- gate to detect `bun.lock` exactly as `full.sh:12-19` does, and it is green
- (`DIST GATE: all 5 checked package(s) clean`, `FULL: green`). Recorded because
- the property generalises and will bite again: **any** script that invokes
- `pnpm` against this repo now fails at the deps check, not at the work. Every
- in-repo caller is off pnpm; the Dockerfiles are M13-003's and CI is M13-004's.
-- **`check:deps` deviates from the `pnpm dlx` -> `bunx` translation, on
- purpose.** `bunx` (and `npx`) cannot give dependency-cruiser the TypeScript
- compiler it needs to tag an edge `type-only`, which is the exemption
- `core-uses-ctx-not-db-internals` is built on; under `bunx` the gate returns
- 82 false errors on `import type` lines. It is not an installer problem —
- `bunx` returns the same 82 on a pnpm-installed tree. The script is now
- `bun tooling/scripts/check-deps.ts`, which installs the cruiser and
- `[email protected]` hoisted into `node_modules/.cache/depcruise`; it reproduces
- pnpm's numbers exactly (2703 modules, 18121 dependencies, zero violations).
- The debt is the shape, not the result: a repo-local dev tool is being fetched
- at gate time because ADR-017 forbids declaring it. Declaring
- `dependency-cruiser` as a root devDependency would delete this script; that is
- a register question, not a P13 one.
- **RESOLVED by M14-002 (2026-09-08)** — the register reopened after P13 (Carl),
- the tool is now a declared root devDependency, and its `typescript` peer does
- resolve under `linker = "isolated"`. The script is deleted. See the M14-002
- section at the end of this file. (The premise "ADR-017 forbids declaring it"
- was also wrong on the letter of the ADR: rule 2 puts additions, like removals,
- outside the register entirely.)
-- **`packageManager` is gone and nothing replaced it as an asserted pin.** It
- was deleted rather than repointed to `[email protected]` (reasoning in the recipe).
- ADR-016 rule 5 wants the Bun pin asserted in three places: `.bun-version`,
- `scripts/doctor.sh`, and a boot log line. Only `apps/api/Dockerfile:4`'s
- `ARG BUN_VERSION=1.4.0` exists today — there is no `.bun-version` file in the
- tree and `scripts/doctor.sh` has no bun check. Creating them is outside
- M13-002's scope (it touches neither a manifest nor the lockfile); it belongs
- with M13-003's Dockerfile work or a CLEAN task.
- **RESOLVED by M14-202 (2026-09-08)** — `.bun-version` (`1.4.0`) and
- `scripts/doctor.sh` both created; `apps/api/src/main.ts`'s "API listening"
- log line gained `bunVersion: Bun.version`. All three now agree with each
- other and with the Dockerfile `ARG`, proven by
- `apps/api/src/config/bun-version.test.ts` rather than by inspection. See the
- M14-202 section at the end of this file.
-- **The root `package-lock.json` is still tracked.** ADR-014 says it should be
- deleted in the same commit as the lockfile swap ("tracked, stale, and a trap
- for any scanner or contributor running `npm ci`"). It is outside M13-002's
- scope globs, so it survives; it is one `git rm` for whoever owns the next P13
- task.
-- **`overrides` row 1, `rolldown: 1.0.0-beta.43`, is now inert** — nothing in
- `bun.lock` requests rolldown since M12 deleted tsdown. Kept because ADR-017
- freezes the register; worth deleting the day that register is reopened.
-- **`packages/core` and `packages/db` still declare a `jiti` devDependency** that
- no script invokes any more (ADR-019 row 7b is otherwise complete: every
- `jiti X.ts` is now `bun X.ts`). Deleting the two declarations is ADR-017
- rule 2's separate CLEAN task; doing it here would make `p13-drift.sh` report
- them `missing`.
-- **`bun pm ls --trusted` is not empty** (it prints `[email protected]`,
- which is on bun's 367-entry default-trusted list). ADR-014 benchmark item 6
- asked for that command to be empty. It cannot be: the list is not the
- enforcement point. `[install] ignoreScripts = true` in `bunfig.toml` is, and
- the property the item was really after — no dependency build script runs, as
- under pnpm's twelve `allowBuilds: false` — does hold.
-
-## M13-003 image sizes
-
-Carl asked for the two P13 images to be compared against the published ones.
-All four numbers below are `docker image inspect --format '{{.Size}}'`, run on
-this box on **2026-09-07**, Docker 29.7.2 with the **containerd snapshotter**.
-
-**Read the caveat before the numbers.** Under the containerd snapshotter
-`.Size` is the sum of the image's **compressed** layer blobs — what a registry
-stores and what a `docker pull` transfers. `docker images`' `DISK USAGE` column
-is the **uncompressed**, unpacked size on disk. They differ by ~5x here and
-mixing them produces a meaningless comparison, so both are given, each labelled,
-and the comparison column uses only the compressed pair.
-
-| Image | Source | COMPRESSED (`inspect .Size`) | uncompressed (`docker images` DISK USAGE) |
-|---|---|---:|---:|
-| `openpanel-api:p13-gate` | built here from `apps/api/Dockerfile` | **412,899,646 B** (412.9 MB / 393.8 MiB) | 2.11 GB |
-| `lindesvard/openpanel-api:latest` | pulled from Docker Hub | **476,399,142 B** (476.4 MB / 454.3 MiB) | 2.39 GB |
-| `openpanel-dashboard:p13-gate` | built here from `apps/start/Dockerfile` | **95,217,524 B** (95.2 MB / 90.8 MiB) | 419 MB |
-| `lindesvard/openpanel-dashboard:latest` | pulled from Docker Hub | **524,333,374 B** (524.3 MB / 500.0 MiB) | 2.77 GB |
-
-Compressed deltas: api **−63.5 MB (−13.3%)**, dashboard **−429.1 MB (−81.8%)**.
-
-### Provenance
-
-The two `p13-gate` tags are exactly what `bash tooling/gates/p13-images.sh`
-builds; the sizes above are the two lines that run prints — from the last of
-four full builds on 2026-09-07. Rebuilding the same tree moves these numbers by
-a few hundred to a few thousand bytes, because build timestamps sit inside the
-layer metadata: the four runs gave the api 412,899,207 / 412,902,099 /
-412,906,098 / 412,899,646 (spread 6.9 KB) and the dashboard 95,217,685 /
-95,217,881 / 95,217,702 / 95,217,524 (spread 357 B). Anything larger than
-~10 KB of drift is a real content change, not this noise. The published images
-were pulled at their `latest` tags on 2026-09-07 and measured with the same
-command:
-
-| Image | digest | image `Created` |
-|---|---|---|
-| `lindesvard/openpanel-api:latest` | `sha256:cee4855cd715a7248c5c49090fe93a28ffc505541de20cb238d8884a6bcb9223` | 2026-08-18T21:22:28Z |
-| `lindesvard/openpanel-dashboard:latest` | `sha256:b773cf864454a0ec89b2a133b48bf06202880ed650a75cc2f1f5c87aaed1cffa` | 2026-08-18T20:50:28Z |
-
-Both were `docker rmi`'d after measuring — this box had ~4.5 GB free at that
-point and two more from-scratch builds had to fit. Re-pull by digest to
-reproduce.
-
-**What the two deltas are not.** They are not a like-for-like measurement of
-"the installer changed". The published images are ~3 weeks older than this
-branch's HEAD and were built from a tree with a different dependency set, so the
-api's −63.5 MB mixes the installer swap with three weeks of unrelated content.
-The dashboard's −429.1 MB is dominated by one deliberate change in this task
-and not by the installer at all: the previous runner stage copied a workspace
-`node_modules`, `packages/db`, `packages/payments`, `packages/sdks/_info` and
-the deleted `@openpanel/auth` tree alongside `.output`, and this one copies only
-`.output`, which is verified standalone (222 bundled packages of its own; it
-serves `/login` from an otherwise empty directory).
-
-### Known break in the shipped compose templates — pre-existing, not P13's
-
-`self-hosting/docker-compose.template.yml`, `self-hosting/coolify.yml` and
-`.github/smoke/docker-compose.yml` all start the api container with
-
-```
-cd /app/packages/db && ./node_modules/.bin/prisma migrate deploy
-```
-
-**That binary is not in the image**, and was not before this task either.
-`prisma` is a `devDependency` of `packages/db`, and both the old and the new
-image install production dependencies only, so it is correctly omitted. Measured
-2026-09-07 against a freshly built `openpanel-api:p13-gate`:
-
-```
-$ docker run --rm --entrypoint sh openpanel-api:p13-gate \
- -c 'cd /app/packages/db && ./node_modules/.bin/prisma migrate deploy'
-sh: 1: ./node_modules/.bin/prisma: not found
-```
-
-(`./node_modules/.bin/jiti`, the second migration command, **is** present —
-`jiti` is a real dependency of `packages/core`.)
-
-`docs/OPS_DEPLOY_MIGRATION.md`'s M9-006 section records these commands as
-"verified", but the verification it describes was run against this box's local
-Postgres/ClickHouse — on the **host**, not inside the container — so the
-image's contents were never the thing under test.
-
-Left unfixed on purpose: the two candidate fixes are "ship the Prisma CLI in the
-production image" and "run migrations from somewhere that has it", and choosing
-between them is a decision about what the image contains, not an installer
-change. M13-003's scope is the swap. The note is repeated in both compose
-templates so a self-hoster reading the file sees it.
-
-**RESOLVED by M15-203 (2026-09-11).** Carl decided the question on 2026-09-08:
-`bunx`, and migrations stay in the api container's start command. All three
-compose files now run `cd /app/packages/db && bunx [email protected] migrate deploy`
-— pinned, because a bare `bunx prisma` fetches latest and can drift from the
-generated client and the schema. The api image does not carry the CLI plus
-`@prisma/engines` (~86 MB) for a once-per-deploy command; the accepted cost is
-that the container needs npm-registry reach at start. `apps/api/Dockerfile`'s
-runtime stage now asserts `packages/db/prisma/schema.prisma`,
-`packages/db/prisma/migrations` and `packages/core/scripts/migrate-code.ts` at
-build time, and `.github/smoke/smoke.sh` gained `assert_migrations_ran`, because
-`sh -c` does not stop on a failed line — which is how this shipped unnoticed.
-Verified 2026-09-11 inside the built image as uid 1000 against a scratch local
-Postgres: "All migrations have been successfully applied.", then "No pending
-migrations to apply." on a re-run.
-
-Two corrections to the paragraph above, both measured 2026-09-11:
-
-- The claim that "both the old and the new image install production
- dependencies only" is wrong about the old one. On `main`,
- `apps/api/Dockerfile` copied `packages/db` from a build stage installed WITH
- devDependencies, so `packages/db/node_modules/.bin/prisma` shipped by
- construction. This was a **rewrite-introduced regression**, not a
- longstanding gap.
-- `./node_modules/.bin/jiti` is no longer present either — `jiti` is not a
- dependency of any workspace package any more, and
- `src/code-migrations/migrate.ts` now only *exports* the runner (ADR-022 R7).
- The compose files run `cd /app/packages/core && bun scripts/migrate-code.ts`
- instead, which is the shell that reads the environment for it.
-
-### ~~`3-init-ch.ts` cannot run against an empty ClickHouse database~~ — WRONG, corrected by M16-004 (2026-09-12)
-
-M15-203 reported, while proving its start command, that
-`3-init-ch.ts` "opens with `RENAME TABLE cohort_events_mv TO
-cohort_events_mv_tmp`" and therefore "cannot run against an empty ClickHouse
-database", dying with `UNKNOWN_TABLE (code 60)`, leaving a fresh self-host
-install partially migrated. **The failure it saw is real and reproduces exactly.
-The explanation is not.** M16-004 ran the whole sequence on fresh scratch
-databases — full evidence in `docs/MIGRATIONS_FRESH_INSTALL.md`:
-
-- **A brand-new install migrates cleanly.** 153 Prisma migrations then all 24
- code-migrations, `SELF_HOSTED=true`, first try, no errors (2026-09-12). On a
- fresh database `3-init-ch.ts` emits **no rename at all** — its first statement
- is `CREATE DATABASE IF NOT EXISTS openpanel` — because the rename block sits
- behind `isSelfHostingOld = existingTables.length !== 0 && isSelfHosting`.
-- **The `3-init-ch.sql:1` the report cites is generated by the failing run
- itself** (`writeSqlDump`), not a repo file. It is untracked and not
- gitignored.
-- **Migrations 1 and 2 are not the cause either** (the operator's 2026-09-12
- hypothesis): `1-settings.ts` is a no-op and `2-accounts.ts` only touches
- Postgres, so neither makes `existingTables` non-empty.
-- **The real cause of the observed failure is the test harness.**
- `getExistingTables()` asks `... WHERE database = 'openpanel'` with the name as
- a literal, so a run aimed at a scratch database still reads the real
- `openpanel`. On the M15-203 box that answered with the prod copy's tables,
- `isSelfHostingOld` went true, and the renames were emitted against a database
- where those tables do not exist. Reproduced byte for byte in `guard` mode.
-- **What IS real, and is not a first-boot bug:** `3-init-ch.ts` is not safely
- retryable when `SELF_HOSTED=true`. Its ledger row is written only after it
- finishes, so an interrupted first boot leaves its tables behind without the
- row, and the next boot takes the self-hosting upgrade path — renaming every
- table aside and creating empty ones. Demonstrated 2026-09-12; empty tables on
- a fresh install, so no data loss there, but 9 orphaned `_tmp` tables and a
- "please drop these" message. **Left unfixed deliberately**: the marker-based
- fix breaks the clustered case (`createTable` creates `events_replicated`
- itself) and changes behaviour for a pre-`events_v2` self-host, and Carl scoped
- upgrade-in-place out of testing — a fix that makes fresh installs work by
- breaking upgrades is worse than the bug.
-- Still true from the original note: the shipped start command is one `sh -c`
- without `set -e`, so a failed migration still lets the api boot.
-
-### Also recorded
-
-- **`.bun-version` still does not exist.** ADR-016 names it as Bun's declared
- home alongside `ARG BUN_VERSION`; both Dockerfiles carry the ARG and nothing
- carries the file. Unchanged from M13-002's note.
- **RESOLVED by M14-202 (2026-09-08)** — see the note against the same item
- in the M13-002 section above.
-- **Both images now `COPY . .` and install the whole workspace**, which is the
- shape ADR-014 Problems §4 rules for a bun-base image. The cost is that a
- source edit invalidates the install layer, so neither image has a
- manifests-only cache tier any more. The benefit is that the hand-maintained
- per-package `COPY packages/x/package.json` list — whose own comment recorded
- that drifting silently omitted a package from `node_modules` — is gone from
- both files.
-- **The api image's production install is `--filter '@openpanel/api'`**, not a
- bare `--production`. A bare install at the workspace root pulls every member's
- production closure, including `apps/start`'s (§5d). Verified on Bun 1.4.0 that
- `--filter` follows `workspace:` edges transitively and installs nothing
- outside the filtered closure.
-
-## M13-005 unifications
-
-`bunx [email protected]` baseline on 2026-09-07 (measured before this task, per
-`docs/SPEC_PLAYBOOK.md` rule 15): 20 errors + 6 warnings — 17
-`multiple-dependency-versions`, one `types-in-dependencies`
-(`apps/start`'s `@types/d3`), one `unsync-similar-dependencies` (the `@trpc/*`
-pair), one `root-package-manager-field`, plus the pre-existing
-`root-package-dependencies` and five `packages-without-package-json` warnings.
-After this task: `bunx [email protected]` exits 0 (0 errors, the same 6
-pre-existing warnings — neither named by this task's acceptance, and warnings
-alone do not fail the default `sherif` invocation).
-
-Per ADR-017 rule 0 and this task's own rule: **every unification below
-converges onto a version `bun.lock` already had resolved for at least one
-workspace member before this task ran** — never a fresh registry fetch of a
-version nobody had. Preference order was the dashboard (`apps/start`, the
-most heavily gated surface — SSR gate, golden compare) when it was a party to
-the duplicate; otherwise the more heavily-tested package (`packages/core`,
-which carries its own `bun test` suite). One exception is called out below.
-
-| # | Dependency | Workspace(s) before | Unified to | Direction |
-|---|---|---|---|---|
-| 1 | `@biomejs/biome` | `.` 2.3.15, `apps/start` 1.9.4 | **1.9.4** | root down to dashboard's |
-| 2 | `@radix-ui/react-slider` | `apps/public` 1.3.6, `apps/start` 1.2.3 | **1.2.3** | public down to dashboard's |
-| 3 | `@radix-ui/react-slot` | `apps/public` 1.2.4, `apps/start` 1.2.3 | **1.2.3** | public down to dashboard's |
-| 4 | `framer-motion` | `apps/public` 12.23.25, `apps/start` 11.18.2 | **11.18.2** | public down to dashboard's |
-| 5 | `lucide-react` | `apps/public` 0.555.0, `apps/start` 0.476.0 | **0.555.0** | **dashboard up to public's — see below** |
-| 6 | `tailwind-merge` | `apps/public` 3.4.0, `apps/start` 3.3.1 | **3.3.1** | public down to dashboard's |
-| 7 | `tailwindcss` | `apps/public` 4.1.17, `apps/start` 4.1.12 | **4.1.12** | public down to dashboard's |
-| 8 | `wrangler` | `apps/start` 4.85.0, `apps/public` 4.65.0 | **4.85.0** | public up to dashboard's |
-| 9 | `@vitejs/plugin-react` | `apps/start` 5.2.0, `apps/testbed` 4.7.0 | **5.2.0** | testbed up to dashboard's |
-| 10 | `vite` | `apps/start` 7.3.0, `apps/testbed` 6.3.5 | **7.3.0** | testbed up to dashboard's |
-| 11 | `@faker-js/faker` | `apps/start` 9.9.0, `apps/api` 9.0.1 | **9.9.0** | api up to dashboard's |
-| 12 | `slugify` | `packages/core` 1.6.9, `apps/start` 1.6.6 | **1.6.6** | core down to dashboard's |
-| 13 | `superjson` | `apps/start` 2.2.2, `packages/core` 1.13.3, `packages/redis` 1.13.3 | **2.2.2** | core+redis up to dashboard's |
-| 14 | `@types/ramda` | `packages/core` 0.31.1, `apps/start` 0.31.0 | **0.31.0** | core down to dashboard's |
-| 15 | `jiti` | `packages/core` 2.6.1, `packages/db` 2.4.1 | **2.6.1** | db up to core's (no dashboard party) |
-| 16 | `lru-cache` | `packages/core` 11.5.1, `packages/redis` 11.2.2 | **11.5.1** | redis up to core's (no dashboard party) |
-| 17 | `@trpc/client` / `@trpc/server` (`unsync-similar-dependencies`) | `apps/start` client 11.17.0 / server 11.17.0, react-query 11.6.0 / tanstack-react-query 11.6.0; `packages/core` server 11.17.0 | **11.6.0**, all four | the only version where no `@trpc/*` package moves *up* — `@trpc/[email protected]`'s own peerDependencies already require `@trpc/[email protected]` + `@trpc/[email protected]`, so this also fixes a live peer mismatch, not just the sherif rule |
-| 18 | `prisma` | `packages/db` 6.14.0, `packages/redis` `^5.1.1`, `packages/sdks/_info` `^5.1.1` | n/a | **not unified** — the two `^5.1.1` devDependencies are unused (grepped: neither package imports `prisma`/`@prisma/*`) and are **deleted**, per ADR-017 rule 2 ("Three surviving workspaces will still declare `prisma@^5.1.1` until a dedicated CLEAN task deletes them") and this task's own acceptance criterion. The now-dead `"prisma@^5.1.1": "5.9.1"` root `overrides` entry (added for exactly those two devDeps, `decisions/ADR-014-installer.md`) is removed in the same commit — nothing left in the workspace declares a range that key would match. |
-
-**Row 5 is the one reversal.** The obvious "prefer the dashboard's lower
-version" move (`apps/public`'s `lucide-react` down to `apps/start`'s
-0.476.0) broke `cd apps/public && bun run typecheck` with the exact
-`fumadocs-core` "two hashed instances" TypeScript error
-`docs/BUN_INSTALL_RECIPE.md`'s row 15 already fixed once: the root
-`overrides` entry `"lucide-react@^1.7.0": "0.555.0"` exists specifically to
-collapse `fumadocs-ui`/`fumadocs-openapi`'s optional `lucide-react` peer onto
-the same version `apps/public` declares directly, so both resolve to one
-`fumadocs-core` instance. Moving `apps/public`'s own pin off 0.555.0
-reintroduces the second instance. Converged both apps onto 0.555.0 instead
-(already installed — it is the override's own target) and re-verified: `cd
-apps/public && bun run typecheck` and `bun run build` are both green (242
-static pages generated) with the SSR gate still green for `apps/start`.
-
-**`root-package-manager-field`** is not a dependency-version row, but it is
-the other error `sherif` reported and required a decision: `docs/BUN_INSTALL_RECIPE.md`'s
-"`packageManager` is removed, not repointed to bun" section documents that
-M13-002 deliberately left the field absent, citing ADR-016 rule 5 ("an
-unasserted exact pin is worse than a range") — a `packageManager: "[email protected]"`
-field would be a value corepack reads and Bun (measured, ADR-016 Problem 2)
-does not enforce. That reasoning is unchanged and this task does not
-reintroduce `packageManager`. Instead the root `package.json` gained
-`devEngines.packageManager: { name: "bun", version: ">=1.4.0", onFail: "warn"
-}` — a different, corepack-blind field, expressed as the same **range**
-`engines.bun` already carries (not a fresh exact pin), satisfying sherif's
-rule without the "lies to corepack" or "unasserted exact pin" problems ADR-016
-raised. `docs/BUN_INSTALL_RECIPE.md` is updated alongside this file to record
-the addition.
-
-## 2026-09-08 — M14-002, `dependency-cruiser` declared, R22's layer rule landed at `warn`
-
-Ran by: ralph (M14-002 implement task), on this box, 2026-09-08.
-
-### The peer-resolution verification (ADR-022's condition), and its result
-
-ADR-022 is accepted "with the R22 condition standing": R22 ships as a
-dependency-cruiser rule only if the tool, once **declared** as a root
-devDependency, can still load the TypeScript compiler. It resolves
-`typescript` — its own optional peer — from *its own directory*, an ESM lookup
-`NODE_PATH` cannot influence. Under `bunx` that fails, and the cruise returns
-82 false `core-uses-ctx-not-db-internals` violations, every one an `import
-type` line the rule explicitly allows. `bunfig.toml` sets `linker = "isolated"`
-(P13), so a declared dependency is symlinked into the `.bun` store and the
-same failure shape was plausible.
-
-**It resolves.** With `"dependency-cruiser": "18.2.0"` in the root
-`devDependencies` and a plain `bun install`:
-
-```
-$ bunx --no-install depcruise --info
- ✔ typescript >=2.0.0 <7.0.0 [email protected]
-```
-
-A real version, not a dash. The reason it works under `linker = "isolated"` —
-and the reason `bunx` never could — is that 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's `node_modules/typescript` (itself a symlink to
-`node_modules/.bun/[email protected]/`). A global `bunx` cache directory is
-outside the repo, so the walk never reaches a `typescript` at all. Verified
-directly: `require.resolve('typescript')` from the cruiser's real directory
-returns `node_modules/.bun/[email protected]/node_modules/typescript/lib/typescript.js`.
-No hoist exception was needed.
-
-### Before / after — the declared tool reproduces the runner exactly
-
-Both run on the same tree, same config, minutes apart:
-
-| Run | Modules | Dependencies | Errors |
-|---|---:|---:|---:|
-| `bun tooling/scripts/check-deps.ts` (the runner, before) | 2700 | 18121 | 0 |
-| `depcruise --config … apps/start packages` (declared, after) | 2700 | 18121 | 0 |
-
-Identical, and the 82 false violations do not appear. Both runs took ~8.3s
-wall. (The runner's own 2026-09-07 entry above records 2703 modules; that was
-three modules ago on a different tree. The number to compare is the pair
-measured together on the same tree, which is what this table is.)
-
-So, per this task's second acceptance branch: `tooling/scripts/check-deps.ts`
-is **deleted**, and `check:deps` is now
-`depcruise --config .dependency-cruiser.cjs --output-type err apps/start packages`,
-resolving the declared binary through `node_modules/.bin`.
-
-### The ADR-017 addition
-
-`[email protected]`, root `devDependencies`. ADR-017's exception
-register **reopened after P13 (Carl, 2026-09-08)**, so this addition needs no
-new exception row. It is also not a version *bump* of anything: rule 1 freezes
-the declared range of an existing dependency, and rule 2 puts additions and
-removals outside the register entirely. The only requirement rule 5 imposes —
-that the addition come from Carl or an ADR rather than an implement task
-deciding for itself — is satisfied by ADR-022's `dependency-cruiser` ruling.
-
-The debt this closes was recorded in the M13-002 entry above as "a repo-local
-dev tool is being fetched at gate time because ADR-017 forbids declaring it".
-That premise was wrong on the letter of ADR-017 and is now moot either way.
-
-### R22 — the layer rule, landed at `warn`
-
-ADR-022 R22: **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. Two consequences drove the encoding:
-
-1. **A module importing `../../jobs/define` is going DOWN** and must not be
- flagged. A rule that fires on every well-formed module is worse than no rule.
-2. **`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. Likewise every module is the same layer, so **cross-module edges
- are out of R22's scope** — R1/R3 own those. Measured: pulling cross-module
- edges into the rule adds **84** violations, which is a different finding
- about module boundaries, not about layering.
-
-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 layer boundary**, six rules sharing the `core-layers-` prefix and one
-`R22_COMMENT`. Baseline, `bun run check:deps`, 2026-09-08:
-
-| Rule | Violations | What they are |
-|---|---:|---|
-| `core-layers-shared-is-the-bottom` | **7** | the seven misfiled `packages/core/src/shared/` files ADR-022 names: `cacheable-per-deps`, `ch-query`, `slug-id` → `services.ts`; `date`, `math` → `report.constants`; `access` → `rpc/errors`; `email-sequence` → `clients/email` |
-| `core-layers-clients-below-transport` | **6** | `clients/integrations/*` and `clients/ai/providers.ts` reaching up into `modules/*` (five to a `*.constants.ts`, one to `modules/event/event.service.ts`) |
-| `core-layers-transport-below-modules` | **10** | the **8** module-internal deep imports ADR-022 counts (`http/auth`, `http/client-auth` ×2, `http/session` ×3, `rpc/base` ×2), plus `http/debug.routes.ts` and `jobs/schedulers.ts` reaching up into `jobs.registry.ts` |
-| `core-layers-modules-below-composition` | **0** | — |
-| `core-layers-composition-below-registries` | **0** | — |
-| `core-layers-registries-below-index` | **0** | — |
-| **total** | **23** | |
-
-This reproduces ADR-022's prediction exactly — "7 violations from
-`packages/core/src/shared/` and 8 from `http/*` and `rpc/base.ts`" — and adds
-8 more genuine upward edges its *Existing implementation* table did not
-enumerate (the 6 from `clients/`, and the 2 into `jobs.registry.ts`).
-
-All six are at `severity: 'warn'`, exactly as `core-uses-ctx-not-db-internals`
-and `core-no-self-barrel` were in M10-001. **They are not flipped to `error`
-while the tree still violates them**; the fix wave flips them at 0. `bun run
-check:deps` therefore still exits `0` (`x 23 dependency violations (0 errors,
-23 warnings)`), and the four pre-existing rules keep their names, their
-`error` severity and their behaviour — unchanged and still at 0.
-
-`core-layers-modules-below-composition` carries the two upward edges R22
-declares legal, both type-only, both encoded as exemptions naming their rule:
-
-- **R3** — a module importing `ServiceDeps` / `Services` from `services.ts`.
- Every one of the 36 factories is `createXService(deps: ServiceDeps, services:
- () => Services)`, so this edge is required, not tolerated. All **47**
- such imports in production files today are `import type`, so
- `dependencyTypesNot: ['type-only']` passes every one.
-- **R8** — a module importing another module's `<name>.constants.ts`, the one
- file blessed for value-import across a boundary (`pathNot:
- '\.constants\.ts$'`).
-
-### Proving the rule fires, and proving it stays quiet
-
-A rule that cannot fire is worth nothing, and a layer rule that fires on
-well-formed code is worse than nothing. Both directions were checked with
-throwaway fixtures (ADR-008 Benchmark 1's idiom), then deleted — never
-committed. One fixture file was placed in the **modules** layer carrying four
-edges at once:
-
-```ts
-// packages/core/src/modules/health/__r22_fixture__.ts
-import { defineJob } from '../../jobs/define'; // DOWN -> silent
-import type { ServiceDeps } from '../../services'; // R3 -> silent
-import { NOT_SET_VALUE } from '../report/report.constants'; // R8 -> silent
-import { appRouter } from '../../rpc.router'; // UP -> FIRES
-```
-
-and one in the **shared** layer, where `jobs/define` is upward rather than
-downward:
-
-```ts
-// packages/core/src/shared/__r22_fixture__.ts
-import { defineJob } from '../jobs/define'; // UP -> FIRES
-```
-
-Result — exactly two new violations, 23 → 25, and the same
-`../../jobs/define` specifier correctly fires from `shared/` and stays silent
-from `modules/`:
-
-```
-warn core-layers-shared-is-the-bottom: packages/core/src/shared/__r22_fixture__.ts → packages/core/src/jobs/define.ts
-warn core-layers-modules-below-composition: packages/core/src/modules/health/__r22_fixture__.ts → packages/core/src/rpc.router.ts
-x 25 dependency violations (0 errors, 25 warnings)
-```
-
-With the fixtures removed the count returns to 23.
-
-### Root `package-lock.json` deleted
-
-`git rm package-lock.json`. ADR-014 wanted it gone in the lockfile-swap commit
-("tracked, stale, and a trap for any scanner or contributor running `npm ci`");
-it fell outside M13-002's scope globs and survived. `lockfileVersion 2`, 359
-entries, one commit ever, still listing `winston` (removed) and `[email protected]`.
-Nothing reads it — `bun.lock` is the lockfile.
-
-## 2026-09-08 — M14-202, the Bun pin asserted at all three ADR-016 rule 5 places
-
-Ran by: ralph (M14-202 implement task), on this box, 2026-09-08.
-
-Before this task: `.bun-version` did not exist, `scripts/doctor.sh` did not
-exist at all (not merely "no bun check", as the M13-002 note understated it),
-and only `apps/api/Dockerfile:4`'s `ARG BUN_VERSION=1.4.0` carried the pin.
-`package.json`'s `devEngines.packageManager` (`bun >=1.4.0`, `onFail: warn`)
-is a range with a warning, not an asserted exact pin, so it was left as is —
-not deleted, not duplicated — per the task's own note that it must simply
-agree with the three new places.
-
-**What landed:**
-
-- `.bun-version` — one line, `1.4.0`, no prefix.
-- `scripts/doctor.sh` — a developer preflight, in the style of
- `tooling/gates/p13-drift.sh` and `apps/api/e2e/boot-proof.sh`: reads
- `.bun-version`, compares it against `bun --version`, exits non-zero naming
- both versions on a mismatch. It is **not** referenced from `verification/`
- or any gate — ADR-016 rule 5 asks for a preflight, not a gate.
-- `apps/api/src/main.ts` — the existing "API listening" boot log (the one
- line that already carried `role`) gained a `bunVersion: Bun.version` field.
- No other behaviour change.
-- `apps/api/src/config/bun-version.test.ts` — the "worth more than the three
- edits" check ADR-016 asked for: asserts `.bun-version` is one line matching
- `\d+\.\d+\.\d+`, that it equals the Dockerfile's `ARG BUN_VERSION`, that
- running `scripts/doctor.sh` actually exits 0 and reports the pinned version
- (spawned for real, not grepped), and that `main.ts` logs `Bun.version`.
-
-**Verification run on this box, 2026-09-08:**
-
-- `bash scripts/doctor.sh` → `OK: bun 1.4.0 matches the pinned version
- (1.4.0)`, exit 0.
-- `bash -c 'grep -q "$(cat .bun-version)" apps/api/Dockerfile'` → match.
-- `bun run typecheck` (root) → `typecheck: 17/17 passed`.
-- `cd packages/core && bun test` → `1475 pass, 12 skip, 0 fail` (1487 tests,
- 154 files).
-- `cd apps/api && bun test --isolate` → `17 pass, 0 fail` (2 files), including
- the new `bun-version.test.ts`.
-
-No ClickHouse SQL touched; no lockfile or manifest changed.
-
-## 2026-09-11 — M15-202, ADR-022's "Existing implementation" table re-measured
-
-Ran by: ralph (M15-202 implement task), on the finished M15 tree (branch
-`rewrite/v2`, working tree at `20f63a8f` plus this task's own diff).
-
-ADR-022's *Existing implementation* section measured the shape of the tree on
-2026-09-07/08 — before the fix wave — and every row of it was a defect the
-wave was authorised to remove. This is the same table, re-measured, so the
-claim "the wave is done" is a number rather than a feeling. Nothing here is
-carried over from the ADR's own run: each "after" figure is from a command
-run today, and the command is named beside it.
-
-**How the after column was measured.** Twelve of the thirteen rows are read
-straight off `bash tooling/gates/conformance.sh --report`, whose
-BASELINE REPRODUCTION block prints exactly these counts; the greps beside
-them are the cross-check, and where a grep and the gate disagree the reason is
-given. The gate's own two traps (an eight-line factory signature a line grep
-misses; a `ReturnType<typeof create` match that is a comment) are covered by
-`tooling/gates/conformance/rules.test.ts`.
-
-| ADR-022 row | Before (2026-09-07/08) | After (2026-09-11) | How |
-|---|---:|---:|---|
-| Composition — factories not on `(deps, services: () => Services)` | 36 of 36 | **0 of 36** | gate `R3`; `grep -rn 'export function create[A-Za-z]*Service('` over `*.service.ts` still finds all 36 factories |
-| Typing — hand-written `export interface XService` outside `services.ts` | 37 | **0** | gate `R5`; `grep -rn '^export interface [A-Za-z]*Service '` → 0 |
-| Typing — `Services` members typed `ReturnType<typeof createXService>` | 0 of 36 | **36 of 36** | gate `R5` (in code, not in the comment that documents the rule) |
-| Sibling access — `load*` dependency loaders | 55 | **0**, of 2 `load*` functions left | gate `R6`. The two survivors are the allowlisted asset loaders ADR-022 names by hand: `clients/geo.ts:27 loadDatabase` (a MaxMind `.mmdb` file) and `modules/integration/src/flush-exports.ts:330 loadCursor` (an export cursor row, read through the handle it was handed) |
-| Compat layer — `v1-compat.ts` | 2,104 lines, 71 importers | **file does not exist** | `ls packages/core/src/v1-compat.ts` → no such file. The 5 remaining textual matches under `packages/core/src` are all in three `*.sql.proof.md` files, prose describing what the seam used to do |
-| Compat layer — unsanctioned `createServices(` call sites | 1 | **0** | gate `R6` |
-| Env — `process.env.` reads in `packages/core/src` (non-test) | 172 across 50 files | **0 across 0 files** | gate `R7`, which counts the bracketed form too. The one raw-grep match left, `rpc/base.ts:251`, is a comment saying core reads none — the same false positive ADR-022 recorded against its own baseline |
-| Auth — `require(Login\|ReadAccess\|WriteAccess\|Access)` definitions outside `rpc/base.ts` and `modules/auth/` | 38 | **0** | gate `R10`. One definition survives in the tree and it is in the auth stack: `modules/auth/auth.service.ts:150 requireLogin` |
-| Layering — `shared/` importing upward | 7 | **0** | gate `R22` (`core-layers-shared-is-the-bottom`, delegated to dependency-cruiser at `error`) |
-| Layering — `http/*` and `rpc/base.ts` deep-importing `modules/*/src/*` | 8 | **0** | gate `R22` (`core-layers-transport-below-modules`) |
-| Duplication — util copies across `apps/*` and `packages/*` | 5 | **0** | gate `R21`. `packages/redis/json.ts` — the file that carried its own "keep in sync with packages/core" comment — is gone; `@openpanel/shared` exists and declares no workspace dependency |
-| Residue — `NEXT_PUBLIC_` in `packages/core/src` | 5 (of 26 in 12 files) | **0** | gate `R14` |
-| Enforcement — `dependency-cruiser` declared | installed into a cache at gate time | **declared**, `"dependency-cruiser": "18.2.0"` in the root `devDependencies` | `package.json:88`; R22 therefore ships as the cruiser rule, not ADR-022's grep fallback |
-
-**`bash tooling/gates/conformance.sh --assert` exits 0** on this tree — the
-M15 gate. Total asserted violations: 0.
-
-### One count fixed here, two still wrong, one script still red
-
-**Fixed here (ADR-022 R15, CONFORMANCE_PLAN.md §1l).** The module-scope
-construction checker looked only at `ts.isIdentifier(node.expression)`, so a
-qualified `new Arctic.Google(...)` was invisible to it, and its constructor
-set did not contain `GitHub` at all. Both spellings are in
-`modules/auth/src/oauth.ts`. The checker now resolves a qualified `new A.B()`
-to its rightmost name before the lookup, and `GitHub`/`Google` joined
-`CONNECTION_CONSTRUCTOR_NAMES`; two tests in
-`tooling/gates/conformance/rules.test.ts` pin both spellings, at module scope
-(2 violations) and inside a factory body (0). **R15 still reports 0** — all
-three arctic clients are built per call, from `config.auth.*` — so the number
-is now trustworthy rather than flattering.
-
-Worth knowing while reading that: **`rules.test.ts` is in no suite.** The root
-`test` script runs four packages plus `vitest run` over
-`vitest.workspace.ts`'s two, and `tooling/` is in neither list, so the gate's
-own regression tests — including the two ADR-022 named as mandatory before
-acceptance — only run when someone runs them by hand
-(`cd tooling/gates/conformance && bun test`: 18 pass, 0 fail, 2026-09-11).
-Pre-existing, and wiring it in means editing the root `package.json`.
-
-**Still under-counted: R14's residue scan does not reach `packages/`.**
-`tooling/gates/conformance/cli.ts:124` builds `residueFiles` from
-`packages/core`, `apps/api` and `apps/start` only, so the one surviving
-`NEXT_PUBLIC_` reference outside `apps/public` —
-`packages/payments/src/polar.ts:66` — is not seen by the rule whose label
-says "elsewhere outside `apps/public/`". Recorded, not fixed: R14 was
-M15-201's target and widening the scan is a change to what that gate asserts.
-
-**Still failing for an unrelated reason:
-`verification/golden/queue-keys/check.sh`.** It imports
-`CRON_SCHEDULES` from `packages/core/src/jobs/schedulers.ts`, which ADR-021
-moved onto the jobs themselves; the export is gone and the script dies on
-`sch.CRON_SCHEDULES.map`. Verified pre-existing by stashing this task's diff
-and re-running: same failure at `20f63a8f`.
-
-## 2026-09-11 — M15-205, `responsive-react-email` deleted; api image measured before/after
-
-`docs/DOCKER_SLIMMING.md` §2.2 (M14-203) had already proved the cause: a
-*production* dependency, `packages/email/package.json:19`'s
-`[email protected]`, pulls `[email protected]` in as a peer, which
-pulls `[email protected]` and both `@next/swc-linux-x64-*` binaries — none of it
-imported anywhere (`grep -rn "responsive-react-email"` over `packages/` and
-`apps/` found only the manifest line). This task deletes the line and
-regenerates `bun.lock` + `tooling/gates/p13-lock-snapshot.json` in the same
-commit.
-
-**Measured here, following `DOCKER_SLIMMING.md` §0's method exactly** — two
-whole `openpanel-api` images, both built from `apps/api/Dockerfile` at the
-same commit (`d8e50c2f`), differing only in this task's three-file diff, never
-from an edited file in the tracked tree (the diff was `git stash`-held during
-the "before" build and restored once the build context had been read):
-
-```
-docker build -f apps/api/Dockerfile -t <tag> \
- --build-arg DATABASE_URL=postgresql://p13-gate:[email protected]:1/p13-gate .
-```
-
-| Image | COMPRESSED (`docker image inspect .Size`) | UNCOMPRESSED (`docker history` layer sum) |
-|---|---:|---:|
-| before — `d8e50c2f`, dependency present | **341,481,099 B** (341.5 MB) | **1,472,071,590 B** (1.47 GB) |
-| after — this task's diff applied | **242,937,660 B** (242.9 MB) | **963,071,590 B** (963.1 MB) |
-| **delta** | **−98,543,439 B (−28.9 %)** | **−509,000,000 B (−34.6 %)** |
-
-The uncompressed figure is `docker history --no-trunc --format '{{.Size}}'`
-summed from Docker's rounded human units (same caveat `DOCKER_SLIMMING.md` §0
-notes about its own per-layer table), so treat it to three significant
-figures; the compressed figure is the exact byte count everything else here
-is keyed to.
-
-`docker history` on the two images is identical line-for-line except one:
-
-```
-COPY --chown=bun:bun /app/node_modules ./node_modules 1.17GB → 661MB
-```
-
-— confirming the whole delta is the one dependency edge, nothing else moved.
-Inside the "after" image's `node_modules/.bun` store: 884 entries (was 951,
-−67); `next`, `react-email` (bare) and both `@next/swc-linux-x64-*` are
-absent; `@react-email/*` (the real, still-declared production dependency of
-`packages/email`) is unaffected. The after image boots: `docker run
---network host` against this box's Postgres/ClickHouse/Redis gives
-`/healthz/ready` → `200` with no `Cannot find module` lines in the log.
-
-This delta (−98.5 MB compressed here) is smaller than §2.2's own
-`bun install --production` probe delta (144,263,771 B) because
-`apps/api/Dockerfile`'s `prod-deps` stage already prunes `*musl*` store
-entries (including `@next/swc-linux-x64-musl`, 54,344,971 B compressed of
-§2.2's four-entry total) as one of M15-203's cuts — that entry was already
-gone from the "before" image measured here, so this task cannot re-save it.
-The `react-email` + `next` + `@next/swc-linux-x64-gnu` chain is what remained
-to cut, and cutting it is exactly what this task does.
diff --git a/packages/core/src/http/bull-board.ts b/packages/core/src/http/bull-board.ts
index 3fade7bd4..433788c9c 100644
--- a/packages/core/src/http/bull-board.ts
+++ b/packages/core/src/http/bull-board.ts
@@ -11,8 +11,7 @@
// 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!".
+// UI halts ALL buffer flushing.** Preserved deliberately.
import type { Queue as BullQueue } from 'bullmq';
import { Elysia } from 'elysia';
diff --git a/packages/core/src/jobs/jobs.metrics.ts b/packages/core/src/jobs/jobs.metrics.ts
index 4ce1d2f90..b23d34fae 100644
--- a/packages/core/src/jobs/jobs.metrics.ts
+++ b/packages/core/src/jobs/jobs.metrics.ts
@@ -2,8 +2,8 @@
// 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`:
+// Three deliberate differences from the metric set this replaces, written up
+// for dashboard owners 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
diff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.ts
index 3f3805278..37b57abc7 100644
--- a/packages/core/src/modules/assistant/assistant.constants.ts
+++ b/packages/core/src/modules/assistant/assistant.constants.ts
@@ -1,9 +1,6 @@
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
diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.ts
index 52600b713..5a00d8253 100644
--- a/packages/core/src/modules/auth/auth.constants.ts
+++ b/packages/core/src/modules/auth/auth.constants.ts
@@ -1,9 +1,3 @@
-// `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.
-//
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
-
import { z } from 'zod';
export const zProvider = z.enum(['email', 'google', 'github']);
diff --git a/packages/core/src/modules/cohort/cohort.constants.ts b/packages/core/src/modules/cohort/cohort.constants.ts
index 2dea732fd..dbc5dbe58 100644
--- a/packages/core/src/modules/cohort/cohort.constants.ts
+++ b/packages/core/src/modules/cohort/cohort.constants.ts
@@ -1,10 +1,3 @@
-// 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.service.ts b/packages/core/src/modules/cohort/cohort.service.ts
index 31a188c7d..3c3dac7e8 100644
--- a/packages/core/src/modules/cohort/cohort.service.ts
+++ b/packages/core/src/modules/cohort/cohort.service.ts
@@ -156,7 +156,7 @@ function trimmedComparand(value: unknown): string {
// One event-property filter. Values bind; the property key is a Map key, so it
// binds as a value too. An `IN`/`NOT IN` list becomes one `Array(String)`
// param — V1's `IN ()` on an empty list and `IN {p:Array(String)}` on an empty
-// array both match nothing (SQL_MIGRATION_RECIPE idioms 9/10).
+// array both match nothing.
function eventPropertyCondition(filter: IChartEventFilter): SqlFragment {
const propertyKey = sql.string(filter.name.replace('properties.', ''));
const { value, operator } = filter;
diff --git a/packages/core/src/modules/conversation/conversation.constants.ts b/packages/core/src/modules/conversation/conversation.constants.ts
index 5c339eb3a..00cc4b30c 100644
--- a/packages/core/src/modules/conversation/conversation.constants.ts
+++ b/packages/core/src/modules/conversation/conversation.constants.ts
@@ -1,8 +1,5 @@
// Shared with the frontend (chat-drawer-header.tsx, title-stream.tsx) so the
-// 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.
+// page size / title length and the zod defaults never drift apart.
export const CONVERSATION_LIST_LIMIT_DEFAULT = 50;
export const CONVERSATION_TITLE_MIN_LENGTH = 1;
diff --git a/packages/core/src/modules/group/group.constants.ts b/packages/core/src/modules/group/group.constants.ts
index 35590004f..39f9df9ab 100644
--- a/packages/core/src/modules/group/group.constants.ts
+++ b/packages/core/src/modules/group/group.constants.ts
@@ -1,5 +1,3 @@
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
-
import { z } from 'zod';
export const zGroupId = z
diff --git a/packages/core/src/modules/import/import.constants.ts b/packages/core/src/modules/import/import.constants.ts
index 8d185eb9d..1e75669ff 100644
--- a/packages/core/src/modules/import/import.constants.ts
+++ b/packages/core/src/modules/import/import.constants.ts
@@ -1,5 +1,3 @@
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
-
import { z } from 'zod';
export type ImportProviderId = 'umami' | 'mixpanel' | 'amplitude';
diff --git a/packages/core/src/modules/ingest/ingest.constants.ts b/packages/core/src/modules/ingest/ingest.constants.ts
index 1a6da68cb..52f9b3511 100644
--- a/packages/core/src/modules/ingest/ingest.constants.ts
+++ b/packages/core/src/modules/ingest/ingest.constants.ts
@@ -1,9 +1,6 @@
// The ingestion wire contract (ADR-008's module map: ingest owns "C"). 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.
-//
-// Isomorphic by rule: zod, another *.constants.ts, or nothing.
+// track body may contain), so they are one file here.
import { z } from 'zod';
diff --git a/packages/core/src/modules/insight/insight.constants.ts b/packages/core/src/modules/insight/insight.constants.ts
index 4f9a4619b..22665d24c 100644
--- a/packages/core/src/modules/insight/insight.constants.ts
+++ b/packages/core/src/modules/insight/insight.constants.ts
@@ -1,6 +1,3 @@
-// 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 own
// requests against the same numbers the procedure enforces.
diff --git a/packages/core/src/modules/notification/notification.constants.ts b/packages/core/src/modules/notification/notification.constants.ts
index 526e5f092..70a090a09 100644
--- a/packages/core/src/modules/notification/notification.constants.ts
+++ b/packages/core/src/modules/notification/notification.constants.ts
@@ -1,15 +1,8 @@
-// `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.
-//
-// Isomorphic by the AGENTS.md rule otherwise: zod and nothing else.
+// `zChartEvent` / `zChartEventFilter` / `zChartEventSegment` are diverged local
+// copies of report.constants.ts's, with the operator and value-type enums
+// inlined as literal tuples instead of derived from `operators` /
+// `filterValueTypes`. The enum sets are identical, so the copies can be
+// collapsed onto report.constants.ts — see ISSUES.md.
import { z } from 'zod';
diff --git a/packages/core/src/modules/onboarding/onboarding.constants.ts b/packages/core/src/modules/onboarding/onboarding.constants.ts
index 61409a5e4..4698793ad 100644
--- a/packages/core/src/modules/onboarding/onboarding.constants.ts
+++ b/packages/core/src/modules/onboarding/onboarding.constants.ts
@@ -1,5 +1,3 @@
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
-
import { z } from 'zod';
import { zTimezone } from '../organization/organization.constants';
diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.ts
index 97db23e86..70be0229d 100644
--- a/packages/core/src/modules/organization/organization.constants.ts
+++ b/packages/core/src/modules/organization/organization.constants.ts
@@ -3,8 +3,6 @@
// 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.
import { z } from 'zod';
diff --git a/packages/core/src/modules/project/project.constants.ts b/packages/core/src/modules/project/project.constants.ts
index 5fb2bee01..cce2c90cd 100644
--- a/packages/core/src/modules/project/project.constants.ts
+++ b/packages/core/src/modules/project/project.constants.ts
@@ -3,13 +3,8 @@
// bodies they validate (project.service.ts's
// createProjectForOrganization/updateProjectForOrganization).
//
-// The project filter/edit schemas below moved from
-// 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.
+// `zChartEvent` is imported by name, not re-exported: `zProjectFilterEvent`
+// extends it as a bound identifier.
import { z } from 'zod';
import { zChartEvent } from '../report/report.constants';
diff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.ts
index 4053eac51..0ecca1a36 100644
--- a/packages/core/src/modules/realtime/realtime.routes.test.ts
+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts
@@ -21,7 +21,7 @@
// `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).
+// own.
import { afterAll, afterEach, beforeEach, expect, mock, test } from 'bun:test';
import { getSuperJson } from '@openpanel/shared';
diff --git a/packages/core/src/modules/realtime/realtime.service.test.ts b/packages/core/src/modules/realtime/realtime.service.test.ts
index e74a88e18..36dbec459 100644
--- a/packages/core/src/modules/realtime/realtime.service.test.ts
+++ b/packages/core/src/modules/realtime/realtime.service.test.ts
@@ -8,7 +8,7 @@
// 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).
+// deferred loads at all.
//
// 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
diff --git a/packages/core/src/modules/reference/reference.constants.ts b/packages/core/src/modules/reference/reference.constants.ts
index 0f70d8c8e..44f519c8f 100644
--- a/packages/core/src/modules/reference/reference.constants.ts
+++ b/packages/core/src/modules/reference/reference.constants.ts
@@ -1,7 +1,5 @@
// 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.
import { z } from 'zod';
diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.ts
index bd17fbe49..4ad9b154f 100644
--- a/packages/core/src/modules/report/report.constants.ts
+++ b/packages/core/src/modules/report/report.constants.ts
@@ -7,8 +7,6 @@
// 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.
-//
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
import { z } from 'zod';
diff --git a/packages/core/src/modules/subscription/subscription.constants.ts b/packages/core/src/modules/subscription/subscription.constants.ts
index 35ce113d3..9f4b75131 100644
--- a/packages/core/src/modules/subscription/subscription.constants.ts
+++ b/packages/core/src/modules/subscription/subscription.constants.ts
@@ -1,5 +1,3 @@
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
-
import { z } from 'zod';
export const zCheckout = z.object({
diff --git a/packages/core/test/MIDNIGHT_FLAKE_PROOF.md b/packages/core/test/MIDNIGHT_FLAKE_PROOF.md
deleted file mode 100644
index ed42ed0b3..000000000
--- a/packages/core/test/MIDNIGHT_FLAKE_PROOF.md
+++ /dev/null
@@ -1,191 +0,0 @@
-# Midnight fixture flake — proof (M35-001)
-
-## The flake
-
-Around 00:00–00:25 UTC, three tests failed because `test/fixtures.ts` seeds at
-`Date.now() - N days - M minutes` while the assertions bucket by calendar day:
-
-- `get_profile_metrics > returns exact metrics for charlie` (`uniqueDaysActive` 1 vs 2)
-- `getChartBucketProfiles > returns the profiles behind one data point, honoring breakdowns`
-- `getChartBucketProfiles > selects only whitelisted profile columns for profile.* references`
-
-## The fix
-
-- `test/fixture-clock.ts`: `pinFixtureClock()` freezes `Date` (bun's
- `setSystemTime`) at the latest 12:00 UTC not after now. `releaseFixtureClock()`
- unfreezes it. Every seeded offset then lands inside one calendar day.
-- `chart.service.test.ts` and `mcp/src/integration/tools.test.ts` pin the clock
- before `setupFixtures` and release it in `afterAll`. The two
- `getChartBucketProfiles` cases compute "two days ago" from `fixtureNow`, not
- `Date.now()`.
-- `test/fixture-clock.test.ts` unit-tests the anchor. Its last case shows that
- charlie's seeded span covers two calendar days at 00:10 under the raw clock
- and one day under the anchor.
-- `test/midnight-window.test.ts` re-runs both suites in child processes with the
- wall clock frozen at 00:01, 00:10 and 00:19 UTC, via
- `test/wall-clock-preload.ts`. It runs in every `bun run test`, so this proof
- is repeated on every run, not just recorded once.
-
-The anchor is a time of day, not a fixed calendar date. Some services compare
-against ClickHouse's own `now()` (the 3-month project card, `inactiveDays`,
-last-seen buckets), and bun cannot fake that clock. The anchor is never in the
-future and never more than 24 h old, so every `now`-relative window still
-contains the fixtures.
-
-**Limitation:** the in-window runs below fake only the JS clock. ClickHouse
-`now()` was the real time (≈11:11 UTC on 2026-09-16), so the JS-to-ClickHouse
-clock gap in these runs is ≈23 h. In a real 00:10 run the gap is ≈12 h. Both
-gaps are inside the 24 h bound above.
-
-All runs below were executed on 2026-09-16 on this box, from
-`packages/core`. `test/preload.ts` (bunfig `[test] preload`, also imported by
-`wall-clock-preload.ts`) pins the infra URLs to the isolated
-`openpanel_test` Postgres/ClickHouse databases. Output is filtered with
-`grep -E "wall clock pinned|\(fail\)|^ *[0-9]+ (pass|fail)|expect\(\) calls|^Ran "`.
-
-## 1. Clock faked INTO the 00:00–00:25 UTC window — passing
-
-Command (run 2026-09-16T11:11:01Z–11:11:30Z):
-
-```bash
-cd packages/core
-for t in 2026-09-16T00:01:00.000Z 2026-09-16T00:10:00.000Z 2026-09-16T00:19:00.000Z; do
- FIXTURE_WALL_CLOCK_ISO=$t \
- BUN_OPTIONS="--preload=$PWD/test/wall-clock-preload.ts" \
- bun test --isolate src/modules/chart/chart.service.test.ts \
- src/modules/mcp/src/integration/tools.test.ts
-done
-```
-
-Output:
-
-```text
-=== FIXTURE_WALL_CLOCK_ISO=2026-09-16T00:01:00.000Z
-wall clock pinned at 2026-09-16T00:01:00.000Z
-wall clock pinned at 2026-09-16T00:01:00.000Z
- 54 pass
- 0 fail
- 160 expect() calls
-Ran 54 tests across 2 files. [10.26s]
-exit=0
-=== FIXTURE_WALL_CLOCK_ISO=2026-09-16T00:10:00.000Z
-wall clock pinned at 2026-09-16T00:10:00.000Z
-wall clock pinned at 2026-09-16T00:10:00.000Z
- 54 pass
- 0 fail
- 160 expect() calls
-Ran 54 tests across 2 files. [10.05s]
-exit=0
-=== FIXTURE_WALL_CLOCK_ISO=2026-09-16T00:19:00.000Z
-wall clock pinned at 2026-09-16T00:19:00.000Z
-wall clock pinned at 2026-09-16T00:19:00.000Z
- 54 pass
- 0 fail
- 160 expect() calls
-Ran 54 tests across 2 files. [9.14s]
-exit=0
-```
-
-The `wall clock pinned at` line is printed once per test file (`--isolate`).
-It shows that each suite ran with the faked time.
-
-## 2. The same suites at a normal hour — passing
-
-Command (real clock, run 2026-09-16T11:11:35Z–11:11:45Z):
-
-```bash
-cd packages/core
-bun test --isolate src/modules/chart/chart.service.test.ts \
- src/modules/mcp/src/integration/tools.test.ts
-```
-
-Output:
-
-```text
- 54 pass
- 0 fail
- 160 expect() calls
-Ran 54 tests across 2 files. [9.87s]
-exit=0
-```
-
-## 3. Negative control — the same in-window runs WITHOUT the fix
-
-The two suite files were temporarily replaced with their `HEAD` versions
-(`git show HEAD:<file> > <file>`) and restored afterwards. The rest of the
-command matches section 1 (run 2026-09-16T11:11:51Z–11:12:24Z). Each run fails
-on exactly the documented flake tests and nothing else:
-
-```text
-=== FIXTURE_WALL_CLOCK_ISO=2026-09-16T00:01:00.000Z (fix reverted)
-(fail) getChartBucketProfiles > returns the profiles behind one data point, honoring breakdowns [11.33ms]
-(fail) getChartBucketProfiles > selects only whitelisted profile columns for profile.* references [9.43ms]
-(fail) get_profile_metrics > returns exact metrics for charlie [17.57ms]
- 51 pass
- 3 fail
-Ran 54 tests across 2 files. [11.09s]
-exit=1
-=== FIXTURE_WALL_CLOCK_ISO=2026-09-16T00:10:00.000Z (fix reverted)
-(fail) get_profile_metrics > returns exact metrics for charlie [26.26ms]
- 53 pass
- 1 fail
-Ran 54 tests across 2 files. [10.98s]
-exit=1
-=== FIXTURE_WALL_CLOCK_ISO=2026-09-16T00:19:00.000Z (fix reverted)
-(fail) get_profile_metrics > returns exact metrics for charlie [15.67ms]
- 53 pass
- 1 fail
-Ran 54 tests across 2 files. [10.79s]
-exit=1
-```
-
-So the fake clock does reproduce the flake, and the passes in section 1 come
-from the fix.
-
-## 4. The committed guard tests
-
-Command (run 2026-09-16T11:12:32Z–11:13:04Z):
-
-```bash
-cd packages/core
-bun test --isolate test/fixture-clock.test.ts test/midnight-window.test.ts
-```
-
-Output:
-
-```text
- 6 pass
- 0 fail
- 18 expect() calls
-Ran 6 tests across 2 files. [32.45s]
-exit=0
-```
-
-## 5. Full gate on this tree
-
-`verification/full.sh` was run from the controller, 2026-09-16T11:13:41Z to
-11:19:12Z, with exit 0. Excerpt:
-
-```text
-OK: bun run test
-GOLDEN: the only differing case(s) are known non-deterministic holes: insights-event-property-values
-GOLDEN: every other case matched byte-exact. Passing.
-OK: golden/compare
-OK: golden/openapi v2-diff.sh
-FULL: green
-```
-
-`openpanel.events` on the prod copy read 321,191,947 before this run and
-321,191,957 after. The e2e ingestion added rows, and none were lost.
-
-## What this does not cover
-
-- The fix covers only the two suites that seed `test/fixtures.ts` from
- packages/core: `chart.service.test.ts` and `mcp/src/integration/tools.test.ts`.
- `test/fixtures.ts` is unchanged, and no other consumer of it (V1's root
- suites, apps/api) was touched.
-- `verification/midnight-flake` (the M34-001 guard) is unchanged. It is still
- the safety net.
-- The children in `midnight-window.test.ts` use the same fixture project ids
- as the suites they re-run. This is safe only because bun runs test files one
- at a time.
diff --git a/tooling/scripts/pin-from-pnpm-lock.ts b/tooling/scripts/pin-from-pnpm-lock.ts
index 24e2456ef..e70593dee 100644
--- a/tooling/scripts/pin-from-pnpm-lock.ts
+++ b/tooling/scripts/pin-from-pnpm-lock.ts
@@ -33,8 +33,7 @@
* 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.
*
* 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