Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

feat: implement CLI telemetry - #536

Closed
aqrln wants to merge 1 commit into
mainfrom
telemetry
Closed

aqrln wants to merge 1 commit into
mainfrom
telemetry

Conversation

@aqrln

@aqrln aqrln commented May 19, 2026

Copy link
Copy Markdown
Member

Linked issue

Summary

Testing performed

Skill update

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated (or n/a if the change is doc-only / refactor with no behavioural delta).
  • The PR title is in TML-NNNN: <sentence-case title> form (Linear ticket prefix + concise title naming the concrete deliverable). See .claude/skills/create-pr/SKILL.md for the full convention.
  • The Skill update section above is filled in (or stated n/a — internal only).

Notes for the reviewer

@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 64c8a367-44a0-4011-b1f8-8714ee41f716

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch telemetry

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented May 19, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-author-tools@536

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@536

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@536

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@536

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@536

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-arktype-json@536

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-cipherstash@536

@prisma-next/middleware-cache

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-cache@536

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@536

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@536

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@536

@prisma-next/extension-postgis

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-postgis@536

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@536

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@536

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@536

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@536

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@536

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@536

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@536

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@536

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@536

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@536

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@536

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@536

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@536

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@536

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@536

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@536

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@536

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@536

@prisma-next/cli-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli-telemetry@536

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@536

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@536

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@536

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@536

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@536

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@536

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@536

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@536

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@536

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@536

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@536

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@536

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@536

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@536

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@536

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@536

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@536

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@536

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@536

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@536

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@536

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@536

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@536

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@536

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@536

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@536

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@536

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@536

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@536

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@536

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@536

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@536

commit: a2f1e18

Comment thread apps/telemetry-backend/src/db.ts Resolved
Comment thread apps/telemetry-backend/src/handler.ts Resolved
Comment thread apps/telemetry-backend/src/handler.ts Resolved
Comment thread apps/telemetry-backend/src/server.ts Resolved
Comment thread apps/telemetry-backend/src/server.ts Resolved
Comment thread apps/telemetry-backend/tsconfig.json Resolved
Comment thread apps/telemetry-backend/src/db.ts Resolved
Comment thread apps/telemetry-backend/src/server.ts Resolved
Comment thread apps/telemetry-backend/src/db.ts Resolved
@aqrln
aqrln force-pushed the telemetry branch 5 times, most recently from b7960e2 to 117a53e Compare May 20, 2026 13:38
@aqrln
aqrln force-pushed the telemetry branch 4 times, most recently from b60f684 to 2f9c2a1 Compare May 20, 2026 14:45
Comment on lines +29 to +67
name: Migrate + deploy
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

# Node version comes from `.tool-versions` at the repo root (matches CI).
- name: Setup mise (Node)
uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4.0.1
with:
cache: true

- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest

- name: Setup pnpm
uses: pnpm/action-setup@91ab88e2619ed1f46221f0ba42d1492c02baf788 # v6.0.6

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Build packages
run: pnpm build

- name: Apply migrations
working-directory: apps/telemetry-backend
env:
DATABASE_URL: ${{ secrets.TELEMETRY_DATABASE_URL_PRODUCTION }}
run: pnpm prisma-next migrate

- name: Deploy to Prisma Compute
working-directory: apps/telemetry-backend
env:
TELEMETRY_DEPLOY_PROJECT_ID: ${{ secrets.TELEMETRY_DEPLOY_PROJECT_ID }}
TELEMETRY_DEPLOY_SERVICE_ID: ${{ secrets.TELEMETRY_DEPLOY_SERVICE_ID }}
TELEMETRY_DEPLOY_SERVICE_TOKEN: ${{ secrets.TELEMETRY_DEPLOY_SERVICE_TOKEN }}
run: pnpm run deploy
Adds the telemetry backend app at `apps/telemetry-backend/`, an
isolated workspace member that lives outside the framework-domain
boundary in `architecture.config.json` (per the spec's
domain-separation requirement). Adds an `apps/*` glob to
`pnpm-workspace.yaml` so pnpm sees the new member; the existing
`packages/`-scoped `lint:deps` config and validate-package-*
scripts continue to ignore it by construction.

The contract authors the `TelemetryEvent` Prisma Next model that
backs the wire payload, with the indexes the team will run MAU and
version-distribution queries against. `pnpm contract emit` produces
`contract.json` + `contract.d.ts` co-located with the source.

feat(telemetry-backend): HTTP ingest endpoint with arktype validation and Prisma Next INSERT

