grada-run 0.41.4 → 0.42.0

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.
@@ -6,12 +6,13 @@ import {
6
6
  UpdateServiceCommand,
7
7
  } from '@aws-sdk/client-ecs';
8
8
  import color from 'picocolors';
9
+ import path from 'path';
9
10
  import { intro, outro, spinner, select, isCancel } from '@clack/prompts';
10
11
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
11
12
  import { failCommand, failAwsError, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
12
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
14
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
14
- import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, resolveWorkspaceSuffix, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
16
  import { requireManagedTree } from '../utils/terraform-metadata.js';
16
17
  import { truncateSpinnerText } from '../utils/spinner-text.js';
17
18
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
@@ -82,6 +83,7 @@ async function runRollbackMain(input = {}) {
82
83
  let projectName;
83
84
  let cluster;
84
85
  let service;
86
+ let namespacedProject;
85
87
  try {
86
88
  cwd = resolveCwd(options);
87
89
  region = resolveRegion(options, cwd);
@@ -89,8 +91,8 @@ async function runRollbackMain(input = {}) {
89
91
 
90
92
  // Namespace cluster/service for PR-preview workspaces; explicit
91
93
  // --cluster/--service flags still win inside the resolvers.
92
- const namespacedProject = `${projectName}${resolveWorkspaceSuffix(options, cwd)}`;
93
- const namespacedOptions = { ...options, projectName: namespacedProject };
94
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
95
+ namespacedProject = namespacedOptions.projectName;
94
96
  cluster = resolveCluster(namespacedOptions, cwd);
95
97
  service = resolveService(namespacedOptions, cwd);
96
98
  } catch {
@@ -301,48 +303,164 @@ async function runRollbackMain(input = {}) {
301
303
  }
302
304
  }
303
305
 
306
+ // 1b. Worker rollback (BUG-85): deploys advance web AND worker,
307
+ // so a rollback must move both — otherwise the worker keeps the bad
308
+ // image. Explicit --service keeps single-service semantics (the
309
+ // escape hatch); workerless trees (no worker.tf) skip. Resolved
310
+ // BEFORE any update so a worker with no rollback history fails
311
+ // loud with zero half-state.
312
+ let workerTarget = null;
313
+ const explicitService = (typeof options.service === 'string' && options.service.trim() !== '')
314
+ || (typeof options.serviceName === 'string' && options.serviceName.trim() !== '');
315
+ if (!explicitService && readFileSafe(path.join(cwd, 'terraform', 'worker.tf')) !== null) {
316
+ const workerService = `${namespacedProject}${readResourceSuffix(cwd)}-worker-service`;
317
+ const workerResp = await ecsClient.send(new DescribeServicesCommand({ cluster, services: [workerService] }));
318
+ const workerDesc = (workerResp.services || [])[0] || null;
319
+ if (!workerDesc || workerDesc.status !== 'ACTIVE') {
320
+ console.log(color.yellow(`⚠ Worker service ${workerService} not found or inactive — rolling back ${service} only.`));
321
+ } else {
322
+ const { family: workerFamily, revNum: workerCurrentRev } = parseFamilyAndRevision(workerDesc.taskDefinition);
323
+ const workerEligible = await discoverWithAdapter(createEcsRevisionAdapter(ecsClient), workerFamily, workerCurrentRev);
324
+ if (workerEligible.length === 0) {
325
+ s.stop(color.yellow('No previous worker revisions.'));
326
+ return failCommand({
327
+ message: `\n⚠ Family ${workerFamily} is on revision ${workerCurrentRev} with no previous ACTIVE revisions — refusing to roll back ${service} alone (the worker would keep the bad image).\n Deploy again to create worker rollback history, or re-run with --service ${service} to roll back the web service only.\n`,
328
+ tone: 'yellow',
329
+ event: 'rollback_run',
330
+ telemetry: { projectName, error_code: 'WORKER_NO_PRIOR_REVISIONS' },
331
+ reason: 'worker-no-prior-revisions',
332
+ resultExtra: { cluster, service, region },
333
+ exitCode: 1,
334
+ });
335
+ }
336
+ const workerTargetArn = pickNewestEligible(workerEligible);
337
+ workerTarget = { service: workerService, taskDefArn: workerTargetArn, revision: workerTargetArn.split(':').pop() };
338
+ }
339
+ }
340
+
304
341
  // 2. Trigger the rollback.
305
- s.start(truncateSpinnerText(`Rolling back ${service} to revision ${targetRevisionNum}...`));
342
+ const triggerLabel = workerTarget
343
+ ? `${service} to revision ${targetRevisionNum} and ${workerTarget.service} to revision ${workerTarget.revision}`
344
+ : `${service} to revision ${targetRevisionNum}`;
345
+ s.start(truncateSpinnerText(`Rolling back ${triggerLabel}...`));
306
346
  await ecsClient.send(new UpdateServiceCommand({
307
347
  cluster,
308
348
  service,
309
349
  taskDefinition: targetTaskDefArn,
310
350
  forceNewDeployment: true,
311
351
  }));
352
+ if (workerTarget) {
353
+ await ecsClient.send(new UpdateServiceCommand({
354
+ cluster,
355
+ service: workerTarget.service,
356
+ taskDefinition: workerTarget.taskDefArn,
357
+ forceNewDeployment: true,
358
+ }));
359
+ }
312
360
 
313
361
  if (options.skipWait === true) {
314
- s.stop(`Rollback to revision ${targetRevisionNum} triggered.`);
315
- await trackSuccess('rollback_run', { projectName, targetRevision: String(targetRevisionNum), skipWait: true });
316
- outro(color.green(`Rollback to revision ${targetRevisionNum} initiated! 🚀`));
317
- return { ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region };
362
+ const skipLabel = workerTarget
363
+ ? `revision ${targetRevisionNum} (web) and ${workerTarget.revision} (worker)`
364
+ : `revision ${targetRevisionNum}`;
365
+ s.stop(`Rollback to ${skipLabel} triggered.`);
366
+ await trackSuccess('rollback_run', {
367
+ projectName,
368
+ targetRevision: String(targetRevisionNum),
369
+ skipWait: true,
370
+ ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision) } : {}),
371
+ });
372
+ outro(color.green(`Rollback to ${skipLabel} initiated! 🚀`));
373
+ return {
374
+ ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region,
375
+ ...(workerTarget ? { worker: { service: workerTarget.service, targetTaskDefArn: workerTarget.taskDefArn, targetRevision: workerTarget.revision } } : {}),
376
+ };
318
377
  }
