gencow 0.1.271 → 0.1.272

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.
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, realpathSync } from "node:fs";
1
+ import { existsSync, lstatSync, realpathSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
3
3
 
4
4
  import { toDrizzleProjectPath } from "./canonical-drizzle-generator-paths.mjs";
@@ -53,6 +53,12 @@ if (!insideProject(projectRoot, migrationsPath)) {
53
53
  throw new Error("Gencow migrations output must stay inside the project root");
54
54
  }
55
55
 
56
+ // Phase marker for the CLI (see migration-schema-load-failure.mjs). Written only after every check
57
+ // above has passed, so a later schema-load failure can be told apart from a config-stage failure.
58
+ // Literal values are the CLI contract: GENCOW_DRIZZLE_PHASE_MARKER and config_loaded. No output.
59
+ const phaseMarkerPath = process.env.GENCOW_DRIZZLE_PHASE_MARKER?.trim();
60
+ if (phaseMarkerPath) writeFileSync(phaseMarkerPath, "config_loaded\n");
61
+
56
62
  export default {
57
63
  dialect: "postgresql",
58
64
  schema: resolveSchemaFiles(projectRoot),
@@ -1,7 +1,6 @@
1
1
  import { formatProcedureRpcDiagnostic } from "./procedure-rpc-diagnostic.mjs";
2
2
  import { describeMigrationFolderFormatFailure } from "./migration-folder-format.mjs";
3
3
  import {
4
- SCHEMA_LOAD_FAILURE_CAUSE_HINT,
5
4
  SCHEMA_LOAD_FAILURE_CLI_ACTION,
6
5
  SCHEMA_LOAD_FAILURE_CLI_MESSAGE,
7
6
  } from "./migration-schema-load-failure.mjs";
@@ -52,7 +51,10 @@ const SAFE_LOCAL_ERROR_CODES = new Map([
52
51
  ? SCHEMA_LOAD_FAILURE_CLI_MESSAGE
53
52
  : "Migration generation failed: Drizzle could not generate migrations from schema.ts.",
54
53
  stage: "migration",
55
- detail: (caught) => (caught.migrationSchemaFailure ? SCHEMA_LOAD_FAILURE_CAUSE_HINT : null),
54
+ detail: (caught) =>
55
+ caught.migrationSchemaFailure?.cause
56
+ ? `Cause (from your schema, unverified): ${caught.migrationSchemaFailure.cause}`
57
+ : null,
56
58
  action: (caught) =>
57
59
  caught.migrationFolderFormat
58
60
  ? describeMigrationFolderFormatFailure(caught.migrationFolderFormat).cliAction
@@ -290,7 +292,7 @@ function commandErrorMessage(caught) {
290
292
  const detail =
291
293
  typeof localDiagnostic.detail === "function" ? localDiagnostic.detail(caught) : localDiagnostic.detail;
292
294
  if (detail) lines.push(detail);
293
- const location = safeSourceLocation(caught);
295
+ const location = safeSourceLocation(caught.migrationSchemaFailure?.location ?? caught);
294
296
  if (location) lines.push(`${localDiagnostic.locationLabel ?? "Source location"}: ${location}`);
295
297
  const action =
296
298
  typeof localDiagnostic.action === "function" ? localDiagnostic.action(caught) : localDiagnostic.action;
@@ -33,11 +33,24 @@ export function readProjectAppTargets(cwd = process.cwd()) {
33
33
  }
34
34
  }
35
35
 
36
+ // Next action when the project's own development app is named with --prod before a prod twin exists.
37
+ const NO_PROD_TWIN_NEXT = "gencow deploy --prod (creates this project's prod app)";
38
+
36
39
  // Single decision for "which prod app does --prod (+ optional --app) target".
40
+ // projectAppId is the project's own development app (gencow.json appId). Naming it with --prod is never
41
+ // a prod target, even before a prodApp exists, so it is rejected here for every caller.
37
42
  // acceptExplicitWithoutProdApp preserves call sites that trust an explicit app
38
43
  // when the project has no prodApp binding (legacy metadata); others fail closed.
39
- export function resolveProdAppTarget({ explicitAppId = null, prodApp = null, acceptExplicitWithoutProdApp = false }) {
44
+ export function resolveProdAppTarget({
45
+ explicitAppId = null,
46
+ prodApp = null,
47
+ projectAppId = null,
48
+ acceptExplicitWithoutProdApp = false,
49
+ }) {
40
50
  if (!prodApp) {
51
+ if (explicitAppId && projectAppId && explicitAppId === projectAppId) {
52
+ return { appId: null, reason: "explicit_app_not_prod_app", prodApp: null, next: NO_PROD_TWIN_NEXT };
53
+ }
41
54
  if (explicitAppId && acceptExplicitWithoutProdApp) return { appId: explicitAppId };
42
55
  return { appId: null, reason: "no_prod_app" };
43
56
  }
@@ -107,6 +120,7 @@ export function resolveCloudAppTarget(restArgs, options = {}) {
107
120
  const prodTarget = resolveProdAppTarget({
108
121
  explicitAppId: explicitApp ? appId : null,
109
122
  prodApp: projectTargets.prodApp,
123
+ projectAppId: projectTargets.appId,
110
124
  acceptExplicitWithoutProdApp: true,
111
125
  });
112
126
  if (!prodTarget.appId) {
@@ -114,7 +128,13 @@ export function resolveCloudAppTarget(restArgs, options = {}) {
114
128
  if (prodTarget.reason !== "explicit_app_not_prod_app") return { error };
115
129
  // Only the explicit mismatch carries its reason and requested app, so callers can render the
116
130
  // typed EXPLICIT_APP_NOT_PROD_APP block; every other failure keeps the { error } shape.
117
- return { error, reason: prodTarget.reason, prodApp: prodTarget.prodApp, explicitAppId: appId };
131
+ return {
132
+ error,
133
+ reason: prodTarget.reason,
134
+ prodApp: prodTarget.prodApp,
135
+ explicitAppId: appId,
136
+ ...(prodTarget.next ? { next: prodTarget.next } : {}),
137
+ };
118
138
  }
119
139
  appId = prodTarget.appId;
120
140
  }
@@ -16,7 +16,7 @@ import { tmpdir } from "os";
16
16
  import { createDbCheckCommand, createDbPushCommand } from "./db-push-command.mjs";
17
17
  import { renderMaintenanceFailure } from "./db-seed-failure-render.mjs";
18
18
  import { logEnvFileOperationWithType } from "./backend-env-resolver.mjs";
19
- import { markMigrationSchemaLoadFailure, runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
19
+ import { runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
20
20
  import { HINTS_DATA_LOSS_NOTICE, parseMigrationHintsArgs } from "./migration-hints.mjs";
21
21
  import { BOLD, CYAN, DIM, GREEN, RED, RESET, error, info, log, success, warn } from "./output.mjs";
22
22
  import {
@@ -56,6 +56,7 @@ export function resolveDbCloudTarget(args, gencowJson = null) {
56
56
  const prodTarget = resolveProdAppTarget({
57
57
  explicitAppId,
58
58
  prodApp: gencowJson.prodApp || null,
59
+ projectAppId: gencowJson.appId || gencowJson.appName || null,
59
60
  acceptExplicitWithoutProdApp: true,
60
61
  });
61
62
  return {
@@ -571,20 +572,16 @@ export function createDbCommands({
571
572
  logImpl(`\n${BOLD}${CYAN}Gencow DB Generate${RESET}\n`);
572
573
  infoImpl("Generating migration files from schema.ts...");
573
574
 
574
- try {
575
- runDrizzleGenerateWithFallback({
576
- cwd: cwdImpl(),
577
- drizzleKitCmdImpl,
578
- env: buildEnv(config),
579
- execSyncImpl,
580
- generatorArgs: hints.args,
581
- spawnSyncImpl,
582
- stdio: "inherit",
583
- warnImpl,
584
- });
585
- } catch (error) {
586
- throw markMigrationSchemaLoadFailure(error);
587
- }
575
+ runDrizzleGenerateWithFallback({
576
+ cwd: cwdImpl(),
577
+ drizzleKitCmdImpl,
578
+ env: buildEnv(config),
579
+ execSyncImpl,
580
+ generatorArgs: hints.args,
581
+ spawnSyncImpl,
582
+ stdio: "inherit",
583
+ warnImpl,
584
+ });
588
585
  successImpl("Migration files generated in gencow/migrations/");
589
586
  },
590
587
 
@@ -55,6 +55,7 @@ import {
55
55
  renderConfirmationRequired,
56
56
  resolveConfirmationMode,
57
57
  } from "./confirm-gate.mjs";
58
+ import { formatCommandError } from "./cli-command-runner.mjs";
58
59
  import { emitMigrationResponsibilityNotice } from "./migration-advisory.mjs";
59
60
  import { describeProdTargetFailure } from "./cloud-targets.mjs";
60
61
  import { cloudTargetRejectionMessage, prodRetryCommandLine } from "./deploy-app-target.mjs";
@@ -478,6 +479,11 @@ function createDbMigrationCommand(deps, command) {
478
479
  if (isNoChangeGenerationError(error)) {
479
480
  if (!jsonMode)
480
481
  deps.logImpl(`${DIM} ✓ Migrations up-to-date — no new schema changes detected${RESET}`);
482
+ } else if (!jsonMode && error?.migrationSchemaFailure) {
483
+ // Text mode shows the same schema-load diagnostic as db:generate. The JSON contract is unchanged.
484
+ deps.errorImpl(formatCommandError(error));
485
+ failureEmitted = true;
486
+ return;
481
487
  } else {
482
488
  const folderFormat = getMigrationFolderFormatFailure(error);
483
489
  emitFailure(
@@ -143,13 +143,19 @@ export function cloudTargetRejectionMessage(rejection, { fallbackMessage, ...opt
143
143
 
144
144
  // `--prod --app <id>` on a project with a prod app must name that prod app. Returns true when the
145
145
  // target is accepted; otherwise prints a typed rejection and exits before any app or metadata change.
146
- export function checkExplicitProdAppTarget({ explicitAppId, prodApp, errorImpl, exitImpl }) {
147
- const prodTarget = resolveProdAppTarget({ explicitAppId, prodApp });
146
+ export function checkExplicitProdAppTarget({ explicitAppId, prodApp, projectAppId = null, errorImpl, exitImpl }) {
147
+ const prodTarget = resolveProdAppTarget({
148
+ explicitAppId,
149
+ prodApp,
150
+ projectAppId,
151
+ acceptExplicitWithoutProdApp: true,
152
+ });
148
153
  if (prodTarget.appId) return true;
149
154
  errorImpl(
150
155
  renderExplicitAppNotProdAppLines({
151
156
  explicitAppId,
152
157
  rejection: prodTarget,
158
+ ...(prodTarget.next ? { next: prodTarget.next } : {}),
153
159
  }).join("\n"),
154
160
  );
155
161
  exitImpl(1);
@@ -135,11 +135,13 @@ export function readDeployProjectContext({
135
135
  }
136
136
  const gencowJsonPath = resolveProjectMetadataPath(projectDir, resolvePathImpl);
137
137
  let appId = explicitAppId;
138
+ let projectAppId = null;
138
139
  let prodAppId = null;
139
140
  let fallbackDisplayName = basenameImpl(projectDir);
140
141
 
141
142
  if (existsSyncImpl(gencowJsonPath)) {
142
143
  const gencowJson = JSON.parse(readFileSyncImpl(gencowJsonPath, "utf8"));
144
+ projectAppId = gencowJson.appId || gencowJson.appName || null;
143
145
  if (!appId) appId = gencowJson.appId || gencowJson.appName || null;
144
146
  if (typeof gencowJson.displayName === "string" && gencowJson.displayName.trim()) {
145
147
  fallbackDisplayName = gencowJson.displayName.trim();
@@ -157,7 +159,7 @@ export function readDeployProjectContext({
157
159
  resolvePathImpl,
158
160
  });
159
161
 
160
- return { appId, displayName, gencowJsonPath, prodAppId, projectDir };
162
+ return { appId, displayName, gencowJsonPath, prodAppId, projectAppId, projectDir };
161
163
  }
162
164
 
163
165
  // gencow.json deliberately keeps the first production deployment separate
@@ -431,7 +433,7 @@ export function createDeployCommand({
431
433
  readFileSyncImpl,
432
434
  resolvePathImpl,
433
435
  });
434
- let { appId, displayName, gencowJsonPath, prodAppId, projectDir } = context;
436
+ let { appId, displayName, gencowJsonPath, prodAppId, projectAppId, projectDir } = context;
435
437
  // Same environment rule as cloud-targets.mjs: --app <project prod app> deploys to prod even without --prod.
436
438
  // Every branch below (static, rollback, existing-bundle, backend) reads this promoted environment.
437
439
  parsed.envTarget = resolveImplicitProdEnvironment({
@@ -441,13 +443,15 @@ export function createDeployCommand({
441
443
  prodApp: prodAppId,
442
444
  });
443
445
  const rootAppId = appId;
444
- // Rollback resolves its own prod target below. Every other --prod --app <id> must name the prod app,
445
- // checked before resolveEnvironmentDeployTarget would otherwise replace the explicit id with prodApp.
446
- if (!parsed.isRollback && parsed.envTarget === "prod" && parsed.appId && prodAppId) {
446
+ // Rollback with a bound prod app resolves its own prod target below. Every other --prod --app <id>
447
+ // (including rollback without a prod app, and any target before a prod twin exists) is checked here,
448
+ // before resolveEnvironmentDeployTarget would otherwise replace the explicit id with prodApp.
449
+ if (parsed.envTarget === "prod" && parsed.appId && !(parsed.isRollback && prodAppId)) {
447
450
  if (
448
451
  !checkExplicitProdAppTarget({
449
452
  explicitAppId: parsed.appId,
450
453
  prodApp: prodAppId,
454
+ projectAppId,
451
455
  errorImpl,
452
456
  exitImpl,
453
457
  })
@@ -7,6 +7,7 @@ import {
7
7
  formatAuthSchemaConflictMessage,
8
8
  isServerCodegenWatchPath,
9
9
  } from "./codegen-command.mjs";
10
+ import { formatCommandError } from "./cli-command-runner.mjs";
10
11
  import { runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
11
12
  import { resolveProjectSelection } from "./project-context.mjs";
12
13
 
@@ -197,8 +198,12 @@ export function createDevLocalCommands({
197
198
  });
198
199
  successImpl("Schema -> migrations synced");
199
200
  } catch (error) {
200
- const stderr = error.stderr?.toString() ?? "";
201
- warnImpl(`db:generate failed — ${stderr.split("\n")[0] || "unknown error"}`);
201
+ if (error?.migrationSchemaFailure) {
202
+ warnImpl(`db:generate failed\n${formatCommandError(error)}`);
203
+ } else {
204
+ const stderr = error.stderr?.toString() ?? "";
205
+ warnImpl(`db:generate failed — ${stderr.split("\n")[0] || "unknown error"}`);
206
+ }
202
207
  infoImpl("Using existing migration files if available...");
203
208
  }
204
209
 
@@ -1,7 +1,8 @@
1
1
  import { SUPPORTED_MIGRATION_GENERATOR_VERSION } from "@gencow/migration-contract";
2
2
  import { spawnSync } from "node:child_process";
3
- import { existsSync, readFileSync } from "node:fs";
4
- import { dirname, resolve } from "node:path";
3
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, relative, resolve } from "node:path";
5
6
 
6
7
  import { classifyMigrationFolderFormatFailure } from "./migration-folder-format.mjs";
7
8
  import {
@@ -9,13 +10,18 @@ import {
9
10
  createMigrationHintsRequiredError,
10
11
  MIGRATION_HINTS_REQUIRED,
11
12
  } from "./migration-hints.mjs";
12
- import { classifySchemaLoadFailure } from "./migration-schema-load-failure.mjs";
13
+ import {
14
+ CONFIG_LOADED_PHASE_MARKER,
15
+ classifySchemaLoadFailure,
16
+ GENERATOR_PHASE_MARKER_ENV,
17
+ } from "./migration-schema-load-failure.mjs";
13
18
 
14
19
  export const SUPPORTED_DRIZZLE_KIT_GENERATOR_VERSION = SUPPORTED_MIGRATION_GENERATOR_VERSION;
15
20
  export const UNKNOWN_DRIZZLE_KIT_GENERATOR_VERSION = "unknown";
16
21
 
17
22
  const DRIZZLE_GENERATOR_ENV_KEYS = Object.freeze([
18
23
  "ESBUILD_BINARY_PATH",
24
+ GENERATOR_PHASE_MARKER_ENV,
19
25
  "GENCOW_FUNCTIONS",
20
26
  "GENCOW_MIGRATIONS",
21
27
  "GENCOW_SCHEMA",
@@ -137,19 +143,90 @@ function getMissingHintsFailure(error) {
137
143
  return classifyMissingHintsOutput(rawGeneratorOutput(error));
138
144
  }
139
145
 
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
+ // Relative path, size, and mtime of every file under `dir`. "absent" when the directory does not
147
+ // exist; null when it cannot be read, which callers treat as "unknown" (never "unchanged").
148
+ function fingerprintTree(dir) {
149
+ try {
150
+ if (!existsSync(dir)) return "absent";
151
+ const entries = [];
152
+ const walk = (current) => {
153
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
154
+ const full = join(current, entry.name);
155
+ if (entry.isDirectory()) {
156
+ walk(full);
157
+ } else {
158
+ const stat = statSync(full);
159
+ entries.push(`${relative(dir, full)}\0${stat.size}\0${stat.mtimeMs}`);
160
+ }
161
+ }
162
+ };
163
+ walk(dir);
164
+ return entries.sort().join("\n");
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+
170
+ // One probe per spawned generator run. It gives the generator config a private marker file
171
+ // and records the migrations state before the run, so the failure can be judged by phase.
172
+ function startGeneratorPhaseProbe({ cwd, migrationsDir }) {
173
+ let dir;
174
+ try {
175
+ dir = mkdtempSync(join(tmpdir(), "gencow-generator-phase-"));
176
+ } catch {
177
+ return null;
178
+ }
179
+ const migrations = typeof migrationsDir === "string" && migrationsDir ? resolve(cwd, migrationsDir) : null;
180
+ return {
181
+ dir,
182
+ markerPath: join(dir, "phase"),
183
+ migrations,
184
+ before: migrations ? fingerprintTree(migrations) : null,
185
+ };
186
+ }
187
+
188
+ function readGeneratorPhaseEvidence(probe) {
189
+ let configLoaded = false;
190
+ try {
191
+ configLoaded = readFileSync(probe.markerPath, "utf8") === `${CONFIG_LOADED_PHASE_MARKER}\n`;
192
+ } catch {
193
+ configLoaded = false;
194
+ }
195
+ const after = probe.migrations ? fingerprintTree(probe.migrations) : null;
196
+ return {
197
+ configLoaded,
198
+ migrationsUnchanged: probe.before !== null && after !== null && probe.before === after,
199
+ };
200
+ }
201
+
202
+ function disposeGeneratorPhaseProbe(probe) {
203
+ if (!probe) return;
204
+ try {
205
+ rmSync(probe.dir, { recursive: true, force: true });
206
+ } catch {
207
+ /* a leftover empty temp directory is harmless */
208
+ }
209
+ }
210
+
211
+ // Runs for every db:generate, db:push, deploy preflight, and dev generation through
212
+ // runDrizzleGenerateWithFallback. Only a failure proven to be in the schema-load phase gets the
213
+ // code; every other failure keeps its raw message.
214
+ function markSchemaLoadFailure(error, { cwd }) {
215
+ const phase = error.gencowGeneratorPhase;
216
+ if (!phase?.exitedNonZero || error.code) return;
217
+ const schemaFailure = classifySchemaLoadFailure({
218
+ configLoaded: phase.configLoaded,
219
+ migrationsUnchanged: phase.migrationsUnchanged,
220
+ rawStderr: phase.rawStderr,
221
+ sanitize: (text) => sanitizeDrizzleGeneratorOutput(text, { cwd }),
222
+ });
223
+ if (!schemaFailure) return;
146
224
  try {
147
225
  error.code = "MIGRATION_GENERATION_FAILED";
148
226
  error.migrationSchemaFailure = schemaFailure;
149
227
  } catch {
150
228
  /* keep the raw generator error; the schema-load code is then unavailable */
151
229
  }
152
- return error;
153
230
  }
154
231
 
155
232
  export function buildMigrationGenerationError(error) {
@@ -163,6 +240,10 @@ export function buildMigrationGenerationError(error) {
163
240
  failure.code = "MIGRATION_GENERATION_FAILED";
164
241
  failure.migrationFolderFormat = folderFormat;
165
242
  }
243
+ if (error?.code === "MIGRATION_GENERATION_FAILED" && error.migrationSchemaFailure) {
244
+ failure.code = "MIGRATION_GENERATION_FAILED";
245
+ failure.migrationSchemaFailure = error.migrationSchemaFailure;
246
+ }
166
247
  return failure;
167
248
  }
168
249
 
@@ -194,37 +275,55 @@ export function runDrizzleGenerateWithFallback({
194
275
  try {
195
276
  const generatorEnv = selectDrizzleGeneratorEnvironment(env, dk.env);
196
277
  if (typeof dk.command === "string" && Array.isArray(dk.args)) {
197
- const result = spawnSyncImpl(dk.command, [...dk.args, ...generatorArgs], {
198
- cwd,
199
- encoding: "utf8",
200
- env: generatorEnv,
201
- maxBuffer: 16 * 1024 * 1024,
202
- shell: false,
203
- stdio: "pipe",
204
- });
205
- const rawStdout = String(result.stdout ?? "");
206
- const rawStderr = String(result.stderr ?? "");
207
- if (result.error || result.status !== 0) {
208
- const rawMessage = rawStderr || rawStdout || result.error?.message || "generator failed";
209
- const redacted = sanitizeDrizzleGeneratorOutput(rawMessage, { cwd });
210
- const failure = new Error(redacted.trim() || "Migration generator failed");
211
- failure.stderr = redacted;
212
- Object.defineProperties(failure, {
213
- gencowGeneratorCwd: { value: cwd },
214
- gencowRawGeneratorMessage: { value: rawMessage },
215
- gencowRawGeneratorOutput: { value: `${rawStdout}\n${rawStderr}\n${result.error?.message ?? ""}` },
278
+ // The marker path is always CLI-owned; a caller-supplied value never reaches the config.
279
+ const probe = startGeneratorPhaseProbe({ cwd, migrationsDir: generatorEnv.GENCOW_MIGRATIONS });
280
+ if (probe) generatorEnv[GENERATOR_PHASE_MARKER_ENV] = probe.markerPath;
281
+ else delete generatorEnv[GENERATOR_PHASE_MARKER_ENV];
282
+ let result;
283
+ try {
284
+ result = spawnSyncImpl(dk.command, [...dk.args, ...generatorArgs], {
285
+ cwd,
286
+ encoding: "utf8",
287
+ env: generatorEnv,
288
+ maxBuffer: 16 * 1024 * 1024,
289
+ shell: false,
290
+ stdio: "pipe",
216
291
  });
217
- throw failure;
218
- }
219
- // Successful runs can still report "No schema changes"; expose that output to callers.
220
- onOutput?.(`${rawStdout}\n${rawStderr}`);
221
- if (stdio === "inherit") {
222
- const stdout = sanitizeDrizzleGeneratorOutput(rawStdout, { cwd });
223
- const stderr = sanitizeDrizzleGeneratorOutput(rawStderr, { cwd });
224
- if (stdout) stdoutWriteImpl(stdout);
225
- if (stderr) stderrWriteImpl(stderr);
292
+ const rawStdout = String(result.stdout ?? "");
293
+ const rawStderr = String(result.stderr ?? "");
294
+ if (result.error || result.status !== 0) {
295
+ const rawMessage = rawStderr || rawStdout || result.error?.message || "generator failed";
296
+ const redacted = sanitizeDrizzleGeneratorOutput(rawMessage, { cwd });
297
+ const failure = new Error(redacted.trim() || "Migration generator failed");
298
+ failure.stderr = redacted;
299
+ const phase = probe ? readGeneratorPhaseEvidence(probe) : { configLoaded: false, migrationsUnchanged: false };
300
+ Object.defineProperties(failure, {
301
+ gencowGeneratorCwd: { value: cwd },
302
+ gencowRawGeneratorMessage: { value: rawMessage },
303
+ gencowRawGeneratorOutput: { value: `${rawStdout}\n${rawStderr}\n${result.error?.message ?? ""}` },
304
+ gencowGeneratorPhase: {
305
+ value: Object.freeze({
306
+ ...phase,
307
+ exitedNonZero: !result.error && typeof result.status === "number" && result.status !== 0,
308
+ rawStderr,
309
+ }),
310
+ },
311
+ });
312
+ throw failure;
313
+ }
314
+ // Successful runs can still report "No schema changes"; expose that output to callers.
315
+ onOutput?.(`${rawStdout}\n${rawStderr}`);
316
+ if (stdio === "inherit") {
317
+ const stdout = sanitizeDrizzleGeneratorOutput(rawStdout, { cwd });
318
+ const stderr = sanitizeDrizzleGeneratorOutput(rawStderr, { cwd });
319
+ if (stdout) stdoutWriteImpl(stdout);
320
+ if (stderr) stderrWriteImpl(stderr);
321
+ }
322
+ } finally {
323
+ disposeGeneratorPhaseProbe(probe);
226
324
  }
227
325
  } else {
326
+ delete generatorEnv[GENERATOR_PHASE_MARKER_ENV];
228
327
  const command = generatorArgs.length
229
328
  ? [dk.cmd, ...generatorArgs.map(shellQuote)].join(" ")
230
329
  : dk.cmd;
@@ -256,6 +355,7 @@ export function runDrizzleGenerateWithFallback({
256
355
  /* keep the raw generator error; the folder-format code is then unavailable */
257
356
  }
258
357
  }
358
+ markSchemaLoadFailure(error, { cwd });
259
359
  }
260
360
  throw error;
261
361
  }
@@ -32,7 +32,11 @@ export function parseFilesCommandArgs(restArgs) {
32
32
 
33
33
  export function resolveFilesAppId({ explicitAppId = null, gencowJson = null, isProd = false }) {
34
34
  if (isProd) {
35
- return resolveProdAppTarget({ explicitAppId, prodApp: gencowJson?.prodApp || null }).appId;
35
+ return resolveProdAppTarget({
36
+ explicitAppId,
37
+ prodApp: gencowJson?.prodApp || null,
38
+ projectAppId: gencowJson?.appId || gencowJson?.appName || null,
39
+ }).appId;
36
40
  }
37
41
 
38
42
  return explicitAppId || gencowJson?.appId || gencowJson?.appName || null;
@@ -150,7 +154,11 @@ export function createFilesCommand({
150
154
  const appId = resolveFilesAppId({ explicitAppId, gencowJson, isProd });
151
155
 
152
156
  if (isProd && !appId) {
153
- const prodTarget = resolveProdAppTarget({ explicitAppId, prodApp: gencowJson?.prodApp || null });
157
+ const prodTarget = resolveProdAppTarget({
158
+ explicitAppId,
159
+ prodApp: gencowJson?.prodApp || null,
160
+ projectAppId: gencowJson?.appId || gencowJson?.appName || null,
161
+ });
154
162
  errorImpl(
155
163
  cloudTargetRejectionMessage(
156
164
  { ...prodTarget, explicitAppId },
@@ -142,7 +142,11 @@ export function resolveJobsAppTarget(params) {
142
142
 
143
143
  const gencowJson = JSON.parse(readFileSyncImpl(gencowJsonPath, "utf8"));
144
144
  if (params.isProd) {
145
- return resolveProdAppTarget({ explicitAppId: params.explicitAppId, prodApp: gencowJson.prodApp || null });
145
+ return resolveProdAppTarget({
146
+ explicitAppId: params.explicitAppId,
147
+ prodApp: gencowJson.prodApp || null,
148
+ projectAppId: gencowJson.appId || gencowJson.appName || null,
149
+ });
146
150
  }
147
151
 
148
152
  return { appId: params.explicitAppId || gencowJson.appId || gencowJson.appName || null };
@@ -1,31 +1,62 @@
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;
1
+ // Classifies a generator failure by its PHASE, not by its message text.
2
+ //
3
+ // The real drizzle-kit 1.0.0-rc.4 prints only `Error <message>` on stderr when the schema
4
+ // fails to load: no error class, no stack. Message text therefore cannot identify the phase.
5
+ // Instead the Gencow-owned generator config (canonical-drizzle-generator.config.mjs) writes
6
+ // the `config_loaded` marker to a CLI-provided path once it has been evaluated. A failure is a
7
+ // schema-load failure only when all of these hold (see drizzle-generate.mjs):
8
+ // 1. the config was evaluated (the marker exists with the exact contract content),
9
+ // 2. the generator exited non-zero and was spawned successfully,
10
+ // 3. the migrations directory is unchanged (drizzle-kit wrote nothing), and
11
+ // 4. the first non-empty stderr line is drizzle-kit's `Error ` wrapper.
12
+ // A config-stage failure (no marker), a snapshot error (no `Error ` wrapper), a spawn failure,
13
+ // and a success with no changes all stay unclassified.
12
14
 
13
15
  export const SCHEMA_LOAD_FAILED_REASON_CODE = "schema_load_failed";
14
16
 
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 });
17
+ // Env var the CLI sets to a temp file path. Shared by the CLI and the generator config.
18
+ export const GENERATOR_PHASE_MARKER_ENV = "GENCOW_DRIZZLE_PHASE_MARKER";
19
+ export const CONFIG_LOADED_PHASE_MARKER = "config_loaded";
20
+
21
+ const DRIZZLE_ERROR_WRAPPER = "Error ";
22
+ // drizzle-kit prints the schema file location on its own line: `<path>/gencow/schema.ts:1:17`.
23
+ // Only the project's canonical schema file is reported; the absolute prefix is never kept.
24
+ const SCHEMA_LOCATION_PATTERN = /gencow[\\/]schema\.ts:(\d{1,6}):(\d{1,6})\b/u;
25
+ const MAX_CAUSE_LENGTH = 200;
26
+
27
+ // Returns { reasonCode, cause, location } for a phase-proven schema-load failure, otherwise null.
28
+ // `rawStderr` is the unsanitized stderr; `sanitize` is the CLI's output redaction function.
29
+ export function classifySchemaLoadFailure({ configLoaded, migrationsUnchanged, rawStderr, sanitize }) {
30
+ if (configLoaded !== true || migrationsUnchanged !== true) return null;
31
+ const raw = String(rawStderr ?? "");
32
+ const firstLine = raw.split(/\r?\n/u).find((line) => line.trim() !== "") ?? "";
33
+ if (!firstLine.startsWith(DRIZZLE_ERROR_WRAPPER)) return null;
34
+
35
+ const rawCause = firstLine.slice(DRIZZLE_ERROR_WRAPPER.length);
36
+ const cause = toSafeCause(sanitize(rawCause));
37
+ const locationMatch = SCHEMA_LOCATION_PATTERN.exec(raw);
38
+ const location = locationMatch
39
+ ? Object.freeze({
40
+ sourceFile: "[project]/gencow/schema.ts",
41
+ line: Number(locationMatch[1]),
42
+ column: Number(locationMatch[2]),
43
+ })
44
+ : null;
45
+ return Object.freeze({ reasonCode: SCHEMA_LOAD_FAILED_REASON_CODE, cause, location });
46
+ }
47
+
48
+ function toSafeCause(sanitizedMessage) {
49
+ const singleLine = String(sanitizedMessage ?? "")
50
+ .replace(/[\u0000-\u001f\u007f]+/gu, " ")
51
+ .replace(/\s+/gu, " ")
52
+ .trim();
53
+ if (!singleLine) return null;
54
+ return singleLine.length > MAX_CAUSE_LENGTH ? `${singleLine.slice(0, MAX_CAUSE_LENGTH - 3)}...` : singleLine;
21
55
  }
22
56
 
23
57
  // The raw generator text is never printed; only these fixed sentences reach the user.
24
58
  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.";
59
+ "Migration generation stopped: drizzle-kit failed while loading or evaluating your schema (gencow/schema.ts), so no migration file was generated.";
29
60
 
30
61
  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`.";
62
+ "Retryable: yes, after gencow/schema.ts is fixed — then run `npx gencow@latest db:generate` to confirm migrations generate.";
@@ -84,16 +84,19 @@ export function readStaticProjectContext(options = {}) {
84
84
  }
85
85
  const gencowJsonPath = resolveProjectMetadataPath(projectRoot, resolvePathImpl);
86
86
  let appId = explicitAppId;
87
+ let projectAppId = null;
87
88
  let prodAppId = null;
88
89
 
89
90
  if (existsSyncImpl(gencowJsonPath)) {
90
91
  const gencowJson = JSON.parse(readFileSyncImpl(gencowJsonPath, "utf8"));
92
+ projectAppId = gencowJson.appId || gencowJson.appName || null;
91
93
  if (!appId) appId = gencowJson.appId || gencowJson.appName;
92
94
  prodAppId = gencowJson.prodApp || null;
93
95
  }
94
96
 
95
97
  return {
96
98
  appId,
99
+ projectAppId,
97
100
  displayName: readProjectDisplayNameImpl({
98
101
  cwd: projectRoot,
99
102
  existsSyncImpl,
@@ -220,6 +223,7 @@ export function createStaticCommand(options = {}) {
220
223
  displayName: initialDisplayName,
221
224
  gencowJsonPath,
222
225
  prodAppId,
226
+ projectAppId,
223
227
  projectRoot,
224
228
  } = readStaticProjectContextImpl({
225
229
  cwd: cwdImpl(),
@@ -299,9 +303,15 @@ export function createStaticCommand(options = {}) {
299
303
  selectedClient && artifactPreflight.targetDir && !isAbsolute(artifactPreflight.targetDir)
300
304
  ? resolvePathImpl(frontendRoot, artifactPreflight.targetDir)
301
305
  : artifactPreflight.targetDir;
302
- if (parsed.isProd && prodAppId) {
306
+ if (parsed.isProd && parsed.appId) {
303
307
  // An explicit --app must be this project's prod app; it is never silently replaced by the default.
304
- const prodTarget = resolveProdAppTarget({ explicitAppId: parsed.appId, prodApp: prodAppId });
308
+ // A project with no prod app yet still rejects its own dev app; any other explicit id keeps legacy acceptance.
309
+ const prodTarget = resolveProdAppTarget({
310
+ explicitAppId: parsed.appId,
311
+ prodApp: prodAppId,
312
+ projectAppId,
313
+ acceptExplicitWithoutProdApp: true,
314
+ });
305
315
  if (!prodTarget.appId) {
306
316
  errorImpl(
307
317
  cloudTargetRejectionMessage(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.271",
3
+ "version": "0.1.272",
4
4
  "description": "Gencow — AI Backend Engine",
5
5
  "type": "module",
6
6
  "bin": {