The handler is a Web-Standard `(Request) => Promise<Response>` so it
composes cleanly under Bun.serve in production and is directly
testable in the Vitest/Node tests in this commit without spinning up
an HTTP server.

Wire-format validation is an arktype schema that enforces:
- `installationId`, `version`, `command` are required non-empty
  strings — payloads missing any of them get a 400.
- `runtimeName`, `runtimeVersion`, `os`, `arch` default to
  `'unknown'` when absent. The contract pins these columns NOT NULL
  per the spec, so a placeholder is the only way to honour both
  schema exactness and the backward-compat acceptance rule.
- `packageManager`, `databaseTarget`, `tsVersion`, `agent`
  default to `null`. These columns are nullable in the contract, so
  omitted-field rows land as NULLs.
- `flags` and `extensions` default to `[]`. The Prisma Next
  contract maps `String[]` to a JSONB column (per
  `buildStorageColumn` in `@prisma-next/sql-contract-ts`), and the
  CREATE TABLE in the test fixture mirrors that.
- Unknown future keys are silently deleted from the parsed result
  via arktype's `'+': 'delete'` clause, giving us forward
  compatibility without storing arbitrary client-supplied fields.

The INSERT goes through the sql() builder lane on the dogfooded
Prisma Next contract, so the runtime executes the same encoded
parameter shapes any other consumer of this contract would. The
backend therefore exercises Prisma Next's INSERT plan path end-to-end
on every accepted event.

The handler-level integration test covers the AC12 forward/backward
compatibility shape with five subtests: fully-populated, unknown
extras, nullable-field omissions, array-field omissions, and the
critical-field rejection. The test spins up an isolated `@prisma/dev`
Postgres instance via `createDevDatabase()` and creates the table
with raw DDL matching the contract's storage map.

feat(telemetry-backend): per-IP token-bucket rate limiter and Bun.serve entry

Mechanism: classic in-process token bucket keyed by client IP. Each
key gets a bucket sized to the configured per-minute threshold;
tokens refill uniformly over the minute, so a same-instant burst is
capped at the threshold but a steady-state client at exactly the
threshold rate is never throttled. Unrelated keys never share a
bucket, so one abusive IP cannot starve compliant traffic from the
same site or NAT.

Why token bucket over a strict fixed window: at the window boundary,
a fixed window admits 2× the threshold in a small interval; a token
bucket smooths that. Why in-process over fronting infrastructure: the
service is a single Bun process at EA volumes (tens to hundreds of
events/day), so the bucket state fits in memory and survives no
restarts — which is acceptable since the limiter is an abuse-shield,
not an availability primitive.

Default threshold is 120 req/min/IP, overridable via
`RATE_LIMIT_RPM`. Picked to leave large headroom for a workplace
NAT (a 100-developer office sending an event per command will sit
well below it on any plausible day) while still rejecting a brute
flood.

The `Bun.serve` entry resolves the client IP via the
`server.requestIP(request)` API (the Bun-native source of truth)
and forwards it to the handler. The handler's IP-resolution fallback
walks the `x-forwarded-for` header for runtimes that don't expose a
peer-IP API, which is also how the rate-limited integration test
addresses callers.

Tests come in two layers: unit tests for the token-bucket primitive
(capacity, isolation, refill timing, capacity cap) drive the
deterministic edge cases via an injected clock; the handler-level
integration test pins the wire contract — compliant clients keep
landing 202s during an abuser's burst, and the abuser's bucket
refills on schedule.

docs(telemetry-backend): wire-format reference, runtime configuration, and deploy hand-off

Documents the package as the operator will encounter it: endpoint
shape with status-code mapping, the arktype-enforced wire format
(required vs. optional vs. nullable fields), the three environment
variables that configure the service, and the local-dev workflow.

The deploy hand-off section is intentionally short: no build step,
no dist artefact — `bun run src/server.ts` is the production
command, with `DATABASE_URL`, `PORT`, and `RATE_LIMIT_RPM` as
the only operational surface. The Prisma Compute deploy itself is
handled by the user after this commit lands; the `*.prisma.build`
URL it produces becomes the client's build-time constant.

chore(telemetry-backend): wire Prisma Compute deploy

- Add `deploy` script invoking the Prisma Compute CLI with the
  telemetry-backend app entry.
- Add `prisma.config.ts` carrying the Prisma Compute project id used
  by the deploy command.
- Bump the bun engine to >=1.3 to match what the deploy tool requires.
- Switch workspace dependency pins from the `0.8.0` literal to
  `workspace:*` after the monorepo version bump.

