OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M14-003): tooling/gates/conformance.sh built from the controller spec: per-rule --report and --assert for the mechanical subset of ADR-022, AST-based where a grep would lie, with the two known miscount traps covered by its own tests
ralphf4b40be57812
diff --git a/tooling/gates/conformance.sh b/tooling/gates/conformance.shnew file mode 100755index 000000000..0bacc1a9a--- /dev/null+++ b/tooling/gates/conformance.sh@@ -0,0 +1,116 @@+#!/usr/bin/env bash+#+# ADR-022 conformance gate — does the tree still have the SHAPE the standard+# describes?+#+# --report per-rule counts and every offender as file:line, one block per+# rule ending in a TOTAL, plus one overall TOTAL. Always exits 0.+# --assert exits 1 if any ASSERTED rule is above its target, printing only+# those rules and their offenders. Exits 0 when the tree is+# conformant. `--assert` exiting 0 is the M14 gate.+# --selftest runs the gate's own bun:test suite — the two miscount traps and+# the R6 asset-loader allowlist. Exits 1 if a test fails.+#+# WHY THIS GATE EXISTS+#+# Every other gate in this plan proves BEHAVIOUR: goldens 137/137, the routing+# golden 217/217, the session e2e 29/29, the wire contracts 67/67, the P13 drift+# gate 0/416. Not one of them proves shape. Each of ADR-022's rules can be broken+# while all of that stays green, which is exactly how the tree arrived at 36+# factories with no composition root, 172 process.env reads in a package whose+# app calls itself "the sole reader", and a 2,104-line v1-compat.ts. A rule with+# no check is advice.+#+# WHY IT WALKS THE AST INSTEAD OF GREPPING+#+# Both of these were measured on 2026-09-08 against packages/core/src, and both+# make a naive gate lie:+#+# 1. `rg 'export function create[A-Za-z]+Service\(deps'` finds 28 factories.+# There are 36 — eight signatures span lines, so the argument list is not on+# the `export function` line. A gate that greps for the opening paren and+# the first parameter together silently passes the eight it cannot see.+#+# 2. `rg -o 'ReturnType<typeof create' packages/core/src/services.ts` matches+# once, and the match is a COMMENT at services.ts:154 explaining why+# `ReturnType<typeof createServices>` is circular. The pattern is applied in+# code ZERO times. A grep scores that comment as one compliant member.+#+# A third turned up while building the gate, in the same family: R7's baseline+# was measured with `rg 'process\.env\.'`, which counts a comment at+# rpc/base.ts:246 saying core reads no process.env, and misses a real read at+# shared/get-client-ip.ts:83 written `process.env?.`. The two errors cancel in+# the occurrence count (172 either way) and do not in the file count. The report+# prints the reconciliation rather than quietly picking one.+#+# A check that cannot tell code from a comment about code is not a check, so+# every count used as evidence walks the TypeScript AST. `typescript` is already+# a declared dependency.+#+# WHAT IS DELEGATED+#+# R22 the layer rules M14-002 landed in .dependency-cruiser.cjs. This gate+# reports their violation counts; it does not reimplement them. ADR-022's+# grep fallback is not in play — M14-002's peer-resolution verification+# passed. A bare `../` depth grep is forbidden either way: a module+# importing `defineJob` at `../../jobs/define` is importing DOWNWARD, and+# a depth check flags every well-formed module in the tree.+# R12 the existing `frontend-values-only-constants` cruiser rule.+#+# WHAT IS REPORTED BUT NOT ASSERTED+#+# R1, R2, R4, R9, R11, R13, R16, R17, R18, R19. They are review rules: passing+# them is a judgement a document makes, not a number. `--report` prints whatever+# is measurable as a hint for the reviewer. R20 is deferred by Carl (2026-09-08)+# and is absent from this gate entirely — do not add it.+#+# The report body carries no timestamps and orders everything by file then line,+# so two runs diff cleanly. That is the property the fix wave needs to prove a+# rule reached zero.++set -uo pipefail++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+cd "$REPO_ROOT" || exit 1++readonly ANALYZER='tooling/gates/conformance/cli.ts'+readonly TEST_DIRECTORY='tooling/gates/conformance'+readonly CRUISER_BINARY='node_modules/.bin/depcruise'++usage() {+ echo "usage: $(basename "$0") --report | --assert | --selftest" >&2+}++require_analyzer() {+ [[ -f "$ANALYZER" ]] || {+ echo "FAIL: $ANALYZER is missing." >&2+ exit 2+ }+ command -v bun >/dev/null 2>&1 || {+ echo "FAIL: bun is not on PATH; the analyzer runs under bun (ADR-010)." >&2+ exit 2+ }+ # R12 and R22 are delegated. A delegated check that silently reports zero+ # because its tool is absent is worse than no check, so say so up front.+ [[ -x "$CRUISER_BINARY" ]] || {+ echo "WARN: $CRUISER_BINARY is missing — R12 and R22 will report UNAVAILABLE" >&2+ echo " and --assert will fail on them. Run \`bun install\`." >&2+ }+}++selftest() {+ echo "== conformance gate self-test ($TEST_DIRECTORY) =="+ bun test "$TEST_DIRECTORY"+}++require_analyzer++case "${1-}" in+ --report) bun "$ANALYZER" --report "$REPO_ROOT" ;;+ --assert) bun "$ANALYZER" --assert "$REPO_ROOT" || exit 1 ;;+ --selftest) selftest || exit 1 ;;+ *)+ usage+ exit 2+ ;;+esacdiff --git a/tooling/gates/conformance/cli.ts b/tooling/gates/conformance/cli.tsnew file mode 100644index 000000000..0d6b5d1d7--- /dev/null+++ b/tooling/gates/conformance/cli.ts@@ -0,0 +1,748 @@+/**+ * Assembles every ADR-022 check into one report and decides --assert.+ *+ * Output contract (docs/CONFORMANCE_GATE_SPEC.md, "Output shape"): one block per+ * rule, offenders as `file:line`, a TOTAL line per rule and one overall, stable+ * ordering and no timestamps in the body — so the fix wave proves a rule reached+ * zero by diffing two reports.+ */++import { readFileSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';++import {+ API_SOURCE_ROOT,+ CORE_SOURCE_ROOT,+ CORE_V1_COMPAT_FILE,+ CRUISER_FRONTEND_RULE_NAME,+ CRUISER_LAYER_RULE_NAMES,+ MAX_OFFENDERS_PRINTED,+ R22_SHARED_UPWARD_RULE,+ R22_TRANSPORT_UPWARD_FROM,+ R22_TRANSPORT_UPWARD_RULE,+ R22_TRANSPORT_UPWARD_TO,+} from './conformance.constants';+import { resolveImportLine, runCruiser, violationsOf } from './cruiser';+import {+ checkAccessChecks,+ checkConfigLoaderShape,+ checkCreateServicesCallSites,+ checkDependencyLoaders,+ checkDuplicateUtilities,+ checkEnvReads,+ checkFactoryReturnShape,+ checkFactorySignatures,+ checkJobPayloadDates,+ checkModuleLayout,+ checkModuleScopeConstruction,+ checkResidue,+ checkRpcProceduresWithoutCallers,+ checkServiceInterfaces,+ checkServicesMembers,+ checkSharedPackageIsolation,+ type Metric,+} from './rules';+import {+ lineOf,+ listSourceFiles,+ type Offender,+ type ParsedSource,+ readSources,+ ts,+ visit,+} from './sources';++interface RuleBlock {+ id: string;+ title: string;+ asserted: boolean;+ metrics: Metric[];+ note?: string;+}++const START_SOURCE_ROOT = 'apps/start/src';+const MODULES_ROOT = `${CORE_SOURCE_ROOT}/modules`;+const CONFIG_ENV_FILE = `${API_SOURCE_ROOT}/config/env.ts`;+// Static `from '../v1-compat'` and dynamic `await import('../v1-compat')` alike:+// 34 of today's importers reach it through a lazy import, which is the R6 defect+// itself and would be missed by a `from` pattern.+const V1_COMPAT_IMPORT = /['"][^'"]*\/v1-compat['"]/;+const RULE_ID_WIDTH = 4;+const SEPARATOR_WIDTH = 80;++const heavy = '='.repeat(SEPARATOR_WIDTH);+const light = '-'.repeat(SEPARATOR_WIDTH);++// --- collection ---------------------------------------------------------------++interface Tree {+ repoRoot: string;+ core: ParsedSource[];+ api: ParsedSource[];+ moduleNames: string[];+ moduleRootFiles: Map<string, string[]>;+ utilityPaths: string[];+ residueFiles: { path: string; text: string }[];+ startText: string;+ configEnv: ParsedSource | undefined;+ /** Core INCLUDING tests — the v1-compat importer count needs them. */+ allCoreText: { path: string; text: string }[];+}++function collect(repoRoot: string): Tree {+ const corePaths = listSourceFiles(repoRoot, CORE_SOURCE_ROOT);+ const apiPaths = listSourceFiles(repoRoot, API_SOURCE_ROOT);+ const startPaths = listSourceFiles(repoRoot, START_SOURCE_ROOT);+ const core = readSources(repoRoot, corePaths);+ const api = readSources(repoRoot, apiPaths);++ const moduleNames = [+ ...new Set(+ corePaths+ .filter((path) => path.startsWith(`${MODULES_ROOT}/`))+ .map((path) => path.slice(MODULES_ROOT.length + 1).split('/')[0])+ ),+ ].sort();++ const moduleRootFiles = new Map<string, string[]>();+ for (const moduleName of moduleNames) {+ const root = `${MODULES_ROOT}/${moduleName}`;+ moduleRootFiles.set(+ moduleName,+ corePaths.filter((path) => dirname(path) === root)+ );+ }++ // R21 looks across every app and package, not just core.+ const utilityPaths = [+ ...startPaths,+ ...corePaths,+ ...listSourceFiles(repoRoot, 'packages'),+ ...listSourceFiles(repoRoot, 'apps'),+ ];++ const residueFiles = [...corePaths, ...apiPaths, ...startPaths].map(+ (path) => ({ path, text: readFileSync(join(repoRoot, path), 'utf8') })+ );++ const startText = startPaths+ .map((path) => readFileSync(join(repoRoot, path), 'utf8'))+ .join('\n');++ return {+ repoRoot,+ core,+ api,+ moduleNames,+ moduleRootFiles,+ utilityPaths: [...new Set(utilityPaths)].sort(),+ residueFiles,+ startText,+ configEnv: api.find((source) => source.path === CONFIG_ENV_FILE),+ allCoreText: listSourceFiles(repoRoot, CORE_SOURCE_ROOT, {+ includeTests: true,+ }).map((path) => ({+ path,+ text: readFileSync(join(repoRoot, path), 'utf8'),+ })),+ };+}++const objectLiteralOf = (+ node: ts.Expression+): ts.ObjectLiteralExpression | undefined => {+ if (ts.isObjectLiteralExpression(node)) {+ return node;+ }+ // `createTRPCRouter({ ... })`.+ if (ts.isCallExpression(node)) {+ const first = node.arguments[0];+ if (first && ts.isObjectLiteralExpression(first)) {+ return first;+ }+ }+ return undefined;+};++/**+ * R2 — the router key each module is mounted under in `rpc.router.ts`, and the+ * procedure names it declares.+ *+ * The key matters: `apps/start` calls `trpc.<key>.<procedure>`, and the key is+ * the registry's, not the file's. `misc.rpc.ts` does not exist; `miscRouter`+ * does, mounted under whatever `rpc.router.ts` says.+ */+function collectRouters(tree: Tree) {+ const registry = tree.core.find(+ (source) => source.path === `${CORE_SOURCE_ROOT}/rpc.router.ts`+ );+ if (!registry) {+ return [];+ }++ // identifier -> the module rpc file it is imported from.+ const importedFrom = new Map<string, string>();+ for (const statement of registry.sourceFile.statements) {+ if (+ !(+ ts.isImportDeclaration(statement) &&+ ts.isStringLiteral(statement.moduleSpecifier)+ )+ ) {+ continue;+ }+ const specifier = statement.moduleSpecifier.text;+ if (!specifier.endsWith('.rpc')) {+ continue;+ }+ const bindings = statement.importClause?.namedBindings;+ if (bindings && ts.isNamedImports(bindings)) {+ for (const element of bindings.elements) {+ importedFrom.set(+ element.name.text,+ `${CORE_SOURCE_ROOT}/${specifier.replace(/^\.\//, '')}.ts`+ );+ }+ }+ }++ // routerKey -> identifier, from `createTRPCRouter({ key: xRouter, ... })`.+ const mounted = new Map<string, string>();+ visit(registry.sourceFile, (node) => {+ if (!(ts.isCallExpression(node) && node.expression.getText().endsWith('Router'))) {+ return;+ }+ const literal = objectLiteralOf(node);+ for (const property of literal?.properties ?? []) {+ if (+ ts.isPropertyAssignment(property) &&+ ts.isIdentifier(property.name) &&+ ts.isIdentifier(property.initializer)+ ) {+ mounted.set(property.name.text, property.initializer.text);+ }+ }+ });++ const routers: {+ routerKey: string;+ source: ParsedSource;+ procedures: { name: string; line: number }[];+ }[] = [];++ for (const [routerKey, identifier] of mounted) {+ const path = importedFrom.get(identifier);+ const source = tree.core.find((candidate) => candidate.path === path);+ if (!source) {+ continue;+ }++ const procedures: { name: string; line: number }[] = [];+ visit(source.sourceFile, (node) => {+ if (+ !(+ ts.isVariableDeclaration(node) &&+ ts.isIdentifier(node.name) &&+ node.name.text === identifier &&+ node.initializer+ )+ ) {+ return;+ }+ for (const property of objectLiteralOf(node.initializer)?.properties ??+ []) {+ if (property.name && ts.isIdentifier(property.name)) {+ procedures.push({+ name: property.name.text,+ line: lineOf(source, property.getStart(source.sourceFile)),+ });+ }+ }+ });++ if (procedures.length > 0) {+ routers.push({ routerKey, source, procedures });+ }+ }++ return routers.sort((a, b) => a.routerKey.localeCompare(b.routerKey));+}++// --- rules --------------------------------------------------------------------++const reviewOnly = (label: string, hint: string): Metric => ({+ label,+ count: 0,+ target: null,+ offenders: [],+ note: hint,+});++function cruiserMetric(+ label: string,+ ruleName: string,+ cruiser: ReturnType<typeof runCruiser>,+ tree: Tree,+ filter?: (violation: { from: string; to: string }) => boolean+): Metric {+ if (!cruiser.available) {+ return {+ label,+ count: -1,+ target: 0,+ offenders: [],+ note: `UNAVAILABLE: ${cruiser.error}`,+ };+ }+ const violations = violationsOf(cruiser, ruleName).filter(+ (violation) => !filter || filter(violation)+ );+ return {+ label,+ count: violations.length,+ target: 0,+ offenders: violations.map((violation) => {+ // dependency-cruiser reports an edge, not a position; resolve it back to+ // the import that made it so the offender is a real file:line.+ const source = tree.core.find(+ (candidate) => candidate.path === violation.from+ );+ return {+ file: violation.from,+ line: source ? resolveImportLine(source, violation.to) : 0,+ detail: `-> ${violation.to} (${violation.rule})`,+ };+ }),+ };+}++/** A metric that restates edges another metric already asserted on. */+const asView = (metric: Metric): Metric => ({+ ...metric,+ target: null,+ note: [metric.note, 'A view of the rules above — already asserted there.']+ .filter(Boolean)+ .join('\n'),+});++function buildRules(tree: Tree): RuleBlock[] {+ const cruiser = runCruiser(tree.repoRoot);+ const routers = collectRouters(tree);+ const v1Compat = tree.core.find(+ (source) => source.path === CORE_V1_COMPAT_FILE+ );+ // Tests count: ADR-022's "69 importers" is what fix-wave step 2 has to move,+ // and a test importing v1-compat is as much a caller as a service is.+ const v1CompatImporters = tree.allCoreText.filter(({ path, text }) =>+ path !== CORE_V1_COMPAT_FILE && V1_COMPAT_IMPORT.test(text)+ ).length;++ return [+ {+ id: 'R1',+ title:+ 'A module is a directory under src/modules/ holding only what it needs',+ asserted: false,+ metrics: [checkModuleLayout(tree.moduleNames, tree.moduleRootFiles)],+ },+ {+ id: 'R2',+ title: 'Take only the transports that have callers',+ asserted: false,+ metrics: [checkRpcProceduresWithoutCallers(routers, tree.startText)],+ },+ {+ id: 'R3',+ title:+ 'services.ts is the composition root: (deps: ServiceDeps, services: () => Services)',+ asserted: true,+ metrics: [checkFactorySignatures(tree.core)],+ },+ {+ id: 'R4',+ title: 'Declare functions first, then `return { one, two, three }`',+ asserted: false,+ metrics: [checkFactoryReturnShape(tree.core)],+ },+ {+ id: 'R5',+ title:+ 'Services members are ReturnType<typeof createXService>; no hand-written XService interface',+ asserted: true,+ metrics: [+ checkServiceInterfaces(tree.core),+ checkServicesMembers(tree.core),+ ],+ },+ {+ id: 'R6',+ title: 'The graph is rebuilt per unit of work; there is no "no context" path',+ asserted: true,+ metrics: [+ checkCreateServicesCallSites([...tree.core, ...tree.api]),+ checkDependencyLoaders(tree.core),+ ],+ note: v1Compat+ ? `v1-compat.ts: ${v1Compat.text.replace(/\n$/, '').split('\n').length} lines, ${v1CompatImporters} importers (tests included) — the headline numbers for fix-wave step 2. ADR-022 measured 2,104 lines / 69 importers at 6694c5b7 on 2026-09-07.`+ : undefined,+ },+ {+ id: 'R7',+ title: 'Nothing but the config loader reads process.env',+ asserted: true,+ metrics: checkEnvReads(tree.core),+ },+ {+ id: 'R9',+ title: 'Clients are transports: config in, typed result or ProviderError out, no logger',+ asserted: false,+ metrics: [+ reviewOnly(+ 'client shape',+ 'Review rule (ADR-022 check line: "review"). Read packages/core/src/clients/*: no logger, built once at boot, a missing thing is null.',+ ),+ ],+ },+ {+ id: 'R10',+ title: 'Access checks live in the auth service and the builders',+ asserted: true,+ metrics: [checkAccessChecks(tree.core)],+ },+ {+ id: 'R11',+ title: 'A .jobs.ts declares and constructs nothing',+ asserted: false,+ metrics: [+ reviewOnly(+ 'job file shape',+ 'Review rule (ADR-022 check line: "review + ADR-021"). See R18 below for the one mechanical half.',+ ),+ ],+ },+ {+ id: 'R12',+ title: 'Frontends import one thing, as a type: AppRouter',+ asserted: true,+ metrics: [+ cruiserMetric(+ `${CRUISER_FRONTEND_RULE_NAME} violations (delegated to dependency-cruiser)`,+ CRUISER_FRONTEND_RULE_NAME,+ cruiser,+ tree+ ),+ ],+ },+ {+ id: 'R13',+ title: 'index.ts exports what the app shell needs and nothing else',+ asserted: false,+ metrics: [+ reviewOnly(+ 'index.ts and main.ts shape',+ 'Review rule (ADR-022 check line: "review of index.ts and main.ts").',+ ),+ ],+ },+ {+ id: 'R14',+ title: 'Dead prefixes and dead names go',+ asserted: true,+ metrics: checkResidue(tree.residueFiles),+ },+ {+ id: 'R15',+ title: 'Core declares, the app constructs',+ asserted: true,+ metrics: [checkModuleScopeConstruction(tree.core)],+ },+ {+ id: 'R16',+ title: 'Whoever opens a connection closes it, and shutdown reverses open',+ asserted: false,+ metrics: [+ reviewOnly(+ 'lifecycle',+ 'Review rule (ADR-022 check line: "main.ts shutdown order vs open order; core does not close handed-in connections").',+ ),+ ],+ },+ {+ id: 'R17',+ title: 'The config loader has a shape',+ asserted: false,+ metrics: [checkConfigLoaderShape(tree.configEnv)],+ },+ {+ id: 'R18',+ title: 'Job payload discipline',+ asserted: false,+ metrics: [checkJobPayloadDates(tree.core)],+ },+ {+ id: 'R19',+ title: 'ProviderError.retryable is load-bearing',+ asserted: false,+ metrics: [+ reviewOnly(+ 'provider error handling',+ 'Review rule (ADR-022 check line: "review of every job-handler catch around a client call").',+ ),+ ],+ },+ {+ id: 'R21',+ title: 'Dumb utilities live below every package',+ asserted: true,+ metrics: [+ checkSharedPackageIsolation(tree.repoRoot),+ checkDuplicateUtilities(tree.utilityPaths),+ ],+ },+ {+ id: 'R22',+ title: 'Layers only import downward — by layer, not by path depth',+ asserted: true,+ metrics: [+ ...CRUISER_LAYER_RULE_NAMES.map((ruleName) =>+ cruiserMetric(+ `${ruleName} violations (delegated to dependency-cruiser)`,+ ruleName,+ cruiser,+ tree+ )+ ),+ // The two slices ADR-022's baseline table states (7 and 8). They are+ // VIEWS of the rules above, not extra violations, so they carry no+ // target: asserting on them would count the same edges twice.+ asView(+ cruiserMetric(+ 'ADR-022 baseline slice: shared/ -> above it',+ R22_SHARED_UPWARD_RULE,+ cruiser,+ tree+ )+ ),+ asView(+ cruiserMetric(+ 'ADR-022 baseline slice: http/*, rpc/base.ts -> modules/*/src/*',+ R22_TRANSPORT_UPWARD_RULE,+ cruiser,+ tree,+ (violation) =>+ R22_TRANSPORT_UPWARD_FROM.test(violation.from) &&+ R22_TRANSPORT_UPWARD_TO.test(violation.to)+ )+ ),+ ],+ note: cruiser.available+ ? 'M14-002 landed these rules and verified cruiser resolves its typescript peer, so R22 is the cruiser rule, not ADR-022\'s grep fallback. A bare ../ depth grep is forbidden: a module importing defineJob at ../../jobs/define is importing DOWNWARD.'+ : undefined,+ },+ // R20 (test shapes) is deferred by Carl, 2026-09-08, and is deliberately+ // absent from this gate. Do not add it.+ ];+}++// --- formatting ---------------------------------------------------------------++const offenderLine = (offender: Offender): string =>+ offender.line > 0+ ? ` ${offender.file}:${offender.line} ${offender.detail}`+ : ` ${offender.file} ${offender.detail}`;++function renderMetric(metric: Metric, lines: string[]): void {+ const target =+ metric.target === null ? 'reported only' : `target ${metric.target}`;+ const count = metric.count < 0 ? 'UNAVAILABLE' : String(metric.count);+ lines.push(` ${metric.label}`);+ lines.push(` count ${count}, ${target}`);++ if (metric.note) {+ for (const noteLine of metric.note.split('\n')) {+ lines.push(` # ${noteLine}`);+ }+ }++ const shown = metric.offenders.slice(0, MAX_OFFENDERS_PRINTED);+ for (const offender of shown) {+ lines.push(offenderLine(offender));+ }+ if (metric.offenders.length > shown.length) {+ lines.push(+ ` ... and ${metric.offenders.length - shown.length} more offender(s)`+ );+ }+ lines.push('');+}++/**+ * An ASSERTED rule totals its asserted metrics; a REPORT rule totals its hints.+ * Printing `TOTAL R1: 0` beside five listed offenders would read as a pass.+ */+function ruleTotal(rule: RuleBlock): number {+ return rule.metrics+ .filter((metric) => rule.asserted === (metric.target !== null))+ .reduce((sum, metric) => sum + Math.max(metric.count, 0), 0);+}++function metricIsAboveTarget(metric: Metric): boolean {+ if (metric.target === null) {+ return false;+ }+ // A delegated check that could not run counts as a failure, not as zero.+ return metric.count < 0 || metric.count > metric.target;+}++/**+ * The headline numbers, up top, so the ADR-022 baseline table can be checked+ * against this run without scrolling 700 lines. Each entry names the rule and+ * the metric it comes from; the numbers themselves come from the same Metric+ * objects the blocks below print, never from a second measurement.+ */+const BASELINE_METRICS: readonly { rule: string; metric: number; label: string }[] =+ [+ { rule: 'R3', metric: 0, label: 'factories not on (deps, services)' },+ { rule: 'R5', metric: 0, label: 'hand-written XService interfaces' },+ { rule: 'R5', metric: 1, label: 'Services members NOT typed by ReturnType (see the block for how many DO)' },+ { rule: 'R6', metric: 0, label: 'unsanctioned createServices( call sites' },+ { rule: 'R6', metric: 1, label: 'load* dependency loaders' },+ { rule: 'R7', metric: 0, label: 'process.env.<name> reads in core' },+ { rule: 'R10', metric: 0, label: 'require* defs outside the auth stack' },+ { rule: 'R14', metric: 0, label: 'NEXT_PUBLIC_ in core' },+ { rule: 'R15', metric: 0, label: 'module-scope construction in core' },+ { rule: 'R21', metric: 1, label: 'duplicate util copies' },+ { rule: 'R22', metric: 6, label: 'upward imports: shared/ -> above' },+ { rule: 'R22', metric: 7, label: 'upward imports: transport -> module src' },+ ];++function renderBaseline(rules: RuleBlock[], lines: string[]): void {+ lines.push('BASELINE REPRODUCTION (ADR-022 / CONFORMANCE_GATE_SPEC.md)');+ lines.push('');+ for (const entry of BASELINE_METRICS) {+ const metric = rules.find((rule) => rule.id === entry.rule)?.metrics[+ entry.metric+ ];+ if (!metric) {+ continue;+ }+ const count = metric.count < 0 ? 'UNAVAILABLE' : String(metric.count);+ lines.push(` ${entry.rule.padEnd(RULE_ID_WIDTH)} ${count.padStart(4)} ${entry.label}`);+ }+ lines.push('');+}++export function renderReport(rules: RuleBlock[]): string {+ const lines: string[] = [+ heavy,+ 'OpenPanel conformance gate (ADR-022) — report',+ heavy,+ '',+ 'Rules R1..R22 in order. ASSERT rules fail `--assert` above their target;',+ 'REPORT rules are review rules and are printed as hints only. R20 is',+ 'deferred by Carl (2026-09-08) and is absent by design.',+ '',+ ];++ renderBaseline(rules, lines);++ let assertedTotal = 0;+ for (const rule of rules) {+ const mode = rule.asserted ? 'ASSERT' : 'REPORT';+ lines.push(light);+ lines.push(`${rule.id.padEnd(RULE_ID_WIDTH)} ${mode} ${rule.title}`);+ lines.push(light);+ if (rule.note) {+ for (const noteLine of rule.note.split('\n')) {+ lines.push(` # ${noteLine}`);+ }+ lines.push('');+ }+ for (const metric of rule.metrics) {+ renderMetric(metric, lines);+ }+ const total = ruleTotal(rule);+ lines.push(+ ` TOTAL ${rule.id}: ${total}${rule.asserted ? '' : ' (reported, not asserted)'}`+ );+ lines.push('');+ if (rule.asserted) {+ assertedTotal += total;+ }+ }++ lines.push(heavy);+ lines.push(`TOTAL asserted violations: ${assertedTotal}`);+ lines.push(heavy);+ return lines.join('\n');+}++export function renderAssert(rules: RuleBlock[]): {+ output: string;+ failed: boolean;+} {+ const lines: string[] = [];+ let failures = 0;++ for (const rule of rules) {+ if (!rule.asserted) {+ continue;+ }+ const above = rule.metrics.filter(metricIsAboveTarget);+ if (above.length === 0) {+ continue;+ }+ lines.push(light);+ lines.push(`${rule.id.padEnd(RULE_ID_WIDTH)} FAIL ${rule.title}`);+ lines.push(light);+ for (const metric of above) {+ renderMetric(metric, lines);+ failures += Math.max(metric.count, 1);+ }+ lines.push(` TOTAL ${rule.id}: ${ruleTotal(rule)}`);+ lines.push('');+ }++ if (failures === 0) {+ return {+ output: 'OK: every asserted ADR-022 rule is at its target.',+ failed: false,+ };+ }++ lines.unshift(+ heavy,+ 'OpenPanel conformance gate (ADR-022) — assert FAILED',+ heavy,+ ''+ );+ lines.push(heavy);+ lines.push(`FAIL: ${failures} asserted ADR-022 violation(s).`);+ lines.push(heavy);+ return { output: lines.join('\n'), failed: true };+}++// --- entrypoint ---------------------------------------------------------------++/**+ * `conformance.sh --report | grep -q 36` closes the pipe on the first match and+ * the remaining ~700 lines land on a dead fd. Without this the gate prints an+ * EPIPE stack over an otherwise successful run.+ */+process.stdout.on('error', (error: NodeJS.ErrnoException) => {+ if (error.code !== 'EPIPE') {+ throw error;+ }+});++const [, , mode, repoRootArgument] = process.argv;+const repoRoot = repoRootArgument ?? process.cwd();+const rules = buildRules(collect(repoRoot));++if (mode === '--assert') {+ const { output, failed } = renderAssert(rules);+ process.stdout.write(`${output}\n`);+ process.exit(failed ? 1 : 0);+}++process.stdout.write(`${renderReport(rules)}\n`);diff --git a/tooling/gates/conformance/conformance.constants.ts b/tooling/gates/conformance/conformance.constants.tsnew file mode 100644index 000000000..93e75c83d--- /dev/null+++ b/tooling/gates/conformance/conformance.constants.ts@@ -0,0 +1,187 @@+/**+ * Every path, allowlist and threshold the conformance checks read.+ *+ * They live here rather than inline because two of them are load-bearing+ * carve-outs a reader has to be able to audit without reading the checks:+ * ASSET_LOADER_ALLOWLIST and SANCTIONED_CREATE_SERVICES_SITES, both R6.+ */++/** The tree ADR-022 governs. Paths everywhere are repo-relative POSIX. */+export const CORE_SOURCE_ROOT = 'packages/core/src';+export const CORE_SERVICES_FILE = 'packages/core/src/services.ts';+export const CORE_V1_COMPAT_FILE = 'packages/core/src/v1-compat.ts';+export const API_SOURCE_ROOT = 'apps/api/src';++/** Directories a source walk never descends into. */+export const IGNORED_DIRECTORY_NAMES = new Set([+ 'node_modules',+ 'dist',+ 'build',+ '.output',+ '.vinxi',+ 'generated',+]);++/**+ * R6 — the only files that may call `createServices(`. ADR-022 R15 names them+ * exhaustively: the composition root itself, the context builder every+ * transport goes through, the routes' lazy builder, the jobs runtime, and the+ * app's boot. A file outside this list is an offender.+ */+export const SANCTIONED_CREATE_SERVICES_SITES: readonly string[] = [+ 'packages/core/src/services.ts',+ 'packages/core/src/context.ts',+ 'packages/core/src/http/define.ts',+ 'packages/core/src/jobs/workers.ts',+ 'apps/api/src/main.ts',+];++/**+ * R6 — the asset-loader carve-out, and the reason for each entry.+ *+ * ADR-022: "Lazy-load assets, never dependencies." Reading a file or a row on+ * first use is data loading and is legal; lazily importing a sibling service or+ * a db/ch/redis handle the caller was already handed is the defect the rule+ * exists to remove.+ *+ * This is an ALLOWLIST of exact `file::function` pairs, deliberately NOT a+ * pattern. A pattern ("loaders that touch the filesystem", "loaders under+ * clients/") would let the next `loadWhatever` join the carve-out by accident,+ * which is how 55 loaders happened in the first place. Adding an entry here is+ * an edit a reviewer sees.+ */+export const ASSET_LOADER_ALLOWLIST: readonly {+ file: string;+ functionName: string;+ reason: string;+}[] = [+ // geo.ts reads a MaxMind .mmdb file from disk on first use. That is an ASSET+ // load: no sibling service, no db/ch/redis handle, nothing the caller already+ // holds. ADR-022 names it as one of the two legitimate cases.+ {+ file: 'packages/core/src/clients/geo.ts',+ functionName: 'loadDatabase',+ reason:+ 'reads a MaxMind .mmdb file from disk on first use - an asset, not a dependency',+ },+ // flush-exports.ts reads an export cursor ROW on first use. Also data, and it+ // reads it through the db handle it was already handed rather than importing+ // one. ADR-022 names it as the second legitimate case.+ {+ file: 'packages/core/src/modules/integration/src/flush-exports.ts',+ functionName: 'loadCursor',+ reason:+ 'reads an export cursor row on first use - data, not a dependency; the db handle it reads through is the one it was handed',+ },+];++/**+ * R10 — where the access checks are allowed to live. ADR-022: "Access checks+ * live in the auth service and the builders, never per rpc file."+ */+export const AUTH_STACK_PATHS: readonly string[] = [+ 'packages/core/src/rpc/base.ts',+ 'packages/core/src/modules/auth/',+];++/** R10 — the four names ADR-022's check line enumerates. */+export const ACCESS_CHECK_FUNCTION_NAMES = new Set([+ 'requireLogin',+ 'requireReadAccess',+ 'requireWriteAccess',+ 'requireAccess',+]);++/** R14 — the prefix, and the one app allowed to keep it. */+export const NEXT_PUBLIC_PREFIX = 'NEXT_PUBLIC_';+export const NEXT_PUBLIC_ALLOWED_ROOT = 'apps/public/';++/** R14 — residue markers that must not survive the rewrite. */+export const RESIDUE_PATTERNS: readonly { label: string; pattern: RegExp }[] = [+ { label: 'NEXT_PUBLIC_ prefix', pattern: /NEXT_PUBLIC_/ },+ // \b so `fika` matches the template's name and not, say, `fikan` in prose.+ { label: 'fika template residue', pattern: /\bfika\b/i },+ { label: '_deprecated marker', pattern: /_deprecated/ },+];++/**+ * R15 — constructors that open a connection or build a client. A `new` of one+ * of these, or a call to one of the factory names, at MODULE scope is the+ * violation; inside a factory body it is exactly what core is supposed to do.+ */+export const CONNECTION_CONSTRUCTOR_NAMES = new Set([+ 'Redis',+ 'RedisClient',+ 'Cluster',+ 'PrismaClient',+ 'ClickHouseClient',+ 'S3Client',+ 'Kafka',+ 'Queue',+ 'Worker',+ 'QueueEvents',+ 'WebSocket',+]);+export const CONNECTION_FACTORY_NAME_PATTERN =+ /^create(?:[A-Z][A-Za-z]*)?(?:Client|Connection|Redis|Db|Pool)$/;++/**+ * R21 — util basenames that are the same helper under two names. `super-json`+ * in apps/start is core's `shared/json`; without the alias a basename check+ * reads them as two unrelated files and undercounts the duplication by one.+ */+export const UTIL_BASENAME_ALIASES = new Map([['super-json', 'json']]);++/**+ * R21 — where a "dumb utility" lives today: an app's `src/utils/`, core's+ * `shared/` drawer, or a package's own top level (`packages/redis/json.ts`).+ */+export const UTIL_DIRECTORY_PATTERNS: readonly RegExp[] = [+ /^apps\/[^/]+\/src\/utils\/[^/]+\.ts$/,+ /^packages\/core\/src\/shared\/[^/]+\.ts$/,+ /^packages\/[^/]+\/[^/]+\.ts$/,+];++/**+ * R21 — a package's entrypoint is not a utility. Every package has one, so+ * without this the basename check reports six `index.ts` "duplicates" and buries+ * the five real copies.+ */+export const UTIL_BASENAME_EXCLUSIONS = new Set(['index', 'types', 'constants']);++/** R21 — the package ADR-022's C7 chore will create. Absent today. */+export const SHARED_PACKAGE_NAME = '@openpanel/shared';+export const SHARED_PACKAGE_ROOT = 'packages/shared';++/**+ * R22 — delegated to dependency-cruiser: M14-002 landed the layer rules and the+ * peer-resolution verification passed, so ADR-022's grep fallback is not in+ * play. These are the rule names whose violation counts this gate reports.+ */+export const CRUISER_LAYER_RULE_NAMES: readonly string[] = [+ 'core-layers-shared-is-the-bottom',+ 'core-layers-clients-below-transport',+ 'core-layers-transport-below-modules',+ 'core-layers-modules-below-composition',+ 'core-layers-composition-below-registries',+ 'core-layers-registries-below-index',+];++/** R12 — delegated to the cruiser rule ADR-008 already ships. */+export const CRUISER_FRONTEND_RULE_NAME = 'frontend-values-only-constants';++/**+ * R22 — the two slices ADR-022's baseline table states (7 and 8). They are+ * narrower than the cruiser rules that produce them, so the gate prints both:+ * the cruiser's own per-rule count (the delegated number) and the baseline+ * slice, computed from the cruiser's own edges rather than re-derived.+ */+export const R22_SHARED_UPWARD_RULE = 'core-layers-shared-is-the-bottom';+export const R22_TRANSPORT_UPWARD_RULE = 'core-layers-transport-below-modules';+export const R22_TRANSPORT_UPWARD_FROM =+ /^packages\/core\/src\/(?:http\/|rpc\/base\.ts)/;+export const R22_TRANSPORT_UPWARD_TO =+ /^packages\/core\/src\/modules\/[^/]+\/src\//;++/** How many offenders a report block prints before summarising the rest. */+export const MAX_OFFENDERS_PRINTED = 400;diff --git a/tooling/gates/conformance/cruiser.ts b/tooling/gates/conformance/cruiser.tsnew file mode 100644index 000000000..3fd238261--- /dev/null+++ b/tooling/gates/conformance/cruiser.ts@@ -0,0 +1,153 @@+/**+ * R12 and R22 are delegated to dependency-cruiser, not reimplemented here.+ *+ * M14-002 made `dependency-cruiser` a declared root devDependency, verified that+ * it resolves its optional `typescript` peer (the 82-false-violation failure+ * ADR-022 made R22 conditional on), and landed the layer rules in+ * .dependency-cruiser.cjs. So this module runs the cruise and reports its+ * per-rule violation counts. ADR-022's layer-aware fallback in this gate is not+ * in play; a bare `../` depth grep is forbidden either way, because a module+ * importing `defineJob` at `../../jobs/define` is importing DOWNWARD.+ *+ * If the cruise cannot run, that is a hard failure: a delegated check that+ * silently reports zero is worse than no check.+ */++import { spawnSync } from 'node:child_process';+import { dirname, join, posix } from 'node:path';+import * as ts from 'typescript';++import { lineOf, type ParsedSource, visit } from './sources';++const CRUISER_BINARY = 'node_modules/.bin/depcruise';+const CRUISER_CONFIG = '.dependency-cruiser.cjs';+/** The same targets `bun run check:deps` cruises. */+const CRUISER_TARGETS = ['apps/start', 'packages'];+const CRUISER_OUTPUT_BYTES = 256 * 1024 * 1024;++export interface CruiserViolation {+ rule: string;+ from: string;+ to: string;+}++export interface CruiserResult {+ available: boolean;+ error?: string;+ violations: CruiserViolation[];+}++export function runCruiser(repoRoot: string): CruiserResult {+ const binary = join(repoRoot, CRUISER_BINARY);+ const run = spawnSync(+ binary,+ [+ '--config',+ CRUISER_CONFIG,+ '--output-type',+ 'json',+ '--no-progress',+ ...CRUISER_TARGETS,+ ],+ { cwd: repoRoot, encoding: 'utf8', maxBuffer: CRUISER_OUTPUT_BYTES }+ );++ if (run.error || !run.stdout) {+ return {+ available: false,+ error: `${binary} did not run: ${run.error?.message ?? run.stderr?.trim() ?? 'no output'}`,+ violations: [],+ };+ }++ let parsed: {+ summary?: { violations?: { rule: { name: string }; from: string; to: string }[] };+ };+ try {+ parsed = JSON.parse(run.stdout);+ } catch (error) {+ return {+ available: false,+ error: `could not parse the cruise output: ${(error as Error).message}`,+ violations: [],+ };+ }++ return {+ available: true,+ violations: (parsed.summary?.violations ?? [])+ .map((violation) => ({+ rule: violation.rule.name,+ from: violation.from,+ to: violation.to,+ }))+ .sort(+ (a, b) =>+ a.rule.localeCompare(b.rule) ||+ a.from.localeCompare(b.from) ||+ a.to.localeCompare(b.to)+ ),+ };+}++export function violationsOf(+ result: CruiserResult,+ ruleName: string+): CruiserViolation[] {+ return result.violations.filter((violation) => violation.rule === ruleName);+}++/** The forms a specifier can take once the extension is dropped. */+const RESOLVED_SUFFIXES = ['.ts', '.tsx', '/index.ts', '/index.tsx', ''];++/**+ * The line of the import that produced a cruiser violation.+ *+ * dependency-cruiser reports an EDGE (`from` -> `to`), not a position, and this+ * gate promises every offender as `file:line`. So the edge is resolved back to+ * the import statement that made it: parse `from`, resolve each relative+ * specifier against its own directory, and take the first one that lands on+ * `to`. Returns 0 when the specifier is not relative (an aliased or package+ * import), which the report renders as a bare path rather than inventing a line.+ */+export function resolveImportLine(+ source: ParsedSource,+ to: string+): number {+ const directory = dirname(source.path);+ let line = 0;++ visit(source.sourceFile, (node) => {+ if (line > 0) {+ return;+ }+ const specifier = importSpecifierOf(node);+ if (!specifier?.text.startsWith('.')) {+ return;+ }+ const resolved = posix.normalize(posix.join(directory, specifier.text));+ if (RESOLVED_SUFFIXES.some((suffix) => `${resolved}${suffix}` === to)) {+ line = lineOf(source, node.getStart(source.sourceFile));+ }+ });++ return line;+}++function importSpecifierOf(node: ts.Node): ts.StringLiteral | undefined {+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {+ return node.moduleSpecifier;+ }+ if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {+ return node.moduleSpecifier;+ }+ if (+ ts.isCallExpression(node) &&+ node.expression.kind === ts.SyntaxKind.ImportKeyword &&+ node.arguments[0] &&+ ts.isStringLiteral(node.arguments[0])+ ) {+ return node.arguments[0];+ }+ return undefined;+}diff --git a/tooling/gates/conformance/rules.test.ts b/tooling/gates/conformance/rules.test.tsnew file mode 100644index 000000000..00aea9a0a--- /dev/null+++ b/tooling/gates/conformance/rules.test.ts@@ -0,0 +1,237 @@+/**+ * The gate's own tests.+ *+ * Two of them are mandatory, and they are the reason this gate parses TypeScript+ * instead of grepping. Both traps were measured against `packages/core/src` on+ * 2026-09-08 and both make a naive gate report the wrong number:+ *+ * trap 1 `rg 'export function create[A-Za-z]+Service\(deps'` finds 28 of the+ * 36 factories, because eight signatures span lines.+ * trap 2 `rg -o 'ReturnType<typeof create' services.ts` matches once and the+ * match is a COMMENT at services.ts:154; the pattern is applied in+ * code zero times.+ *+ * The fixtures below contain exactly those shapes. A regression that reverts a+ * check to a line-oriented match fails here.+ */++import { describe, expect, test } from 'bun:test';++import { ASSET_LOADER_ALLOWLIST } from './conformance.constants';+import {+ checkCreateServicesCallSites,+ checkDependencyLoaders,+ checkFactorySignatures,+ checkServicesMembers,+ collectEnvReads,+} from './rules';+import { parseSource } from './sources';++const NAIVE_FACTORY_GREP = /export function create[A-Za-z]+Service\(deps/g;+const NAIVE_RETURN_TYPE_GREP = /ReturnType<typeof create/g;++const matchCount = (text: string, pattern: RegExp): number =>+ (text.match(pattern) ?? []).length;++describe('trap 1 — a factory signature that spans lines', () => {+ // Three factories: one on a single line, one whose argument list starts on the+ // next line, and one already conformant. A line-oriented grep sees one.+ const source = `+import type { ServiceDeps, Services } from '../../services';++export function createOneLineService(deps: ServiceDeps) {+ return { a: () => deps };+}++export function createWrappedService(+ deps: ServiceDeps+) {+ return { b: () => deps };+}++export function createConformantService(+ deps: ServiceDeps,+ services: () => Services+) {+ return { c: () => services() };+}+`;++ test('the naive grep undercounts, which is why it is not the check', () => {+ expect(matchCount(source, NAIVE_FACTORY_GREP)).toBe(1);+ });++ test('the AST check sees all three factories', () => {+ const metric = checkFactorySignatures([+ parseSource('packages/core/src/modules/x/x.service.ts', source),+ ]);+ expect(metric.label).toContain('of 3');+ });++ test('it flags both non-conformant signatures, including the wrapped one', () => {+ const metric = checkFactorySignatures([+ parseSource('packages/core/src/modules/x/x.service.ts', source),+ ]);+ expect(metric.count).toBe(2);+ expect(metric.offenders.map((offender) => offender.detail)).toEqual([+ expect.stringContaining('createOneLineService'),+ expect.stringContaining('createWrappedService'),+ ]);+ });++ test('an arrow-function factory is counted too', () => {+ const arrows = `+import type { ServiceDeps } from '../../services';+export const createArrowService = (deps: ServiceDeps) => ({ a: () => deps });+`;+ const metric = checkFactorySignatures([+ parseSource('packages/core/src/modules/y/y.service.ts', arrows),+ ]);+ expect(metric.count).toBe(1);+ });+});++describe('trap 2 — ReturnType<typeof create...> in a comment', () => {+ // The comment is the shape of the real one at services.ts:154. One member is+ // typed by hand, one is typed the way R5 wants.+ const source = `+// Two type rules the compiler enforces but cannot explain:+//+// 1. \`Services\` must stay an INTERFACE. A type alias over+// \`ReturnType<typeof createServices>\` is circular — resolving it needs+// every factory's signature and every factory's signature names+// \`Services\`.+export interface Services {+ auth: AuthService;+ chart: ReturnType<typeof createChartService>;+}+`;++ test('the naive grep counts the comment as a compliant member', () => {+ // Two matches for one real member: the grep cannot tell them apart.+ expect(matchCount(source, NAIVE_RETURN_TYPE_GREP)).toBe(2);+ });++ test('the AST check ignores the comment and counts only the real member', () => {+ const metric = checkServicesMembers([+ parseSource('packages/core/src/services.ts', source),+ ]);+ expect(metric.label).toContain('1 of 2');+ expect(metric.count).toBe(1);+ expect(metric.offenders[0].detail).toContain('auth: AuthService');+ });++ test('a file whose only match is the comment scores zero compliant members', () => {+ const commentOnly = `+// \`ReturnType<typeof createServices>\` is circular.+export interface Services {+ auth: AuthService;+}+`;+ const metric = checkServicesMembers([+ parseSource('packages/core/src/services.ts', commentOnly),+ ]);+ expect(matchCount(commentOnly, NAIVE_RETURN_TYPE_GREP)).toBe(1);+ expect(metric.label).toContain('0 of 1');+ });+});++describe('R6 — the asset-loader carve-out is an allowlist, not a pattern', () => {+ const geo = parseSource(+ 'packages/core/src/clients/geo.ts',+ 'async function loadDatabase(filename: string) { return filename; }\n'+ );+ const flushExports = parseSource(+ 'packages/core/src/modules/integration/src/flush-exports.ts',+ 'async function loadCursor(id: string) { return id; }\n'+ );++ test('the two allowlisted asset loaders are not offenders', () => {+ const metric = checkDependencyLoaders([geo, flushExports]);+ expect(metric.count).toBe(0);+ expect(metric.label).toContain('0 of 2 load* functions');+ });++ test('the allowlist is exactly the two ADR-022 names, each with a reason', () => {+ expect(ASSET_LOADER_ALLOWLIST.map((entry) => entry.file)).toEqual([+ 'packages/core/src/clients/geo.ts',+ 'packages/core/src/modules/integration/src/flush-exports.ts',+ ]);+ for (const entry of ASSET_LOADER_ALLOWLIST) {+ expect(entry.reason.length).toBeGreaterThan(0);+ }+ });++ test('a NEW loader cannot join the allowlist by looking like one', () => {+ const impostor = parseSource(+ 'packages/core/src/modules/other/src/thing.ts',+ 'async function loadDatabase() { return null; }\n'+ );+ const metric = checkDependencyLoaders([impostor]);+ expect(metric.count).toBe(1);+ });++ test('the same name in the WRONG file is still an offender', () => {+ const wrongFile = parseSource(+ 'packages/core/src/clients/geo-other.ts',+ 'async function loadCursor() { return null; }\n'+ );+ expect(checkDependencyLoaders([wrongFile]).count).toBe(1);+ });+});++describe('R6 — createServices call sites', () => {+ test('a call in a comment or a string is not a call site', () => {+ const source = parseSource(+ 'packages/core/src/modules/x/x.service.ts',+ `+// createServices( is built once per unit of work.+const documentation = 'call createServices( only at the sanctioned sites';+`+ );+ expect(checkCreateServicesCallSites([source]).count).toBe(0);+ });++ test('a real call outside the sanctioned sites is an offender', () => {+ const source = parseSource(+ 'packages/core/src/v1-compat.ts',+ 'const services = createServices(deps);\n'+ );+ expect(checkCreateServicesCallSites([source]).count).toBe(1);+ });++ test('the same call inside a sanctioned site is not', () => {+ const source = parseSource(+ 'packages/core/src/context.ts',+ 'const services = createServices(deps);\n'+ );+ expect(checkCreateServicesCallSites([source]).count).toBe(0);+ });+});++describe('R7 — process.env forms a `process.env.` grep gets wrong', () => {+ const source = parseSource(+ 'packages/core/src/shared/get-client-ip.ts',+ `+// core reads no process.env.+const a = process.env.PLAIN;+const b = process.env?.OPTIONAL;+const c = process.env['BRACKETED'];+`+ );++ test('the comment is not a read and the optional-chained one is', () => {+ const { dotted, bracketed } = collectEnvReads([source]);+ expect(dotted.map((offender) => offender.detail)).toEqual([+ 'process.env.PLAIN',+ 'process.env.OPTIONAL',+ ]);+ expect(bracketed).toHaveLength(1);+ });++ test('the naive grep gets a different answer to the AST', () => {+ const grepped = matchCount(source.text, /process\.env\./g);+ // One comment counted, one `process.env?.` missed, one `process.env[` missed.+ expect(grepped).toBe(2);+ });+});diff --git a/tooling/gates/conformance/rules.ts b/tooling/gates/conformance/rules.tsnew file mode 100644index 000000000..2e02b70c2--- /dev/null+++ b/tooling/gates/conformance/rules.ts@@ -0,0 +1,898 @@+/**+ * The ADR-022 conformance checks.+ *+ * Every check is a pure function over already-parsed sources, so the gate's own+ * tests can run it against a fixture string. That is not decoration: the two+ * miscount traps in docs/CONFORMANCE_GATE_SPEC.md can only be proven covered by+ * feeding a check a source that contains them.+ *+ * Where a grep would lie, the check walks the TypeScript AST:+ *+ * R3 a factory signature can span lines, so the argument list is not on the+ * `export function` line. `rg 'create[A-Za-z]+Service\(deps'` saw 28 of+ * 36 on 2026-09-08.+ * R5 `ReturnType<typeof create` appears once in services.ts and the match is+ * a COMMENT (services.ts:154) explaining the circularity rule. The+ * pattern is applied in code zero times.+ * R6 `createServices(` in a comment or a string is not a call site.+ * R7 `rg 'process\.env\.'` both over- and under-counts: rpc/base.ts:246 is a+ * comment saying core reads no process.env, and get-client-ip.ts:83 is a+ * real read written `process.env?.` that the pattern misses.+ * R15 `new Redis(` inside a factory body is exactly what core is supposed to+ * do; at module scope it is the violation. Only scope tells them apart.+ */++import { existsSync, readFileSync } from 'node:fs';+import { basename, join } from 'node:path';++import {+ ACCESS_CHECK_FUNCTION_NAMES,+ ASSET_LOADER_ALLOWLIST,+ AUTH_STACK_PATHS,+ CONNECTION_CONSTRUCTOR_NAMES,+ CONNECTION_FACTORY_NAME_PATTERN,+ CORE_SERVICES_FILE,+ CORE_SOURCE_ROOT,+ NEXT_PUBLIC_ALLOWED_ROOT,+ NEXT_PUBLIC_PREFIX,+ RESIDUE_PATTERNS,+ SANCTIONED_CREATE_SERVICES_SITES,+ SHARED_PACKAGE_NAME,+ SHARED_PACKAGE_ROOT,+ UTIL_BASENAME_ALIASES,+ UTIL_BASENAME_EXCLUSIONS,+ UTIL_DIRECTORY_PATTERNS,+} from './conformance.constants';+import {+ isAtModuleScope,+ isExported,+ lineOf,+ namedFunctions,+ type NamedFunction,+ type Offender,+ type ParsedSource,+ ts,+ visit,+} from './sources';++export interface Metric {+ label: string;+ count: number;+ /** `null` marks a reported-only metric: it has no pass/fail line. */+ target: number | null;+ offenders: Offender[];+ note?: string;+}++const SERVICE_FACTORY_NAME = /^create[A-Z][A-Za-z]*Service$/;+const SERVICE_INTERFACE_NAME = /^[A-Z][A-Za-z]*Service$/;+const DEPENDENCY_LOADER_NAME = /^load[A-Z]/;+const SERVICE_DEPS_TYPE = 'ServiceDeps';+const SERVICES_TYPE = 'Services';+const SERVICES_INTERFACE_NAME = 'Services';+const CREATE_SERVICES_CALLEE = 'createServices';+const MODULE_ROOT_FILE = /^([a-z0-9-]+)\.(rpc|service|routes|jobs|constants)\.tsx?$/;++const byFileThenLine = (a: Offender, b: Offender): number =>+ a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1;++const sorted = (offenders: Offender[]): Offender[] =>+ [...offenders].sort(byFileThenLine);++const isUnder = (path: string, roots: readonly string[]): boolean =>+ roots.some((root) => path === root || path.startsWith(root));++// --- R3 -----------------------------------------------------------------------++const typeText = (node: ts.TypeNode | undefined): string =>+ node ? node.getText().replace(/\s+/g, ' ') : '<untyped>';++/** `services: () => Services`, in any of the ways that can be written. */+const isServicesThunk = (+ parameter: ts.ParameterDeclaration+): boolean => {+ const type = parameter.type;+ if (!(type && ts.isFunctionTypeNode(type))) {+ return false;+ }+ return (+ type.parameters.length === 0 &&+ ts.isTypeReferenceNode(type.type) &&+ type.type.typeName.getText() === SERVICES_TYPE+ );+};++const isServiceDeps = (+ parameter: ts.ParameterDeclaration+): boolean =>+ Boolean(+ parameter.type &&+ ts.isTypeReferenceNode(parameter.type) &&+ parameter.type.typeName.getText() === SERVICE_DEPS_TYPE+ );++export function serviceFactories(sources: ParsedSource[]): {+ source: ParsedSource;+ fn: NamedFunction;+}[] {+ const factories: { source: ParsedSource; fn: NamedFunction }[] = [];+ for (const source of sources) {+ for (const fn of namedFunctions(source)) {+ if (SERVICE_FACTORY_NAME.test(fn.name)) {+ factories.push({ source, fn });+ }+ }+ }+ return factories;+}++/** R3 — every factory is `(deps: ServiceDeps, services: () => Services)`. */+export function checkFactorySignatures(sources: ParsedSource[]): Metric {+ const factories = serviceFactories(sources);+ const offenders: Offender[] = [];++ for (const { source, fn } of factories) {+ const parameters = fn.declaration.parameters;+ const hasDeps = parameters.length >= 1 && isServiceDeps(parameters[0]);+ const hasThunk = parameters.length >= 2 && isServicesThunk(parameters[1]);+ if (hasDeps && hasThunk && parameters.length === 2) {+ continue;+ }++ const signature = parameters+ .map((parameter) => `${parameter.name.getText()}: ${typeText(parameter.type)}`)+ .join(', ');+ const missing = hasThunk+ ? 'first parameter is not ServiceDeps'+ : 'missing the `services: () => Services` thunk';+ offenders.push({+ file: source.path,+ line: lineOf(source, fn.anchor.getStart(source.sourceFile)),+ detail: `${fn.name}(${signature}) — ${missing}`,+ });+ }++ return {+ label: `createXService factories whose signature is not (deps: ServiceDeps, services: () => Services) — ${offenders.length} of ${factories.length}`,+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++// --- R5 -----------------------------------------------------------------------++/** R5a — no hand-written `export interface XService` outside services.ts. */+export function checkServiceInterfaces(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];++ for (const source of sources) {+ if (source.path === CORE_SERVICES_FILE) {+ continue;+ }+ visit(source.sourceFile, (node) => {+ if (+ ts.isInterfaceDeclaration(node) &&+ isExported(node) &&+ SERVICE_INTERFACE_NAME.test(node.name.text)+ ) {+ offenders.push({+ file: source.path,+ line: lineOf(source, node.name.getStart(source.sourceFile)),+ detail: `export interface ${node.name.text} — R5 types a service by ReturnType<typeof create${node.name.text}>, not by hand`,+ });+ }+ });+ }++ return {+ label: 'hand-written `export interface XService` outside services.ts',+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++const isReturnTypeOfFactory = (+ type: ts.TypeNode | undefined+): boolean => {+ if (!(type && ts.isTypeReferenceNode(type))) {+ return false;+ }+ if (type.typeName.getText() !== 'ReturnType') {+ return false;+ }+ const argument = type.typeArguments?.[0];+ return Boolean(+ argument &&+ ts.isTypeQueryNode(argument) &&+ SERVICE_FACTORY_NAME.test(argument.exprName.getText())+ );+};++/**+ * R5b — every member of the `Services` interface is typed+ * `ReturnType<typeof createXService>`, IN CODE.+ *+ * The trap: `rg -o 'ReturnType<typeof create' packages/core/src/services.ts`+ * returns 1, and that match is the comment at services.ts:154 explaining why+ * `ReturnType<typeof createServices>` is circular. The AST never sees a comment,+ * so this counts 0 today, which is the true number.+ */+export function checkServicesMembers(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];+ let members = 0;+ let conforming = 0;++ for (const source of sources) {+ visit(source.sourceFile, (node) => {+ if (+ !(+ ts.isInterfaceDeclaration(node) &&+ node.name.text === SERVICES_INTERFACE_NAME+ )+ ) {+ return;+ }+ for (const member of node.members) {+ if (!ts.isPropertySignature(member)) {+ continue;+ }+ members++;+ if (isReturnTypeOfFactory(member.type)) {+ conforming++;+ continue;+ }+ offenders.push({+ file: source.path,+ line: lineOf(source, member.getStart(source.sourceFile)),+ detail: `${member.name.getText()}: ${typeText(member.type)} — R5 wants ReturnType<typeof createXService>`,+ });+ }+ });+ }++ return {+ label: `Services members typed ReturnType<typeof createXService> in code (not comments) — ${conforming} of ${members}`,+ // The metric ADR-022's baseline states is the number of CONFORMING members;+ // the assert target is that every member conforms.+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ note: `${conforming} conforming member(s) of ${members}; baseline 2026-09-08 was 0`,+ };+}++// --- R6 -----------------------------------------------------------------------++/** R6a — `createServices(` only at the sanctioned construction sites. */+export function checkCreateServicesCallSites(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];++ for (const source of sources) {+ if (isUnder(source.path, SANCTIONED_CREATE_SERVICES_SITES)) {+ continue;+ }+ visit(source.sourceFile, (node) => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === CREATE_SERVICES_CALLEE+ ) {+ offenders.push({+ file: source.path,+ line: lineOf(source, node.getStart(source.sourceFile)),+ detail:+ 'createServices( outside the five sanctioned construction sites (ADR-022 R15)',+ });+ }+ });+ }++ return {+ label:+ 'files calling createServices( outside services.ts / context.ts / http/define.ts / jobs/workers.ts / apps/api/src/main.ts',+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++const allowedAssetLoader = (+ file: string,+ functionName: string+): { reason: string } | undefined =>+ ASSET_LOADER_ALLOWLIST.find(+ (entry) => entry.file === file && entry.functionName === functionName+ );++/**+ * R6b — no `load*` dependency loaders.+ *+ * The carve-out is the explicit ASSET_LOADER_ALLOWLIST, not a pattern: a loader+ * that reads a MaxMind database or a cursor row is loading DATA, and ADR-022+ * allows it. A loader that lazily imports a sibling service or a db/ch/redis+ * handle the caller already holds is the defect. Since nothing in the source+ * text reliably separates the two, the gate refuses to guess — a new loader has+ * to be added to the allowlist by hand, with a reason, in a diff a reviewer+ * reads.+ */+export function checkDependencyLoaders(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];+ let total = 0;+ const allowed: Offender[] = [];++ for (const source of sources) {+ for (const fn of namedFunctions(source)) {+ if (!DEPENDENCY_LOADER_NAME.test(fn.name)) {+ continue;+ }+ total++;+ const line = lineOf(source, fn.anchor.getStart(source.sourceFile));+ const carveOut = allowedAssetLoader(source.path, fn.name);+ if (carveOut) {+ allowed.push({+ file: source.path,+ line,+ detail: `${fn.name} — allowlisted asset loader: ${carveOut.reason}`,+ });+ continue;+ }+ offenders.push({+ file: source.path,+ line,+ detail: `${fn.name} — a lazy loader; R6 says the graph is rebuilt per unit of work and reached through deps/ctx`,+ });+ }+ }++ return {+ label: `load* dependency loaders, excluding the ${ASSET_LOADER_ALLOWLIST.length} allowlisted asset loaders — ${offenders.length} of ${total} load* functions`,+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ note: sorted(allowed)+ .map((entry) => `allowlisted: ${entry.file}:${entry.line} ${entry.detail}`)+ .join('\n'),+ };+}++// --- R7 -----------------------------------------------------------------------++const isProcessEnv = (node: ts.Node): boolean =>+ ts.isPropertyAccessExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === 'process' &&+ node.name.text === 'env';++export interface EnvReadSplit {+ dotted: Offender[];+ bracketed: Offender[];+}++/** R7 — every `process.env` read in core, split by the form it is written in. */+export function collectEnvReads(sources: ParsedSource[]): EnvReadSplit {+ const dotted: Offender[] = [];+ const bracketed: Offender[] = [];++ for (const source of sources) {+ visit(source.sourceFile, (node) => {+ if (ts.isPropertyAccessExpression(node) && isProcessEnv(node.expression)) {+ dotted.push({+ file: source.path,+ line: lineOf(source, node.getStart(source.sourceFile)),+ detail: `process.env.${node.name.text}`,+ });+ return;+ }+ if (ts.isElementAccessExpression(node) && isProcessEnv(node.expression)) {+ bracketed.push({+ file: source.path,+ line: lineOf(source, node.getStart(source.sourceFile)),+ detail: `process.env[${node.argumentExpression.getText()}]`,+ });+ }+ });+ }++ return { dotted: sorted(dotted), bracketed: sorted(bracketed) };+}++export function checkEnvReads(sources: ParsedSource[]): Metric[] {+ const { dotted, bracketed } = collectEnvReads(sources);+ const dottedFiles = new Set(dotted.map((offender) => offender.file));+ const bracketedFiles = new Set(bracketed.map((offender) => offender.file));+ const allFiles = new Set([...dottedFiles, ...bracketedFiles]);++ return [+ {+ label: `process.env.<name> reads in packages/core/src (non-test) — across ${dottedFiles.size} files`,+ count: dotted.length,+ target: 0,+ offenders: dotted,+ note:+ 'ADR-022 baseline 2026-09-08: 172 occurrences across 50 files, measured with `rg process\\.env\\.`.\n' ++ "That grep's file count is one high: rpc/base.ts:246 is a COMMENT saying core reads no process.env,\n" ++ 'and it misses shared/get-client-ip.ts:83, a real read written `process.env?.`. The two errors cancel\n' ++ 'in the occurrence count and do not in the file count, so the AST reads 172 across 49 files.',+ },+ {+ label: `process.env[...] reads in packages/core/src (non-test) — across ${bracketedFiles.size} files`,+ count: bracketed.length,+ target: 0,+ offenders: bracketed,+ note:+ 'The bracketed form is the same violation and no grep for `process.env.` sees it.\n' ++ `Both forms together: ${dotted.length + bracketed.length} reads across ${allFiles.size} files. R7's target is 0 of either.`,+ },+ ];+}++// --- R10 ----------------------------------------------------------------------++/** R10 — the access checks live in the auth service and the builders only. */+export function checkAccessChecks(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];++ for (const source of sources) {+ if (isUnder(source.path, AUTH_STACK_PATHS)) {+ continue;+ }+ for (const fn of namedFunctions(source)) {+ if (!ACCESS_CHECK_FUNCTION_NAMES.has(fn.name)) {+ continue;+ }+ offenders.push({+ file: source.path,+ line: lineOf(source, fn.anchor.getStart(source.sourceFile)),+ detail: `${fn.name} — R10 keeps access checks in the auth service and rpc/base.ts; protectedProcedure already enforces login`,+ });+ }+ }++ return {+ label:+ 'require(Login|ReadAccess|WriteAccess|Access) definitions outside rpc/base.ts and modules/auth/',+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++// --- R14 ----------------------------------------------------------------------++export interface ResidueScanInput {+ path: string;+ text: string;+}++/**+ * R14 — dead prefixes and dead names.+ *+ * Deliberately a TEXT scan, not an AST one: residue in a comment is still+ * residue, and `NEXT_PUBLIC_` most often survives inside a string or a doc line.+ */+export function checkResidue(files: ResidueScanInput[]): Metric[] {+ const metrics: Metric[] = [];++ for (const { label, pattern } of RESIDUE_PATTERNS) {+ const offenders: Offender[] = [];+ const global = new RegExp(pattern.source, `${pattern.flags}g`);++ for (const file of files) {+ if (+ pattern.source.includes(NEXT_PUBLIC_PREFIX) &&+ file.path.startsWith(NEXT_PUBLIC_ALLOWED_ROOT)+ ) {+ continue;+ }+ const lines = file.text.split('\n');+ for (const [index, line] of lines.entries()) {+ global.lastIndex = 0;+ const matches = line.match(global);+ if (!matches) {+ continue;+ }+ for (const match of matches) {+ offenders.push({+ file: file.path,+ line: index + 1,+ detail: `${match} — ${line.trim().slice(0, 100)}`,+ });+ }+ }+ }++ // ADR-022's baseline states NEXT_PUBLIC_ for packages/core/src on its own+ // (10 across 10 files); the rest of the tree is a second, wider metric. Both+ // are asserted, so splitting them costs nothing and keeps the baseline+ // number reproducible line-for-line.+ if (pattern.source.includes(NEXT_PUBLIC_PREFIX)) {+ const inCore = offenders.filter((offender) =>+ offender.file.startsWith(`${CORE_SOURCE_ROOT}/`)+ );+ const elsewhere = offenders.filter(+ (offender) => !offender.file.startsWith(`${CORE_SOURCE_ROOT}/`)+ );+ const coreFiles = new Set(inCore.map((offender) => offender.file));+ metrics.push({+ label: `${label} occurrences in ${CORE_SOURCE_ROOT} — across ${coreFiles.size} files`,+ count: inCore.length,+ target: 0,+ offenders: sorted(inCore),+ });+ metrics.push({+ label: `${label} occurrences elsewhere outside ${NEXT_PUBLIC_ALLOWED_ROOT}`,+ count: elsewhere.length,+ target: 0,+ offenders: sorted(elsewhere),+ });+ continue;+ }++ metrics.push({+ label: `${label} occurrences`,+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ });+ }++ return metrics;+}++// --- R15 ----------------------------------------------------------------------++/**+ * R15 — core declares, the app constructs. Nothing in core opens a socket,+ * connection or client at import time.+ *+ * Scope is the whole check: `new S3Client({...})` inside `createS3Adapter` is+ * correct; the same line at module scope is the violation. A grep sees one+ * thing.+ */+export function checkModuleScopeConstruction(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];++ for (const source of sources) {+ visit(source.sourceFile, (node) => {+ if (!isAtModuleScope(node)) {+ return;+ }+ if (+ ts.isNewExpression(node) &&+ ts.isIdentifier(node.expression) &&+ CONNECTION_CONSTRUCTOR_NAMES.has(node.expression.text)+ ) {+ offenders.push({+ file: source.path,+ line: lineOf(source, node.getStart(source.sourceFile)),+ detail: `new ${node.expression.text}( at module scope`,+ });+ return;+ }+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ CONNECTION_FACTORY_NAME_PATTERN.test(node.expression.text)+ ) {+ offenders.push({+ file: source.path,+ line: lineOf(source, node.getStart(source.sourceFile)),+ detail: `${node.expression.text}( at module scope`,+ });+ }+ });+ }++ return {+ label:+ 'connection/client construction at module scope in packages/core/src (non-test)',+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++// --- R21 ----------------------------------------------------------------------++const utilKey = (path: string): string | undefined => {+ if (!UTIL_DIRECTORY_PATTERNS.some((pattern) => pattern.test(path))) {+ return undefined;+ }+ const name = basename(path).replace(/\.tsx?$/, '');+ if (UTIL_BASENAME_EXCLUSIONS.has(name)) {+ return undefined;+ }+ return UTIL_BASENAME_ALIASES.get(name) ?? name;+};++/**+ * R21 — nothing is copied between packages to dodge a dependency edge.+ *+ * The count is duplicate COPIES, not colliding names: one file per group is the+ * canonical one and the rest are the copies to delete. ADR-022's expected end+ * state says "5 duplicate util copies deleted", which is this number.+ */+export function checkDuplicateUtilities(paths: string[]): Metric {+ const groups = new Map<string, string[]>();++ for (const path of paths) {+ const key = utilKey(path);+ if (!key) {+ continue;+ }+ const group = groups.get(key) ?? [];+ group.push(path);+ groups.set(key, group);+ }++ const offenders: Offender[] = [];+ for (const [key, members] of [...groups.entries()].sort()) {+ if (members.length < 2) {+ continue;+ }+ const [canonical, ...copies] = members.sort();+ for (const copy of copies) {+ offenders.push({+ file: copy,+ line: 1,+ detail: `duplicates ${canonical} (util "${key}") — R21 moves the shared version to ${SHARED_PACKAGE_NAME}`,+ });+ }+ }++ return {+ label: 'duplicate util copies across apps/* and packages/*',+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++/** R21 — `@openpanel/shared` imports no workspace package. */+export function checkSharedPackageIsolation(repoRoot: string): Metric {+ const manifest = join(repoRoot, SHARED_PACKAGE_ROOT, 'package.json');+ if (!existsSync(manifest)) {+ return {+ label: `workspace dependencies declared by ${SHARED_PACKAGE_NAME}`,+ count: 0,+ target: 0,+ offenders: [],+ note: `${SHARED_PACKAGE_ROOT} does not exist yet — ADR-022's C7 chore creates it. Nothing to check.`,+ };+ }++ const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as {+ dependencies?: Record<string, string>;+ peerDependencies?: Record<string, string>;+ };+ const offenders: Offender[] = [];+ for (const [name, range] of Object.entries({+ ...parsed.dependencies,+ ...parsed.peerDependencies,+ })) {+ if (name.startsWith('@openpanel/')) {+ offenders.push({+ file: `${SHARED_PACKAGE_ROOT}/package.json`,+ line: 1,+ detail: `${name}@${range} — R21: the shared package imports no workspace package`,+ });+ }+ }++ return {+ label: `workspace dependencies declared by ${SHARED_PACKAGE_NAME}`,+ count: offenders.length,+ target: 0,+ offenders: sorted(offenders),+ };+}++// --- reported-only hints ------------------------------------------------------++/** R1 — a module's root files carry the `<name>.` prefix and stop at `src/`. */+export function checkModuleLayout(+ modulePaths: string[],+ moduleRootFiles: Map<string, string[]>+): Metric {+ const offenders: Offender[] = [];++ for (const moduleName of [...modulePaths].sort()) {+ for (const file of (moduleRootFiles.get(moduleName) ?? []).sort()) {+ const match = MODULE_ROOT_FILE.exec(basename(file));+ if (!match) {+ offenders.push({+ file,+ line: 1,+ detail: `root file is not <name>.{rpc,service,routes,jobs,constants}.ts`,+ });+ continue;+ }+ if (match[1] !== moduleName) {+ offenders.push({+ file,+ line: 1,+ detail: `root file is prefixed "${match[1]}." but the module is "${moduleName}"`,+ });+ }+ }+ }++ return {+ label: `module root files not named <name>.<transport>.ts — ${modulePaths.length} modules`,+ count: offenders.length,+ target: null,+ offenders: sorted(offenders),+ };+}++/** R4 — declare functions first, then `return { one, two, three }`. */+export function checkFactoryReturnShape(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];++ for (const { source, fn } of serviceFactories(sources)) {+ const body = fn.declaration.body;+ if (!(body && ts.isBlock(body))) {+ continue;+ }+ const last = body.statements.at(-1);+ const returnsObjectLiteral =+ last &&+ ts.isReturnStatement(last) &&+ last.expression &&+ ts.isObjectLiteralExpression(last.expression);+ if (returnsObjectLiteral) {+ continue;+ }+ offenders.push({+ file: source.path,+ line: lineOf(source, fn.anchor.getStart(source.sourceFile)),+ detail: `${fn.name} does not end in \`return { ... }\` — R4 makes that line the module's index`,+ });+ }++ return {+ label: 'service factories not ending in a `return { ... }` index line',+ count: offenders.length,+ target: null,+ offenders: sorted(offenders),+ };+}++/** R18 — a job payload must survive a JSON round-trip, so no `z.date()`. */+export function checkJobPayloadDates(sources: ParsedSource[]): Metric {+ const offenders: Offender[] = [];++ for (const source of sources) {+ if (!source.path.endsWith('.jobs.ts')) {+ continue;+ }+ visit(source.sourceFile, (node) => {+ if (+ ts.isCallExpression(node) &&+ ts.isPropertyAccessExpression(node.expression) &&+ node.expression.name.text === 'date' &&+ node.expression.expression.getText() === 'z'+ ) {+ offenders.push({+ file: source.path,+ line: lineOf(source, node.getStart(source.sourceFile)),+ detail: 'z.date() in a job file — a payload must survive a JSON round-trip',+ });+ }+ });+ }++ return {+ label: 'z.date() in a *.jobs.ts payload',+ count: offenders.length,+ target: null,+ offenders: sorted(offenders),+ };+}++/**+ * R2 — nothing has an rpc procedure with no frontend caller.+ *+ * A textual `<router>.<procedure>` search of the dashboard. It is a hint, not a+ * verdict: a procedure reached through a computed key would read as uncalled,+ * which is exactly why R2 is reported and not asserted.+ */+export function checkRpcProceduresWithoutCallers(+ routers: { routerKey: string; source: ParsedSource; procedures: { name: string; line: number }[] }[],+ frontendText: string+): Metric {+ const offenders: Offender[] = [];++ for (const router of routers) {+ for (const procedure of router.procedures) {+ if (frontendText.includes(`${router.routerKey}.${procedure.name}`)) {+ continue;+ }+ offenders.push({+ file: router.source.path,+ line: procedure.line,+ detail: `${router.routerKey}.${procedure.name} — no textual call site in apps/start`,+ });+ }+ }++ return {+ label: 'rpc procedures with no apps/start call site',+ count: offenders.length,+ target: null,+ offenders: sorted(offenders),+ };+}++/** R17 — refines precede the transform, and loadConfig takes env as a parameter. */+export function checkConfigLoaderShape(source: ParsedSource | undefined): Metric {+ if (!source) {+ return {+ label: 'config loader shape (apps/api/src/config/env.ts)',+ count: 0,+ target: null,+ offenders: [],+ note: 'apps/api/src/config/env.ts not found.',+ };+ }++ const offenders: Offender[] = [];+ let transformLine: number | undefined;+ const refineLines: number[] = [];++ visit(source.sourceFile, (node) => {+ if (+ !(+ ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)+ )+ ) {+ return;+ }+ const line = lineOf(source, node.getStart(source.sourceFile));+ const method = node.expression.name.text;+ if (method === 'transform' && transformLine === undefined) {+ transformLine = line;+ }+ if (method === 'refine' || method === 'superRefine') {+ refineLines.push(line);+ }+ });++ for (const line of refineLines) {+ if (transformLine !== undefined && line > transformLine) {+ offenders.push({+ file: source.path,+ line,+ detail: `.refine at line ${line} comes after the .transform at line ${transformLine} — R17 puts cross-field invariants first`,+ });+ }+ }++ const loadConfig = namedFunctions(source).find(+ (fn) => fn.name === 'loadConfig'+ );+ if (!loadConfig) {+ offenders.push({+ file: source.path,+ line: 1,+ detail: 'no loadConfig function found',+ });+ } else if (!loadConfig.declaration.parameters[0]?.initializer) {+ offenders.push({+ file: source.path,+ line: lineOf(source, loadConfig.anchor.getStart(source.sourceFile)),+ detail:+ 'loadConfig has no defaulted `source` parameter — R17 wants loadConfig(source = process.env) so a test can pass a minimal object',+ });+ }++ return {+ label: 'config loader shape (apps/api/src/config/env.ts)',+ count: offenders.length,+ target: null,+ offenders: sorted(offenders),+ note: `${refineLines.length} refine(s), transform at line ${transformLine ?? 'none'}`,+ };+}diff --git a/tooling/gates/conformance/sources.ts b/tooling/gates/conformance/sources.tsnew file mode 100644index 000000000..6a59069f2--- /dev/null+++ b/tooling/gates/conformance/sources.ts@@ -0,0 +1,188 @@+/**+ * Source collection and parsing for the conformance checks.+ *+ * Every check takes an array of `ParsedSource` rather than reading the disk+ * itself. That is what makes the checks testable against a fixture string —+ * which is the only way to prove the two miscount traps in+ * docs/CONFORMANCE_GATE_SPEC.md are actually covered.+ */++import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+// A namespace import rather than ~30 named ones: `ts.isCallExpression` is the+// compiler API's own idiom and reads far better at 30 call sites.+import * as ts from 'typescript';++import { IGNORED_DIRECTORY_NAMES } from './conformance.constants';++export interface ParsedSource {+ /** Repo-relative POSIX path, e.g. `packages/core/src/services.ts`. */+ path: string;+ text: string;+ sourceFile: ts.SourceFile;+}++export interface Offender {+ file: string;+ line: number;+ detail: string;+}++const TYPESCRIPT_FILE_PATTERN = /\.tsx?$/;+const TEST_FILE_PATTERN = /\.(?:test|spec)\.tsx?$/;++const toPosix = (path: string): string => path.split(sep).join('/');++/** Depth-first, name-sorted, so two runs of the gate list files identically. */+export function listSourceFiles(+ repoRoot: string,+ directory: string,+ { includeTests = false }: { includeTests?: boolean } = {}+): string[] {+ const absolute = join(repoRoot, directory);+ const found: string[] = [];++ const descend = (current: string): void => {+ let entries: string[];+ try {+ entries = readdirSync(current).sort();+ } catch {+ return;+ }+ for (const entry of entries) {+ if (IGNORED_DIRECTORY_NAMES.has(entry)) {+ continue;+ }+ const child = join(current, entry);+ if (statSync(child).isDirectory()) {+ descend(child);+ } else if (+ TYPESCRIPT_FILE_PATTERN.test(entry) &&+ (includeTests || !TEST_FILE_PATTERN.test(entry))+ ) {+ found.push(toPosix(relative(repoRoot, child)));+ }+ }+ };++ descend(absolute);+ return found;+}++export function parseSource(path: string, text: string): ParsedSource {+ return {+ path,+ text,+ sourceFile: ts.createSourceFile(+ path,+ text,+ ts.ScriptTarget.Latest,+ // setParentNodes: the checks need `node.parent` to decide module scope.+ true,+ path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS+ ),+ };+}++export function readSources(repoRoot: string, paths: string[]): ParsedSource[] {+ return paths.map((path) =>+ parseSource(path, readFileSync(join(repoRoot, path), 'utf8'))+ );+}++/** 1-indexed, the way every editor and every `file:line` offender reads. */+export function lineOf(source: ParsedSource, position: number): number {+ return (+ source.sourceFile.getLineAndCharacterOfPosition(position).line + 1+ );+}++export function visit(+ node: ts.Node,+ callback: (node: ts.Node) => void+): void {+ callback(node);+ ts.forEachChild(node, (child) => visit(child, callback));+}++/**+ * True when `node` is not nested inside any function, method, constructor or+ * class body — i.e. it runs the moment the module is imported. R15 turns on+ * exactly this distinction, and it is the one a grep for `new Redis(` cannot+ * make.+ */+export function isAtModuleScope(node: ts.Node): boolean {+ let current = node.parent;+ while (current) {+ if (+ ts.isFunctionDeclaration(current) ||+ ts.isFunctionExpression(current) ||+ ts.isArrowFunction(current) ||+ ts.isMethodDeclaration(current) ||+ ts.isConstructorDeclaration(current) ||+ ts.isGetAccessorDeclaration(current) ||+ ts.isSetAccessorDeclaration(current) ||+ ts.isClassDeclaration(current) ||+ ts.isClassExpression(current)+ ) {+ return false;+ }+ current = current.parent;+ }+ return true;+}++export function isExported(node: ts.Node): boolean {+ const modifiers = ts.canHaveModifiers(node)+ ? ts.getModifiers(node)+ : undefined;+ return Boolean(+ modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)+ );+}++/**+ * Every named function-like declaration: `function f() {}`, `const f = () => {}`+ * and `const f = function () {}`. R3/R6/R10 all count "functions named X", and+ * missing the arrow forms would undercount them the same way the spec's trap 1+ * undercounts factories.+ */+export interface NamedFunction {+ name: string;+ /** Narrow enough that `.parameters` and `.body` are both reachable. */+ declaration: ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction;+ /** The node whose position the offender line is reported at. */+ anchor: ts.Node;+}++export function namedFunctions(source: ParsedSource): NamedFunction[] {+ const functions: NamedFunction[] = [];++ visit(source.sourceFile, (node) => {+ if (ts.isFunctionDeclaration(node) && node.name) {+ functions.push({+ name: node.name.text,+ declaration: node,+ anchor: node.name,+ });+ return;+ }+ if (+ ts.isVariableDeclaration(node) &&+ ts.isIdentifier(node.name) &&+ node.initializer &&+ (ts.isArrowFunction(node.initializer) ||+ ts.isFunctionExpression(node.initializer))+ ) {+ functions.push({+ name: node.name.text,+ declaration: node.initializer,+ anchor: node.name,+ });+ }+ });++ return functions;+}++export { ts };