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

TML-2557: Implement CLI telemetry - #550

Merged
aqrln merged 30 commits into
mainfrom
telemetry
May 20, 2026
Merged

aqrln merged 30 commits into
mainfrom
telemetry

Conversation

@tensordreams

@tensordreams tensordreams commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2557

Supersedes #536.

At a glance

const payload: ParentToSenderPayload = {
  installationId: config.installationId,
  version: inputs.version,
  command: sanitised.command,
  flags: sanitised.flags,
  databaseTarget: inputs.databaseTarget,
  extensions: inputs.extensions,
  projectRoot: inputs.projectRoot,
  endpoint: resolveTelemetryEndpoint(env),
};

Telemetry starts from a sanitized parent-process payload: command + flag names only, no positional args or flag values, then a detached child enriches and sends it.

Decision

This PR ships Phase 1 CLI telemetry for Prisma Next: an explicit opt-in consent path in prisma-next init, a detached sender process that posts anonymous command-start events without blocking CLI work, and a Bun/Postgres backend that stores accepted events through Prisma Next itself.

It deliberately does not ship crash/error reporting. That path has different privacy and lifecycle constraints and stays deferred to a separate Phase 2.

Reviewer notes

  • This is a large first implementation PR because the client, backend, contract, workspace wiring, and integration tests need to land together for the end-to-end path to be reviewable.
  • The backend lives under apps/telemetry-backend and pnpm-workspace.yaml now includes apps/*; the existing package-layer dependency checks remain scoped to packages/.
  • The privacy-sensitive part is the CLI parent path: gates resolve before project config loading, and command sanitization only emits long flag names supplied by the user.
  • The replacement PR was created from the already-pushed telemetry branch while ignoring local uncommitted WIP, per the recreation request.

How it fits together

  1. Backend storage is contract-first. apps/telemetry-backend/src/prisma/contract.prisma defines a single TelemetryEvent model, with committed contract.json / contract.d.ts artifacts and migration outputs so the ingest service dogfoods Prisma Next.
  2. The ingest API is small and forward-compatible. POST /events requires the stable core fields, defaults omitted optional fields to null / [], drops unknown future keys, enforces request-size limits, and rate-limits callers before INSERT.
  3. User consent is per-user and default-off. @prisma-next/cli-telemetry stores enableTelemetry and a random v4 installationId under the user config directory; env overrides and CI suppress telemetry without mutating that file.
  4. The CLI fires at command start. A preAction hook resolves CI/env/user gates first, then loads only the telemetry-safe pieces of project config, sanitizes Commander metadata, and forks a detached sender.
  5. The child owns all I/O. The sender enriches the payload with runtime, package manager, TypeScript version, OS/arch, and best-effort agent markers, POSTs with a hard timeout, and exits 0 while swallowing failures.

Behavior changes & evidence

  • Adds the telemetry backend ingest service. The service accepts POST /events, validates the payload, enforces 32 KiB request limits and per-IP rate limiting, then inserts via Prisma Next.

    • Implementation: apps/telemetry-backend/src/handler.ts, apps/telemetry-backend/src/schema.ts, apps/telemetry-backend/src/rate-limiter.ts
    • Evidence: apps/telemetry-backend/test/handler.test.ts, apps/telemetry-backend/test/rate-limit.handler.test.ts
  • Adds default-off, opt-in telemetry consent. init asks a final interactive consent question only when prompting is allowed, --yes is not auto-accepting, CI/env overrides are absent, and no stored answer exists.

    • Implementation: packages/1-framework/3-tooling/cli/src/commands/init/inputs.ts, packages/1-framework/3-tooling/cli-telemetry/src/user-config.ts, packages/1-framework/3-tooling/cli-telemetry/src/gating.ts
    • Evidence: packages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.ts, packages/1-framework/3-tooling/cli-telemetry/test/gating.test.ts
  • Adds detached command-start delivery. The CLI preAction hook forks the sender, disconnects/unrefs it, and keeps telemetry failures out of the parent command’s stdout/stderr and exit path.

    • Implementation: packages/1-framework/3-tooling/cli/src/cli.ts, packages/1-framework/3-tooling/cli/src/utils/telemetry.ts, packages/1-framework/3-tooling/cli-telemetry/src/spawn.ts, packages/1-framework/3-tooling/cli-telemetry/src/sender.ts
    • Evidence: packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts, packages/1-framework/3-tooling/cli-telemetry/test/spawn.test.ts, packages/1-framework/3-tooling/cli-telemetry/test/integration.test.ts
  • Adds sanitization and enrichment without user values. Events include command name, user-supplied long flag names, runtime/package metadata, target, extensions, and agent markers; they intentionally exclude positionals and flag values.

    • Implementation: packages/1-framework/3-tooling/cli-telemetry/src/sanitize.ts, packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts, packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts
    • Evidence: packages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.ts, packages/1-framework/3-tooling/cli-telemetry/test/enrich.test.ts, packages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.ts

Compatibility / migration / risk

  • Telemetry remains off unless the user explicitly opts in; PRISMA_NEXT_DISABLE_TELEMETRY, DO_NOT_TRACK=1, and CI all suppress it.
  • The backend wire format is backward-compatible for optional fields and forward-compatible for unknown future fields.
  • apps/* is now part of the workspace so the telemetry backend participates in install/build/test orchestration.
  • The production endpoint URL is currently a build-time constant; if Prisma Compute reassigns it, the client constant needs to be updated before release.

Testing performed

Not rerun locally while recreating the PR; local uncommitted WIP was intentionally ignored.

Previous PR #536 CI at recreation time:

  • Passed: DCO, Build, Coverage, E2E Tests, Fixtures, Integration Tests, CodeQL / code scanning, secret detection, preview release.
  • Failing: Lint, Test, Type Check.

Skill update

n/a — this PR changes CLI telemetry behavior and documents the telemetry client/backend in repo docs and READMEs; no existing shared user-facing skill needed an 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).

Alternatives considered

  • Send telemetry synchronously from the parent process. Rejected because network failures or slow DNS could affect the CLI UX.
  • Use a per-project telemetry setting. Rejected because one developer’s project config should not enroll or opt out teammates.
  • Collect crash/error reporting in Phase 1. Rejected because stack traces and failure lifecycle need separate consent and sanitization rules.

Summary by CodeRabbit

  • New Features

    • CLI telemetry with opt-in consent during init and local config management
    • Dedicated telemetry backend service for anonymized usage events
    • Sender forks that enrich and transmit sanitized command payloads
  • Bug Fixes / Reliability

    • Request-size limits, per-IP rate limiting, and payload validation with clear HTTP status responses
    • Graceful startup/shutdown and robust error handling for the telemetry service
  • Chores

    • CI workflow to build/migrate/deploy telemetry backend
    • Extensive tests and workspace config updates to support telemetry tooling

Review Change Stack

@tensordreams
tensordreams requested a review from a team as a code owner May 20, 2026 15:49
@tensordreams tensordreams mentioned this pull request May 20, 2026
5 tasks
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@aqrln has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 3 minutes and 15 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: bc72c267-18d6-44c5-9f21-bc6744a8f965

📥 Commits

Reviewing files that changed from the base of the PR and between 4b2cacc and fc91a20.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/cli-telemetry/plan.md is excluded by !projects/**
  • projects/cli-telemetry/spec.md is excluded by !projects/**
📒 Files selected for processing (87)
  • .github/workflows/deploy-telemetry-backend.yml
  • apps/telemetry-backend/README.md
  • apps/telemetry-backend/biome.jsonc
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.d.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/ops.json
  • apps/telemetry-backend/package.json
  • apps/telemetry-backend/prisma-next.config.ts
  • apps/telemetry-backend/scripts/deploy.ts
  • apps/telemetry-backend/src/bun-server.ts
  • apps/telemetry-backend/src/db.ts
  • apps/telemetry-backend/src/handler.ts
  • apps/telemetry-backend/src/logger.ts
  • apps/telemetry-backend/src/node-server.ts
  • apps/telemetry-backend/src/prisma/contract.d.ts
  • apps/telemetry-backend/src/prisma/contract.json
  • apps/telemetry-backend/src/prisma/contract.prisma
  • apps/telemetry-backend/src/rate-limiter.ts
  • apps/telemetry-backend/src/schema.ts
  • apps/telemetry-backend/src/server-node.ts
  • apps/telemetry-backend/src/server-runtime.ts
  • apps/telemetry-backend/src/server.ts
  • apps/telemetry-backend/test/db-setup.ts
  • apps/telemetry-backend/test/handler.test.ts
  • apps/telemetry-backend/test/node-server.test.ts
  • apps/telemetry-backend/test/rate-limit.handler.test.ts
  • apps/telemetry-backend/test/rate-limit.test.ts
  • apps/telemetry-backend/test/server-runtime.test.ts
  • apps/telemetry-backend/tsconfig.json
  • apps/telemetry-backend/vitest.config.ts
  • architecture.config.json
  • examples/cipherstash-integration/package.json
  • examples/mongo-blog-leaderboard/package.json
  • examples/mongo-demo/package.json
  • examples/paradedb-demo/package.json
  • examples/prisma-next-cloudflare-worker/package.json
  • examples/prisma-next-demo-sqlite/package.json
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-postgis-demo/package.json
  • examples/retail-store/package.json
  • package.json
  • packages/1-framework/3-tooling/cli-telemetry/README.md
  • packages/1-framework/3-tooling/cli-telemetry/biome.jsonc
  • packages/1-framework/3-tooling/cli-telemetry/package.json
  • packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/endpoint.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/exports/index.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/gating.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/payload.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/sanitize.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/sender.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/spawn.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/user-config.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/endpoint.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/enrich.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/gating.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/integration.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/no-spawn-in-tests.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/payload.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/spawn.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/user-config.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/tsconfig.json
  • packages/1-framework/3-tooling/cli-telemetry/tsdown.config.ts
  • packages/1-framework/3-tooling/cli-telemetry/vitest.config.ts
  • packages/1-framework/3-tooling/cli/package.json
  • packages/1-framework/3-tooling/cli/src/cli.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/index.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/init.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/inputs.ts
  • packages/1-framework/3-tooling/cli/src/utils/global-flags.ts
  • packages/1-framework/3-tooling/cli/src/utils/is-ci.ts
  • packages/1-framework/3-tooling/cli/src/utils/telemetry.ts
  • packages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.ts
  • packages/1-framework/3-tooling/cli/test/setup.ts
  • packages/1-framework/3-tooling/cli/test/utils/is-ci.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/no-parallel-ci-detection.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts
  • packages/1-framework/3-tooling/cli/tsconfig.json
  • packages/1-framework/3-tooling/prisma-next/package.json
  • pnpm-workspace.yaml
  • skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/instructions.md
  • vitest.config.ts
📝 Walkthrough

Walkthrough

Adds a telemetry system: a Bun/Node HTTP backend that validates and persists telemetry events to Postgres, a standalone CLI telemetry package that forks a detached sender to post enriched events, CLI integration for consent and pre-action firing, tests, and CI/workspace/deploy wiring.

Changes

Telemetry Backend Service

Layer / File(s) Summary
Prisma schema and migrations
apps/telemetry-backend/src/prisma/contract.prisma, apps/telemetry-backend/src/prisma/contract.d.ts, apps/telemetry-backend/migrations/app/20260520T1317_migration/*
Adds TelemetryEvent model, generated contract types/JSON, migration ops/manifest and migration runner to create telemetry_event table and ingestedAt index.
Payload validation and rate limiter
apps/telemetry-backend/src/schema.ts, apps/telemetry-backend/src/rate-limiter.ts
Defines arktype payload schema with max-length constants and an in-process token-bucket rate limiter with RPM helper.
HTTP handler and DB persistence
apps/telemetry-backend/src/handler.ts, apps/telemetry-backend/src/db.ts
Implements POST /events handler with content-length/stream caps, JSON parse + schema validation, per-IP rate limiting key extraction, and typed Prisma runtime insert of telemetry rows.
Server adapters, runtime, and graceful shutdown
apps/telemetry-backend/src/bun-server.ts, apps/telemetry-backend/src/node-server.ts, apps/telemetry-backend/src/server-runtime.ts, apps/telemetry-backend/src/server.ts
Adds Bun and Node server adapters, runtime wiring resolving env config, app creation (DB + rate limiter), start entrypoints, and coordinated shutdown with timeout handling.
Tests, packaging, docs, and deploy
apps/telemetry-backend/test/*, apps/telemetry-backend/package.json, apps/telemetry-backend/tsconfig.json, apps/telemetry-backend/vitest.config.ts, apps/telemetry-backend/README.md, .github/workflows/deploy-telemetry-backend.yml, apps/telemetry-backend/scripts/deploy.ts
Adds test utilities and suites (handler, rate-limit, node-server, server-runtime), package build/test configs, README, GitHub Actions workflow for serialized migrate+deploy, and Bun-based deploy script using Prisma Compute.

CLI Telemetry Client Library

Layer / File(s) Summary
IPC types and sanitization
packages/1-framework/3-tooling/cli-telemetry/src/payload.ts, packages/1-framework/3-tooling/cli-telemetry/src/sanitize.ts
Defines ParentToSenderPayload and TelemetryEvent shapes, runtime validator, and sanitizeCommanderResult to emit command and long-flag names only.
User config and gating
packages/1-framework/3-tooling/cli-telemetry/src/user-config.ts, packages/1-framework/3-tooling/cli-telemetry/src/gating.ts
XDG-based user config read/write with atomic writes and installationId generation; resolveGating with env opt-outs and precedence (env > DO_NOT_TRACK > stored > default-off).
Enrichment and endpoint
packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts, packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts, packages/1-framework/3-tooling/cli-telemetry/src/endpoint.ts
Builds enriched TelemetryEvent from parent payload and process/project snapshot: runtime/os/arch, package manager, tsVersion, agent detection, and endpoint resolution with override fallback.
Spawn and sender
packages/1-framework/3-tooling/cli-telemetry/src/spawn.ts, packages/1-framework/3-tooling/cli-telemetry/src/sender.ts
runTelemetry forks a detached sender, sends IPC payload; sender validates/enriches and POSTs to backend with 1.5s abort timeout and silent error swallowing.
Tests and build config
packages/1-framework/3-tooling/cli-telemetry/test/*, packages/1-framework/3-tooling/cli-telemetry/package.json, tsdown.config.ts, tsconfig.json, vitest.config.ts
Adds comprehensive unit/integration tests, package exports, tsdown build entries, TypeScript and Vitest configs, and README.

CLI Integration and Consent

Layer / File(s) Summary
Init consent flow
packages/1-framework/3-tooling/cli/src/commands/init/inputs.ts, packages/1-framework/3-tooling/cli/src/commands/init/init.ts
resolveTelemetryConsent added to init inputs (TELEMETRY_CONSENT_MESSAGE), persists user choice, exposes enableTelemetry in resolved inputs, and supports afterFirstTelemetryConsent callback.
Pre-action hook and wiring
packages/1-framework/3-tooling/cli/src/cli.ts, packages/1-framework/3-tooling/cli/src/utils/telemetry.ts, packages/1-framework/3-tooling/cli/src/commands/init/index.ts
Registers preAction hook to snapshot command, apply gating, best-effort load project config, resolve sender path, and call runTelemetry non-blockingly (errors swallowed).
CI detection and test harness
packages/1-framework/3-tooling/cli/src/utils/is-ci.ts, packages/1-framework/3-tooling/cli/src/utils/global-flags.ts, packages/1-framework/3-tooling/cli/test/setup.ts
Adds centralized isCI() wrapper for ci-info, uses it for color defaults and gating; test harness sandboxes XDG_CONFIG_HOME and forces telemetry-off in tests.

Infrastructure and Workspace

Layer / File(s) Summary
Workspace and architecture mappings
pnpm-workspace.yaml, architecture.config.json
Adds apps/* to workspace packages, updates catalog tsx entry, and enumerates explicit tooling package mappings (including cli-telemetry).
Root test env and example deps
vitest.config.ts, various example package.json files, package.json
Root Vitest forces PRISMA_NEXT_DISABLE_TELEMETRY for tests; numerous example devDependencies for tsx switched to catalog reference and root devDep updated.

Sequence Diagram (high-level CLI send flow):

sequenceDiagram
  participant CLI
  participant TelemetrySender
  participant TelemetryBackend
  participant PostgresDB
  CLI->>TelemetrySender: fork + IPC ParentToSenderPayload
  TelemetrySender->>TelemetryBackend: POST /events (enriched JSON)
  TelemetryBackend->>PostgresDB: INSERT telemetry_event row
  TelemetryBackend-->>TelemetrySender: 202 / error
  TelemetrySender--x CLI: exit(0)
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • prisma/prisma-next#551: Introduces a deploy workflow for telemetry backend; related to the workflow changes here.

Suggested reviewers

  • aqrln
  • SevInf

"🐰 I fork and I send, then scurry away,
Events find a home at the break of day,
Consent kept gentle, privacy on display,
Quiet sender departs — success is OK,
Logs hop softly onward, in tidy array."

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

@pkg-pr-new

pkg-pr-new Bot commented May 20, 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@550

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/extension-cipherstash

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: fc91a20

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (2)
apps/telemetry-backend/test/db-setup.ts (1)

3-3: ⚡ Quick win

Use pathe instead of node:path in this TypeScript test helper.

Please replace the node:path import with pathe to match the repo-wide cross-runtime path rule.

♻️ Proposed fix
-import { join } from 'node:path';
+import { join } from 'pathe';

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: Use pathe instead of node:path for path manipulation in TypeScript files."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/telemetry-backend/test/db-setup.ts` at line 3, Replace the import of
join from 'node:path' with the cross-runtime 'pathe' package: update the import
statement that currently reads "import { join } from 'node:path';" to import
join from 'pathe' so the test helper follows the repo rule; no other code
changes should be necessary as 'join' usage in db-setup.ts remains the same.
packages/1-framework/3-tooling/cli-telemetry/README.md (1)

7-43: ⚡ Quick win

Refocus README on usage and add a minimal example.

This reads mostly like internal design notes. Please add a short “when to use” + concrete usage snippet, and move deep implementation details to contributor-focused docs.

As per coding guidelines: “For user-facing packages: keep README.md focused on what the package does, when to use it, and a few concrete examples; avoid internal implementation details unless they materially affect usage.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli-telemetry/README.md` around lines 7 - 43,
The README currently contains internal design details; create a user-facing
README that starts with a short “When to use” paragraph and a minimal usage
example showing how to invoke the package (showing consent flow, calling the
telemetry sender, and optionally overriding PRISMA_NEXT_TELEMETRY_ENDPOINT for
tests), and move the deep implementation/architecture notes (the current
"Responsibilities", "Dependencies", and detailed contributor guidance about
endpoint overrides and child-process behavior) into a new contributor doc (e.g.,
CONTRIBUTING.md or docs/CONTRIBUTOR.md). Ensure the README keeps only what
affects users (purpose, when to use, quick example, link to contributor docs)
and reference the PRISMA_NEXT_TELEMETRY_ENDPOINT constant only in the
contributor doc.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/deploy-telemetry-backend.yml:
- Around line 32-33: The Checkout step currently uses
actions/checkout@de0fac2... and leaves credentials persisted; update the
"Checkout" step (the actions/checkout usage) to add persist-credentials: false
so the checkout action does not write a writable token into the local git config
for subsequent steps.

In `@apps/telemetry-backend/prisma-next.config.ts`:
- Around line 1-18: The current file imports defineConfig from
`@prisma-next/postgres/config` and omits explicit metadata; update it to import
defineConfig from `@prisma-next/cli/config-types`, keep the readRequiredEnv and
databaseUrl usage, and change the exported defineConfig call to include explicit
family, target, adapter, and driver fields (with IDs matching each other)
alongside contract and db.connection so the config follows the canonical pattern
used in examples like examples/paradedb-demo/prisma-next.config.ts.

In `@apps/telemetry-backend/README.md`:
- Around line 109-113: Replace the transient phrase "The deploy itself is out of
scope for this milestone" with a time-independent operational statement
clarifying deployment steps and intent; for example, change the sentence in the
README section describing Prisma Compute so it reads that deployment is a
separate manual step (e.g., "Deployment is performed separately: push the
package directory, provision a Postgres database, set the environment variables
above, and run `pnpm --filter `@prisma-next/telemetry-backend` start`"), ensuring
the README no longer references "milestone" or other transient planning
language.

In `@apps/telemetry-backend/src/db.ts`:
- Line 2: The import in db.ts uses a file extension ("./prisma/contract.d")
which violates project TypeScript import rules; update the import of the
Contract type to remove the ".d" extension (change the import path referenced in
the file where Contract is imported) so it reads './prisma/contract' and keep
the imported symbol name Contract unchanged.

In `@apps/telemetry-backend/src/handler.ts`:
- Around line 55-60: The rateLimitKey function currently trusts x-forwarded-for
first which allows clients to spoof identities; change rateLimitKey to prefer
info.remoteAddress by default and only fall back to
firstForwardedAddress(request.headers.get('x-forwarded-for')) when an explicit
trusted-proxy mode is enabled (e.g. a boolean flag or env var like
trustedProxyEnabled passed into the handler). Update the function signature or
surrounding config so rateLimitKey can access that flag, ensure the lookup order
becomes info.remoteAddress ?? (trustedProxyEnabled ? firstForwardedAddress(...)
: undefined) ?? 'unknown', and add minimal validation/comments indicating
x-forwarded-for is only used in trusted-proxy mode.

In `@packages/1-framework/3-tooling/cli-telemetry/src/endpoint.ts`:
- Around line 22-24: resolveTelemetryEndpoint() can throw if
PRISMA_NEXT_TELEMETRY_ENDPOINT is a malformed URL; wrap the URL construction in
a try/catch inside resolveTelemetryEndpoint() so that any URL parsing TypeError
falls back to using TELEMETRY_BACKEND_URL (or the safe base) and returns the
default endpoint string instead of throwing. Reference
resolveTelemetryEndpoint(), the env var PRISMA_NEXT_TELEMETRY_ENDPOINT,
TELEMETRY_BACKEND_URL, and TELEMETRY_ENDPOINT_PATH when implementing the safe
fallback.

In `@packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts`:
- Line 2: Add pathe to the cli-telemetry package dependencies and replace all
imports of node:path with pathe using the same API; specifically, update
packages/1-framework/3-tooling/cli-telemetry/package.json to include "pathe":
"^2.0.3" and change imports like "import { join } from 'node:path'" in
src/enrich.ts and the other listed files (src/user-config.ts,
test/user-config.test.ts, test/spawn.test.ts, test/no-spawn-in-tests.test.ts,
test/integration.test.ts) to "import { join, dirname, resolve } from 'pathe'"
(only include the actual functions used in each file) so the existing
join/dirname/resolve calls keep working without other code changes.

In `@packages/1-framework/3-tooling/cli-telemetry/src/sender.ts`:
- Around line 54-62: Replace the manual partial guard in isPayload with a
reusable Arktype schema: define and export an Arktype schema/validator for
ParentToSenderPayload in payload.ts that validates all required fields
(installationId, endpoint, command, version, flags, databaseTarget, extensions,
projectRoot and their shapes/types), then import that validator into sender.ts
and use it to validate the incoming value (instead of the current ad-hoc checks
in isPayload). Ensure the exported schema is typed to ParentToSenderPayload so
callers keep type inference and update any references to isPayload to call the
Arktype validator (e.g., validate or isValid) so malformed payloads are rejected
before buildTelemetryEventFromProcess uses projectRoot.
- Around line 75-84: Replace the IPC listener registered with
process.on('message', ...) by using process.once('message', ...) to reflect that
exactly one payload is expected; locate the block that validates with isPayload,
logs with debugLog, calls postEvent and finally exitClean (the current handler
that calls postEvent(...).catch(...).finally(exitClean)) and change the
registration method to process.once while keeping the same validation, logging,
postEvent error handling and the final exitClean invocation.

In `@packages/1-framework/3-tooling/cli-telemetry/test/integration.test.ts`:
- Around line 118-133: The startBackend function spawns the bun process but
lacks an error listener, so add a child.on('error', (err) => { /* surface
meaningful error */ }) identical in behavior to the handlers used by
spawnCommand/spawnSenderDirect: push the error message into the stderr array (or
log it) and reject/throw a descriptive error (include err.message) so CI ENOENT
cases are surfaced instead of crashing; also ensure waitForBackendReady observes
this error path (e.g., have startBackend return a Promise that rejects on the
child's 'error' event or set a flag that waitForBackendReady checks) so
immediate spawn failures are detected before the first poll.

In `@packages/1-framework/3-tooling/cli-telemetry/test/no-spawn-in-tests.test.ts`:
- Line 4: Replace the Node built-in path import with the repo-standard pathe
import: change the import that currently reads "import { dirname, join } from
'node:path';" to import dirname and join from 'pathe' instead so the test uses
the cross-platform pathe API consistent with the codebase; ensure any usages of
dirname and join in this test remain unchanged and that the new import compiles
under TypeScript.

In `@packages/1-framework/3-tooling/cli-telemetry/test/spawn.test.ts`:
- Around line 91-92: The assertion `expect(result.spawned === true ||
result.spawned === false).toBe(true)` is tautological; replace it with a
concrete behavioral assertion on the `result` object (inspect `result.spawned`
and other relevant properties returned by the spawn helper) — for example assert
the expected boolean value for `result.spawned` given the test scenario (e.g.,
`result.spawned` is true when the command should be spawned), or if the test is
about non-throwing and shape, assert `result.spawned` is defined and assert
other fields (like `result.pid` is a number or `result.error` is undefined) to
validate real behavior rather than tautology.

In `@packages/1-framework/3-tooling/cli/src/cli.ts`:
- Around line 75-79: The preAction hook currently awaits
fireTelemetryFromPreAction which can block command start; change the hook to
invoke fireTelemetryFromPreAction(actionCommand) without awaiting it
(fire-and-forget) and attach a .catch(...) to swallow errors so telemetry runs
asynchronously and cannot delay the command; update the reference in the hook
where program.hook('preAction', async (_thisCommand, actionCommand) => { ... })
calls fireTelemetryFromPreAction to call it non-blockingly instead of awaiting
it.

In `@packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts`:
- Around line 66-68: CLI_VERSION in src/utils/telemetry.ts is currently
uninitialized; wire it to the package.json version so tests pass. In
telemetry.ts initialize/export CLI_VERSION by reading the CLI package's version
from its package.json (e.g., import or require the package.json and set
CLI_VERSION = cliPackageJson.version) and ensure the exported symbol CLI_VERSION
is used by the test; update any existing initialization logic in telemetry.ts
(the CLI_VERSION declaration) to assign the value from the imported package JSON
rather than leaving it undefined.

---

Nitpick comments:
In `@apps/telemetry-backend/test/db-setup.ts`:
- Line 3: Replace the import of join from 'node:path' with the cross-runtime
'pathe' package: update the import statement that currently reads "import { join
} from 'node:path';" to import join from 'pathe' so the test helper follows the
repo rule; no other code changes should be necessary as 'join' usage in
db-setup.ts remains the same.