User-authored on top of m1 R1; bundled here so the round artefact
chain stays linear.

docs(cli-telemetry): require runtime/os/arch fields on the wire

FR13 originally combined a stable backward-compat clause with a
tolerance for missing fields, which forced the backend to default
`runtimeName`/`runtimeVersion`/`os`/`arch` to a literal `"unknown"`
sentinel since FR16 pinned those columns NOT NULL. Downstream
adoption-rate and version-distribution queries would then have to
filter the sentinel out of real values for the lifetime of the data.

Amend the contract instead of the analysis. The four fields join the
wire-format required-set (alongside `installationId`, `version`,
`command`); the backend rejects with 400 when any is missing.
Optional fields (`flags`, `packageManager`, `databaseTarget`,
`tsVersion`, `agent`, `extensions`) keep their relaxed handling.
Unknown-field drop for forward compat is unchanged.

AC12 is re-stated to cover three sub-cases: superset accepts and
drops unknown; required-set with optionals omitted accepts and
stores nulls/empties; missing required field returns 400.

Resolves OI6; chooses option (a) for OI5 (fold the backend into the
root `fixtures:emit` filter). Records the m1 deploy URL on OI4.

feat(telemetry-backend): tighten arktype required-set to match amended FR13

FR13 (as amended in the same merge train as this commit) elevates
`runtimeName`, `runtimeVersion`, `os`, and `arch` from
optional-with-`'unknown'`-sentinel to required. The schema previously
defaulted these four to the string "unknown" when omitted, which let
older or quirky clients land 202s with degraded rows; the amended
contract instead has the backend reject 400 so the column never
carries the sentinel and downstream MAU / version-distribution
queries don't need to filter it out.

Mechanically: drop the four `.default('unknown')` clauses, line the
four fields up with `installationId` / `version` / `command`
using the same non-empty-string validator. Optional-field
defaulting (`packageManager` / `databaseTarget` / `tsVersion` /
`agent` → `null`; `flags` / `extensions` → `[]`) and the
`'+': 'delete'` unknown-field drop remain unchanged.

Test reorganization mirrors the three AC12 sub-cases the amendment
introduced:

  (a) one test posts the required-set + all optional fields + three
      unknown future keys, expects 202, and verifies the row
      round-trips the known fields and drops the unknowns;
  (b) one test posts only the required-set, expects 202, and verifies
      omitted nullable scalars are `NULL` and omitted arrays are
      `[]` in storage;
  (c) a parametrized describe block loops over every required field,
      omits it, and asserts 400 + zero rows persisted. Iterating the
      list (not hand-rolling seven `it`s) keeps the test honest if
      the required-set ever shifts again — adding a field to
      `REQUIRED_FIELDS` automatically extends the negative-test
      coverage.

The supplementary 404 / 405 / malformed-JSON cases stay; they pin
the handler's HTTP shape, not the wire-format contract.

chore(fixtures): include telemetry-backend in workspace-wide contract emission

OI5 resolution path (a) per `projects/cli-telemetry/plan.md § Open
Items`: the backend joins the recursive filter that drives
`pnpm fixtures:emit`, so running the workspace-wide emit refresh
no longer silently skips
`apps/telemetry-backend/src/prisma/{contract.json,contract.d.ts}`.
Verified locally: `pnpm fixtures:check` exits 0 and the backend's
emit produces the same storage hash currently committed
(`sha256:e8147cd…`).

chore(fixtures): gate telemetry-backend contract drift in workspace check

The R2 `fixtures:emit` edit made the workspace-wide emit pass
through `apps/telemetry-backend/src/prisma/{contract.json,contract.d.ts}`,
but `fixtures:check`'s subsequent `git diff --exit-code` was
still scoped to the original explicit path list — meaning a future
contributor could mutate the backend's contract source without
re-committing the artefacts and the workspace gate would silently
exit 0. Append the two backend artefact paths to the existing list
(preserving order; new entries at the end) so the gate now fails on
backend drift. `pnpm fixtures:check` still exits 0 against the
current tree.

feat(cli): consolidate CI detection behind the `ci-info` package

The single `process.env['CI']` read at `global-flags.ts:74` (which
disables coloured output under CI) is the only CI-detection site in
the tree today. Telemetry-skip will need the same definition, and a
second hand-rolled read in the new cli-telemetry package would let
the two paths drift the moment a new CI provider is added upstream.

