gencow 0.1.268 → 0.1.270

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,12 @@ import { existsSync, readFileSync } from "node:fs";
4
4
  import { dirname, resolve } from "node:path";
5
5
 
6
6
  import { classifyMigrationFolderFormatFailure } from "./migration-folder-format.mjs";
7
+ import {
8
+ classifyMissingHintsOutput,
9
+ createMigrationHintsRequiredError,
10
+ MIGRATION_HINTS_REQUIRED,
11
+ } from "./migration-hints.mjs";
12
+ import { classifySchemaLoadFailure } from "./migration-schema-load-failure.mjs";
7
13
 
8
14
  export const SUPPORTED_DRIZZLE_KIT_GENERATOR_VERSION = SUPPORTED_MIGRATION_GENERATOR_VERSION;
9
15
  export const UNKNOWN_DRIZZLE_KIT_GENERATOR_VERSION = "unknown";
@@ -119,7 +125,37 @@ export function getMigrationFolderFormatFailure(error) {
119
125
  );
120
126
  }
121
127
 
128
+ // Every raw stream the generator wrote; drizzle-kit reports hint requests on stdout.
129
+ function rawGeneratorOutput(error) {
130
+ return (
131
+ error?.gencowRawGeneratorOutput ??
132
+ [error?.stdout, error?.stderr, error?.message].map((value) => String(value ?? "")).join("\n")
133
+ );
134
+ }
135
+
136
+ function getMissingHintsFailure(error) {
137
+ return classifyMissingHintsOutput(rawGeneratorOutput(error));
138
+ }
139
+
140
+ // db:generate only. Runs after the hints and folder-format judgments, so an error that already
141
+ // carries a code keeps it. Other callers keep the generic path they had before.
142
+ export function markMigrationSchemaLoadFailure(error) {
143
+ if (!error || typeof error !== "object" || error.code) return error;
144
+ const schemaFailure = classifySchemaLoadFailure(rawGeneratorOutput(error));
145
+ if (!schemaFailure) return error;
146
+ try {
147
+ error.code = "MIGRATION_GENERATION_FAILED";
148
+ error.migrationSchemaFailure = schemaFailure;
149
+ } catch {
150
+ /* keep the raw generator error; the schema-load code is then unavailable */
151
+ }
152
+ return error;
153
+ }
154
+
122
155
  export function buildMigrationGenerationError(error) {
156
+ if (error?.code === MIGRATION_HINTS_REQUIRED && error.migrationHints) {
157
+ return createMigrationHintsRequiredError(error.migrationHints);
158
+ }
123
159
  const firstLine = getCommandErrorMessage(error).split("\n")[0] || "unknown generator error";
124
160
  const failure = new Error(`Migration generation failed: ${firstLine}`);
125
161
  const folderFormat = getMigrationFolderFormatFailure(error);
@@ -135,11 +171,18 @@ export function shouldRetryLegacyGenerate(error) {
135
171
  return message.includes("unknown command 'generate'") && message.includes("generate:pg");
136
172
  }
137
173
 
174
+ // Quotes one argv element for the legacy string-command path (never used for spawn).
175
+ function shellQuote(value) {
176
+ return `'${String(value).replace(/'/gu, `'\\''`)}'`;
177
+ }
178
+
138
179
  export function runDrizzleGenerateWithFallback({
139
180
  cwd,
140
181
  drizzleKitCmdImpl,
141
182
  env = {},
142
183
  execSyncImpl,
184
+ generatorArgs = [],
185
+ onOutput,
143
186
  spawnSyncImpl = spawnSync,
144
187
  stderrWriteImpl = (value) => process.stderr.write(value),
145
188
  stdio = "inherit",
@@ -151,7 +194,7 @@ export function runDrizzleGenerateWithFallback({
151
194
  try {
152
195
  const generatorEnv = selectDrizzleGeneratorEnvironment(env, dk.env);
153
196
  if (typeof dk.command === "string" && Array.isArray(dk.args)) {
154
- const result = spawnSyncImpl(dk.command, dk.args, {
197
+ const result = spawnSyncImpl(dk.command, [...dk.args, ...generatorArgs], {
155
198
  cwd,
156
199
  encoding: "utf8",
157
200
  env: generatorEnv,
@@ -169,9 +212,12 @@ export function runDrizzleGenerateWithFallback({
169
212
  Object.defineProperties(failure, {
170
213
  gencowGeneratorCwd: { value: cwd },
171
214
  gencowRawGeneratorMessage: { value: rawMessage },
215
+ gencowRawGeneratorOutput: { value: `${rawStdout}\n${rawStderr}\n${result.error?.message ?? ""}` },
172
216
  });
173
217
  throw failure;
174
218
  }
219
+ // Successful runs can still report "No schema changes"; expose that output to callers.
220
+ onOutput?.(`${rawStdout}\n${rawStderr}`);
175
221
  if (stdio === "inherit") {
176
222
  const stdout = sanitizeDrizzleGeneratorOutput(rawStdout, { cwd });
177
223
  const stderr = sanitizeDrizzleGeneratorOutput(rawStderr, { cwd });
@@ -179,7 +225,10 @@ export function runDrizzleGenerateWithFallback({
179
225
  if (stderr) stderrWriteImpl(stderr);
180
226
  }
181
227
  } else {
182
- execSyncImpl(dk.cmd, { cwd, env: generatorEnv, stdio });
228
+ const command = generatorArgs.length
229
+ ? [dk.cmd, ...generatorArgs.map(shellQuote)].join(" ")
230
+ : dk.cmd;
231
+ execSyncImpl(command, { cwd, env: generatorEnv, stdio });
183
232
  }
184
233
  } catch (error) {
185
234
  if (error && typeof error === "object") {
@@ -188,6 +237,16 @@ export function runDrizzleGenerateWithFallback({
188
237
  } catch {
189
238
  /* preserve the original generator error when the thrown value is immutable */
190
239
  }
240
+ const missingHints = getMissingHintsFailure(error);
241
+ if (missingHints) {
242
+ try {
243
+ error.code = MIGRATION_HINTS_REQUIRED;
244
+ error.migrationHints = { ...missingHints, hintsProvided: generatorArgs.length > 0 };
245
+ } catch {
246
+ /* keep the raw generator error; the hints code is then unavailable */
247
+ }
248
+ throw error;
249
+ }
191
250
  const folderFormat = getMigrationFolderFormatFailure(error);
192
251
  if (folderFormat) {
193
252
  try {
@@ -6,10 +6,10 @@ import {
6
6
  resolveBackendEnvFile,
7
7
  resolveExplicitEnvFile,
8
8
  } from "./backend-env-resolver.mjs";
9
- import { resolveCloudAppTarget } from "./cloud-targets.mjs";
9
+ import { resolveCloudAppTargetWithServerEnvironment } from "./cloud-target-environment.mjs";
10
10
  import { cloudTargetRejectionMessage, prodRetryCommandLine, redactConfigSetValue, redactEnvPairs } from "./deploy-app-target.mjs";
11
11
  import { BOLD, CYAN, DIM, GREEN, RESET, error, info, log, success, warn } from "./output.mjs";
12
- import { platformFetch, requireCreds } from "./platform-client.mjs";
12
+ import { platformFetch, requireCreds, rpcQuery } from "./platform-client.mjs";
13
13
 
14
14
  const ENV_RESPONSE_UNREADABLE_CODE = "ENV_RESPONSE_UNREADABLE";
15
15
 
@@ -141,7 +141,8 @@ export function createEnvCommand(deps = {}) {
141
141
  const cwdImpl = deps.cwdImpl ?? (() => process.cwd());
142
142
  const loadConfigImpl = deps.loadConfig ?? (async () => ({ rootDir: "./gencow", envFile: "./gencow/.env" }));
143
143
  const readFileSyncImpl = deps.readFileSync ?? readFileSync;
144
- const resolveAppTargetImpl = deps.resolveCloudAppTarget ?? resolveCloudAppTarget;
144
+ const resolveAppTargetImpl = deps.resolveCloudAppTarget ?? resolveCloudAppTargetWithServerEnvironment;
145
+ const rpcQueryImpl = deps.rpcQuery ?? rpcQuery;
145
146
  const resolvePathImpl = deps.resolvePathImpl ?? resolve;
146
147
  const sleepImpl = deps.sleep ?? ((ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms)));
147
148
  const projectionPollAttempts = deps.projectionPollAttempts ?? 40;
@@ -255,7 +256,11 @@ export function createEnvCommand(deps = {}) {
255
256
  return;
256
257
  }
257
258
  const creds = requireCredsImpl();
258
- const target = resolveAppTargetImpl(restArgs, {
259
+ const target = await resolveAppTargetImpl(restArgs, {
260
+ creds,
261
+ rpcQueryImpl,
262
+ stage: "env target resolution",
263
+ command: `env ${subcmd}`,
259
264
  missingAppMessage: "App ID not found. Run gencow deploy first.",
260
265
  missingProdMessage: "No prod app yet. Run gencow deploy --prod first.",
261
266
  });
@@ -1,5 +1,7 @@
1
1
  const ADVISORY_SUMMARIES = Object.freeze({
2
2
  MIGRATION_POTENTIAL_DATA_LOSS: "The pending migration may remove tenant data.",
3
+ MIGRATION_NOT_NULL_NO_DEFAULT_RISK:
4
+ "ADD COLUMN … NOT NULL without a DEFAULT fails if the table already has rows. Make the column nullable, add a DEFAULT, or use expand → backfill → contract.",
3
5
  MIGRATION_LOCK_RISK: "The pending migration may take a blocking PostgreSQL lock.",
4
6
  MIGRATION_COMPATIBILITY_RISK: "Coordinate this schema change with application rollout compatibility.",
5
7
  MIGRATION_BACKUP_NOT_CREATED:
@@ -6,6 +6,7 @@ import {
6
6
  } from "@gencow/migration-contract";
7
7
 
8
8
  import { describeMigrationFolderFormatFailure } from "./migration-folder-format.mjs";
9
+ import { buildHintsRequiredCommand, HINTS_DATA_LOSS_NOTICE, SAFE_COLUMN_REFERENCE } from "./migration-hints.mjs";
9
10
 
10
11
  const FORBIDDEN_ACTIONS = [
11
12
  "Do not use --force to bypass migration safety checks.",
@@ -50,6 +51,13 @@ const USER_FIXABLE_FAILURES = {
50
51
  detail:
51
52
  "Fix schema imports, types, or Drizzle configuration before uploading any existing migration bundle.",
52
53
  },
54
+ MIGRATION_HINTS_REQUIRED: {
55
+ phase: "GENERATE",
56
+ target: "SCHEMA_SOURCE",
57
+ summary: "Drizzle needs a rename or create decision for changed columns before it can generate migrations.",
58
+ detail:
59
+ "Run `npx gencow@latest db:generate --hints '<json-array>'` with one rename or create decision per changed column, then rerun this command. Do not edit applied migration files.",
60
+ },
53
61
  MIGRATION_BUNDLE_SCHEMA_CHANGE_WITHOUT_FORWARD_MIGRATION: {
54
62
  phase: "PREFLIGHT",
55
63
  target: "PENDING_MIGRATION",
@@ -93,6 +101,30 @@ export function buildClientUserFixableDiagnostic(code, correlationId) {
93
101
  };
94
102
  }
95
103
 
104
+ // Same stable code and state as MIGRATION_HINTS_REQUIRED from db:generate, with the exact
105
+ // retry command for the named column in text fields (USER_FIXABLE diagnostics cannot carry one).
106
+ export function buildMigrationHintsRequiredDiagnostic(hints, correlationId) {
107
+ const columns = Array.isArray(hints?.columns)
108
+ ? hints.columns.filter((value) => typeof value === "string" && SAFE_COLUMN_REFERENCE.test(value))
109
+ : [];
110
+ const command = buildHintsRequiredCommand(columns);
111
+ const detail = `Declare each changed column with \`${command}\` (use {"type":"create",...} to add a new column instead), then rerun this command. ${HINTS_DATA_LOSS_NOTICE} Do not edit applied migration files.`;
112
+ const base = buildClientUserFixableDiagnostic("MIGRATION_HINTS_REQUIRED", correlationId);
113
+ return {
114
+ ...base,
115
+ retryCondition: "Run db:generate with --hints for each changed column, then rerun this command.",
116
+ reason: { code: "migration_hints_required", summary: base.reason.summary, detail },
117
+ suggestedFixes: [
118
+ {
119
+ ...base.suggestedFixes[0],
120
+ id: "migration_hints_required-fix",
121
+ title: "Declare the column decisions with db:generate --hints",
122
+ detail,
123
+ },
124
+ ],
125
+ };
126
+ }
127
+
96
128
  // Same stable code and state as MIGRATION_GENERATION_FAILED, with the folder-format reason and the
97
129
  // pinned conversion command in text fields (USER_FIXABLE diagnostics cannot carry a command).
98
130
  export function buildMigrationFolderFormatDiagnostic(folderFormat, correlationId) {
@@ -3,6 +3,15 @@ import { readFileSync, realpathSync } from "node:fs";
3
3
  import { relative, resolve, sep } from "node:path";
4
4
  import { escapeTerminalControls, safeDiagnosticText } from "./migration-diagnostic-contract.mjs";
5
5
  import { formatLatestCliInvocation } from "./cli-update-guidance.mjs";
6
+ import {
7
+ UNLOCATED_ROLLBACK_DETAIL,
8
+ UNLOCATED_ROLLBACK_RETRY_CONDITION,
9
+ UNLOCATED_ROLLBACK_SUMMARY,
10
+ isUserFixableRolledBackDiagnostic,
11
+ renderRollbackCauseLine,
12
+ renderUnlocatedRollbackFix,
13
+ renderUnlocatedRollbackLocation,
14
+ } from "./migration-rollback-cause.mjs";
6
15
 
7
16
  export {
8
17
  extractActionableMigrationDiagnostic,
@@ -320,6 +329,12 @@ export function renderMigrationDiagnosticLines(diagnostic) {
320
329
  lines.push(`Correlation: ${diagnostic.correlationId}`);
321
330
  return lines.map((line) => escapeTerminalControls(line));
322
331
  }
332
+ // Without a verified local span, the server's "exact statement" wording would overclaim.
333
+ const unlocatedRollback =
334
+ isUserFixableRolledBackDiagnostic(diagnostic) && !diagnostic.localSource?.projectRelativePath;
335
+ const retryCondition = unlocatedRollback
336
+ ? UNLOCATED_ROLLBACK_RETRY_CONDITION
337
+ : diagnostic.retryCondition;
323
338
  const lines = [
324
339
  migrationDiagnosticTitle(diagnostic),
325
340
  "",
@@ -327,7 +342,7 @@ export function renderMigrationDiagnosticLines(diagnostic) {
327
342
  `Phase: ${diagnostic.phase}`,
328
343
  `Database state: ${diagnostic.databaseState}`,
329
344
  `Safe to retry now: ${diagnostic.safeToRetryNow ? "YES" : "NO"}`,
330
- `Retry policy: ${diagnostic.retryPolicy}${diagnostic.retryCondition ? ` — ${diagnostic.retryCondition}` : ""}`,
345
+ `Retry policy: ${diagnostic.retryPolicy}${retryCondition ? ` — ${retryCondition}` : ""}`,
331
346
  ];
332
347
  const source = diagnostic.localSource;
333
348
  if (source?.projectRelativePath) {
@@ -342,6 +357,10 @@ export function renderMigrationDiagnosticLines(diagnostic) {
342
357
  } else if (diagnostic.migration?.name) {
343
358
  lines.push("", `Migration: ${diagnostic.migration.name}`);
344
359
  }
360
+ if (unlocatedRollback) {
361
+ if (diagnostic.migration?.name) lines.push(renderUnlocatedRollbackLocation(diagnostic));
362
+ else lines.push("", renderUnlocatedRollbackLocation(diagnostic));
363
+ }
345
364
  if (diagnostic.operation?.kind) {
346
365
  lines.push(
347
366
  `Operation: ${diagnostic.operation.kind}${diagnostic.operation.objectName ? ` ${diagnostic.operation.objectName}` : ""}`,
@@ -349,12 +368,20 @@ export function renderMigrationDiagnosticLines(diagnostic) {
349
368
  }
350
369
  if (diagnostic.receiptId) lines.push(`Receipt: ${diagnostic.receiptId}`);
351
370
  if (diagnostic.statusLookup?.code) lines.push(`Status lookup: ${diagnostic.statusLookup.code}`);
352
- lines.push("", "Why this failed:", ` ${diagnostic.reason.summary}`, ` ${diagnostic.reason.detail}`);
353
- if (diagnostic.suggestedFixes?.length > 0) {
371
+ const causeLine = renderRollbackCauseLine(diagnostic);
372
+ if (causeLine) lines.push("", causeLine);
373
+ lines.push(
374
+ "",
375
+ "Why this failed:",
376
+ ` ${unlocatedRollback ? UNLOCATED_ROLLBACK_SUMMARY : diagnostic.reason.summary}`,
377
+ ` ${unlocatedRollback ? UNLOCATED_ROLLBACK_DETAIL : diagnostic.reason.detail}`,
378
+ );
379
+ const fixes = unlocatedRollback
380
+ ? [renderUnlocatedRollbackFix(diagnostic)]
381
+ : (diagnostic.suggestedFixes ?? []);
382
+ if (fixes.length > 0) {
354
383
  lines.push("", "Possible fixes:");
355
- diagnostic.suggestedFixes.forEach((fix, index) =>
356
- lines.push(` ${index + 1}. ${fix.title}`, ` ${fix.detail}`),
357
- );
384
+ fixes.forEach((fix, index) => lines.push(` ${index + 1}. ${fix.title}`, ` ${fix.detail}`));
358
385
  }
359
386
  if (shouldRenderForbiddenActions(diagnostic) && diagnostic.forbiddenActions?.length > 0) {
360
387
  lines.push("", "Do not:");
@@ -0,0 +1,116 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+
4
+ // drizzle-kit reports column rename-or-create decisions it cannot infer as
5
+ // `missing_hints: N unresolved decisions` on stdout and exits non-zero. This module is the
6
+ // single judgment for that output and for the user's --hints / --hints-file input.
7
+ export const MIGRATION_HINTS_REQUIRED = "MIGRATION_HINTS_REQUIRED";
8
+ export const MIGRATION_HINTS_INVALID = "MIGRATION_HINTS_INVALID";
9
+
10
+ const MAX_HINTS_BYTES = 32 * 1024;
11
+ const MAX_LISTED_COLUMNS = 8;
12
+ const ANSI_PATTERN = /\u001b\[[0-9;]*m/gu;
13
+ const MISSING_HINTS_PATTERN = /^missing_hints:\s*(\d{1,4})\s+unresolved\b/mu;
14
+ const DECISION_LINE_PATTERN = /^\s*\d+\.\s+Rename or create\b/u;
15
+ const COLUMN_REF_PATTERN = /\bcolumn\s+(\S+)/u;
16
+ // schema.table.column only; anything else is never echoed back to the user.
17
+ export const SAFE_COLUMN_REFERENCE =
18
+ /^[A-Za-z_][A-Za-z0-9_]{0,62}\.[A-Za-z_][A-Za-z0-9_]{0,62}\.[A-Za-z_][A-Za-z0-9_]{0,62}$/u;
19
+
20
+ // Returns { count, columns } when the generator output asks for hints, otherwise null.
21
+ export function classifyMissingHintsOutput(rawOutput) {
22
+ const text = String(rawOutput ?? "").replace(ANSI_PATTERN, "");
23
+ const match = MISSING_HINTS_PATTERN.exec(text);
24
+ if (!match) return null;
25
+ const columns = [];
26
+ for (const line of text.split("\n")) {
27
+ if (!DECISION_LINE_PATTERN.test(line)) continue;
28
+ const ref = COLUMN_REF_PATTERN.exec(line)?.[1];
29
+ if (ref && SAFE_COLUMN_REFERENCE.test(ref) && !columns.includes(ref)) {
30
+ columns.push(ref);
31
+ if (columns.length === MAX_LISTED_COLUMNS) break;
32
+ }
33
+ }
34
+ return { count: Number(match[1]), columns };
35
+ }
36
+
37
+ // Shared by db:generate, db:push, and the db:generate help so the wording cannot drift.
38
+ export const HINTS_DATA_LOSS_NOTICE =
39
+ "A rename keeps the existing column's data, while create adds a new column; an old column that is not renamed may be dropped and its data lost. Review the generated migration SQL before applying it.";
40
+
41
+ // Exact retry command for the single decision we can name; placeholders otherwise.
42
+ export function buildHintsRequiredCommand(columns) {
43
+ const [table, column] =
44
+ columns.length === 1 ? columns[0].split(".").slice(1) : ["<table>", "<new-column>"];
45
+ return `npx gencow@latest db:generate --hints '[{"type":"rename","kind":"column","from":["public","${table}","<old-column>"],"to":["public","${table}","${column}"]}]'`;
46
+ }
47
+
48
+ export function createMigrationHintsRequiredError({ count, columns, hintsProvided }) {
49
+ const error = new Error(`Migration generation needs ${count} decision(s) for changed columns.`);
50
+ error.code = MIGRATION_HINTS_REQUIRED;
51
+ error.migrationHints = { count, columns, hintsProvided: hintsProvided === true };
52
+ return error;
53
+ }
54
+
55
+ function invalidHints(reason, source) {
56
+ const error = new Error(`Migration hints rejected: ${reason}.`);
57
+ error.code = MIGRATION_HINTS_INVALID;
58
+ error.hintsReason = reason;
59
+ error.hintsSource = source;
60
+ return error;
61
+ }
62
+
63
+ function isHintsArray(value) {
64
+ return (
65
+ Array.isArray(value) && value.every((item) => item !== null && typeof item === "object" && !Array.isArray(item))
66
+ );
67
+ }
68
+
69
+ function validateHintsJson(text, source) {
70
+ if (Buffer.byteLength(text, "utf8") > MAX_HINTS_BYTES) throw invalidHints("too_large", source);
71
+ let parsed;
72
+ try {
73
+ parsed = JSON.parse(text);
74
+ } catch {
75
+ throw invalidHints("json_invalid", source);
76
+ }
77
+ if (!isHintsArray(parsed)) throw invalidHints("not_array", source);
78
+ }
79
+
80
+ // Parses --hints / --hints-file (also in --flag=value form). Unknown arguments are ignored
81
+ // as before. Returns the extra generator arguments; never invokes the generator itself.
82
+ export function parseMigrationHintsArgs(args, { cwd, readFileSyncImpl = readFileSync, resolvePathImpl = resolve } = {}) {
83
+ const occurrences = [];
84
+ for (let index = 0; index < args.length; index += 1) {
85
+ const arg = String(args[index]);
86
+ const flag = arg.startsWith("--hints-file") ? "--hints-file" : arg.startsWith("--hints") ? "--hints" : null;
87
+ if (!flag) continue;
88
+ const rest = arg.slice(flag.length);
89
+ if (rest !== "" && rest[0] !== "=") continue;
90
+ if (rest.startsWith("=")) {
91
+ occurrences.push({ flag, value: rest.slice(1) });
92
+ } else {
93
+ const next = args[index + 1];
94
+ occurrences.push({ flag, value: typeof next === "string" && !next.startsWith("--") ? next : undefined });
95
+ if (next !== undefined && !String(next).startsWith("--")) index += 1;
96
+ }
97
+ }
98
+ if (occurrences.length === 0) return { args: [] };
99
+ if (occurrences.length > 1) throw invalidHints("conflicting_options", "argument");
100
+ const [{ flag, value }] = occurrences;
101
+ const source = flag === "--hints" ? "inline" : "file";
102
+ if (typeof value !== "string" || value === "") throw invalidHints("value_missing", source);
103
+ if (flag === "--hints") {
104
+ validateHintsJson(value, source);
105
+ return { args: ["--hints", value] };
106
+ }
107
+ const absolutePath = resolvePathImpl(cwd ?? ".", value);
108
+ let text;
109
+ try {
110
+ text = readFileSyncImpl(absolutePath, "utf8");
111
+ } catch {
112
+ throw invalidHints("file_unreadable", source);
113
+ }
114
+ validateHintsJson(String(text), source);
115
+ return { args: ["--hints-file", absolutePath] };
116
+ }
@@ -0,0 +1,75 @@
1
+ // Plain-language one-liners for the PostgreSQL reason codes the Platform already
2
+ // classifies as user-fixable (migration-execution-outcome.ts). Only static text is
3
+ // printed here; the server never sends SQL, row values, or parameters for these codes.
4
+ const USER_FIXABLE_CAUSES = new Map([
5
+ ["string_data_right_truncation", "a value is longer than its column type allows"],
6
+ ["invalid_text_representation", "a value does not match the column's data type"],
7
+ ["active_sql_transaction", "the statement cannot run inside a transaction block"],
8
+ [
9
+ "not_null_violation",
10
+ "a NOT NULL constraint rejected the statement (a populated table needs a DEFAULT or a nullable column)",
11
+ ],
12
+ ["foreign_key_violation", "a foreign key constraint rejected existing or new rows"],
13
+ ["unique_violation", "a UNIQUE constraint rejected rows with duplicate values"],
14
+ ["syntax_error", "PostgreSQL could not parse the statement"],
15
+ ["duplicate_column", "the column already exists"],
16
+ ["undefined_column", "the statement references a column that does not exist"],
17
+ ["undefined_table", "the statement references a table that does not exist"],
18
+ ["duplicate_table", "the table already exists"],
19
+ ]);
20
+
21
+ // Extra guidance for causes whose generic repair advice needs a specific hint.
22
+ const NOT_NULL_REPAIR_HINT =
23
+ "For a NOT NULL failure, give the new column a DEFAULT or make it nullable, or split the change into forward migrations (expand → backfill → contract).";
24
+
25
+ const SAFE_REASON_CODE = /^[a-z0-9_]{1,80}$/u;
26
+
27
+ export function isUserFixableRolledBackDiagnostic(diagnostic) {
28
+ return (
29
+ diagnostic?.code === "MIGRATION_TRANSACTION_ROLLED_BACK" &&
30
+ diagnostic.databaseState === "ROLLED_BACK" &&
31
+ diagnostic.failureClass === "USER_FIXABLE"
32
+ );
33
+ }
34
+
35
+ export function safeRollbackReasonCode(diagnostic) {
36
+ const code = diagnostic?.reason?.code;
37
+ return typeof code === "string" && SAFE_REASON_CODE.test(code) ? code : null;
38
+ }
39
+
40
+ // Returns the "Cause:" line for a user-fixable rollback, or null when no safe code exists.
41
+ export function renderRollbackCauseLine(diagnostic) {
42
+ if (!isUserFixableRolledBackDiagnostic(diagnostic)) return null;
43
+ const code = safeRollbackReasonCode(diagnostic);
44
+ if (!code) return null;
45
+ const cause = USER_FIXABLE_CAUSES.get(code);
46
+ return cause ? `Cause: ${code} — ${cause}` : `Cause: ${code}`;
47
+ }
48
+
49
+ // Honest replacement for the server's "exact statement" wording when the CLI could not
50
+ // verify a local source span. Only the already-safe migration name is shown.
51
+ export function renderUnlocatedRollbackFix(diagnostic) {
52
+ const name = diagnostic?.migration?.name;
53
+ const code = safeRollbackReasonCode(diagnostic);
54
+ const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : "";
55
+ return {
56
+ title: name
57
+ ? `Inspect the unapplied migration file ${name}`
58
+ : "Inspect the pending migrations listed by db:check",
59
+ detail: `Repair only the unapplied migration source for the cause above, review the generated diff, and create a fresh plan. Applied migrations and the journal are not edited.${hint}`,
60
+ };
61
+ }
62
+
63
+ export function renderUnlocatedRollbackLocation(diagnostic) {
64
+ const name = diagnostic?.migration?.name;
65
+ return name
66
+ ? `Statement location: unavailable — inspect the unapplied migration file ${name}`
67
+ : "Statement location: unavailable — inspect the pending migrations listed by db:check";
68
+ }
69
+
70
+ export const UNLOCATED_ROLLBACK_SUMMARY =
71
+ "PostgreSQL rejected a pending migration statement and rolled back the transaction.";
72
+ export const UNLOCATED_ROLLBACK_RETRY_CONDITION =
73
+ "Fix only the unapplied migration source for the cause above, then create and check a fresh plan.";
74
+ export const UNLOCATED_ROLLBACK_DETAIL =
75
+ "The failed transaction did not commit any migration or journal change.";
@@ -0,0 +1,31 @@
1
+ // Single judgment for a db:generate failure where drizzle-kit throws a JavaScript runtime
2
+ // error AND its output names schema.ts. A runtime error alone is not enough: tooling and
3
+ // environment errors (for example `require is not defined` or `fetch failed`) also surface
4
+ // as TypeError/ReferenceError. Without the schema context those stay on the raw fallback.
5
+ // The construct inside schema.ts is still unknown, so the copy never confirms a cause.
6
+ const RUNTIME_ERROR_PATTERNS = Object.freeze([
7
+ /^\s*(?:TypeError|ReferenceError):\s/mu,
8
+ /\bCannot read properties of (?:undefined|null) \(reading '/u,
9
+ ]);
10
+ // Matched against the raw output, because the sanitized text replaces paths and loses the file name.
11
+ const SCHEMA_CONTEXT_PATTERN = /\bschema(?:-auth)?(?:\.gen)?\.[cm]?[jt]sx?\b/u;
12
+
13
+ export const SCHEMA_LOAD_FAILED_REASON_CODE = "schema_load_failed";
14
+
15
+ // Returns { reasonCode } when the output is a runtime error that names the schema, otherwise null.
16
+ export function classifySchemaLoadFailure(rawMessage) {
17
+ const message = String(rawMessage ?? "");
18
+ if (!RUNTIME_ERROR_PATTERNS.some((pattern) => pattern.test(message))) return null;
19
+ if (!SCHEMA_CONTEXT_PATTERN.test(message)) return null;
20
+ return Object.freeze({ reasonCode: SCHEMA_LOAD_FAILED_REASON_CODE });
21
+ }
22
+
23
+ // The raw generator text is never printed; only these fixed sentences reach the user.
24
+ export const SCHEMA_LOAD_FAILURE_CLI_MESSAGE =
25
+ "Migration generation stopped: drizzle-kit failed while generating migrations (possibly while loading your schema), so no migration file was generated.";
26
+
27
+ export const SCHEMA_LOAD_FAILURE_CAUSE_HINT =
28
+ "Possible cause (not confirmed): a table callback (the third argument of pgTable) returns an entry that is not an index, policy, or constraint. If a policy helper returns an array, spread it into the returned array with `...`. The tooling or environment may also be the cause.";
29
+
30
+ export const SCHEMA_LOAD_FAILURE_CLI_ACTION =
31
+ "Retryable: no — check the schema source (schema.ts) and the local tooling or environment, then rerun `gencow db:generate`.";
@@ -1,11 +1,19 @@
1
1
  import { appResponseError } from "./app-response-error.mjs";
2
+ import {
3
+ formatRegionUnavailableMessage,
4
+ readRegionUnavailableDiagnostic,
5
+ } from "./prod-create-region-diagnostic.mjs";
2
6
 
3
7
  /** One rendering of a failed `create-prod` response for every CLI deploy path. */
4
- export function prodCreateFailureMessage(errData, response) {
8
+ export function prodCreateFailureMessage(errData, response, options = {}) {
5
9
  const fallback =
6
10
  response.status === 503
7
11
  ? "Prod app creation is temporarily unavailable."
8
12
  : errData?.error || response.statusText || `HTTP ${response.status}`;
13
+ const regionDiagnostic = readRegionUnavailableDiagnostic(errData, response);
14
+ if (regionDiagnostic) {
15
+ return formatRegionUnavailableMessage(regionDiagnostic, fallback, options.requestedRegion ?? null);
16
+ }
9
17
  return [
10
18
  `Prod app creation failed: ${appResponseError(errData, fallback, response)}`,
11
19
  "Retry: run the same command again; if another gencow command is creating this app, wait for it to finish first.",
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Renders the public REGION_UNAVAILABLE diagnostic from a create-prod 503.
3
+ * Every field is allow-listed: unknown, oversized or malformed values are
4
+ * dropped rather than echoed, and nothing is inferred when the server omits it.
5
+ * Older servers that send only the code keep the legacy rendering (null here).
6
+ */
7
+ const STAGES = new Set(["prod_app_create_node_selection", "prod_app_create_node_proxy"]);
8
+ const REASON_TEXT = new Map([
9
+ ["capacity_exhausted", "all nodes in this region are at app capacity"],
10
+ ["no_active_node", "no active node serves this environment and region"],
11
+ ["node_unavailable", "the matching node is not reporting healthy right now"],
12
+ ["gateway_unavailable", "the target node's gateway is not ready"],
13
+ ["node_config_invalid", "the target node has an invalid internal configuration (Platform-owned)"],
14
+ ]);
15
+ const RETRY_CLASSES = new Set(["operator-action", "platform-action", "retryable-infra", "terminal-client"]);
16
+ const MAX_RETRY_AFTER_MS = 600_000;
17
+ // Same pattern the server uses for region slugs (apps-deploy-routes.ts create-prod validation).
18
+ const REGION_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/u;
19
+ // Same shape as the correlation-ID check in app-response-error.mjs.
20
+ const CORRELATION_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/u;
21
+ const STATUS_COMMAND = "gencow deploy status --prod";
22
+
23
+ export function readRegionUnavailableDiagnostic(body, response) {
24
+ if (response?.status !== 503) return null;
25
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
26
+ if (body.code !== "REGION_UNAVAILABLE") return null;
27
+
28
+ const diagnostic = {
29
+ stage: STAGES.has(body.stage) ? body.stage : null,
30
+ reason: REASON_TEXT.has(body.reason) ? body.reason : null,
31
+ stateUnchanged: body.stateChanged === false,
32
+ retryClass: RETRY_CLASSES.has(body.retryClass) ? body.retryClass : null,
33
+ retryAfterMs:
34
+ Number.isSafeInteger(body.retryAfterMs) && body.retryAfterMs >= 0 && body.retryAfterMs <= MAX_RETRY_AFTER_MS
35
+ ? body.retryAfterMs
36
+ : null,
37
+ correlationId:
38
+ typeof body.correlationId === "string" && CORRELATION_ID_PATTERN.test(body.correlationId)
39
+ ? body.correlationId
40
+ : null,
41
+ };
42
+ const hasAnyField = Object.entries(diagnostic).some(([key, value]) =>
43
+ key === "stateUnchanged" ? value : value !== null,
44
+ );
45
+ return hasAnyField ? diagnostic : null;
46
+ }
47
+
48
+ // The next step follows the server's retryClass; without one the CLI does not guess a retry.
49
+ // The region is echoed only when the user passed a valid --region; otherwise the region came
50
+ // from the dev app, so the user is pointed there.
51
+ function nextStepFor(retryClass, waitHint, requestedRegion) {
52
+ if (retryClass === "retryable-infra") {
53
+ const wait = waitHint ? ` after ${waitHint}` : "";
54
+ return `run \`${STATUS_COMMAND}\` to confirm no prod app was created, then run the same command again${wait}.`;
55
+ }
56
+ if (retryClass === "terminal-client") {
57
+ const regionStep =
58
+ requestedRegion && REGION_SLUG_PATTERN.test(requestedRegion)
59
+ ? `check that \`--region ${requestedRegion}\` is available to this account, or pass a different --region`
60
+ : "check the region of your dev app, or pass `--region` with a region available to this account";
61
+ return `${regionStep}, then run the command again. Run \`${STATUS_COMMAND}\` first to see whether a prod app already exists.`;
62
+ }
63
+ if (retryClass === "platform-action") {
64
+ return `do not change your project. Run \`${STATUS_COMMAND}\` to check the current state; if it keeps failing after a few minutes, keep the Correlation ID for a Platform status check.`;
65
+ }
66
+ return `run \`${STATUS_COMMAND}\` to check whether a prod app was created.`;
67
+ }
68
+
69
+ function formatWait(ms) {
70
+ return ms >= 1000 ? `${Math.round(ms / 1000)}s` : `${ms}ms`;
71
+ }
72
+
73
+ export function formatRegionUnavailableMessage(diagnostic, fallback, requestedRegion = null) {
74
+ const lines = [`Prod app creation failed: ${fallback}`, "Code: REGION_UNAVAILABLE"];
75
+ if (diagnostic.stage) lines.push(`Stage: ${diagnostic.stage}`);
76
+ if (diagnostic.reason) lines.push(`Reason: ${REASON_TEXT.get(diagnostic.reason)}`);
77
+ if (diagnostic.stateUnchanged) lines.push("Changed: nothing (no prod app was created)");
78
+ const retryable = diagnostic.retryClass === "retryable-infra";
79
+ if (diagnostic.retryClass) lines.push(`Retryable: ${retryable ? "yes" : "no"}`);
80
+ // A wait hint is only meaningful when the server marks the failure retryable.
81
+ const waitHint = retryable && diagnostic.retryAfterMs !== null ? formatWait(diagnostic.retryAfterMs) : null;
82
+ if (waitHint) lines.push(`Retry after: ${waitHint}`);
83
+ lines.push(`Next: ${nextStepFor(diagnostic.retryClass, waitHint, requestedRegion)}`);
84
+ if (diagnostic.correlationId) lines.push(`Correlation ID: ${diagnostic.correlationId}`);
85
+ return lines.join("\n");
86
+ }
@@ -135,7 +135,7 @@ async function ensureStaticProductionTarget({
135
135
 
136
136
  if (!createProdRes.ok) {
137
137
  const errData = await readJsonObjectResponse(createProdRes);
138
- errorImpl(prodCreateFailureMessage(errData, createProdRes));
138
+ errorImpl(prodCreateFailureMessage(errData, createProdRes, { requestedRegion: region }));
139
139
  exitImpl(1);
140
140
  return null;
141
141
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.268",
3
+ "version": "0.1.270",
4
4
  "description": "Gencow — AI Backend Engine",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,7 +21,7 @@
21
21
  "dashboard/"
22
22
  ],
23
23
  "dependencies": {
24
- "@gencow/migration-contract": "0.1.21",
24
+ "@gencow/migration-contract": "0.1.22",
25
25
  "@modelcontextprotocol/sdk": "^1.32.1",
26
26
  "drizzle-kit": "1.0.0-rc.4",
27
27
  "drizzle-orm": "1.0.0-rc.4",
@@ -41,9 +41,9 @@
41
41
  "better-auth": "1.7.11",
42
42
  "postgres": "^3.4.9",
43
43
  "@gencow/client": "0.2.8",
44
- "@gencow/react": "0.2.8",
45
- "@gencow/core": "0.1.47",
46
44
  "@gencow/server": "0.1.3",
45
+ "@gencow/core": "0.1.47",
46
+ "@gencow/react": "0.2.8",
47
47
  "@gencow/shared": "0.0.0"
48
48
  },
49
49
  "scripts": {