In `@packages/1-framework/3-tooling/cli-telemetry/README.md`:
- Around line 7-43: The README currently contains internal design details;
create a user-facing README that starts with a short “When to use” paragraph and
a minimal usage example showing how to invoke the package (showing consent flow,
calling the telemetry sender, and optionally overriding
PRISMA_NEXT_TELEMETRY_ENDPOINT for tests), and move the deep
implementation/architecture notes (the current "Responsibilities",
"Dependencies", and detailed contributor guidance about endpoint overrides and
child-process behavior) into a new contributor doc (e.g., CONTRIBUTING.md or
docs/CONTRIBUTOR.md). Ensure the README keeps only what affects users (purpose,
when to use, quick example, link to contributor docs) and reference the
PRISMA_NEXT_TELEMETRY_ENDPOINT constant only in the contributor doc.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: ce1b5d7d-2833-41c2-acf6-36f890130dc6

📥 Commits

Reviewing files that changed from the base of the PR and between 664a9ae and a2f1e18.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/cli-telemetry/plan.md is excluded by !projects/**
  • projects/cli-telemetry/spec.md is excluded by !projects/**
📒 Files selected for processing (68)
  • .github/workflows/deploy-telemetry-backend.yml
  • apps/telemetry-backend/README.md
  • apps/telemetry-backend/biome.jsonc
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.d.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/ops.json
  • apps/telemetry-backend/package.json
  • apps/telemetry-backend/prisma-next.config.ts
  • apps/telemetry-backend/scripts/deploy.ts
  • apps/telemetry-backend/src/db.ts
  • apps/telemetry-backend/src/handler.ts
  • apps/telemetry-backend/src/prisma/contract.d.ts
  • apps/telemetry-backend/src/prisma/contract.json
  • apps/telemetry-backend/src/prisma/contract.prisma
  • apps/telemetry-backend/src/rate-limiter.ts
  • apps/telemetry-backend/src/schema.ts
  • apps/telemetry-backend/src/server.ts
  • apps/telemetry-backend/test/db-setup.ts
  • apps/telemetry-backend/test/handler.test.ts
  • apps/telemetry-backend/test/rate-limit.handler.test.ts
  • apps/telemetry-backend/test/rate-limit.test.ts
  • apps/telemetry-backend/tsconfig.json
  • apps/telemetry-backend/vitest.config.ts
  • architecture.config.json
  • package.json
  • packages/1-framework/3-tooling/cli-telemetry/README.md
  • packages/1-framework/3-tooling/cli-telemetry/biome.jsonc
  • packages/1-framework/3-tooling/cli-telemetry/package.json
  • packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/endpoint.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/exports/index.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/gating.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/payload.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/sanitize.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/sender.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/spawn.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/user-config.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/endpoint.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/enrich.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/gating.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/integration.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/no-spawn-in-tests.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/spawn.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/user-config.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/tsconfig.json
  • packages/1-framework/3-tooling/cli-telemetry/tsdown.config.ts
  • packages/1-framework/3-tooling/cli-telemetry/vitest.config.ts
  • packages/1-framework/3-tooling/cli/package.json
  • packages/1-framework/3-tooling/cli/src/cli.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/index.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/init.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/inputs.ts
  • packages/1-framework/3-tooling/cli/src/utils/global-flags.ts
  • packages/1-framework/3-tooling/cli/src/utils/is-ci.ts
  • packages/1-framework/3-tooling/cli/src/utils/telemetry.ts
  • packages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.ts
  • packages/1-framework/3-tooling/cli/test/setup.ts
  • packages/1-framework/3-tooling/cli/test/utils/is-ci.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/no-parallel-ci-detection.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts
  • packages/1-framework/3-tooling/cli/tsconfig.json
  • pnpm-workspace.yaml
  • vitest.config.ts

Comment thread apps/telemetry-backend/README.md Resolved
Comment thread apps/telemetry-backend/src/db.ts Resolved
Comment thread apps/telemetry-backend/src/handler.ts Resolved
@aqrln
aqrln force-pushed the telemetry branch 3 times, most recently from 5066c3a to 6e5e0ef Compare May 20, 2026 16:31
@tensordreams

Copy link
Copy Markdown
Contributor Author

Triage of the review body (A13a–A13d)

Thanks for the thorough review. Of the 14 actionable + 2 nitpick findings in the review body, 12 are mirrored as inline threads and have been triaged individually. The remaining four findings only present in this review body break down as follows:

A13a — apps/telemetry-backend/src/handler.ts ~L55-60 (rateLimitKey trusts x-forwarded-for first): will address. Will change the priority so info?.remoteAddress is the default and x-forwarded-for is only consulted when an explicit trusted-proxy mode is enabled (via a handler-dep flag wired from an env var). The current behaviour lets any direct caller spoof their identity for rate-limiting purposes, which is the right thing to fix for an unauthenticated public endpoint.

A13b — cli/test/utils/telemetry.test.ts ~L66-68 (CLI_VERSION wiring): not actionable. The claim that CLI_VERSION is uninitialized in cli/src/utils/telemetry.ts is incorrect. Line 12 of that file already does import { version as CLI_VERSION } from '../../package.json' with { type: 'json' }; and line 119 passes it through as version: CLI_VERSION. The CLI's own package.json declares "version": "0.10.0". Nothing to change.

A13c — packages/.../cli-telemetry/README.md (refocus on user-facing usage): won't address in this PR. @prisma-next/cli-telemetry is primarily internal infrastructure consumed by @prisma-next/cli. While the package is published, there is no current external consumer pattern that justifies reorienting the README around "how to install and call this from your own CLI" — the only stable export (runTelemetry) requires a Commander-shaped snapshot most outside consumers will not have. The current Responsibilities + Dependencies + For-contributors framing matches the real audience today. Happy to revisit if external consumption becomes a documented use case.

A13d — apps/telemetry-backend/test/db-setup.ts:3 (use pathe): will address. Folded into the same pathe sweep that's touching cli-telemetry (per the enrich.ts thread). Will add pathe to apps/telemetry-backend's deps and switch the import.

aqrln

This comment was marked as outdated.

aqrln pushed a commit that referenced this pull request May 20, 2026
Adds a no-op .github/workflows/deploy-telemetry-backend.yml whose path and `name:` match the workflow shipped by #550. GitHub Actions only exposes workflow_dispatch for workflows already present on the default branch, so this stub unlocks dispatching the real deploy workflow against the #550 branch for end-to-end verification before it merges.

Refs: TML-2557
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@tensordreams

Copy link
Copy Markdown
Contributor Author

A13a (trust-proxy gate for x-forwarded-for): on it 👍

@tensordreams

Copy link
Copy Markdown
Contributor Author

A13a (trust-proxy gate for x-forwarded-for): done in b9b4965. Defaulted rateLimitKey to socket address; trusted-proxy mode opt-in via the new TELEMETRY_TRUST_FORWARDED_FOR env (1/true/yes). New rate-limit tests cover both default-ignore and trusted-mode behavior; README configuration table updated.

@tensordreams

Copy link
Copy Markdown
Contributor Author

A13d (pathe sweep for apps/telemetry-backend): done in fa9f40c. Added pathe@^2.0.3 to devDependencies and switched test/db-setup.ts from node:path to pathe.

Comment thread apps/telemetry-backend/README.md Resolved
Comment thread apps/telemetry-backend/README.md Resolved
tensordreams and others added 8 commits May 20, 2026 21:03
Implements Phase 1 CLI telemetry for Prisma Next: an explicit opt-in
consent path in `prisma-next init`, a detached sender process that posts
anonymous command-start events without blocking CLI work, and a
Bun/Postgres backend that stores accepted events through Prisma Next
itself.

Deliberately out of scope: crash/error reporting. That path has
different privacy and lifecycle constraints and is deferred to a
separate Phase 2.

## At a glance

```ts
const payload: ParentToSenderPayload = {
  installationId: config.installationId,
  version: inputs.version,
  command: sanitised.command,
  flags: sanitised.flags,
  databaseTarget: inputs.databaseTarget,
  extensions: inputs.extensions,
  projectRoot: inputs.projectRoot,
  endpoint: resolveTelemetryEndpoint(env),
};
```

Telemetry starts from a sanitized parent-process payload — command and
flag names only, no positional args or flag values — and a detached
child enriches and sends it.

## How it fits together

- **Backend storage is contract-first.**
  `apps/telemetry-backend/src/prisma/contract.prisma` defines a single
  `TelemetryEvent` model, with committed `contract.json` /
  `contract.d.ts` artifacts and migration outputs so the ingest service
  dogfoods Prisma Next.
- **The ingest API is small and forward-compatible.** `POST /events`
  requires the stable core fields, defaults omitted optional fields to
  `null` / `[]`, drops unknown future keys, enforces request-size
  limits, and rate-limits callers before INSERT.
- **User consent is per-user and default-off.**
  `@prisma-next/cli-telemetry` stores `enableTelemetry` and a random v4
  `installationId` under the user config directory; env overrides and
  CI suppress telemetry without mutating that file.
- **The CLI fires at command start.** A `preAction` hook resolves
  CI/env/user gates first, then loads only the telemetry-safe pieces of
  project config, sanitizes Commander metadata, and forks a detached
  sender.
- **The child owns all I/O.** The sender enriches the payload with
  runtime, package manager, TypeScript version, OS/arch, and
  best-effort agent markers, POSTs with a hard timeout, and exits 0
  while swallowing failures.

## Behavior changes

Adds the telemetry backend ingest service. Accepts `POST /events`,
validates the payload, enforces 32 KiB request limits and per-IP rate
limiting, then inserts via Prisma Next.

- Implementation: `apps/telemetry-backend/src/handler.ts`,
  `apps/telemetry-backend/src/schema.ts`,
  `apps/telemetry-backend/src/rate-limiter.ts`
- Tests: `apps/telemetry-backend/test/handler.test.ts`,
  `apps/telemetry-backend/test/rate-limit.handler.test.ts`

Adds default-off, opt-in telemetry consent. `init` asks a final
interactive consent question only when prompting is allowed, `--yes`
is not auto-accepting, CI/env overrides are absent, and no stored
answer exists.

- Implementation:
  `packages/1-framework/3-tooling/cli/src/commands/init/inputs.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/src/user-config.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/src/gating.ts`
- Tests:
  `packages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/test/gating.test.ts`

Adds detached command-start delivery. The CLI preAction hook forks the
sender, disconnects/unrefs it, and keeps telemetry failures out of the
parent command's stdout/stderr and exit path.

- Implementation: `packages/1-framework/3-tooling/cli/src/cli.ts`,
  `packages/1-framework/3-tooling/cli/src/utils/telemetry.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/src/spawn.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/src/sender.ts`
- Tests:
  `packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/test/spawn.test.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/test/integration.test.ts`

Adds sanitization and enrichment without user values. Events include
command name, user-supplied long flag names, runtime/package metadata,
target, extensions, and agent markers; they intentionally exclude
positionals and flag values.

- Implementation:
  `packages/1-framework/3-tooling/cli-telemetry/src/sanitize.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts`
- Tests:
  `packages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/test/enrich.test.ts`,
  `packages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.ts`

## Compatibility, migration, risk

- Telemetry remains off unless the user explicitly opts in;
  `PRISMA_NEXT_DISABLE_TELEMETRY`, `DO_NOT_TRACK=1`, and CI all
  suppress it.
- The backend wire format is backward-compatible for optional fields
  and forward-compatible for unknown future fields.
- `apps/*` is now part of the workspace, so the telemetry backend
  participates in install/build/test orchestration. Existing
  package-layer dependency checks remain scoped to `packages/`.
- The production endpoint URL is currently a build-time constant; if
  Prisma Compute reassigns it, the client constant needs to be updated
  before release.

## Alternatives considered

- **Send telemetry synchronously from the parent process.** Rejected
  because network failures or slow DNS could affect the CLI UX.
- **Use a per-project telemetry setting.** Rejected because one
  developer's project config should not enroll or opt out teammates.
- **Collect crash/error reporting in Phase 1.** Rejected because stack
  traces and failure lifecycle need separate consent and sanitization
  rules.

Refs TML-2557

Co-authored-by: Alexey Orlenko <[email protected]>
Signed-off-by: Alexey Orlenko <[email protected]>
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Drop the persisted writable token from the deploy workflow checkout step.
The deploy workflow does not push back to the repository, so the token is
unnecessary attack surface. Aligns with the zizmor `artipacked` lint
flagged in the CodeRabbit review.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…nd-off

Replace "out of scope for this milestone" with operational phrasing
("Deployment is performed separately: …") so the deploy hand-off paragraph
in the README stays accurate after the milestone closes.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
AGENTS.md golden rule: never add file extensions to imports in TypeScript.
TypeScript resolves "./prisma/contract" to contract.d.ts either way.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…OINT

Wrap the `new URL(...)` construction in `resolveTelemetryEndpoint` in a
try/catch so a malformed override silently falls back to the production
TELEMETRY_BACKEND_URL. Without this, a typo in the env var (dev shell or
CI config) throws synchronously and — once preAction telemetry becomes
fire-and-forget — surfaces as an unhandled rejection, contradicting the
silent-on-failure contract of the telemetry layer.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Add `pathe@^2.0.3` to dependencies and convert every `node:path` import
across `src/` and `test/` to `pathe` for cross-runtime path consistency,
matching `.cursor/rules/use-pathe-for-paths.mdc` and the rest of the
monorepo tooling.

Folds in A10 (test/no-spawn-in-tests.test.ts) as part of the same sweep.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Define `parentToSenderPayloadSchema` + `isParentToSenderPayload` in
payload.ts and use them to gate `postEvent` in sender.ts so a payload
missing any of the eight required fields is rejected instead of
silently producing a degraded telemetry event downstream.

Previously the manual guard only checked three fields (installationId,
endpoint, command); the arktype schema mirrors the backend pattern and
validates the full shape (required scalars are non-empty strings;
databaseTarget is string | null; flags / extensions are string arrays).

Adds `arktype` to dependencies and a new `test/payload.test.ts` covering
valid payloads, missing fields, and wrong-type fields.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
The sender exits after the first payload — `process.once(...)` documents
that single-message expectation and removes the listener from the
EventEmitter after invocation. Pure clarity / defensive change.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
`pnpm prisma-next migrate` (no script of that name in the current
package, no built-in match) falls back to recursive workspace exec and
fails with ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL. `pnpm exec prisma-next
migrate` runs the binary directly from `apps/telemetry-backend/node_modules/.bin/prisma-next`
which is installed via the `@prisma-next/cli` devDep. Mirrors the
existing `emit` script convention.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Drop the `TELEMETRY_` prefix added in the iter-1 trust-proxy commit to
match the unprefixed convention of the other env vars in this app
(`DATABASE_URL`, `PORT`, `RATE_LIMIT_RPM`). The app is already scoped to
`@prisma-next/telemetry-backend`, so the prefix is redundant.

Only two sites updated: the read site in `src/server-runtime.ts:114`
and the configuration table in `README.md:77`. The internal
`trustForwardedFor` config field name stays.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
`packages/1-framework/3-tooling/prisma-next/scripts/lint-sync.mjs`
requires the shim dependencies to deep-equal `@prisma-next/cli`
dependencies. The iter-1 telemetry commit added `@prisma-next/cli-telemetry`
and `ci-info` to the cli without mirroring them, so CI now fails with a
drift diff on `pnpm --filter prisma-next lint`.

Add both entries in the same insertion-order slots they occupy in the
cli package (`@prisma-next/cli-telemetry` after `@prisma-next/psl-printer`,
`ci-info` after `c12`).

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
iter-2 prescription `pnpm exec prisma-next migrate` (commit b832dad)
also fails on CI with `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Command
"prisma-next" not found`, even though it resolves locally. Same
recursive-workspace-exec fallback as the original `pnpm prisma-next
migrate`. Owning that the iter-2 fix was wrong on CI.

The idiom that actually works in this package is the plain script form
already used by `emit` and `deploy`: a `scripts` entry invoked via
`pnpm run <script>` resolves the bin from `node_modules/.bin/`
deterministically through pnpm's standard script runner.

Add `"migrate": "prisma-next migrate"` to
`apps/telemetry-backend/package.json` next to the existing `emit`
script and change the workflow step to `pnpm run migrate`.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
The previous section was stale on two counts: (1) it claimed "this
package builds nothing for deployment" when `scripts/deploy.ts`
actually drives `@prisma/compute-sdk`'s `BunBuild` strategy, and (2)
it described a manual "push the package directory and `pnpm ... start`
takes over" flow that has been superseded by the `pnpm run deploy`
script and the `deploy-telemetry-backend.yml` GitHub Actions workflow.

Replace the section with the operational truth: `pnpm run deploy` (or
the CI workflow that runs `pnpm run migrate` + `pnpm run deploy` on
`main` pushes), the three `TELEMETRY_DEPLOY_*` env vars consumed by
`scripts/deploy.ts`, a link to the workflow file, and the manual
re-deploy command. The smoke-test curl is preserved verbatim.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Replace the six `console.{log,error}` lifecycle sites in
`apps/telemetry-backend/src/{bun-server,node-server,server-runtime}.ts`
with structured `log.info` / `log.error` calls via evlog. Each call
passes structured fields (`event`, `port`, `requestsPerMinute`,
`signal`, `timeoutMs`, `error`) instead of baking them into a message
string, so the downstream wide events carry the same context the
previous console messages did.

The new `src/logger.ts` calls `initLogger` once at module load and
re-exports `log`. `enabled: false` under `NODE_ENV=test` keeps vitest
output quiet — the lifecycle log sites are not part of the assertions
that exercise this package.

Scope per the area owner: `scripts/deploy.ts` stays on `console` (it
runs outside the request/lifecycle path), and `src/handler.ts` is
untouched (it has no log sites today; no new per-request middleware in
this PR).

Adds `evlog@^1.9.0` to `apps/telemetry-backend/package.json`
dependencies (the 1.9.0 pin matches the existing
`trustPolicyExclude` entry in `pnpm-workspace.yaml`).

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…olves

`pnpm install` on first pass writes a bin shim for `prisma-next` that
points at `@prisma-next/cli`'s `dist/cli.js`, but the target does not
exist until after `pnpm build`. Re-running `pnpm install` post-build
relinks the bin, matching the `fixtures` and `test` job patterns in
`ci.yml`.

The two earlier attempts in this PR (`pnpm prisma-next migrate`, then
`pnpm exec prisma-next migrate`) both worked around the symptom rather
than the root cause. `pnpm run migrate` is the right script invocation;
it just needs the bin to be linked first.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (4)
apps/telemetry-backend/test/server-runtime.test.ts (1)

21-21: ⚡ Quick win

Replace hardcoded timeout literals with shared timeout helpers.

Line 21 and Line 36 hardcode 10_000; switch to the shared timeout constant from @prisma-next/test-utils so timeout policy stays centralized and consistent.

As per coding guidelines, "Use shared timeout helpers from @prisma-next/test-utils in tests instead of hardcoded numeric timeout values".

Also applies to: 36-36

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/telemetry-backend/test/server-runtime.test.ts` at line 21, Replace the
hardcoded 10_000 used in vi.advanceTimersByTimeAsync calls with the shared
timeout constant exported from `@prisma-next/test-utils`: import the shared
timeout symbol (e.g., the TEST_TIMEOUT/TIMEOUT_MS constant) at the top of the
test file and use that constant in both vi.advanceTimersByTimeAsync(...)
occurrences (the calls shown in the diff); ensure the import name matches the
actual export from `@prisma-next/test-utils` and update both lines (the
vi.advanceTimersByTimeAsync usages) to reference that constant so timeouts are
centralized.
apps/telemetry-backend/test/rate-limit.test.ts (1)

83-85: ⚡ Quick win

Assert the warm-up requests are accepted before testing throttle edge.

This loop silently ignores failures, so an early-regression in token accounting could still pass this test.

Suggested patch
-    for (let i = 0; i < 60; i += 1) {
-      limiter.allow('client');
-    }
+    for (let i = 0; i < 60; i += 1) {
+      expect(limiter.allow('client')).toBe(true);
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/telemetry-backend/test/rate-limit.test.ts` around lines 83 - 85, The
warm-up loop calling limiter.allow('client') currently ignores return values;
change the loop in rate-limit.test.ts to assert that each warm-up call succeeds
(e.g., expect(limiter.allow('client')).toBeTruthy() or similar) so that all 60
warm-up requests are confirmed accepted before proceeding to the throttle
assertions; target the loop containing limiter.allow('client') to add these
per-iteration assertions.
packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts (1)

3-3: ⚡ Quick win

Use pathe instead of node:path in this TypeScript test.

This import violates the repository-wide path utility rule for TS files.

Suggested fix
-import { dirname, join } from 'node:path';
+import { dirname, join } from 'pathe';

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: Use pathe instead of node:path for path manipulation in TypeScript files."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts` at line 3,
The test imports Node's path module directly ("import { dirname, join } from
'node:path';") which violates the TS rule; replace that import with the pathe
equivalents (e.g., "import { dirname, join } from 'pathe';") so the test uses
the repository-standard path utility—update any usages relying on dirname/join
to remain unchanged.
packages/1-framework/3-tooling/cli/test/setup.ts (1)

3-3: ⚡ Quick win

Switch path import to pathe for consistency with TS path rules.

Suggested fix
-import { join } from 'node:path';
+import { join } from 'pathe';

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: Use pathe instead of node:path for path manipulation in TypeScript files."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/test/setup.ts` at line 3, The import
currently uses node:path; replace the import of join from 'node:path' with an
import from 'pathe' (i.e., import { join } from 'pathe') so TypeScript path
rules are consistent; update any other uses of join in this file (e.g., in
setup.ts) if necessary to ensure no runtime/type changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/telemetry-backend/src/rate-limiter.ts`:
- Around line 31-35: Validate numeric inputs for the token bucket in the
constructor of the rate limiter (constructor(options: TokenBucketOptions)) and
the other initialization site around lines 69-74 by asserting that rpm,
capacity, and refillTokensPerMs are finite numbers > 0 (not 0, not negative, not
NaN, not Infinity); if any value is invalid, throw a clear Error mentioning the
offending option. Use the TokenBucketOptions shape and the constructor
parameters (`#capacity`, `#refillTokensPerMs`, rpm) as the location hints and ensure
the same validation logic is applied wherever those fields are used to create or
reconfigure the bucket.

In `@apps/telemetry-backend/src/server-runtime.ts`:
- Around line 46-53: parsePositiveIntegerFromEnv currently reads process.env
directly which ignores the env parameter passed into
resolveTelemetryBackendConfig; update parsePositiveIntegerFromEnv to accept an
env object (e.g., record<string,string|undefined>) and read values from that
object instead of process.env, then update calls (used for PORT and
RATE_LIMIT_RPM) in resolveTelemetryBackendConfig to pass the provided env
through so tests and embedded runtimes use the supplied environment values.
- Line 115: The code uses the wrong environment variable key when calling
parseBooleanEnv: change the key string passed to parseBooleanEnv from
'TRUST_FORWARDED_FOR' to the documented 'TELEMETRY_TRUST_FORWARDED_FOR' so that
the variable bound to trustForwardedFor respects the contract; update the call
site that defines const trustForwardedFor (and any related references to the env
key) to use 'TELEMETRY_TRUST_FORWARDED_FOR' while leaving parseBooleanEnv, env,
and the trustForwardedFor variable name unchanged.
- Around line 148-151: The shutdown currently always leaves exitCode at 0 even
when stopTelemetryBackend(server, app) returns 'timed-out' or throws; change the
logic so that if await stopTelemetryBackend(...) === 'timed-out' you set
exitCode = 1, and also set exitCode = 1 inside the catch block (and keep the
thrown error handling/logging as is), ensuring the final process exit uses that
updated exitCode variable so timeouts/failures surface to supervisors.

In `@apps/telemetry-backend/test/db-setup.ts`:
- Around line 35-60: The driver is created before the try so if
postgresDriverDescriptor.create(connectionString) throws the finally block
(which removes projectRoot) won't run; declare driver as undefined before the
try, move the postgresDriverDescriptor.create(...) call into the try (assigning
to driver), and in the finally use a safe close (e.g., check driver exists or
use optional chaining on driver.close) before calling rm(projectRoot, {
recursive: true, force: true }) so temp-dir cleanup always runs even when
creation fails.

In `@packages/1-framework/3-tooling/cli-telemetry/package.json`:
- Line 3: The package.json in packages/1-framework/3-tooling/cli-telemetry has
"version": "0.9.0" which is inconsistent with workspace consumers expecting
0.10.0; update the version field in that package.json to "0.10.0" so it matches
references like workspace:0.10.0 (ensure any package.json that declares name
"`@prisma-next/cli-telemetry`" uses the same version), then run your workspace
install/check to confirm dependency resolution succeeds.

In `@packages/1-framework/3-tooling/cli/src/commands/init/init.ts`:
- Line 120: The telemetry callback type afterFirstTelemetryConsent should allow
async functions and be awaited: change its signature from readonly
afterFirstTelemetryConsent?: (inputs: ResolvedInitInputs) => void to readonly
afterFirstTelemetryConsent?: (inputs: ResolvedInitInputs) => void |
Promise<void> (or Promise<void> only) and ensure every invocation of
afterFirstTelemetryConsent (and the other callbacks mentioned around lines
152-158) is awaited inside try/catch so promise rejections are caught; update
call sites to await afterFirstTelemetryConsent(...) and handle errors within the
existing swallow-failures try/catch.

In `@vitest.config.ts`:
- Around line 9-10: The inline comment "the standard opt-out the spec ships;
reusing it here keeps a single source of truth instead of adding a test-only env
var." should not reference "spec" or provenance; update the comment in
vitest.config.ts to describe the behavior and intent directly (for example:
state that this line reuses the standard opt-out setting to keep test behavior
consistent across environments and avoid introducing a test-only env var),
removing any phrasing like "per spec" or "the spec ships."

---

Nitpick comments:
In `@apps/telemetry-backend/test/rate-limit.test.ts`:
- Around line 83-85: The warm-up loop calling limiter.allow('client') currently
ignores return values; change the loop in rate-limit.test.ts to assert that each
warm-up call succeeds (e.g., expect(limiter.allow('client')).toBeTruthy() or
similar) so that all 60 warm-up requests are confirmed accepted before
proceeding to the throttle assertions; target the loop containing
limiter.allow('client') to add these per-iteration assertions.

In `@apps/telemetry-backend/test/server-runtime.test.ts`:
- Line 21: Replace the hardcoded 10_000 used in vi.advanceTimersByTimeAsync
calls with the shared timeout constant exported from `@prisma-next/test-utils`:
import the shared timeout symbol (e.g., the TEST_TIMEOUT/TIMEOUT_MS constant) at
the top of the test file and use that constant in both
vi.advanceTimersByTimeAsync(...) occurrences (the calls shown in the diff);
ensure the import name matches the actual export from `@prisma-next/test-utils`
and update both lines (the vi.advanceTimersByTimeAsync usages) to reference that
constant so timeouts are centralized.

In `@packages/1-framework/3-tooling/cli/test/setup.ts`:
- Line 3: The import currently uses node:path; replace the import of join from
'node:path' with an import from 'pathe' (i.e., import { join } from 'pathe') so
TypeScript path rules are consistent; update any other uses of join in this file
(e.g., in setup.ts) if necessary to ensure no runtime/type changes.

In `@packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts`:
- Line 3: The test imports Node's path module directly ("import { dirname, join
} from 'node:path';") which violates the TS rule; replace that import with the
pathe equivalents (e.g., "import { dirname, join } from 'pathe';") so the test
uses the repository-standard path utility—update any usages relying on
dirname/join to remain unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: ea46b3d6-e48b-42e6-9184-c4f0e6a56e44

📥 Commits

Reviewing files that changed from the base of the PR and between a2f1e18 and 4b2cacc.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/cli-telemetry/plan.md is excluded by !projects/**
  • projects/cli-telemetry/spec.md is excluded by !projects/**
📒 Files selected for processing (89)
  • .github/workflows/deploy-telemetry-backend.yml
  • apps/telemetry-backend/README.md
  • apps/telemetry-backend/biome.jsonc
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.d.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/ops.json
  • apps/telemetry-backend/package.json
  • apps/telemetry-backend/prisma-next.config.ts
  • apps/telemetry-backend/scripts/deploy.ts
  • apps/telemetry-backend/src/bun-server.ts
  • apps/telemetry-backend/src/db.ts
  • apps/telemetry-backend/src/handler.ts
  • apps/telemetry-backend/src/logger.ts
  • apps/telemetry-backend/src/node-server.ts
  • apps/telemetry-backend/src/prisma/contract.d.ts
  • apps/telemetry-backend/src/prisma/contract.json
  • apps/telemetry-backend/src/prisma/contract.prisma
  • apps/telemetry-backend/src/rate-limiter.ts
  • apps/telemetry-backend/src/schema.ts
  • apps/telemetry-backend/src/server-node.ts
  • apps/telemetry-backend/src/server-runtime.ts
  • apps/telemetry-backend/src/server.ts
  • apps/telemetry-backend/test/db-setup.ts
  • apps/telemetry-backend/test/handler.test.ts
  • apps/telemetry-backend/test/node-server.test.ts
  • apps/telemetry-backend/test/rate-limit.handler.test.ts
  • apps/telemetry-backend/test/rate-limit.test.ts
  • apps/telemetry-backend/test/server-runtime.test.ts
  • apps/telemetry-backend/tsconfig.json
  • apps/telemetry-backend/vitest.config.ts
  • architecture.config.json
  • examples/cipherstash-integration/package.json
  • examples/mongo-blog-leaderboard/package.json
  • examples/mongo-demo/package.json
  • examples/paradedb-demo/package.json
  • examples/prisma-next-cloudflare-worker/package.json
  • examples/prisma-next-demo-sqlite/package.json
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-postgis-demo/package.json
  • examples/retail-store/package.json
  • package.json
  • packages/1-framework/3-tooling/cli-telemetry/README.md
  • packages/1-framework/3-tooling/cli-telemetry/biome.jsonc
  • packages/1-framework/3-tooling/cli-telemetry/package.json
  • packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/endpoint.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/enrich.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/exports/index.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/gating.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/payload.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/sanitize.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/sender.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/spawn.ts
  • packages/1-framework/3-tooling/cli-telemetry/src/user-config.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/endpoint.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/enrich.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/gating.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/integration.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/no-spawn-in-tests.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/payload.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/spawn.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/test/user-config.test.ts
  • packages/1-framework/3-tooling/cli-telemetry/tsconfig.json
  • packages/1-framework/3-tooling/cli-telemetry/tsdown.config.ts
  • packages/1-framework/3-tooling/cli-telemetry/vitest.config.ts
  • packages/1-framework/3-tooling/cli/package.json
  • packages/1-framework/3-tooling/cli/src/cli.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/index.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/init.ts
  • packages/1-framework/3-tooling/cli/src/commands/init/inputs.ts
  • packages/1-framework/3-tooling/cli/src/utils/global-flags.ts
  • packages/1-framework/3-tooling/cli/src/utils/is-ci.ts
  • packages/1-framework/3-tooling/cli/src/utils/telemetry.ts
  • packages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.ts
  • packages/1-framework/3-tooling/cli/test/setup.ts
  • packages/1-framework/3-tooling/cli/test/utils/is-ci.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/no-parallel-ci-detection.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts
  • packages/1-framework/3-tooling/cli/tsconfig.json
  • packages/1-framework/3-tooling/prisma-next/package.json
  • pnpm-workspace.yaml
  • skills-contrib/drive-agent-personas/SKILL.md
  • skills-contrib/drive-discussion/SKILL.md
  • skills-contrib/github-review-iteration/SKILL.md
  • vitest.config.ts
💤 Files with no reviewable changes (2)
  • skills-contrib/drive-agent-personas/SKILL.md
  • skills-contrib/github-review-iteration/SKILL.md
✅ Files skipped from review due to trivial changes (21)
  • examples/paradedb-demo/package.json
  • examples/mongo-blog-leaderboard/package.json
  • packages/1-framework/3-tooling/cli-telemetry/tsconfig.json
  • apps/telemetry-backend/src/db.ts
  • apps/telemetry-backend/prisma-next.config.ts
  • apps/telemetry-backend/tsconfig.json
  • apps/telemetry-backend/src/schema.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.json
  • examples/mongo-demo/package.json
  • packages/1-framework/3-tooling/cli-telemetry/src/detect-agent.ts
  • packages/1-framework/3-tooling/cli-telemetry/README.md
  • packages/1-framework/3-tooling/cli/tsconfig.json
  • packages/1-framework/3-tooling/cli-telemetry/biome.jsonc
  • packages/1-framework/3-tooling/cli-telemetry/tsdown.config.ts
  • .github/workflows/deploy-telemetry-backend.yml
  • apps/telemetry-backend/package.json
  • packages/1-framework/3-tooling/cli/src/utils/global-flags.ts
  • apps/telemetry-backend/src/prisma/contract.d.ts
  • apps/telemetry-backend/src/prisma/contract.json
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.d.ts
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.json

Comment thread apps/telemetry-backend/test/db-setup.ts Resolved
Comment thread vitest.config.ts Resolved
The original telemetry commit (6e5e0ef) added `tsx: ^4.22.3` to the
workspace catalog in `pnpm-workspace.yaml` and rewrote the `tsx`
devDependency in all 9 example `package.json` files from `^4.19.2` to
`catalog:`. That diff inside `examples/` trips the
`check:upgrade-coverage` PR gate, which requires an upgrade-instructions
directory at `skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/`
for any `examples/` change.

The rewrite is an internal-only devDependency normalization with no
consumer-facing impact: both `^4.19.2` and the catalogued `^4.22.3`
resolve to the same `tsx` major, and the change keeps example
`package.json` files aligned with the catalog convention already used
for `@types/node`, `typescript`, `vitest`, etc. Per the
`record-upgrade-instructions` skill, incidental no-op-for-consumers
diffs ship with `changes: []` to record the gate exit explicitly.

Future breaking changes shipping in the 0.10 → 0.11 cycle will append
to this same file as `changes[]` entries.

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

Copy link
Copy Markdown
Contributor Author

Triage of the new review body (A10a–A10e)

Thanks for the iter-4 pass. Of the 12 findings in the review body, 7 of the 8 actionable ones are mirrored as inline threads and triaged there (A01–A07 — all will_address). The remaining 1 body-only actionable and the 4 nitpicks are decomposed below.

A10a — server-runtime.ts L115 env var key revert · not actionable

CodeRabbit asks to change parseBooleanEnv('TRUST_FORWARDED_FOR', env, false) back to parseBooleanEnv('TELEMETRY_TRUST_FORWARDED_FOR', env, false) because "the documented" key is the prefixed one.

The current key TRUST_FORWARDED_FOR is the documented one — it's the result of iter-2 (commit fb776c63), where @aqrln explicitly asked to rename TELEMETRY_TRUST_FORWARDED_FOR → TRUST_FORWARDED_FOR to match the unprefixed convention of the surrounding env vars (DATABASE_URL, PORT, RATE_LIMIT_RPM). apps/telemetry-backend/README.md:77 already documents TRUST_FORWARDED_FOR; the code and docs are in sync.

A10b — apps/telemetry-backend/test/rate-limit.test.ts:83-85 warm-up assertion · will address

Wrapping the 60-iteration warm-up loop with expect(limiter.allow('client')).toBe(true) to match the sibling test in the same describe block (~L73-78). One-line consistency fix.

A10c — apps/telemetry-backend/test/server-runtime.test.ts:21,36 hardcoded 10_000 · not actionable

CodeRabbit cites .cursor/rules/use-timeouts-helper-in-tests.mdc and asks to replace vi.advanceTimersByTimeAsync(10_000) with a timeouts.* constant from @prisma-next/test-utils. The rule targets test framework timeouts ({ timeout: ... }, vitest's hookTimeout / testTimeout) where the number is "how long to wait before failing the test". Here 10_000 is a fake-timer advance whose value must exactly equal the production constant SHUTDOWN_TIMEOUT_MS = 10_000 (from server-runtime.ts) to trigger the timeout branch under test. A timeouts.* constant scales with TEST_TIMEOUT_MULTIPLIER and would break that relationship.

A10d — packages/1-framework/3-tooling/cli/test/setup.ts:3 pathe · will address

import { join } from 'node:path' → import { join } from 'pathe' per .cursor/rules/use-pathe-for-paths.mdc. Missed by the iter-1 sweep.

A10e — packages/1-framework/3-tooling/cli/test/utils/telemetry.test.ts:3 pathe · will address

import { dirname, join } from 'node:path' → import { dirname, join } from 'pathe' per the same rule. Pair with A10d in one commit.

The 3 will_address items here (A10b, A10d, A10e) will be picked up alongside the 7 inline-thread actions next. Will follow up once landed.

…puts

Reject misconfigured rate-limiter parameters at construction time so a
bad `RATE_LIMIT_RPM` fails loudly instead of silently producing a
no-op or NaN-poisoned limiter.

- `TokenBucketRateLimiter` constructor throws when `capacity` is not a
  finite number > 0, or when `refillTokensPerMs` is not a finite number
  >= 0 (>= 0 to preserve the existing no-refill test pattern that uses
  `refillTokensPerMs: 0`).
- `createRequestsPerMinuteRateLimiter` throws when `rpm` is not a
  finite number > 0.

Each error message names the offending option and includes the actual
value. Adds parametric vitest cases covering 0 / negative / NaN /
Infinity for each guarded parameter.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
`resolveTelemetryBackendConfig(env = process.env)` is documented to
accept a synthetic environment so tests and embedders can drive it
without mutating real `process.env`. The `DATABASE_URL` lookup and the
`parseBooleanEnv` call already honour that parameter, but
`parsePositiveIntegerFromEnv` reads from `process.env` directly,
silently ignoring the caller-provided env for `PORT` and
`RATE_LIMIT_RPM`.

Thread the `env` parameter through `parsePositiveIntegerFromEnv` to
match `parseBooleanEnv`'s signature, and pass `env` at both call sites
in `resolveTelemetryBackendConfig`. Adds a regression test that
overrides `PORT` and `RATE_LIMIT_RPM` via the env argument and a
companion test that exercises the default fallbacks.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
The signal-handler shutdown closure already logs an error via
`log.error({ event: 'shutdown-timeout' })`, but it discarded
`stopTelemetryBackend`'s return value and unconditionally exited 0 on
the happy path. Process supervisors (systemd, Kubernetes, Prisma
Compute) read that as a clean shutdown and never retry / alert.

Extract a tiny `shutdownExitCode(result)` helper that maps
`'stopped' | 'timed-out'` to `0 | 1`, and call it on the awaited
result. The `catch` branch is unchanged (still `exitCode = 1`).

Adds two focused unit tests for the helper: clean stop returns 0,
timeout returns 1.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
If `postgresDriverDescriptor.create(connectionString)` rejected (bad
URL, server unreachable, auth failure) the `mkdtemp`'d
`telemetry-backend-schema-*` directory leaked because control never
reached the `finally` block.

Declare `driver` outside the `try`, assign it inside, and guard the
`finally` block against the undefined case. Now both the driver close
and the temp-dir cleanup run regardless of where the driver-creation
or schema-init code throws.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
`@prisma-next/cli-telemetry`'s package.json declared `0.9.0` while every
sibling tooling package and its consumers (`@prisma-next/cli`, the
`prisma-next` shim, the lint-sync mirror) reference it as
`workspace:0.10.0`. Lockfile installs only kept working because the
existing entries were pinned at the older spec; any clean install or
new consumer would trip pnpm strict workspace resolution.

Bumps `version` to `0.10.0` and updates the three intra-workspace
devDeps (`@prisma-next/test-utils`, `@prisma-next/tsconfig`,
`@prisma-next/tsdown`) from `workspace:0.9.0` to `workspace:0.10.0` so
they match the actual workspace versions. Lockfile regenerated via
`pnpm install`; `pnpm install --frozen-lockfile` now exits clean and
tests / lint stay green at the new version.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Widen the `afterFirstTelemetryConsent` callback signature in `runInit`
from `(inputs) => void` to `(inputs) => void | Promise<void>` and
`await` the invocation inside the existing swallow-failures `try/catch`.

Today the only caller wires it to a sync function, but TypeScript would
silently let a future async caller assign in — and the comment "init
success must not depend on telemetry" would quietly become false because
an unhandled rejection from the unawaited promise would escape the
`try/catch`. Awaiting puts the rejection back inside the swallowed
boundary.

Mirrors the iter-1 `cli.ts` preAction discussion (A09): inside a sync
boundary, async telemetry callbacks must be awaited even when the
caller doesn't care about the outcome.

Adds a regression test using a rejecting async `vi.fn` that asserts
init still exits with `INIT_EXIT_OK`.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Rework the `PRISMA_NEXT_DISABLE_TELEMETRY` comment in `vitest.config.ts`
to describe the env var directly instead of leaking doc-provenance
("the spec ships"). The env var name and the single-source-of-truth
rationale are preserved verbatim; only the framing changes.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…t test

The sibling burst-cap test already asserts `expect(limiter.allow(...)).toBe(true)`
inside its 60-iteration warm-up loop; the refill-interval test was the only
case-of-the-pair that called `limiter.allow(...)` without asserting on it,
so a regression in token accounting during warm-up would pass through to
the refill assertion. One-line consistency fix.

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

Copy link
Copy Markdown
Contributor Author

A10b (rate-limit warm-up assertion): done in 4744b4d. Added expect(limiter.allow('client')).toBe(true) inside the warm-up loop of the refill-interval test to match the sibling burst-cap test.

Two files in `packages/1-framework/3-tooling/cli/test/` (`setup.ts` and
`utils/telemetry.test.ts`) still used `node:path` after the iter-1 sweep
of `cli-telemetry`. Convert both to `pathe` per `.cursor/rules/use-pathe-for-paths.mdc`.

`pathe` is already a transitive dep of the cli package; no
package.json changes needed. The broader `cli` tree still has other
`node:path` imports (scaffold scripts, several other test files); those
are out of scope for this fix and untouched.

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

Copy link
Copy Markdown
Contributor Author

A10d + A10e (pathe sweep in cli/test/): done in fc91a20. Switched packages/1-framework/3-tooling/cli/test/setup.ts and test/utils/telemetry.test.ts from node:path to pathe. Other node:path imports in the cli tree (scaffold scripts, several other test files) were not called out by the review and remain untouched.

@aqrln
aqrln enabled auto-merge (rebase) May 20, 2026 19:56

@aqrln aqrln left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

@aqrln
aqrln merged commit bf663db into main May 20, 2026
16 checks passed
@aqrln
aqrln deleted the telemetry branch May 20, 2026 19:59
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