Add `ci-info` as a CLI dependency and wrap it in a single
`isCI()` helper at `src/utils/is-ci.ts`. Replace the inline
`process.env['CI']` read with the helper. Two regression
guardrails come with the change: a unit-level wiring test pinning
that we forward `ci-info`'s verdict verbatim, and a tree-scan
audit that fails the next time someone re-introduces a raw
`process.env.CI` read anywhere under `packages/**`.

feat(cli-telemetry): scaffold package with shared-plane architecture entry

Adds `@prisma-next/cli-telemetry` under
`packages/1-framework/3-tooling/cli-telemetry/` and a more-specific
entry in `architecture.config.json` overriding the umbrella tooling
glob: the telemetry path fires at command start, before the migration
runtime boundary kicks in, so it belongs on the shared plane rather
than inheriting the umbrella's `migration` assignment.

The package exposes two entry points (`./` for the public surface,
`./sender` for the forked child script). Both are stubs in this
commit so the workspace builds and `pnpm lint:deps` validates the
new arch entry against an actual package on disk; functionality
arrives in subsequent commits.

Wires `@prisma-next/cli-telemetry` as a dependency of
`@prisma-next/cli` so the spawn site in `cli.ts` can import it
once the real surface lands.

feat(cli-telemetry): pure-function building blocks (user-config, gating, sanitize, agent detector)

Four standalone pure-function modules that the spawn site and the
sender child will compose. Each is independently unit-tested
(39 tests across the four) so the orchestration layers added in
the next commits only have to bring their wiring concerns.

- user-config.ts: read/write `config.json` at
  `$XDG_CONFIG_HOME/prisma-next/` (Unix incl. macOS \u2014 the spec
  picks XDG over the macOS-native `~/Library/Preferences`
  convention so the path is test-overridable) or `%APPDATA%`
  on Windows. Reads tolerate missing/malformed files by returning
  `{}`. Writes are atomic via temp-file + rename, merge the partial
  into the existing object so unknown fields survive, and generate
  the v4 `installationId` UUID alongside the first
  `enableTelemetry: true` persist (never rotated thereafter, and
  never generated on a `false` answer).

- gating.ts: pure resolution over `(env, config)`. Env-var override
  (`PRISMA_NEXT_DISABLE_TELEMETRY` truthy or `DO_NOT_TRACK=1`)
  wins; otherwise stored `enableTelemetry === true` enables and
  everything else (false, undefined, or file missing) disables.
  Returns a discriminated union with a `reason` for the disabled
  branch so debug-mode logging can explain why it skipped.

- sanitize.ts: projects commander's parsed-result shape into the
  wire-format `{ command, flags }` pair. Drops the root program
  name, projects flag names from `Object.keys(parsedOptions)` only
  (values are discarded by construction), and explicitly accepts a
  `positionalArgs` field it never reads \u2014 making it obvious at
  every call site that positionals never leave the parent.

- detect-agent.ts: env-var allowlist with uniform comparison shape.
  Six entries (Claude Code, Cursor, Windsurf, Aider, Cody, Continue)
  driving a first-match-wins lookup. Includes the `TODO: a
  ci-info-for-agents would be nice` comment naming the future
  abstraction. Detector runs in the child sender, never the parent.

Two architectural side effects:

- Replaces the catch-all `packages/1-framework/3-tooling/**`
  arch-config entry with explicit per-package entries. The catch-all
  collided with the new cli-telemetry shared-plane entry: any file
  under cli-telemetry matched BOTH globs, so dependency-cruiser saw
  an intra-package import as a shared\u2192migration plane violation.
  Enumerating the existing five tooling packages explicitly keeps
  their migration-plane assignment intact while letting cli-telemetry
  be the sole shared-plane entry under tooling.

- Switches the config-dir resolution off `env-paths` to a hand-rolled
  XDG-on-Unix / APPDATA-on-Windows resolver because `env-paths` maps
  macOS to `~/Library/Preferences` which contradicts the spec and
  breaks `XDG_CONFIG_HOME` overriding under test.

feat(cli-telemetry): detached sender, parent spawn, and CLI preAction wiring

Composes the building blocks from the previous commit into the
detached-subprocess pipeline the spec describes:

  parent (cli.ts preAction)              child (sender.ts)
       \u2502                                     \u2502
       \u2502 fork(senderPath, { detached, ipc }) \u2502
       \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25b6\u2502
       \u2502 child.send(payload)                 \u2502
       \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25b6\u2502 enrich + POST
       \u2502 disconnect() + unref()              \u2502 (1.5 s timeout)
       \u2502 \u2192 returns synchronously            \u2502 \u2192 exit 0
       \u25bc                                     \u25bc
   action runs                            backend