319
378
 
320
- // 3. Monitor the deployment until it stabilizes or times out,
321
- // with live spinner updates on every non-terminal tick.
322
- const startTime = Date.now();
323
- const deadline = startTime + timeoutMs;
324
- while (true) {
325
- const pollResp = await ecsClient.send(new DescribeServicesCommand({ cluster, services: [service] }));
326
- const svc = (pollResp.services || [])[0] || null;
327
- const primary = svc?.deployments?.find(
328
- (d) => d.status === 'PRIMARY' && d.taskDefinition === targetTaskDefArn
329
- );
330
-
331
- if (primary && (primary.rolloutState === 'COMPLETED'
332
- || (primary.runningCount === primary.desiredCount
333
- && primary.desiredCount > 0
334
- && (svc.deployments || []).length === 1))) {
335
- s.stop(color.green(`Rolled back to revision ${targetRevisionNum}.`));
336
- await trackSuccess('rollback_run', { projectName, targetRevision: String(targetRevisionNum) });
337
- outro(color.green(`Service successfully rolled back to revision ${targetRevisionNum}! 🚀`));
338
- return { ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region };
339
- }
379
+ // 3. Monitor each deployment until it stabilizes or times out,
380
+ // with live spinner updates on every non-terminal tick. Web
381
+ // first, then the worker; a worker failure names the completed
382
+ // web rollback so the half-state is never a mystery.
383
+ const webWait = await waitForPrimaryStable({
384
+ s, ecsClient, cluster, service, targetTaskDefArn, targetRevisionNum,
385
+ pollIntervalMs, timeoutMs, projectName, region,
386
+ });
387
+ if (!webWait.ok) return webWait.failure;
388
+ if (workerTarget) {
389
+ const workerWait = await waitForPrimaryStable({
390
+ s, ecsClient, cluster, service: workerTarget.service,
391
+ targetTaskDefArn: workerTarget.taskDefArn, targetRevisionNum: workerTarget.revision,
392
+ pollIntervalMs, timeoutMs, projectName, region,
393
+ doneNote: `${service} already rolled back to revision ${targetRevisionNum}`,
394
+ });
395
+ if (!workerWait.ok) return workerWait.failure;
396
+ }
340
397
 
341
- if (primary?.rolloutState === 'FAILED') {
342
- s.stop(color.red('❌ Rollback deployment failed.'));
343
- return failCommand({
398
+ const doneLabel = workerTarget
399
+ ? `revision ${targetRevisionNum} (web) and ${workerTarget.revision} (worker)`
400
+ : `revision ${targetRevisionNum}`;
401
+ s.stop(color.green(`Rolled back to ${doneLabel}.`));
402
+ await trackSuccess('rollback_run', {
403
+ projectName,
404
+ targetRevision: String(targetRevisionNum),
405
+ ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision) } : {}),
406
+ });
407
+ outro(color.green(workerTarget
408
+ ? `Services successfully rolled back to ${doneLabel}! 🚀`
409
+ : `Service successfully rolled back to revision ${targetRevisionNum}! 🚀`));
410
+ return {
411
+ ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region,
412
+ ...(workerTarget ? { worker: { service: workerTarget.service, targetTaskDefArn: workerTarget.taskDefArn, targetRevision: workerTarget.revision } } : {}),
413
+ };
414
+ } catch (error) {
415
+ if (isAuthError(error)) {
416
+ await trackFailure('rollback_run', { projectName, error_code: 'AUTH_EXPIRED' });
417
+ handleAwsAuthError(error, s, options);
418
+ return { ok: false, reason: 'auth-error', cluster, service, region };
419
+ }
420
+ s.stop(color.red('❌ Rollback failed.'));
421
+ return failAwsError({
422
+ event: 'rollback_run',
423
+ error,
424
+ telemetry: { projectName },
425
+ reason: 'error',
426
+ resultExtra: { cluster, service, region },
427
+ exitCode: 1,
428
+ });
429
+ }
430
+ }
431
+
432
+ // Polls one service until its PRIMARY deployment settles on the target
433
+ // revision (or fails/times out). Shared by the web and worker waits;
434
+ // `doneNote` names already-completed work on the failure prints so a
435
+ // late worker failure never hides the finished web rollback.
436
+ async function waitForPrimaryStable({
437
+ s, ecsClient, cluster, service, targetTaskDefArn, targetRevisionNum,
438
+ pollIntervalMs, timeoutMs, projectName, region, doneNote = null,
439
+ }) {
440
+ const startTime = Date.now();
441
+ const deadline = startTime + timeoutMs;
442
+ while (true) {
443
+ const pollResp = await ecsClient.send(new DescribeServicesCommand({ cluster, services: [service] }));
444
+ const svc = (pollResp.services || [])[0] || null;
445
+ const primary = svc?.deployments?.find(
446
+ (d) => d.status === 'PRIMARY' && d.taskDefinition === targetTaskDefArn
447
+ );
448
+
449
+ if (primary && (primary.rolloutState === 'COMPLETED'
450
+ || (primary.runningCount === primary.desiredCount
451
+ && primary.desiredCount > 0
452
+ && (svc.deployments || []).length === 1))) {
453
+ return { ok: true };
454
+ }
455
+
456
+ if (primary?.rolloutState === 'FAILED') {
457
+ s.stop(color.red('❌ Rollback deployment failed.'));
458
+ return {
459
+ ok: false,
460
+ failure: await failCommand({
344
461
  print: () => {
345
462
  console.log(color.red('\n✖ The rollback deployment failed to stabilize.'));
463
+ if (doneNote) console.log(color.yellow(` Note: ${doneNote}.`));
346
464
  console.log(` Check service health with ${color.green('npx grada-run status')} and recent output with ${color.green('npx grada-run logs')}.\n`);
347
465
  },
348
466
  event: 'rollback_run',
@@ -350,35 +468,39 @@ async function runRollbackMain(input = {}) {
350
468
  reason: 'rollout-failed',
351
469
  resultExtra: { cluster, service, region },
352
470
  exitCode: 1,
353
- });
354
- }
471
+ }),
472
+ };
473
+ }
355
474
 
