gencow 0.1.270 → 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
  }
@@ -66,6 +66,23 @@ function targetedNextAction(nextAction, appId, envTarget) {
66
66
  return `${nextAction} ${envTargetFlags(appId, envTarget)}`;
67
67
  }
68
68
 
69
+ /**
70
+ * Renders the safe ACK miss kind from the API. Only the kind and the two integer
71
+ * revisions can appear; any other shape is dropped rather than printed.
72
+ */
73
+ function formatEnvMismatch(mismatch) {
74
+ if (!mismatch || typeof mismatch !== "object" || typeof mismatch.kind !== "string") return null;
75
+ if (!/^[A-Z_]{1,40}$/u.test(mismatch.kind)) return null;
76
+ if (mismatch.kind !== "REVISION_BEHIND" && mismatch.kind !== "REVISION_AHEAD") {
77
+ return `Mismatch: ${mismatch.kind}`;
78
+ }
79
+ // The API does not record the process revision yet, so an actual revision is shown only when present.
80
+ const parts = [];
81
+ if (Number.isSafeInteger(mismatch.expectedRevision)) parts.push(`expected revision ${mismatch.expectedRevision}`);
82
+ if (Number.isSafeInteger(mismatch.actualRevision)) parts.push(`actual revision ${mismatch.actualRevision}`);
83
+ return parts.length > 0 ? `Mismatch: ${mismatch.kind} (${parts.join(", ")})` : `Mismatch: ${mismatch.kind}`;
84
+ }
85
+
69
86
  function envListCommand(appId, envTarget) {
70
87
  return `gencow env list ${envTargetFlags(appId, envTarget)}`;
71
88
  }
@@ -201,6 +218,7 @@ export function createEnvCommand(deps = {}) {
201
218
  typeof result.retryable === "boolean" ? `Retryable: ${result.retryable ? "yes" : "no"}` : null,
202
219
  Number.isSafeInteger(Number(result.attemptCount)) ? `Attempts: ${Number(result.attemptCount)}` : null,
203
220
  result.failureCode ? `Failure class: ${result.failureCode}` : null,
221
+ formatEnvMismatch(result.mismatch),
204
222
  result.correlationId ? `Correlation: ${result.correlationId}` : null,
205
223
  result.retryPrecondition ? `Retry precondition: ${result.retryPrecondition}` : null,
206
224
  `Next action: ${nextAction}`,
@@ -222,6 +240,13 @@ export function createEnvCommand(deps = {}) {
222
240
  return result.runtimeState === "failed" || result.statusQueryFailed === true ? 1 : 0;
223
241
  }
224
242
 
243
+ // Backend-only tips (handler/restart guidance) apply only when some key reached
244
+ // a running backend. A set/unset whose every projected key ended not_running has
245
+ // no backend process to act on, so those tips would be inaccurate.
246
+ function onlyStaticProjections(runtimeStates) {
247
+ return runtimeStates.length > 0 && runtimeStates.every((state) => state === "not_running");
248
+ }
249
+
225
250
  return async function env(...envArgs) {
226
251
  const filteredArgs = envArgs.filter((arg) => arg !== "--local");
227
252
 
@@ -355,6 +380,7 @@ export function createEnvCommand(deps = {}) {
355
380
 
356
381
  let appliedCount = 0;
357
382
  let commandFailed = false;
383
+ const projectionStates = [];
358
384
  for (const pair of pairs) {
359
385
  const eqIdx = pair.indexOf("=");
360
386
  if (eqIdx < 1) {
@@ -405,6 +431,7 @@ export function createEnvCommand(deps = {}) {
405
431
  const mutation = await res.json().catch(() => ({}));
406
432
  const projection = await waitForProjection(creds, appId, mutation, envTarget);
407
433
  const projectionExitCode = renderProjectionResult(projection, appId, envTarget);
434
+ projectionStates.push(projection.runtimeState);
408
435
  if (projectionExitCode === 0) {
409
436
  success(`Stored ${BOLD}${name}${RESET} ${DIM}(cloud: ${appId}, ${envTarget})${RESET}`);
410
437
  } else {
@@ -416,7 +443,7 @@ export function createEnvCommand(deps = {}) {
416
443
  commandFailed = true;
417
444
  }
418
445
  }
419
- if (appliedCount > 0) {
446
+ if (appliedCount > 0 && !onlyStaticProjections(projectionStates)) {
420
447
  log(
421
448
  `\n ${DIM}Runtime applied is reported only after the running process acknowledges the revision.${RESET}`,
422
449
  );
@@ -437,6 +464,7 @@ export function createEnvCommand(deps = {}) {
437
464
  return;
438
465
  }
439
466
  let commandFailed = false;
467
+ const projectionStates = [];
440
468
  for (const rawKey of keys) {
441
469
  const key = sanitizeCloudEnvKey(rawKey);
442
470
  try {
@@ -458,6 +486,7 @@ export function createEnvCommand(deps = {}) {
458
486
  const mutation = await res.json().catch(() => ({}));
459
487
  const projection = await waitForProjection(creds, appId, mutation, envTarget);
460
488
  const projectionExitCode = renderProjectionResult(projection, appId, envTarget);
489
+ projectionStates.push(projection.runtimeState);
461
490
  if (projectionExitCode === 0) {
462
491
  success(`Removed ${BOLD}${key}${RESET} ${DIM}(cloud: ${appId}, ${envTarget})${RESET}`);
463
492
  } else {
@@ -468,10 +497,12 @@ export function createEnvCommand(deps = {}) {
468
497
  commandFailed = true;
469
498
  }
470
499
  }
471
- log(
472
- `\n ${DIM}Runtime applied is reported only after the running process acknowledges the revision.${RESET}`,
473
- );
474
- log(` ${DIM}⚠ Platform-managed or startup-captured settings require restart/redeploy${RESET}\n`);
500
+ if (!onlyStaticProjections(projectionStates)) {
501
+ log(
502
+ `\n ${DIM}Runtime applied is reported only after the running process acknowledges the revision.${RESET}`,
503
+ );
504
+ log(` ${DIM}⚠ Platform-managed or startup-captured settings require restart/redeploy${RESET}\n`);
505
+ }
475
506
  return commandFailed ? 1 : 0;
476
507
  }
477
508
 
@@ -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 };