Files added:

- endpoint.ts pins the deployed Prisma Compute URL as a build-time
  constant, with a  env-var override
  reserved for the integration-test mock server (intentionally not
  surfaced as a public API).

- payload.ts declares the two IPC and wire shapes
  (`ParentToSenderPayload` and `TelemetryEvent`) that both sides
  version-couple on.

- enrich.ts is the pure-function builder for the wire event. Takes
  an injected `EnrichEnvironment` so unit tests can pin every probe
  (runtime, arch, package manager, ts version, agent) deterministically;
  the sender entry wraps it with the live `process` snapshot plus a
  best-effort `<projectRoot>/package.json` read.

- sender.ts is the forked child entry. Listens for IPC `message`,
  enriches, fetches with an `AbortController` timeout, swallows every
  error, exits 0. `PRISMA_NEXT_DEBUG=1` is the only path that
  produces output \u2014 to stderr, behind the env-gate.

- spawn.ts is the parent-side `runTelemetry` entry. Reads the user
  config, runs gating, and on the enabled branch calls
  `fork(senderPath, [], { detached: true, stdio: ['pipe','ignore','ignore','ipc'] })`,
  sends the payload, disconnects, unrefs. Every fork-side failure is
  caught and reported as `fork-failed`.

CLI wiring lands in two files:

- `cli/src/utils/telemetry.ts` adapts commander's `Command` shape
  into the package's framework-agnostic `CommanderResultShape`,
  best-effort-loads the project config for `databaseTarget` /
  `extensions`, and calls `runTelemetry` with the consumer's
  resolved sender path.

- `cli/src/cli.ts` registers a `program.hook('preAction', \u2026)`
  that fires the helper. The hook is async (so the best-effort
  config load happens before the action), but its return is
  discarded \u2014 the action runs whether the load succeeded or not.

68 cli-telemetry unit tests cover the four pure-function modules
plus the spawn gating decisions; the existing 874 CLI tests still
pass with the preAction hook installed.

feat(cli): wire telemetry consent prompt into prisma-next init

The interactive init flow grows a final clack.confirm that asks
"Help us prioritize features by sharing anonymous usage data?"
with a default of Yes. Wording follows the spec's ecosystem-precedent
proposal (Next.js, Astro); the default-Yes makes consent a single
keystroke once it's been disclosed.

Prompt gating is the triple intersection the spec pins:

  canPrompt === true   AND
  autoAcceptPrompts === false   AND
  readUserConfig().enableTelemetry === undefined

Outside that window the helper returns null and leaves the stored
preference untouched. Inside it, the answer is persisted via
writeUserConfig before the helper returns; on Yes,
`writeUserConfig` generates and stores the v4 `installationId` in
the same write.

`ResolvedInitInputs` grows an `enableTelemetry: boolean | null`
field so the post-init summary can surface what the user chose. The
field is null whenever no prompt was shown.

Two side-changes that go with the prompt:

- The CLI vitest setup file (`test/setup.ts`) now sandboxes
  `$XDG_CONFIG_HOME` to a per-worker tempdir. Without this, any test
  that exercises the init prompt path under a mocked `clack.confirm`
  would write to the developer's real user-level config (this
  happened while developing this commit; the path was cleaned up
  before staging).

- A focused unit test at
  `test/commands/init/consent-prompt.test.ts` exercises every
  branch of the gating triple: fresh-machine-yes, fresh-machine-no,
  second-run-skip, --yes-suppression, non-interactive-suppression,
  and unknown-field preservation on the merged write.

feat(test-harness): suppress telemetry across test runs and add NFR-probe

Two-layer harness short-circuit so the CLI's preAction hook never
forks a sender child during a test run:

  1. Root `vitest.config.ts` injects
     `PRISMA_NEXT_DISABLE_TELEMETRY=1` into every project's env.
     This is the path `pnpm test:packages` walks; the env is
     inherited by every per-package vitest project the root
     config enumerates.
  2. The cli-telemetry package's own `vitest.config.ts` mirrors
     the same env injection. `pnpm --filter @prisma-next/cli-telemetry test`
     reads only that file (the root config doesn't apply under a
     package filter); without the local mirror, the probe test
     below would fail in filter-mode and the in-process telemetry
     path would actually fire during single-package test runs.