356
- const elapsedSec = Math.floor((Date.now() - startTime) / 1000);
357
- // Every poll frame goes through the width budget: the
358
- // crashing-container variant walls past 131 columns on long
359
- // service names without it.
360
- const progressStem = `Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s]`;
361
- if (!primary) {
362
- s.message(truncateSpinnerText(`${progressStem} (registering deployment...)`));
475
+ const elapsedSec = Math.floor((Date.now() - startTime) / 1000);
476
+ // Every poll frame goes through the width budget: the
477
+ // crashing-container variant walls past 131 columns on long
478
+ // service names without it.
479
+ const progressStem = `Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s]`;
480
+ if (!primary) {
481
+ s.message(truncateSpinnerText(`${progressStem} (registering deployment...)`));
482
+ } else {
483
+ const runningCount = primary.runningCount ?? 0;
484
+ const desiredCount = primary.desiredCount ?? 0;
485
+ const pendingCount = primary.pendingCount ?? 0;
486
+ const failedTasks = primary.failedTasks ?? 0;
487
+ if (failedTasks > 0) {
488
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`));
489
+ } else if (runningCount >= desiredCount && desiredCount > 0 && pendingCount === 0) {
490
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running — draining previous tasks)`));
363
491
  } else {
364
- const runningCount = primary.runningCount ?? 0;
365
- const desiredCount = primary.desiredCount ?? 0;
366
- const pendingCount = primary.pendingCount ?? 0;
367
- const failedTasks = primary.failedTasks ?? 0;
368
- if (failedTasks > 0) {
369
- s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`));
370
- } else if (runningCount >= desiredCount && desiredCount > 0 && pendingCount === 0) {
371
- s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running — draining previous tasks)`));
372
- } else {
373
- s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending)`));
374
- }
492
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending)`));
375
493
  }
