Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions docs/product/command-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,18 @@ The beta package includes these command groups:
- `app`
- `build` (includes `build logs`)

The beta package also includes two top-level commands:
The beta package also includes three top-level commands:

- `version`
- `init`
- `feedback`

`version` is intentionally outside the workflow groups: it reports CLI build and environment state, requires no auth, no project context, and no network, and is the canonical answer to "is this CLI installed and on the build I expect?"

`feedback` is also outside the workflow groups: it sends a message to the
Prisma CLI team's feedback service and touches no platform resource, so it
requires no auth, no workspace, and no project context.

`init` is a top-level workflow verb: it acts on the local project directory
(writing the committed compute config) rather than managing a remote resource,
so it sits beside the ORM's verb register (`generate`, `migrate`, `validate`)
Expand All @@ -44,7 +49,7 @@ Out of scope for the current beta:
## Global Rules

- Canonical shape is `prisma <group> <action>`.
- `version` and `init` are the top-level commands outside that shape (see Scope above).
- `version`, `init`, and `feedback` are the top-level commands outside that shape (see Scope above).
- Every command supports `--json`.
- Shared global flags are:
- `--json`
Expand Down Expand Up @@ -435,6 +440,32 @@ prisma-cli init --format ts
prisma-cli init --json
```

## `prisma-cli feedback <message> --email <email>`
Comment thread
coderabbitai[bot] marked this conversation as resolved.

Purpose:

- send feedback about the CLI to the Prisma team

Behavior:

- requires no auth, no workspace, no project context, and no config; never prompts, in any mode
- anonymous by default; `--email <address>` opts into being contactable, and the address is validated when passed
- attaches non-PII environment context to every submission: CLI version, node version, and OS platform and arch; the command help discloses exactly this list
- the feedback service uses the client IP transiently, in memory, to rate limit submissions; the IP is never stored with the feedback
- `<message>` is required, trimmed, and limited to 4000 characters; an empty or oversized message is a usage error and nothing is sent
- posts to the feedback service with a 3-second timeout; delivery failures (unreachable service, timeout, non-2xx response) fail with `FEEDBACK_SEND_FAILED` and exit 1, and the message is not persisted anywhere locally
- `PRISMA_CLI_FEEDBACK_URL` overrides the service endpoint for testing and staging
- unexpected CLI crashes point here: the human crash message ends with a `Tell us what happened: prisma-cli feedback "..."` hint pre-filled with the failing command and error line (suppressed by `--quiet`), and `--json` crashes return an `UNEXPECTED_ERROR` envelope whose `nextActions` carries the same pre-filled command as a `recover` action; expected failures and usage errors never advertise feedback
- in `--json`, `result` includes the submission `id` returned by the service (null when the response carries none), the `email` sent (null when anonymous), and the attached `context`

Examples:

```bash
prisma-cli feedback "the deploy flow is great"
prisma-cli feedback "please add X" --email you@example.com
prisma-cli feedback "agent output is solid" --json
```

## `<runner> @prisma/cli@latest agent install --agent <agent> --all-agents --skill <skill> --global --copy`

Purpose:
Expand Down
6 changes: 5 additions & 1 deletion docs/product/error-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Examples:
- unexpected `undefined`
- internal serialization or state invariant broken

Bugs should fail fast and preserve stack traces. Catch them only at the outermost boundary for crash formatting.
Bugs should fail fast and preserve stack traces. Catch them only at the outermost boundary for crash formatting. At that boundary, `--json` runs still emit the standard error envelope with code `UNEXPECTED_ERROR`, and both output modes point at `prisma-cli feedback` pre-filled with the failing command and error line (`--quiet` suppresses the human hint; expected failures never carry the feedback suggestion).

## Boundary Handling

Expand Down Expand Up @@ -159,6 +159,8 @@ Rules:
These codes are the minimum stable set for the MVP:

- `USAGE_ERROR`
- `UNEXPECTED_ERROR`
- `FEEDBACK_SEND_FAILED`
Comment thread
coderabbitai[bot] marked this conversation as resolved.
- `AUTH_REQUIRED`
- `AUTH_CONFIG_INVALID`
- `AGENT_SKILLS_INSTALL_FAILED`
Expand Down Expand Up @@ -234,6 +236,8 @@ These codes are the minimum stable set for the MVP:
Recommended meanings:

- `USAGE_ERROR`: invalid arguments or invalid command combination
- `UNEXPECTED_ERROR`: the CLI crashed on an unexpected fault; the envelope carries a `recover` next action suggesting `prisma-cli feedback`
- `FEEDBACK_SEND_FAILED`: the feedback service was unreachable, timed out, or returned a non-2xx response
- `AUTH_REQUIRED`: command needs an authenticated session
- `AUTH_CONFIG_INVALID`: environment auth configuration is present but unusable, such as an empty `PRISMA_SERVICE_TOKEN`
- `AGENT_SKILLS_INSTALL_FAILED`: installing Prisma skills through the external skills CLI failed; callers should inspect the command, exit code, and stderr in `error.meta`
Expand Down
1 change: 1 addition & 0 deletions docs/product/output-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ Current MVP commands map to patterns like this:
| Command | Pattern |
| --- | --- |
| `version` | `show` |
| `feedback` | `show` (send confirmation card) |
| `auth login` | `mutate` |
| `auth logout` | `mutate` |
| `auth whoami` | `show` |
Expand Down
23 changes: 22 additions & 1 deletion packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createAuthCommand } from "./commands/auth";
import { createBranchCommand } from "./commands/branch";
import { createBuildCommand } from "./commands/build";
import { createDatabaseCommand } from "./commands/database";
import { createFeedbackCommand } from "./commands/feedback";
import { createGitCommand } from "./commands/git";
import { createInitCommand } from "./commands/init";
import { createProjectCommand } from "./commands/project";
Expand All @@ -19,9 +20,11 @@ import { CliError } from "./shell/errors";
import { addCompactGlobalFlags } from "./shell/global-flags";
import {
formatUnexpectedError,
unexpectedErrorFeedbackCommand,
writeHumanError,
writeJsonError,
writeJsonSuccess,
writeJsonUnexpectedError,
} from "./shell/output";
import { disposePromptState } from "./shell/prompt";
import {
Expand Down Expand Up @@ -62,8 +65,25 @@ export async function runCli(options: RunCliOptions = {}): Promise<number> {
return error.code === "commander.helpDisplayed" ? 0 : 2;
}

// Crashes must not break the --json contract; agents get a structured
// UNEXPECTED_ERROR envelope with a recover action pointing at feedback.
if (runtime.argv.includes("--json")) {
writeJsonUnexpectedError(
{ stdout: runtime.stdout, stderr: runtime.stderr },
runtime.argv,
error,
);
return 1;
}

const quiet =
runtime.argv.includes("--quiet") || runtime.argv.includes("-q");
runtime.stderr.write(
formatUnexpectedError(error, runtime.argv.includes("--trace")),
formatUnexpectedError(
error,
runtime.argv.includes("--trace"),
quiet ? undefined : unexpectedErrorFeedbackCommand(runtime.argv, error),
),
);
return 1;
} finally {
Expand All @@ -85,6 +105,7 @@ export function createProgram(runtime: CliRuntime): Command {

program.addCommand(createVersionCommand(runtime));
program.addCommand(createInitCommand(runtime));
program.addCommand(createFeedbackCommand(runtime));
program.addCommand(createAgentCommand(runtime));
program.addCommand(createAuthCommand(runtime));
program.addCommand(createProjectCommand(runtime));
Expand Down
43 changes: 43 additions & 0 deletions packages/cli/src/commands/feedback/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Command, Option } from "commander";

import { type FeedbackFlags, runFeedback } from "../../controllers/feedback";
import { renderFeedbackSuccess } from "../../presenters/feedback";
import { attachCommandDescriptor } from "../../shell/command-meta";
import { runCommand } from "../../shell/command-runner";
import { addGlobalFlags } from "../../shell/global-flags";
import { type CliRuntime, configureRuntimeCommand } from "../../shell/runtime";
import type { FeedbackResult } from "../../types/feedback";

export function createFeedbackCommand(runtime: CliRuntime): Command {
const command = attachCommandDescriptor(
configureRuntimeCommand(new Command("feedback"), runtime),
"feedback",
);

command
.argument("<message>", "Feedback text (up to 4000 characters)")
.addOption(
new Option(
"--email <address>",
"Contact email if you want a reply; feedback is anonymous without it",
),
);
addGlobalFlags(command);

command.action(async (message: string, options) => {
const flags = options as FeedbackFlags;

await runCommand<FeedbackResult>(
runtime,
"feedback",
options as Record<string, unknown>,
(context) => runFeedback(context, message, { email: flags.email }),
{
renderHuman: (context, descriptor, result) =>
renderFeedbackSuccess(context, descriptor, result),
},
);
});

return command;
}
175 changes: 175 additions & 0 deletions packages/cli/src/controllers/feedback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { getCliVersion } from "../lib/version";
import { CliError, usageError } from "../shell/errors";
import type { CommandSuccess } from "../shell/output";
import type { CommandContext } from "../shell/runtime";
import type { FeedbackContext, FeedbackResult } from "../types/feedback";

const DEFAULT_FEEDBACK_ENDPOINT =
"https://hiieirp2pwqnjvq9axzyg6d0.fra.prisma.build/feedback";
// Feedback must never feel slower than the thought it carries; a service
// that cannot answer quickly is treated as unavailable.
const FEEDBACK_TIMEOUT_MS = 3_000;
// Mirrors the feedback service's own limits so refusals happen before the
// network round trip.
const MAX_MESSAGE_LENGTH = 4_000;
const MAX_EMAIL_LENGTH = 320;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export interface FeedbackFlags {
email?: string;
}

export async function runFeedback(
context: CommandContext,
messageArg: string,
flags: FeedbackFlags,
): Promise<CommandSuccess<FeedbackResult>> {
const message = messageArg.trim();
if (!message) {
throw usageError(
"Feedback message required",
"The message argument is empty.",
"Pass a non-empty message.",
['prisma-cli feedback "the deploy flow is great"'],
);
}
if (message.length > MAX_MESSAGE_LENGTH) {
throw usageError(
"Feedback message too long",
`The message is ${message.length} characters; the limit is ${MAX_MESSAGE_LENGTH}.`,
"Shorten the message.",
);
}

const email = flags.email?.trim();
if (
email !== undefined &&
(email.length > MAX_EMAIL_LENGTH || !EMAIL_PATTERN.test(email))
) {
throw usageError(
"Invalid email",
`"${flags.email}" is not a valid email address of at most ${MAX_EMAIL_LENGTH} characters.`,
"Pass a valid address with --email, or drop the flag to stay anonymous.",
['prisma-cli feedback "please add X" --email you@example.com'],
);
}

const feedbackContext: FeedbackContext = {
cliVersion: getCliVersion(),
nodeVersion: process.version,
platform: process.platform,
arch: process.arch,
};

const endpoint =
context.runtime.env.PRISMA_CLI_FEEDBACK_URL || DEFAULT_FEEDBACK_ENDPOINT;
const id = await postFeedback(context, endpoint, {
message,
...(email ? { email } : {}),
meta: { ...feedbackContext },
});

return {
command: "feedback",
result: {
id,
email: email ?? null,
context: feedbackContext,
},
warnings: [],
nextSteps: [],
};
}

async function postFeedback(
context: CommandContext,
endpoint: string,
body: Record<string, unknown>,
): Promise<string | null> {
let response: Response;
try {
response = await fetch(endpoint, {
method: "POST",
headers: {
"content-type": "application/json",
"user-agent": `prisma-cli/${getCliVersion()}`,
},
body: JSON.stringify(body),
signal: AbortSignal.any([
context.runtime.signal,
AbortSignal.timeout(FEEDBACK_TIMEOUT_MS),
]),
});
} catch (error) {
if (context.runtime.signal.aborted) {
throw error;
}
const detail =
error instanceof Error && error.name === "TimeoutError"
? TIMEOUT_DETAIL
: `The feedback service could not be reached${error instanceof Error && error.cause instanceof Error ? ` (${error.cause.message})` : ""}.`;
throw feedbackSendFailed(detail);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

if (!response.ok) {
throw feedbackSendFailed(
`The feedback service responded with HTTP ${response.status}${await readServiceError(context, response)}.`,
);
}

// The body read runs under the same abort signal as the request, so a
// stalled response or a user cancellation here must not be mistaken for a
// fully received non-JSON body.
let payload: { id?: unknown } | null;
try {
payload = (await response.json()) as { id?: unknown } | null;
} catch (error) {
if (context.runtime.signal.aborted) {
throw error;
}
if (!(error instanceof SyntaxError)) {
throw feedbackSendFailed(
error instanceof Error && error.name === "TimeoutError"
? TIMEOUT_DETAIL
: "The feedback service response could not be read.",
);
}
// The body arrived but was not JSON; the submission itself succeeded.
payload = null;
}
return typeof payload?.id === "string" ? payload.id : null;
}

const TIMEOUT_DETAIL = `The feedback service did not answer within ${FEEDBACK_TIMEOUT_MS / 1000} seconds.`;

async function readServiceError(
context: CommandContext,
response: Response,
): Promise<string> {
let payload: { error?: { message?: unknown } } | null;
try {
payload = (await response.json()) as {
error?: { message?: unknown };
} | null;
} catch (error) {
if (context.runtime.signal.aborted) {
throw error;
}
return "";
}
return typeof payload?.error?.message === "string"
? ` (${payload.error.message})`
: "";
}

function feedbackSendFailed(detail: string): CliError {
return new CliError({
code: "FEEDBACK_SEND_FAILED",
domain: "cli",
summary: "Feedback could not be delivered",
why: detail,
fix: "Check your network and rerun the command.",
exitCode: 1,
nextSteps: [],
});
}
Loading
Loading