Repository navigation
Conversation
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (3)
📒 Files selected for processing (87)
📝 WalkthroughWalkthroughAdds 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. ChangesTelemetry Backend Service
CLI Telemetry Client Library
CLI Integration and Consent
Infrastructure and Workspace
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)
Estimated code review effort 🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests (beta)
|
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/extension-cipherstash
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 14
🧹 Nitpick comments (2)
apps/telemetry-backend/test/db-setup.ts (1)
3-3: ⚡ Quick winUse
patheinstead ofnode:pathin this TypeScript test helper.Please replace the
node:pathimport withpatheto 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}: Usepatheinstead ofnode:pathfor 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 winRefocus 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.mdfocused 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
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/cli-telemetry/plan.mdis excluded by!projects/**projects/cli-telemetry/spec.mdis excluded by!projects/**
📒 Files selected for processing (68)
.github/workflows/deploy-telemetry-backend.ymlapps/telemetry-backend/README.mdapps/telemetry-backend/biome.jsoncapps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.d.tsapps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.jsonapps/telemetry-backend/migrations/app/20260520T1317_migration/migration.jsonapps/telemetry-backend/migrations/app/20260520T1317_migration/migration.tsapps/telemetry-backend/migrations/app/20260520T1317_migration/ops.jsonapps/telemetry-backend/package.jsonapps/telemetry-backend/prisma-next.config.tsapps/telemetry-backend/scripts/deploy.tsapps/telemetry-backend/src/db.tsapps/telemetry-backend/src/handler.tsapps/telemetry-backend/src/prisma/contract.d.tsapps/telemetry-backend/src/prisma/contract.jsonapps/telemetry-backend/src/prisma/contract.prismaapps/telemetry-backend/src/rate-limiter.tsapps/telemetry-backend/src/schema.tsapps/telemetry-backend/src/server.tsapps/telemetry-backend/test/db-setup.tsapps/telemetry-backend/test/handler.test.tsapps/telemetry-backend/test/rate-limit.handler.test.tsapps/telemetry-backend/test/rate-limit.test.tsapps/telemetry-backend/tsconfig.jsonapps/telemetry-backend/vitest.config.tsarchitecture.config.jsonpackage.jsonpackages/1-framework/3-tooling/cli-telemetry/README.mdpackages/1-framework/3-tooling/cli-telemetry/biome.jsoncpackages/1-framework/3-tooling/cli-telemetry/package.jsonpackages/1-framework/3-tooling/cli-telemetry/src/detect-agent.tspackages/1-framework/3-tooling/cli-telemetry/src/endpoint.tspackages/1-framework/3-tooling/cli-telemetry/src/enrich.tspackages/1-framework/3-tooling/cli-telemetry/src/exports/index.tspackages/1-framework/3-tooling/cli-telemetry/src/gating.tspackages/1-framework/3-tooling/cli-telemetry/src/payload.tspackages/1-framework/3-tooling/cli-telemetry/src/sanitize.tspackages/1-framework/3-tooling/cli-telemetry/src/sender.tspackages/1-framework/3-tooling/cli-telemetry/src/spawn.tspackages/1-framework/3-tooling/cli-telemetry/src/user-config.tspackages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.tspackages/1-framework/3-tooling/cli-telemetry/test/endpoint.test.tspackages/1-framework/3-tooling/cli-telemetry/test/enrich.test.tspackages/1-framework/3-tooling/cli-telemetry/test/gating.test.tspackages/1-framework/3-tooling/cli-telemetry/test/integration.test.tspackages/1-framework/3-tooling/cli-telemetry/test/no-spawn-in-tests.test.tspackages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.tspackages/1-framework/3-tooling/cli-telemetry/test/spawn.test.tspackages/1-framework/3-tooling/cli-telemetry/test/user-config.test.tspackages/1-framework/3-tooling/cli-telemetry/tsconfig.jsonpackages/1-framework/3-tooling/cli-telemetry/tsdown.config.tspackages/1-framework/3-tooling/cli-telemetry/vitest.config.tspackages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/src/cli.tspackages/1-framework/3-tooling/cli/src/commands/init/index.tspackages/1-framework/3-tooling/cli/src/commands/init/init.tspackages/1-framework/3-tooling/cli/src/commands/init/inputs.tspackages/1-framework/3-tooling/cli/src/utils/global-flags.tspackages/1-framework/3-tooling/cli/src/utils/is-ci.tspackages/1-framework/3-tooling/cli/src/utils/telemetry.tspackages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.tspackages/1-framework/3-tooling/cli/test/setup.tspackages/1-framework/3-tooling/cli/test/utils/is-ci.test.tspackages/1-framework/3-tooling/cli/test/utils/no-parallel-ci-detection.test.tspackages/1-framework/3-tooling/cli/test/utils/telemetry.test.tspackages/1-framework/3-tooling/cli/tsconfig.jsonpnpm-workspace.yamlvitest.config.ts
5066c3a to
6e5e0ef
Compare
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 — A13b — A13c — A13d — |
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]>
|
A13a (trust-proxy gate for x-forwarded-for): on it 👍 |
|
A13a (trust-proxy gate for x-forwarded-for): done in b9b4965. Defaulted |
|
A13d (pathe sweep for apps/telemetry-backend): done in fa9f40c. Added pathe@^2.0.3 to devDependencies and switched |
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]>
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (4)
apps/telemetry-backend/test/server-runtime.test.ts (1)
21-21: ⚡ Quick winReplace 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-utilsso timeout policy stays centralized and consistent.As per coding guidelines, "Use shared timeout helpers from
@prisma-next/test-utilsin 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 winAssert 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 winUse
patheinstead ofnode:pathin 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}: Usepatheinstead ofnode:pathfor 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 winSwitch path import to
pathefor consistency with TS path rules.Suggested fix
-import { join } from 'node:path'; +import { join } from 'pathe';As per coding guidelines: "
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor 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
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/cli-telemetry/plan.mdis excluded by!projects/**projects/cli-telemetry/spec.mdis excluded by!projects/**
📒 Files selected for processing (89)
.github/workflows/deploy-telemetry-backend.ymlapps/telemetry-backend/README.mdapps/telemetry-backend/biome.jsoncapps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.d.tsapps/telemetry-backend/migrations/app/20260520T1317_migration/end-contract.jsonapps/telemetry-backend/migrations/app/20260520T1317_migration/migration.jsonapps/telemetry-backend/migrations/app/20260520T1317_migration/migration.tsapps/telemetry-backend/migrations/app/20260520T1317_migration/ops.jsonapps/telemetry-backend/package.jsonapps/telemetry-backend/prisma-next.config.tsapps/telemetry-backend/scripts/deploy.tsapps/telemetry-backend/src/bun-server.tsapps/telemetry-backend/src/db.tsapps/telemetry-backend/src/handler.tsapps/telemetry-backend/src/logger.tsapps/telemetry-backend/src/node-server.tsapps/telemetry-backend/src/prisma/contract.d.tsapps/telemetry-backend/src/prisma/contract.jsonapps/telemetry-backend/src/prisma/contract.prismaapps/telemetry-backend/src/rate-limiter.tsapps/telemetry-backend/src/schema.tsapps/telemetry-backend/src/server-node.tsapps/telemetry-backend/src/server-runtime.tsapps/telemetry-backend/src/server.tsapps/telemetry-backend/test/db-setup.tsapps/telemetry-backend/test/handler.test.tsapps/telemetry-backend/test/node-server.test.tsapps/telemetry-backend/test/rate-limit.handler.test.tsapps/telemetry-backend/test/rate-limit.test.tsapps/telemetry-backend/test/server-runtime.test.tsapps/telemetry-backend/tsconfig.jsonapps/telemetry-backend/vitest.config.tsarchitecture.config.jsonexamples/cipherstash-integration/package.jsonexamples/mongo-blog-leaderboard/package.jsonexamples/mongo-demo/package.jsonexamples/paradedb-demo/package.jsonexamples/prisma-next-cloudflare-worker/package.jsonexamples/prisma-next-demo-sqlite/package.jsonexamples/prisma-next-demo/package.jsonexamples/prisma-next-postgis-demo/package.jsonexamples/retail-store/package.jsonpackage.jsonpackages/1-framework/3-tooling/cli-telemetry/README.mdpackages/1-framework/3-tooling/cli-telemetry/biome.jsoncpackages/1-framework/3-tooling/cli-telemetry/package.jsonpackages/1-framework/3-tooling/cli-telemetry/src/detect-agent.tspackages/1-framework/3-tooling/cli-telemetry/src/endpoint.tspackages/1-framework/3-tooling/cli-telemetry/src/enrich.tspackages/1-framework/3-tooling/cli-telemetry/src/exports/index.tspackages/1-framework/3-tooling/cli-telemetry/src/gating.tspackages/1-framework/3-tooling/cli-telemetry/src/payload.tspackages/1-framework/3-tooling/cli-telemetry/src/sanitize.tspackages/1-framework/3-tooling/cli-telemetry/src/sender.tspackages/1-framework/3-tooling/cli-telemetry/src/spawn.tspackages/1-framework/3-tooling/cli-telemetry/src/user-config.tspackages/1-framework/3-tooling/cli-telemetry/test/detect-agent.test.tspackages/1-framework/3-tooling/cli-telemetry/test/endpoint.test.tspackages/1-framework/3-tooling/cli-telemetry/test/enrich.test.tspackages/1-framework/3-tooling/cli-telemetry/test/gating.test.tspackages/1-framework/3-tooling/cli-telemetry/test/integration.test.tspackages/1-framework/3-tooling/cli-telemetry/test/no-spawn-in-tests.test.tspackages/1-framework/3-tooling/cli-telemetry/test/payload.test.tspackages/1-framework/3-tooling/cli-telemetry/test/sanitize.test.tspackages/1-framework/3-tooling/cli-telemetry/test/spawn.test.tspackages/1-framework/3-tooling/cli-telemetry/test/user-config.test.tspackages/1-framework/3-tooling/cli-telemetry/tsconfig.jsonpackages/1-framework/3-tooling/cli-telemetry/tsdown.config.tspackages/1-framework/3-tooling/cli-telemetry/vitest.config.tspackages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/src/cli.tspackages/1-framework/3-tooling/cli/src/commands/init/index.tspackages/1-framework/3-tooling/cli/src/commands/init/init.tspackages/1-framework/3-tooling/cli/src/commands/init/inputs.tspackages/1-framework/3-tooling/cli/src/utils/global-flags.tspackages/1-framework/3-tooling/cli/src/utils/is-ci.tspackages/1-framework/3-tooling/cli/src/utils/telemetry.tspackages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.tspackages/1-framework/3-tooling/cli/test/setup.tspackages/1-framework/3-tooling/cli/test/utils/is-ci.test.tspackages/1-framework/3-tooling/cli/test/utils/no-parallel-ci-detection.test.tspackages/1-framework/3-tooling/cli/test/utils/telemetry.test.tspackages/1-framework/3-tooling/cli/tsconfig.jsonpackages/1-framework/3-tooling/prisma-next/package.jsonpnpm-workspace.yamlskills-contrib/drive-agent-personas/SKILL.mdskills-contrib/drive-discussion/SKILL.mdskills-contrib/github-review-iteration/SKILL.mdvitest.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
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]>
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 A10a — server-runtime.ts L115 env var key revert · not actionableCodeRabbit asks to change The current key A10b —
|
…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]>
|
A10b (rate-limit warm-up assertion): done in 4744b4d. Added |
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]>
|
A10d + A10e (pathe sweep in cli/test/): done in fc91a20. Switched |
Linked issue
Refs TML-2557
Supersedes #536.
At a glance
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
apps/telemetry-backendandpnpm-workspace.yamlnow includesapps/*; the existing package-layer dependency checks remain scoped topackages/.telemetrybranch while ignoring local uncommitted WIP, per the recreation request.How it fits together
apps/telemetry-backend/src/prisma/contract.prismadefines a singleTelemetryEventmodel, with committedcontract.json/contract.d.tsartifacts and migration outputs so the ingest service dogfoods Prisma Next.POST /eventsrequires the stable core fields, defaults omitted optional fields tonull/[], drops unknown future keys, enforces request-size limits, and rate-limits callers before INSERT.@prisma-next/cli-telemetrystoresenableTelemetryand a random v4installationIdunder the user config directory; env overrides and CI suppress telemetry without mutating that file.preActionhook resolves CI/env/user gates first, then loads only the telemetry-safe pieces of project config, sanitizes Commander metadata, and forks a detached sender.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.apps/telemetry-backend/src/handler.ts,apps/telemetry-backend/src/schema.ts,apps/telemetry-backend/src/rate-limiter.tsapps/telemetry-backend/test/handler.test.ts,apps/telemetry-backend/test/rate-limit.handler.test.tsAdds default-off, opt-in telemetry consent.
initasks a final interactive consent question only when prompting is allowed,--yesis not auto-accepting, CI/env overrides are absent, and no stored answer exists.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.tspackages/1-framework/3-tooling/cli/test/commands/init/consent-prompt.test.ts,packages/1-framework/3-tooling/cli-telemetry/test/gating.test.tsAdds 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.
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.tspackages/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.tsAdds 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.
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.tspackages/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.tsCompatibility / migration / risk
PRISMA_NEXT_DISABLE_TELEMETRY,DO_NOT_TRACK=1, and CI all suppress it.apps/*is now part of the workspace so the telemetry backend participates in install/build/test orchestration.Testing performed
Not rerun locally while recreating the PR; local uncommitted WIP was intentionally ignored.
Previous PR #536 CI at recreation time:
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
git commit -s) per the DCO. The DCO status check will block merge if any commit is missing aSigned-off-by:trailer.n/aif the change is doc-only / refactor with no behavioural delta).TML-NNNN: <sentence-case title>form (Linear ticket prefix + concise title naming the concrete deliverable). See.claude/skills/create-pr/SKILL.mdfor the full convention.n/a — internal only).Alternatives considered
Summary by CodeRabbit
New Features
Bug Fixes / Reliability
Chores