494
+ }
376
495
 
377
- if (Date.now() >= deadline) {
378
- s.stop(color.yellow('⚠ Rollback timed out waiting for ECS stabilization.'));
379
- return failCommand({
496
+ if (Date.now() >= deadline) {
497
+ s.stop(color.yellow('⚠ Rollback timed out waiting for ECS stabilization.'));
498
+ return {
499
+ ok: false,
500
+ failure: await failCommand({
380
501
  print: () => {
381
502
  console.log(color.yellow('\n⚠ The rollback is still in progress.'));
503
+ if (doneNote) console.log(color.yellow(` Note: ${doneNote}.`));
382
504
  console.log(` Check progress with ${color.green('npx grada-run status')}.\n`);
383
505
  },
384
506
  event: 'rollback_run',
@@ -386,26 +508,11 @@ async function runRollbackMain(input = {}) {
386
508
  reason: 'rollout-timeout',
387
509
  resultExtra: { cluster, service, region },
388
510
  exitCode: 1,
389
- });
390
- }
391
-
392
- await sleep(pollIntervalMs);
511
+ }),
512
+ };
393
513
  }
394
- } catch (error) {
395
- if (isAuthError(error)) {
396
- await trackFailure('rollback_run', { projectName, error_code: 'AUTH_EXPIRED' });
397
- handleAwsAuthError(error, s, options);
398
- return { ok: false, reason: 'auth-error', cluster, service, region };
399
- }
400
- s.stop(color.red('❌ Rollback failed.'));
401
- return failAwsError({
402
- event: 'rollback_run',
403
- error,
404
- telemetry: { projectName },
405
- reason: 'error',
406
- resultExtra: { cluster, service, region },
407
- exitCode: 1,
408
- });
514
+
515
+ await sleep(pollIntervalMs);
409
516
  }
410
517
  }
411
518
 
@@ -6,10 +6,10 @@ import { spinner, confirm, outro, isCancel } from '@clack/prompts';
6
6
  import color from 'picocolors';
7
7
  import path from 'path';
8
8
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
9
- import { failCommand, isProgrammaticCall, refuseIfNonInteractive } from '../utils/command.js';
9
+ import { failCommand, refuseIfNonInteractive } from '../utils/command.js';
10
10
  import { atomicWriteFile } from '../utils/atomic-write.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
- import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
12
+ import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, readRenderedContainerEnvNames } from '../utils/resolvers.js';
13
13
  import { ADDON_ENV_VARS, ADDON_REGISTRY } from '../utils/addons.js';
14
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
15
15
  import { truncateSpinnerText } from '../utils/spinner-text.js';
@@ -149,7 +149,7 @@ const BASE_MANAGED_ENV = {
149
149
  ecs: ['PORT', 'NODE_ENV'],
150
150
  lambda: ['PORT', 'AWS_LWA_PORT', 'APP_SECRETS_ARN'],
151
151
  };
152
- const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_ENGINE', 'DB_USER', 'DB_PASSWORD'];
152
+ const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_USER', 'DB_PASSWORD'];
153
153
 
154
154
  // Wiring-like names whose local-dev values break production when pushed:
155
155
  // the migrate gate trusts a present DATABASE_URL verbatim, so a localhost
@@ -159,7 +159,9 @@ const NON_PROD_VALUE_PATTERN = /localhost|127\.0\.0\.1|0\.0\.0\.0|example\.(com|
159
159
 
160
160
  // Managed-name set for this tree: the target base set, plus DB names when
161
161
  // a database file exists, plus each enabled addon's injected names
162
- // (capability file present under terraform/). Sorted for stable output.
162
+ // (capability file present under terraform/), plus every name in the
163
+ // RENDERED task definitions (covers compose-injected and hand-added env
164
+ // the maps cannot predict). Sorted for stable output.
163
165
  export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
164
166
  const names = new Set(BASE_MANAGED_ENV[target] || BASE_MANAGED_ENV.ecs);
165
167
  let tfFiles = [];
@@ -168,14 +170,33 @@ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
168
170
  } catch {
169
171
  return [...names].sort();
170
172
  }
171
- if (tfFiles.some((file) => file.startsWith('database') && file.endsWith('.tf'))) {
173
+ // NODE_ENV is injected only when the worker renders (the generator
174
+ // scopes it to worker trees): on workerless trees it is a legitimate
175
+ // custom key and must not auto-skip (BUG-95). Unreadable dirs keep
176
+ // the base set above (fail-closed; the TF precondition backstops
177
+ // real collisions there).
178
+ if (!tfFiles.includes('worker.tf')) names.delete('NODE_ENV');
179
+ const dbFile = tfFiles.find((file) => file.startsWith('database') && file.endsWith('.tf'));
180
+ if (dbFile) {
172
181
  for (const name of DB_MANAGED_ENV) names.add(name);
182
+ // DB_ENGINE is rendered only for non-postgres engines: including
183
+ // it blindly would auto-skip a legitimate custom key on postgres
184
+ // trees with a false "injected by Grada" notice. Unparseable
185
+ // files exclude it — the preflights still catch real collisions.
186
+ try {
187
+ const dbContent = await fs.readFile(path.join(cwd, 'terraform', dbFile), 'utf-8');
188
+ const engine = /engine\s*=\s*"([^"]+)"/.exec(dbContent)?.[1];
189
+ if (engine && engine !== 'postgres') names.add('DB_ENGINE');
190
+ } catch {
191
+ // Fall through with the base DB set.
192
+ }
173
193
  }
174
194
  for (const [capability, entry] of Object.entries(ADDON_REGISTRY)) {
175
195
  const envEntries = ADDON_ENV_VARS[capability];
176
196
  if (!envEntries || !entry.file || !tfFiles.includes(entry.file)) continue;
177
197
  for (const { name } of envEntries) names.add(name);
178
198
  }
199
+ for (const name of readRenderedContainerEnvNames(cwd)) names.add(name);
179
200
  return [...names].sort();
180
201
  }
181
202
 
@@ -361,16 +382,24 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
361
382
  return;
362
383
  }
363
384
 
364
- // Pre-write guards (BUG-79): collisions brick ECS deploys with a
365
- // RegisterTaskDefinition 400, and local-dev wiring values get
366
- // trusted verbatim by the migrate gate — both must surface before
385
+ // Pre-write guards (BUG-79/81): colliding keys are auto-skipped
386
+ // on ECS — pushing them can only brick the deploy, so excluding
387
+ // them with a loud notice beats refusing and demanding a hand
388
+ // edit. Local-dev wiring values warn. Everything surfaces before
367
389
  // any AWS or keys-file write. The spinner stops once for all
368
390
  // pre-write output and restarts when the push proceeds.
369
391
  const pushTarget = readTerraformComputeTarget(process.cwd());
370
392
  const managedNames = await getManagedEnvNames(process.cwd(), pushTarget);
371
393
  const collisions = Object.keys(parsedSecrets).filter((key) => managedNames.includes(key));
372
394
  const wiringHits = findNonProdWiring(parsedSecrets);
373
- const needsPreWriteOutput = collisions.length > 0 || wiringHits.length > 0;
395
+ // Explicit --yes/--auto-approve pushes everything (vault-storage
396
+ // escape hatch); the apply preflight still backstops deploys.
397
+ const skipBypassed = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
398
+ const skipped = (collisions.length > 0 && pushTarget !== 'lambda' && !skipBypassed) ? collisions : [];
399
+ const skippedSet = new Set(skipped);
400
+ const pushableSecrets = Object.fromEntries(Object.entries(parsedSecrets).filter(([key]) => !skippedSet.has(key)));
401
+ const needsPreWriteOutput = skipped.length > 0 || wiringHits.length > 0
402
+ || (collisions.length > 0 && (pushTarget === 'lambda' || skipBypassed));
374
403
  if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