The probe test (`test/no-spawn-in-tests.test.ts`) is the
positive-side verification: it spies on `node:child_process.fork`,
calls `runTelemetry` with a stored opt-in, and asserts the harness
env suppression keeps the fork from happening. Reusing the
spec-shipped opt-out env var rather than introducing a test-only
flag keeps the harness's suppression mechanism and the user-facing
opt-out path the same code path.

test(cli-telemetry): end-to-end integration suite via mock backend

Spins up an `http.createServer` on an ephemeral port, forks the
compiled sender into a child that POSTs to that mock, and asserts
the captured request matches the wire shape the production backend
accepts. Substitutes for the real Prisma Compute backend because
the cli-telemetry package lives in `packages/` (the architectural
boundary forbids importing from `apps/`) and the deployed URL is
a moving target across deploys.

Coverage:

  - happy path: parent payload round-trips into the wire body, with
    the child-side probes (runtime name+version, os, arch,
    tsVersion from project package.json) populated.
  - sanitiser wire-side check: posted body contains the supplied
    flag-name array verbatim and contains no trace of the sensitive
    flag-value strings used in the test fixture.
  - extensions are a flat `string[]` of declared pack ids,
    transmitted in input order, with no first-party/community split.
  - agent detection from the child env when a marker is set, and
    null when no marker is present.
  - the wire body always carries the seven required-set fields the
    amended backend wire contract enforces.
  - non-2xx / network-unreachable: child exits 0; parent receives
    no signal of failure.
  - sender idle timeout: child exits 0 even when no payload arrives.

The enrichment module also gets a tighter `VersionsSnapshot` type
in place of `NodeJS.ProcessVersions` so the test bodies can pass
plain literals without casting through the full `@types/node`
runtime-versions surface (which adds members between Node releases
and includes many fields the enrichment never touches).

fix(scaffold): restore files accidentally deleted in cli-telemetry scaffold commit

Commit acae93ab9 (`feat(cli-telemetry): scaffold package with shared-plane architecture entry`)
unintentionally also deleted, from the index:

  - root `vitest.config.ts`
  - `tsconfig.base.json`
  - `turbo.json`
  - the entire `skills/` tree (the published user-facing skill clusters)

I cannot pinpoint the exact mechanism that staged those deletions \u2014
my `git add` invocation named only the new cli-telemetry files plus
two intentional modifications (architecture.config.json, the CLI
package.json) \u2014 but the `git commit` output reported `delete mode`
lines that I missed at the time. The integration suite uncovered the
damage downstream: `prisma-next init` invokes `skills add <clone>/skills`
and the clone no longer contained a `skills/` directory, so the
test asserted exit code 6 (SKILL_INSTALL_FAILED).

Recovery: `git checkout 62d97d2 -- skills tsconfig.base.json turbo.json vitest.config.ts`
restores the deleted content verbatim from m1 R2's final HEAD; the
recovered `vitest.config.ts` also picks up the harness-short-circuit
env injection that the original commit 6 \(`feat(test-harness)\u2026`)
intended to make but couldn't because the file was deleted.

The unrelated `skills-contrib/**` worktree-vs-HEAD drift the
orchestrator flagged at round start is left alone here \u2014 it's
not in scope and the staging in this commit is explicit.

Signed-off-by: Alexey Orlenko <[email protected]>

Simplify telemetry DB factory

Use typed telemetry table access

Note prepared telemetry inserts follow-up

Trim telemetry event indexes

Move rate limiter interface ownership

Refactor token bucket rate limiter

Make telemetry rate-limit IP handling explicit

Fix telemetry rate-limit test request typing

Bound telemetry backend shutdown

Use Prisma Next schema setup in telemetry handler tests

Assert telemetry handler rows through Prisma Next

Use Prisma Next schema setup in rate limit tests

Rely on Bun types for telemetry backend

Detect Gemini CLI telemetry sessions

Document telemetry package version enrichment

Document telemetry config path rationale

test cli telemetry against backend

revise telemetry consent prompt

Explain telemetry DB type narrowing

Unref telemetry shutdown timeout

Document telemetry enrichment env snapshot

Reuse telemetry consent prompt constant


Co-authored-by: Alexey Orlenko <[email protected]>
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@tensordreams

Copy link
Copy Markdown
Contributor

Superseded by a replacement PR from the same branch under the currently authenticated GitHub account. I will link the replacement PR here once GitHub accepts it.

@tensordreams tensordreams mentioned this pull request May 20, 2026
5 tasks done
@tensordreams

Copy link
Copy Markdown
Contributor

Superseded by #550: #550

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants