@grada-run/grada 0.41.2 → 0.41.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grada-run/grada",
3
- "version": "0.41.2",
3
+ "version": "0.41.4",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -43,8 +43,11 @@ function exitZeroForCli() {
43
43
  // Manual adopt equivalent, safe to re-run: strip any existing line
44
44
  // for the key (indented or not, present or not), then append exactly
45
45
  // one copy. A bare `echo … >>` duplicates the key on re-run and
46
- // Terraform fails hard on the redefinition.
47
- export const OIDC_ADOPT_MANUAL_COMMAND = `grep -v "^[[:space:]]*create_oidc_provider[[:space:]]*=" terraform/grada.auto.tfvars 2>/dev/null > terraform/grada.auto.tfvars.tmp; mv terraform/grada.auto.tfvars.tmp terraform/grada.auto.tfvars; echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`;
46
+ // Terraform fails hard on the redefinition. The `|| true` keeps the
47
+ // paste alive under `set -e`: grep -v exits 1 when it selects
48
+ // nothing (single-key file), which would otherwise stop the chain
49
+ // before the move and append.
50
+ export const OIDC_ADOPT_MANUAL_COMMAND = `grep -v "^[[:space:]]*create_oidc_provider[[:space:]]*=" terraform/grada.auto.tfvars 2>/dev/null > terraform/grada.auto.tfvars.tmp || true; mv terraform/grada.auto.tfvars.tmp terraform/grada.auto.tfvars; echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`;
48
51
 
49
52
  // Offline reconcile: an `init --offline` tree carries
50
53
  // YOUR_AWS_ACCOUNT_ID placeholders instead of an account id and has no
@@ -8,6 +8,7 @@ import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/a
8
8
  import { resolveRegion, resolveProjectName, resolveAppName, resolveCwd } from '../../utils/resolvers.js';
9
9
  import { findDbTarget, generateSnapshotId, isValidSnapshotId, resolveDbIdentifier, resolveDbClusterIdentifier } from '../../utils/rds.js';
10
10
  import { pollUntil, parseTimeoutSeconds } from '../../utils/system.js';
11
+ import { truncateSpinnerText } from '../../utils/spinner-text.js';
11
12
 
12
13
  export const DEFAULT_BACKUP_TIMEOUT_SECONDS = 900;
13
14
  export const DEFAULT_BACKUP_POLL_INTERVAL_MS = 5000;
@@ -137,7 +138,7 @@ async function runDbBackupMain(input = {}) {
137
138
  ? options.snapshotId.trim()
138
139
  : generateSnapshotId(target.id);
139
140
 
140
- s.message(`Creating snapshot ${snapshotId}...`);
141
+ s.message(truncateSpinnerText(`Creating snapshot ${snapshotId}...`));
141
142
  const snapshotTags = [
142
143
  { Key: 'ManagedBy', Value: 'grada' },
143
144
  { Key: 'Project', Value: projectName },
@@ -165,7 +166,7 @@ async function runDbBackupMain(input = {}) {
165
166
  return { ok: true, snapshotId, status: 'creating' };
166
167
  }
167
168
 
168
- s.message(`Waiting for snapshot ${snapshotId} to become available...`);
169
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId} to become available...`));
169
170
  const outcome = await pollUntil({
170
171
  intervalMs: pollIntervalMs,
171
172
  timeoutMs,
@@ -188,7 +189,7 @@ async function runDbBackupMain(input = {}) {
188
189
  // creation (eventual consistency), so keep polling.
189
190
  const notFoundNames = isCluster ? CLUSTER_SNAPSHOT_NOT_FOUND_NAMES : SNAPSHOT_NOT_FOUND_NAMES;
190
191
  if (error && notFoundNames.has(error.name)) {
191
- s.message(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`);
192
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`));
192
193
  return { done: false };
193
194
  }
194
195
  throw error;
@@ -203,7 +204,7 @@ async function runDbBackupMain(input = {}) {
203
204
  if (snapshot && TERMINAL_SNAPSHOT_STATUSES.has(String(snapshot.Status || '').toLowerCase())) {
204
205
  return { done: true, value: { terminalFailure: true, status: snapshot.Status } };
205
206
  }
206
- s.message(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`);
207
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`));
207
208
  return { done: false };
208
209
  },
209
210
  });
@@ -14,6 +14,7 @@ import { findDbTarget, dbStatusOf, resolveDbIdentifier, resolveDbClusterIdentifi
14
14
  import { requireManagedTree, parseStateBucketBackend } from '../utils/terraform-metadata.js';
15
15
  import { guardSleepingEnv } from '../utils/sleep-state.js';
16
16
  import { normalizeOptions, parseFlags, normalizeArgv } from '../utils/args.js';
17
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
17
18
 
18
19
  export const DEFAULT_DESTROY_DB_TIMEOUT_MS = 600000;
19
20
  export const DEFAULT_DESTROY_DB_SETTLE_TIMEOUT_MS = 1800000;
@@ -323,7 +324,7 @@ async function destroyStackMain(input = {}) {
323
324
  if (status === 'stopped' || status === 'available' || status === null) {
324
325
  return { done: true, value: status };
325
326
  }
326
- s.message(`Waiting for ${dbTarget.id} to settle (${status})... [${Math.floor(elapsedMs / 1000)}s]`);
327
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} to settle (${status})... [${Math.floor(elapsedMs / 1000)}s]`));
327
328
  return { done: false };
328
329
  },
329
330
  });
@@ -334,7 +335,7 @@ async function destroyStackMain(input = {}) {
334
335
  onTick: async ({ elapsedMs }) => {
335
336
  const status = await readStatus();
336
337
  if (status === 'available' || status === null) return { done: true, value: status };
337
- s.message(`Waiting for ${dbTarget.id} to become available... [${Math.floor(elapsedMs / 1000)}s]`);
338
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} to become available... [${Math.floor(elapsedMs / 1000)}s]`));
338
339
  return { done: false };
339
340
  },
340
341
  });
@@ -404,7 +405,7 @@ async function destroyStackMain(input = {}) {
404
405
  // (nothing left to protect).
405
406
  if (dbNeedsProtection) {
406
407
  const snapshotId = generateSnapshotId(dbTarget.id);
407
- s.start(`Snapshotting database ${dbTarget.id} before destruction...`);
408
+ s.start(truncateSpinnerText(`Snapshotting database ${dbTarget.id} before destruction...`));
408
409
  try {
409
410
  if (dbTarget.kind === 'cluster') {
410
411
  await rdsClient.send(new CreateDBClusterSnapshotCommand({ DBClusterSnapshotIdentifier: snapshotId, DBClusterIdentifier: dbTarget.id }));
@@ -441,7 +442,7 @@ async function destroyStackMain(input = {}) {
441
442
  // warns and proceeds — terraform reports the authoritative outcome.
442
443
  if (dbTarget && dbTarget.status !== 'deleting') {
443
444
  const isCluster = dbTarget.kind === 'cluster';
444
- s.start(`Lifting RDS deletion protection on ${dbTarget.id}...`);
445
+ s.start(truncateSpinnerText(`Lifting RDS deletion protection on ${dbTarget.id}...`));
445
446
  let lifted = false;
446
447
  try {
447
448
  if (isCluster) {
@@ -474,7 +475,7 @@ async function destroyStackMain(input = {}) {
474
475
  status = null;
475
476
  }
476
477
  if (status === 'available' || status === null || status === 'deleting') return { done: true, value: status };
477
- s.message(`Waiting for ${dbTarget.id} after lifting protection (${status})... [${Math.floor(elapsedMs / 1000)}s]`);
478
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} after lifting protection (${status})... [${Math.floor(elapsedMs / 1000)}s]`));
478
479
  return { done: false };
479
480
  },
480
481
  });
@@ -585,7 +586,7 @@ async function destroyStackMain(input = {}) {
585
586
  });
586
587
 
587
588
  if (deleteS3Bucket && typeof deleteS3Bucket !== 'symbol') {
588
- s.start(`Emptying and deleting S3 state bucket: ${bucketName}...`);
589
+ s.start(truncateSpinnerText(`Emptying and deleting S3 state bucket: ${bucketName}...`));
589
590
  try {
590
591
  const bucketResult = await teardownStateBucket(region, bucketName);
591
592
  const remaining = bucketResult && typeof bucketResult === 'object' && Array.isArray(bucketResult.remaining)
@@ -6,6 +6,7 @@ import { intro, outro, spinner } from '@clack/prompts';
6
6
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
7
7
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, isProgrammaticCall } from '../utils/command.js';
8
8
  import { normalizeOptions } from '../utils/args.js';
9
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
9
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
10
11
  import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
11
12
  import { pickNewestRunningTask } from '../utils/ecs.js';
@@ -173,7 +174,7 @@ export async function runLambdaDiagnose(input = {}) {
173
174
  const lastUpdateStatus = configuration.LastUpdateStatus || 'UNKNOWN';
174
175
  const configUnhealthy = state !== 'Active' || lastUpdateStatus === 'Failed';
175
176
 
176
- s.message(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${functionName}"...`);
177
+ s.message(truncateSpinnerText(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${functionName}"...`));
177
178
  let logs = [];
178
179
  let logGroupMissing = false;
179
180
  let logFetchFailed = false;
@@ -400,7 +401,7 @@ async function runDiagnoseMain(input = {}) {
400
401
  };
401
402
  }
402
403
 
403
- s.message(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${containerName}"...`);
404
+ s.message(truncateSpinnerText(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${containerName}"...`));
404
405
 
405
406
  // CloudWatch stream names follow `ecs/<containerName>/<taskId>`.
406
407
  const taskId = extractTaskIdFromArn(failedTask.taskArn);
@@ -13,6 +13,7 @@ import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
13
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
14
14
  import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, resolveWorkspaceSuffix, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
15
  import { requireManagedTree } from '../utils/terraform-metadata.js';
16
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
16
17
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
17
18
  import {
18
19
  discoverEligibleRevisions as discoverWithAdapter,
@@ -301,7 +302,7 @@ async function runRollbackMain(input = {}) {
301
302
  }
302
303
 
303
304
  // 2. Trigger the rollback.
304
- s.start(`Rolling back ${service} to revision ${targetRevisionNum}...`);
305
+ s.start(truncateSpinnerText(`Rolling back ${service} to revision ${targetRevisionNum}...`));
305
306
  await ecsClient.send(new UpdateServiceCommand({
306
307
  cluster,
307
308
  service,
@@ -353,19 +354,23 @@ async function runRollbackMain(input = {}) {
353
354
  }
354
355
 
355
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]`;
356
361
  if (!primary) {
357
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (registering deployment...)`);
362
+ s.message(truncateSpinnerText(`${progressStem} (registering deployment...)`));
358
363
  } else {
359
364
  const runningCount = primary.runningCount ?? 0;
360
365
  const desiredCount = primary.desiredCount ?? 0;
361
366
  const pendingCount = primary.pendingCount ?? 0;
362
367
  const failedTasks = primary.failedTasks ?? 0;
363
368
  if (failedTasks > 0) {
364
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`);
369
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`));
365
370
  } else if (runningCount >= desiredCount && desiredCount > 0 && pendingCount === 0) {
366
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (${runningCount}/${desiredCount} running — draining previous tasks)`);
371
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running — draining previous tasks)`));
367
372
  } else {
368
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (${runningCount}/${desiredCount} running, ${pendingCount} pending)`);
373
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending)`));
369
374
  }
370
375
  }
371
376
 
@@ -6,11 +6,13 @@ 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, refuseIfNonInteractive } from '../utils/command.js';
9
+ import { failCommand, isProgrammaticCall, refuseIfNonInteractive } from '../utils/command.js';
10
10
  import { atomicWriteFile } from '../utils/atomic-write.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
12
  import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
13
+ import { ADDON_ENV_VARS, ADDON_REGISTRY } from '../utils/addons.js';
13
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
15
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
14
16
 
15
17
  // Static sites provision no secrets vault, so push/pull/audit would fail
16
18
  // obscurely against a Secrets Manager secret that can never exist. One
@@ -138,6 +140,65 @@ function resolvePullAuditArgs(projectName, options) {
138
140
  };
139
141
  }
140
142
 
143
+ // Names Grada itself injects into the runtime environment. A pushed vault
144
+ // key sharing one of these names collides in the ECS task definition
145
+ // (RegisterTaskDefinition 400: a secret name must be unique and not shared
146
+ // with any environment variable) or is silently shadowed on Lambda, where
147
+ // the same names arrive as plain environment variables.
148
+ const BASE_MANAGED_ENV = {
149
+ ecs: ['PORT', 'NODE_ENV'],
150
+ lambda: ['PORT', 'AWS_LWA_PORT', 'APP_SECRETS_ARN'],
151
+ };
152
+ const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_ENGINE', 'DB_USER', 'DB_PASSWORD'];
153
+
154
+ // Wiring-like names whose local-dev values break production when pushed:
155
+ // the migrate gate trusts a present DATABASE_URL verbatim, so a localhost
156
+ // value pushed from a dev .env would be dialed from inside the ECS task.
157
+ const WIRING_LIKE_NAMES = ['DATABASE_URL', 'DB_URL', 'REDIS_URL', 'VALKEY_URL', 'DB_HOST', 'REDIS_HOST'];
158
+ const NON_PROD_VALUE_PATTERN = /localhost|127\.0\.0\.1|0\.0\.0\.0|example\.(com|org|net)/i;
159
+
160
+ // Managed-name set for this tree: the target base set, plus DB names when
161
+ // a database file exists, plus each enabled addon's injected names
162
+ // (capability file present under terraform/). Sorted for stable output.
163
+ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
164
+ const names = new Set(BASE_MANAGED_ENV[target] || BASE_MANAGED_ENV.ecs);
165
+ let tfFiles = [];
166
+ try {
167
+ tfFiles = await fs.readdir(path.join(cwd, 'terraform'));
168
+ } catch {
169
+ return [...names].sort();
170
+ }
171
+ if (tfFiles.some((file) => file.startsWith('database') && file.endsWith('.tf'))) {
172
+ for (const name of DB_MANAGED_ENV) names.add(name);
173
+ }
174
+ for (const [capability, entry] of Object.entries(ADDON_REGISTRY)) {
175
+ const envEntries = ADDON_ENV_VARS[capability];
176
+ if (!envEntries || !entry.file || !tfFiles.includes(entry.file)) continue;
177
+ for (const { name } of envEntries) names.add(name);
178
+ }
179
+ return [...names].sort();
180
+ }
181
+
182
+ // Values that look like local-dev placeholders on wiring-like names.
183
+ // Returns [{ key, indicator }] — the matched indicator only, never the
184
+ // value itself, so warnings stay safe to print and count in telemetry.
185
+ export function findNonProdWiring(parsedSecrets = {}) {
186
+ const hits = [];
187
+ for (const [key, value] of Object.entries(parsedSecrets)) {
188
+ if (!WIRING_LIKE_NAMES.includes(key)) continue;
189
+ const match = NON_PROD_VALUE_PATTERN.exec(String(value ?? ''));
190
+ if (match) hits.push({ key, indicator: match[0] });
191
+ }
192
+ return hits;
193
+ }
194
+
195
+ // Names a few keys for confirm prompts without blowing the density
196
+ // budget: first 8 inline, remainder as a count.
197
+ function summarizeKeys(keys) {
198
+ if (keys.length <= 8) return keys.join(', ');
199
+ return `${keys.slice(0, 8).join(', ')} (+${keys.length - 8} more)`;
200
+ }
201
+
141
202
  export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) {
142
203
  // Own-property checks: `in` matches inherited names (toString,
143
204
  // __proto__), which would misclassify real vault keys.
@@ -242,7 +303,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
242
303
  : path.basename(process.cwd());
243
304
 
244
305
  const s = spinner();
245
- s.start(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`);
306
+ s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
246
307
 
247
308
  try {
248
309
  // 1. Read and parse the local .env file
@@ -300,6 +361,63 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
300
361
  return;
301
362
  }
302
363
 
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
367
+ // any AWS or keys-file write. The spinner stops once for all
368
+ // pre-write output and restarts when the push proceeds.
369
+ const pushTarget = readTerraformComputeTarget(process.cwd());
370
+ const managedNames = await getManagedEnvNames(process.cwd(), pushTarget);
371
+ const collisions = Object.keys(parsedSecrets).filter((key) => managedNames.includes(key));
372
+ const wiringHits = findNonProdWiring(parsedSecrets);
373
+ const needsPreWriteOutput = collisions.length > 0 || wiringHits.length > 0;
374
+ if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
375
+ for (const { key, indicator } of wiringHits) {
376
+ console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
377
+ }
378
+ if (collisions.length > 0 && pushTarget === 'lambda') {
379
+ 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
+ }
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
+ }
418
+ }
419
+ if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
420
+
303
421
  // 2. Resolve the region (explicit flag > env > backend.tf > default)
304
422
  // so the AWS client is never constructed without one.
305
423
  const targetRegion = await resolveSecretsRegion(opts);
@@ -330,6 +448,37 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
330
448
  }
331
449
  }
332
450
 
451
+ // BUG-80: push is full-replace, so vault keys absent from .env are
452
+ // deleted by the update below. Name every victim before writing;
453
+ // interactive runs confirm first, headless proceeds loudly.
454
+ const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
455
+ if (removed.length > 0) {
456
+ s.stop('Pre-flight checks done.');
457
+ console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`));
458
+ for (const key of removed) console.log(color.red(`- ${key} (removed from the vault)`));
459
+ const headlessPush = opts.isHeadless || opts.headless || process.env.CI;
460
+ const removalApproved = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
461
+ if (!headlessPush && !removalApproved) {
462
+ const refusedRemoval = await refuseIfNonInteractive(opts, {
463
+ message: `\n✖ secrets push needs approval before deleting ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} missing from ${resolvedFilePath}.`,
464
+ hint: ' Re-run with --headless to delete non-interactively (removals are named above), or run interactively to decide.\n',
465
+ event: 'secrets_pushed',
466
+ telemetry: { projectName: resolvedProjectName, removed_count: removed.length },
467
+ errorCode: 'SECRETS_NON_INTERACTIVE',
468
+ });
469
+ if (refusedRemoval) return refusedRemoval;
470
+ const proceed = await confirm({
471
+ message: `Delete ${summarizeKeys(removed)} from the vault?`,
472
+ initialValue: false,
473
+ });
474
+ if (isCancel(proceed) || proceed !== true) {
475
+ console.log(color.dim('Secrets push cancelled. The vault and secret_keys.json are unchanged.'));
476
+ return;
477
+ }
478
+ }
479
+ s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
480
+ }
481
+
333
482
  // 5. Update the secret string in AWS
334
483
  const command = new UpdateSecretCommand({
335
484
  SecretId: `${secretVaultId(resolvedProjectName)}`,
@@ -364,7 +513,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
364
513
  projectName: resolvedProjectName,
365
514
  secret_count: Object.keys(parsedSecrets).length,
366
515
  keys_changed: false,
367
- ecs_restart: false
516
+ ecs_restart: false,
517
+ removed_count: removed.length,
518
+ managed_collisions: collisions.length
368
519
  });
369
520
  return { keysChanged: false, restarted: false };
370
521
  }
@@ -377,7 +528,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
377
528
  projectName: resolvedProjectName,
378
529
  secret_count: Object.keys(parsedSecrets).length,
379
530
  keys_changed: false,
380
- ecs_restart: false
531
+ ecs_restart: false,
532
+ removed_count: removed.length,
533
+ managed_collisions: collisions.length
381
534
  });
382
535
  return { keysChanged: false, restarted: false };
383
536
  }
@@ -415,7 +568,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
415
568
  projectName: resolvedProjectName,
416
569
  secret_count: Object.keys(parsedSecrets).length,
417
570
  keys_changed: false,
418
- ecs_restart: true
571
+ ecs_restart: true,
572
+ removed_count: removed.length,
573
+ managed_collisions: collisions.length
419
574
  });
420
575
  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')}`));
421
576
  return { keysChanged: false, restarted: true, cluster, service };
@@ -426,7 +581,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
426
581
  await trackSuccess('secrets_pushed', {
427
582
  projectName: resolvedProjectName,
428
583
  secret_count: Object.keys(parsedSecrets).length,
429
- keys_changed: keysChanged
584
+ keys_changed: keysChanged,
585
+ removed_count: removed.length,
586
+ managed_collisions: collisions.length
430
587
  });
431
588
  return { keysChanged };
432
589
 
@@ -659,15 +816,30 @@ async function auditSecretsMain(envFilePath, projectName, options = {}) {
659
816
  }
660
817
  }
661
818
 
819
+ // BUG-79: flag both limbs — keys colliding with Grada-managed
820
+ // environment names (fatal on ECS, shadowing on Lambda) and
821
+ // wiring-like values that look like local-dev placeholders.
822
+ const auditTarget = readTerraformComputeTarget(process.cwd());
823
+ const auditManaged = await getManagedEnvNames(process.cwd(), auditTarget);
824
+ const auditedKeys = [...new Set([...Object.keys(localSecrets), ...Object.keys(remoteSecrets)])];
825
+ const collisions = auditedKeys.filter((key) => auditManaged.includes(key));
826
+ for (const key of collisions) {
827
+ console.log(color.red(`! ${key} (collides with a Grada-managed environment name)`));
828
+ }
829
+ for (const { key, indicator } of findNonProdWiring(remoteSecrets)) {
830
+ console.log(color.yellow(`⚠️ ${key} looks like a local-dev value (contains "${indicator}") — production wiring would dial it.`));
831
+ }
832
+
662
833
  outro(`Audit complete. ${driftCount} drifted variable(s) found.`);
663
834
 
664
835
  trackEvent('secrets_audit', {
665
836
  projectName: resolvedProjectName,
666
837
  driftCount,
838
+ collision_count: collisions.length,
667
839
  });
668
840
  await flushTelemetry();
669
841
 
670
- return { missingLocally, mismatched, untrackedLocally, driftCount };
842
+ return { missingLocally, mismatched, untrackedLocally, driftCount, collisions };
671
843
  } catch (error) {
672
844
  return handleSecretsCatch({
673
845
  error,
@@ -7,6 +7,7 @@ import { intro, outro, spinner, confirm, cancel } from '@clack/prompts';
7
7
  import { trackEvent, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
8
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
10
11
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
12
  import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget } from '../utils/resolvers.js';
12
13
  import { requireManagedTree } from '../utils/terraform-metadata.js';
@@ -219,7 +220,7 @@ async function runSleepMain(input = {}) {
219
220
  const runSync = options.spawnSyncImpl || spawnSync;
220
221
 
221
222
  const s = spinner();
222
- s.start(`Putting ${target.envKey} to sleep...`);
223
+ s.start(truncateSpinnerText(`Putting ${target.envKey} to sleep...`));
223
224
 
224
225
  try {
225
226
  // Read-only probes first: the fast-path check below must see live
@@ -13,6 +13,7 @@ import { requireManagedTree } from '../utils/terraform-metadata.js';
13
13
  import { findDbTarget, dbStatusOf } from '../utils/rds.js';
14
14
  import { fetchActiveService, detectTaskFailure } from '../utils/ecs.js';
15
15
  import { pollUntil } from '../utils/system.js';
16
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
16
17
  import {
17
18
  resolveSleepTarget,
18
19
  readSleepState,
@@ -231,7 +232,7 @@ async function runWakeMain(input = {}) {
231
232
  }
232
233
 
233
234
  const s = spinner();
234
- s.start(`Waking ${target.envKey}...`);
235
+ s.start(truncateSpinnerText(`Waking ${target.envKey}...`));
235
236
 
236
237
  try {
237
238
  // 1. Start the database first so booting containers never
@@ -261,7 +262,7 @@ async function runWakeMain(input = {}) {
261
262
 
262
263
  if (!noWait && dbTarget && dbStarted) {
263
264
  const isCluster = dbTarget.kind === 'cluster';
264
- s.message(`Waiting for ${dbTarget.id} to become available...`);
265
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} to become available...`));
265
266
  const outcome = await pollUntil({
266
267
  intervalMs: pollIntervalMs,
267
268
  timeoutMs,
@@ -275,7 +276,7 @@ async function runWakeMain(input = {}) {
275
276
  ? (resp.DBClusters || [])[0] || null
276
277
  : (resp.DBInstances || [])[0] || null;
277
278
  if (dbStatusOf(current, isCluster ? 'cluster' : 'instance') === 'available') return { done: true, value: current };
278
- s.message(`Waiting for ${dbTarget.id}... [${Math.floor(elapsedMs / 1000)}s]`);
279
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id}... [${Math.floor(elapsedMs / 1000)}s]`));
279
280
  return { done: false };
280
281
  },
281
282
  });
@@ -8,6 +8,7 @@ import { FilterLogEventsCommand, GetLogEventsCommand } from '@aws-sdk/client-clo
8
8
  import color from 'picocolors';
9
9
  import { fetchActiveService, pickRuntimeContainer } from './ecs.js';
10
10
  import { sleep, pollUntil } from './system.js';
11
+ import { truncateSpinnerText } from './spinner-text.js';
11
12
  import { isNotFoundError, buildLogStreamName } from '../commands/logs.js';
12
13
 
13
14
  export const DEFAULT_RUNNER_POLL_INTERVAL_MS = 2000;
@@ -259,7 +260,7 @@ export async function runEphemeralEcsTask({
259
260
  console.log(color.dim(` task ${taskId} — press Ctrl+C to abort and stop the remote task.\n`));
260
261
  } else if (!streaming && status && status !== lastPhase) {
261
262
  lastPhase = status;
262
- spinner?.message(phaseMessage(status));
263
+ spinner?.message(truncateSpinnerText(phaseMessage(status)));
263
264
  }
264
265
  return { done: false };
265
266
  },
@@ -0,0 +1,30 @@
1
+ // Terminal-width truncation for spinner frames. Clack re-renders the
2
+ // current frame every ~80ms, and any frame wider than the terminal
3
+ // wraps — on viewers that split frames into lines (harness PTYs, log
4
+ // capture) each wrapped frame fossilizes as extra scrollback lines.
5
+ // Every dynamic spinner message goes through here so over-width
6
+ // frames can never wall, on any terminal width.
7
+
8
+ // Spinner chrome around the message: glyph + animated dots + padding.
9
+ export const SPINNER_FRAME_OVERHEAD = 9;
10
+
11
+ // Wide terminals keep the historical 120-column cap.
12
+ export const SPINNER_TEXT_MAX = 120;
13
+
14
+ // Visible columns available for spinner text: the terminal width
15
+ // minus caller-reserved fixed text (e.g. a `Prefix - ` stem, counted
16
+ // via fixedOverhead) and spinner chrome. Floored so tiny terminals
17
+ // still show something; falls back to 80 when piped.
18
+ export function spinnerTextBudget({ columns = process.stdout?.columns ?? 80, fixedOverhead = SPINNER_FRAME_OVERHEAD } = {}) {
19
+ return Math.max(20, Math.min(SPINNER_TEXT_MAX, columns - fixedOverhead));
20
+ }
21
+
22
+ // Cuts text to the spinner budget (with `...`), code-point safe so
23
+ // emoji survive. Pass uncolored text and color after: ANSI escapes
24
+ // would count as visible columns and slicing could split them.
25
+ export function truncateSpinnerText(text, options = {}) {
26
+ const chars = Array.from(String(text ?? ''));
27
+ const budget = spinnerTextBudget(options);
28
+ if (chars.length <= budget) return chars.join('');
29
+ return `${chars.slice(0, budget - 3).join('')}...`;
30
+ }
@@ -155,11 +155,20 @@ export function upsertAutoTfvar(tfDir, key, value) {
155
155
  const created = content === '';
156
156
  const line = `${key} = ${value ? 'true' : 'false'}`;
157
157
  const pattern = new RegExp(`^[ \\t]*${key}\\s*=.*$`, 'm');
158
+ const matches = content.match(new RegExp(`^[ \\t]*${key}\\s*=.*$`, 'gm')) || [];
158
159
  let changed;
159
- if (pattern.test(content)) {
160
+ if (matches.length === 1) {
160
161
  const next = content.replace(pattern, line);
161
162
  changed = next !== content;
162
163
  content = next;
164
+ } else if (matches.length > 1) {
165
+ // Pre-existing duplicates (the old single-echo guidance ran
166
+ // twice): first-match replace would keep the dup and report
167
+ // unchanged while Terraform fails hard. Collapse to one copy.
168
+ const stripped = content.replace(new RegExp(`^[ \\t]*${key}\\s*=.*$\\n?`, 'gm'), '');
169
+ const next = `${stripped === '' ? '' : stripped.replace(/\n*$/, '\n')}${line}\n`;
170
+ changed = next !== content;
171
+ content = next;
163
172
  } else {
164
173
  const header = '# Managed by grada: machine-written variable overrides. Safe to delete an entry to restore its default.\n';
165
174
  content = `${created ? header : content.replace(/\n*$/, '\n')}${line}\n`;
@@ -5,6 +5,7 @@ import color from 'picocolors';
5
5
  import { classifyTerraformError } from './terraform-errors.js';
6
6
  import { SLEEP_STATE_DIRNAME } from './sleep-state.js';
7
7
  import { isActiveEnvValue } from '../core/telemetry.js';
8
+ import { truncateSpinnerText, SPINNER_FRAME_OVERHEAD } from './spinner-text.js';
8
9
 
9
10
  export const LAST_RUN_FILENAME = 'last-run.json';
10
11
  // Generous per-phase ceiling: CloudFront teardown and Aurora provisioning
@@ -223,16 +224,18 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
223
224
  if (typeof onStdoutLine === 'function') {
224
225
  for (const line of lines) onStdoutLine(line);
225
226
  }
227
+ // Both emits cut the line to the terminal budget (truncate
228
+ // before coloring so ANSI escapes never count as columns).
229
+ const lineOverhead = `${loadingPrefix} - `.length + SPINNER_FRAME_OVERHEAD;
226
230
  for (const line of lines) {
227
231
  const trimmed = line.trim();
228
232
  if (SUMMARY_LINE_RE.test(trimmed)) {
229
- emit(`${loadingPrefix} - ${color.dim(trimmed)}`);
233
+ emit(`${loadingPrefix} - ${color.dim(truncateSpinnerText(trimmed, { fixedOverhead: lineOverhead }))}`);
230
234
  }
231
235
  }
232
236
  if (lines.length > 0) {
233
237
  const latestLine = lines[lines.length - 1].trim();
234
- const display = latestLine.length > 120 ? latestLine.substring(0, 117) + '...' : latestLine;
235
- emit(`${loadingPrefix} - ${color.dim(display)}`);
238
+ emit(`${loadingPrefix} - ${color.dim(truncateSpinnerText(latestLine, { fixedOverhead: lineOverhead }))}`);
236
239
  }
237
240
  });
238
241
 
@@ -27,8 +27,10 @@ provider "aws" {
27
27
  }
28
28
 
29
29
  locals {
30
- # Safely read the keys generated by the CLI, default to empty list if file doesn't exist
31
- secret_keys = fileexists("${path.module}/secret_keys.json") ? jsondecode(file("${path.module}/secret_keys.json")) : []
30
+ # Safely read the keys generated by the CLI, default to empty list if file doesn't exist.
31
+ # toset() collapses hand-duplicated entries: duplicate secrets render the
32
+ # same RegisterTaskDefinition 400 as a name collision (BUG-79).
33
+ secret_keys = fileexists("${path.module}/secret_keys.json") ? toset(jsondecode(file("${path.module}/secret_keys.json"))) : []
32
34
 
33
35
  # Workspace suffix for PR preview environments (e.g., "-pr-123"). Empty for production.
34
36
  env_suffix = terraform.workspace == "default" ? "" : "-${terraform.workspace}"