375
404
  for (const { key, indicator } of wiringHits) {
376
405
  console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
@@ -378,43 +407,16 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
378
407
  if (collisions.length > 0 && pushTarget === 'lambda') {
379
408
  console.log(color.yellow(`⚠️ Warning: ${summarizeKeys(collisions)} ${collisions.length === 1 ? 'is' : 'are'} also injected by Grada as plain environment variables — the pushed vault value may be shadowed at runtime.`));
380
409
  }
381
- if (collisions.length > 0 && pushTarget !== 'lambda') {
382
- console.log(color.yellow(`⚠️ Warning: ${summarizeKeys(collisions)} ${collisions.length === 1 ? 'collides' : 'collide'} with names Grada injects into the container — the next deploy would fail with an ECS task-definition error.`));
383
- // Explicit --yes/--auto-approve acknowledges the collision and
384
- // proceeds; every other non-interactive caller refuses loudly
385
- // (a colliding push guarantees a broken deploy, so proceeding
386
- // silently is never the safe default).
387
- const explicitlyApproved = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
388
- if (!explicitlyApproved) {
389
- if (opts.isHeadless || opts.headless || process.env.CI) {
390
- return failCommand({
391
- noExit: isProgrammaticCall(opts),
392
- message: `\n✖ secrets push refuses to push ${summarizeKeys(collisions)}: Grada-managed environment names cannot also be vault secrets on ECS targets.`,
393
- hint: ' Rename the key in your .env file, or re-run with --yes to acknowledge the collision and push anyway.\n',
394
- event: 'secrets_pushed',
395
- telemetry: { projectName: resolvedProjectName, managed_collisions: collisions.length },
396
- errorCode: 'SECRETS_MANAGED_KEY_COLLISION',
397
- reason: 'managed-key-collision',
398
- exitCode: 1,
399
- });
400
- }
401
- const refusedCollision = await refuseIfNonInteractive(opts, {
402
- message: `\n✖ secrets push needs approval before pushing ${summarizeKeys(collisions)}: Grada-managed environment names cannot also be vault secrets on ECS targets.`,
403
- hint: ' Re-run with --yes to acknowledge the collision non-interactively, or run interactively to decide.\n',
404
- event: 'secrets_pushed',
405
- telemetry: { projectName: resolvedProjectName, managed_collisions: collisions.length },
406
- errorCode: 'SECRETS_MANAGED_KEY_COLLISION',
407
- });
408
- if (refusedCollision) return refusedCollision;
409
- const proceed = await confirm({
410
- message: `Push ${collisions.length === 1 ? 'this colliding key' : 'these colliding keys'} anyway? Deploys will fail until the collision is removed.`,
411
- initialValue: false,
412
- });
413
- if (isCancel(proceed) || proceed !== true) {
414
- console.log(color.dim('Secrets push cancelled. The vault and secret_keys.json are unchanged.'));
415
- return;
416
- }
417
- }
410
+ if (collisions.length > 0 && skipBypassed && pushTarget !== 'lambda') {
411
+ console.log(color.yellow(`⚠️ Warning: pushing ${summarizeKeys(collisions)} anyway (--yes) though Grada injects ${collisions.length === 1 ? 'it' : 'them'} — the apply preflight refuses until conflicting keys leave .env.`));
412
+ }
413
+ if (skipped.length > 0) {
414
+ console.log(color.yellow(`⚠️ Skipping ${skipped.length} colliding ${skipped.length === 1 ? 'key' : 'keys'} (injected by Grada — remove from .env to silence this):`));
415
+ for (const key of skipped) console.log(color.yellow(`- ${key} (skipped — Grada-managed name)`));
416
+ }
417
+ if (Object.keys(pushableSecrets).length === 0) {
418
+ console.log(color.dim('Nothing left to push — the vault and secret_keys.json are unchanged.'));
419
+ return;
418
420
  }
419
421
  if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
420
422
 
@@ -451,7 +453,20 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
451
453
  // BUG-80: push is full-replace, so vault keys absent from .env are
452
454
  // deleted by the update below. Name every victim before writing;
453
455
  // interactive runs confirm first, headless proceeds loudly.
456
+ // Skipped keys are present in .env, so they never land here — their
457
+ // exclusion from the vault write is covered by the skip notice
458
+ // above, not by this confirm.
454
459
  const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
460
+ // BUG-89: skipped keys are present in .env (so they never land in
461
+ // `removed`) but excluded from the vault write — a stale vault
462
+ // value for a skipped key is wiped by the full-replace update.
463
+ // Name every such victim loudly. The skip notice above is the
464
+ // acknowledgment, so unlike BUG-80 removals these never confirm.
465
+ const staleSkipped = skipped.filter((key) => (existingKeys ?? []).includes(key));
466
+ if (staleSkipped.length > 0) {
467
+ console.log(color.yellow(`⚠️ ${staleSkipped.length} skipped ${staleSkipped.length === 1 ? 'key' : 'keys'} still ${staleSkipped.length === 1 ? 'has' : 'have'} a stale vault value that this push deletes (no longer pushed):`));
468
+ for (const key of staleSkipped) console.log(color.red(`- ${key} (stale vault value deleted — key is skipped)`));
469
+ }
455
470
  if (removed.length > 0) {
456
471
  s.stop('Pre-flight checks done.');
457
472
  console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`));
@@ -482,17 +497,17 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
482
497
  // 5. Update the secret string in AWS
483
498
  const command = new UpdateSecretCommand({
484
499
  SecretId: `${secretVaultId(resolvedProjectName)}`,
485
- SecretString: JSON.stringify(parsedSecrets),
500
+ SecretString: JSON.stringify(pushableSecrets),
486
501
  });
487
502
 
488
503
  await client.send(command);
489
504
 
490
- const keys = Object.keys(parsedSecrets);
505
+ const keys = Object.keys(pushableSecrets);
491
506
  const keysFilePath = path.join(process.cwd(), 'terraform', 'secret_keys.json');
492
507
 
493
508
  await atomicWriteFile(keysFilePath, JSON.stringify(keys, null, 2));
494
509
 
495
- s.stop(`✅ Successfully pushed ${Object.keys(parsedSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`);
510
+ s.stop(`✅ Successfully pushed ${Object.keys(pushableSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`);
496
511
 
497
512
  const sortedExisting = [...(existingKeys ?? [])].sort();
498
513
  const sortedNew = [...keys].sort();
@@ -511,13 +526,15 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
511
526
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
512
527
  await trackSuccess('secrets_pushed', {
513
528
  projectName: resolvedProjectName,
514
- secret_count: Object.keys(parsedSecrets).length,
529
+ secret_count: Object.keys(pushableSecrets).length,
515
530
  keys_changed: false,
516
531
  ecs_restart: false,
517
532
  removed_count: removed.length,
518
- managed_collisions: collisions.length
533
+ managed_collisions: collisions.length,
534
+ skipped_count: skipped.length,
535
+ stale_skipped_count: staleSkipped.length
519
536
  });
520
- return { keysChanged: false, restarted: false };
537
+ return { keysChanged: false, restarted: false, skipped };
521
538
  }
522
539
  // Automated runs cannot answer prompts: skip the restart (fresh
523
540
  // deploys pick up the values) instead of hanging on confirm.
@@ -526,13 +543,15 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
526
543
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
527
544
  await trackSuccess('secrets_pushed', {
528
545
  projectName: resolvedProjectName,
529
- secret_count: Object.keys(parsedSecrets).length,
546
+ secret_count: Object.keys(pushableSecrets).length,
530
547
  keys_changed: false,
531
548
  ecs_restart: false,
532
549
  removed_count: removed.length,
533
- managed_collisions: collisions.length
550
+ managed_collisions: collisions.length,
551
+ skipped_count: skipped.length,
552
+ stale_skipped_count: staleSkipped.length
534
553
  });
535
- return { keysChanged: false, restarted: false };
554
+ return { keysChanged: false, restarted: false, skipped };
536
555
  }
537
556
  const refused = await refuseIfNonInteractive(opts, {
538
557
  message: `\n✖ secrets push needs approval before triggering the ECS restart.`,
@@ -546,7 +565,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
546
565
  message: 'Keys are unchanged. Trigger a rolling ECS restart to apply new values immediately?',
547
566
  initialValue: false,
548
567
  });
549
- if (shouldRestart) {
568
+ if (shouldRestart === true) {
550
569
  const cluster = resolveEcsCluster(resolvedProjectName, opts);
551
570
  const service = resolveEcsService(resolvedProjectName, opts);
552
571
  const ecsClient = resolveClient(opts.ecsClient ?? opts.ecs, ECSClient, targetRegion ? { region: targetRegion } : {});
@@ -566,26 +585,30 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
566
585
  }
567
586
  await trackSuccess('secrets_pushed', {
568
587
  projectName: resolvedProjectName,
569
- secret_count: Object.keys(parsedSecrets).length,
588
+ secret_count: Object.keys(pushableSecrets).length,
570
589
  keys_changed: false,
571
590
  ecs_restart: true,
572
591
  removed_count: removed.length,
573
- managed_collisions: collisions.length
592
+ managed_collisions: collisions.length,
593
+ skipped_count: skipped.length,
594
+ stale_skipped_count: staleSkipped.length
574
595
  });
575
596
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
576
- return { keysChanged: false, restarted: true, cluster, service };
597
+ return { keysChanged: false, restarted: true, cluster, service, skipped };
577
598
  }
578
599
  }
579
600
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
580
601
 
581
602
  await trackSuccess('secrets_pushed', {
582
603
  projectName: resolvedProjectName,
583
- secret_count: Object.keys(parsedSecrets).length,
604
+ secret_count: Object.keys(pushableSecrets).length,
584
605
  keys_changed: keysChanged,
585
606
  removed_count: removed.length,
586
- managed_collisions: collisions.length
607
+ managed_collisions: collisions.length,
608
+ skipped_count: skipped.length,
609
+ stale_skipped_count: staleSkipped.length
587
610
  });
588
- return { keysChanged };
611
+ return { keysChanged, skipped };
589
612
 
590
613
  } catch (error) {
591
614
  return handleSecretsCatch({