grada-run 0.41.5 → 0.43.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.
Files changed (65) hide show
  1. package/bin/cli.js +18 -8
  2. package/package.json +1 -1
  3. package/src/commands/add.js +93 -11
  4. package/src/commands/alerts.js +69 -31
  5. package/src/commands/apply.js +62 -10
  6. package/src/commands/db/backup.js +1 -2
  7. package/src/commands/db/connect.js +27 -14
  8. package/src/commands/db/enable-vector.js +19 -6
  9. package/src/commands/db/import.js +114 -22
  10. package/src/commands/db/migrate.js +77 -73
  11. package/src/commands/db/restore.js +38 -6
  12. package/src/commands/destroy.js +68 -6
  13. package/src/commands/diagnose.js +57 -32
  14. package/src/commands/doctor.js +5 -3
  15. package/src/commands/domain.js +55 -7
  16. package/src/commands/drift.js +2 -1
  17. package/src/commands/eject.js +13 -2
  18. package/src/commands/exec.js +9 -4
  19. package/src/commands/gc.js +135 -6
  20. package/src/commands/init.js +75 -9
  21. package/src/commands/logs.js +127 -38
  22. package/src/commands/mcp.js +3 -2
  23. package/src/commands/rollback.js +230 -74
  24. package/src/commands/secrets.js +251 -61
  25. package/src/commands/status.js +17 -8
  26. package/src/commands/sync-ai.js +4 -3
  27. package/src/commands/wake.js +45 -1
  28. package/src/data/action-pins.js +26 -0
  29. package/src/utils/addons.js +9 -6
  30. package/src/utils/ai-rules.js +3 -2
  31. package/src/utils/backup.js +16 -2
  32. package/src/utils/command.js +20 -0
  33. package/src/utils/db-tunnel.js +15 -5
  34. package/src/utils/detector.js +8 -0
  35. package/src/utils/ecs-runner.js +16 -3
  36. package/src/utils/frameworks.js +14 -2
  37. package/src/utils/generator.js +33 -16
  38. package/src/utils/prompts.js +20 -4
  39. package/src/utils/resolvers.js +74 -11
  40. package/src/utils/revision-discovery.js +19 -7
  41. package/templates/docker/nestjs.Dockerfile +2 -2
  42. package/templates/docker/nextjs.Dockerfile +3 -3
  43. package/templates/docker/node.Dockerfile +2 -2
  44. package/templates/docker/nuxt.Dockerfile +2 -2
  45. package/templates/docker/static.Dockerfile +1 -1
  46. package/templates/docker/svelte.Dockerfile +2 -2
  47. package/templates/github/deploy-lambda.yml +73 -11
  48. package/templates/github/deploy-static.yml +4 -3
  49. package/templates/github/deploy.yml +114 -12
  50. package/templates/github/drift.yml +74 -5
  51. package/templates/github/preview-lambda.yml +143 -13
  52. package/templates/github/preview.yml +141 -13
  53. package/templates/github/teardown.yml +77 -12
  54. package/templates/terraform/addons/bedrock.tf +6 -2
  55. package/templates/terraform/addons/s3.tf +33 -0
  56. package/templates/terraform/backend.tf +7 -0
  57. package/templates/terraform/cloudfront-lambda.tf +125 -6
  58. package/templates/terraform/cloudfront.tf +137 -10
  59. package/templates/terraform/database-mysql.tf +5 -1
  60. package/templates/terraform/database.tf +5 -1
  61. package/templates/terraform/main.tf +36 -1
  62. package/templates/terraform/network.tf +5 -2
  63. package/templates/terraform/oidc.tf +3 -2
  64. package/templates/terraform/secrets.tf +6 -4
  65. package/templates/terraform/worker.tf +7 -0
@@ -2,7 +2,7 @@ import fsSync from 'fs';
2
2
  import path from 'path';
3
3
  import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
4
4
  import color from 'picocolors';
5
- import { RDSClient, DescribeDBInstancesCommand, DescribeDBClustersCommand, StartDBInstanceCommand, StartDBClusterCommand, CreateDBSnapshotCommand, CreateDBClusterSnapshotCommand, ModifyDBInstanceCommand, ModifyDBClusterCommand } from '@aws-sdk/client-rds';
5
+ import { RDSClient, DescribeDBInstancesCommand, DescribeDBClustersCommand, DescribeDBSnapshotsCommand, DescribeDBClusterSnapshotsCommand, StartDBInstanceCommand, StartDBClusterCommand, CreateDBSnapshotCommand, CreateDBClusterSnapshotCommand, ModifyDBInstanceCommand, ModifyDBClusterCommand } from '@aws-sdk/client-rds';
6
6
  import { S3Client } from '@aws-sdk/client-s3';
7
7
  import { teardownStateBucket, drainBucketObjects, resolveClient } from '../utils/aws.js';
8
8
  import { checkDependency, pollUntil } from '../utils/system.js';
@@ -19,6 +19,7 @@ import { truncateSpinnerText } from '../utils/spinner-text.js';
19
19
  export const DEFAULT_DESTROY_DB_TIMEOUT_MS = 600000;
20
20
  export const DEFAULT_DESTROY_DB_SETTLE_TIMEOUT_MS = 1800000;
21
21
  export const DEFAULT_DESTROY_DB_POLL_INTERVAL_MS = 5000;
22
+ export const DEFAULT_DESTROY_SNAPSHOT_TIMEOUT_MS = 1800000;
22
23
 
23
24
  // True when the tree's database template declares the data-loss variable
24
25
  // (new templates only). Destroy passes the -var override exclusively in
@@ -52,7 +53,8 @@ export function parseDestroyArgs(argv = []) {
52
53
  // other recognized failures get a named runbook instead of raw stderr.
53
54
  // Returns `{ retried: true }` when the destroy recovered so the caller
54
55
  // continues to bucket cleanup, else `{ retried: false, result }`.
55
- async function handleDestroyTerraformError({ options, tfDirPath, attemptDestroy, error }) {
56
+ // Exported for unit tests: every branch must honor this contract.
57
+ export async function handleDestroyTerraformError({ options, tfDirPath, attemptDestroy, error }) {
56
58
  const actualProjectName = path.basename(process.cwd());
57
59
  const errString = String(error.message || error);
58
60
  const structuredCode = typeof error.code === 'string' && ERROR_CODES.includes(error.code) ? error.code : null;
@@ -105,7 +107,7 @@ async function handleDestroyTerraformError({ options, tfDirPath, attemptDestroy,
105
107
  telemetry: { projectName: actualProjectName },
106
108
  errorCode: 'DESTROY_NON_INTERACTIVE',
107
109
  });
108
- if (refused) return refused;
110
+ if (refused) return { retried: false, result: refused };
109
111
  const runbook = getRunbook('STATE_LOCK_HELD', { headless: false, lockId });
110
112
  console.error(color.red(`✖ ${runbook.message}`));
111
113
  console.log(` ${runbook.hint}`);
@@ -196,6 +198,7 @@ async function destroyStackMain(input = {}) {
196
198
 
197
199
  const timeoutMs = options.timeoutMs ?? DEFAULT_DESTROY_DB_TIMEOUT_MS;
198
200
  const settleTimeoutMs = options.dbSettleTimeoutMs ?? DEFAULT_DESTROY_DB_SETTLE_TIMEOUT_MS;
201
+ const snapshotTimeoutMs = options.snapshotTimeoutMs ?? DEFAULT_DESTROY_SNAPSHOT_TIMEOUT_MS;
199
202
  const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_DESTROY_DB_POLL_INTERVAL_MS;
200
203
  const pollOverrides = {
201
204
  ...(options.sleepFn ? { sleepFn: options.sleepFn } : {}),
@@ -266,7 +269,7 @@ async function destroyStackMain(input = {}) {
266
269
  initialValue: false,
267
270
  });
268
271
 
269
- if (!proceed) {
272
+ if (proceed !== true) {
270
273
  cancel('Destruction cancelled. Your infrastructure is safe.');
271
274
  process.exit(0);
272
275
  }
@@ -403,6 +406,7 @@ async function destroyStackMain(input = {}) {
403
406
  // 1c. Pre-destroy snapshot checkpoint (M1). Skipped only with
404
407
  // --allow-data-loss (explicit acceptance) or a `deleting` database
405
408
  // (nothing left to protect).
409
+ let snapshotReadyId = null;
406
410
  if (dbNeedsProtection) {
407
411
  const snapshotId = generateSnapshotId(dbTarget.id);
408
412
  s.start(truncateSpinnerText(`Snapshotting database ${dbTarget.id} before destruction...`));
@@ -423,7 +427,59 @@ async function destroyStackMain(input = {}) {
423
427
  reason: 'db-snapshot-failed',
424
428
  });
425
429
  }
426
- s.stop(`Database snapshot ${snapshotId} started.`);
430
+ // Wait for the snapshot to reach `available` before touching the
431
+ // database: deleting while it is still `creating` races snapshot
432
+ // completion on large DBs (BUG-98). A failed snapshot or a timeout
433
+ // refuses the destroy — re-run with --allow-data-loss to skip.
434
+ // Re-message (never re-start): the phase spinner is already
435
+ // running, and a second start leaks clack's first interval so the
436
+ // session never exits (BUG-198).
437
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId} to complete...`));
438
+ const snapshotReady = await pollUntil({
439
+ intervalMs: pollIntervalMs,
440
+ timeoutMs: snapshotTimeoutMs,
441
+ ...pollOverrides,
442
+ onTick: async () => {
443
+ let status = null;
444
+ let percent = null;
445
+ try {
446
+ if (dbTarget.kind === 'cluster') {
447
+ const resp = await rdsClient.send(new DescribeDBClusterSnapshotsCommand({ DBClusterSnapshotIdentifier: snapshotId }));
448
+ status = resp.DBClusterSnapshots?.[0]?.Status ?? null;
449
+ percent = resp.DBClusterSnapshots?.[0]?.PercentProgress ?? null;
450
+ } else {
451
+ const resp = await rdsClient.send(new DescribeDBSnapshotsCommand({ DBSnapshotIdentifier: snapshotId }));
452
+ status = resp.DBSnapshots?.[0]?.Status ?? null;
453
+ percent = resp.DBSnapshots?.[0]?.PercentProgress ?? null;
454
+ }
455
+ } catch (error) {
456
+ return { done: true, value: { failed: true, reason: `snapshot describe failed (${error.message})` } };
457
+ }
458
+ if (status === 'available') return { done: true, value: { failed: false } };
459
+ if (status === 'failed' || status === 'deleted') {
460
+ return { done: true, value: { failed: true, reason: `snapshot ${status}` } };
461
+ }
462
+ // BUG-196: surface PercentProgress while creating so long
463
+ // snapshots don't look wedged.
464
+ const detail = typeof percent === 'number' ? `${status || 'pending'} (${percent}% complete)` : (status || 'pending');
465
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId} to complete... (${detail})`));
466
+ return { done: false };
467
+ },
468
+ });
469
+ if (snapshotReady.timedOut || snapshotReady.value?.failed) {
470
+ s.stop(color.red('❌ Pre-destroy snapshot did not complete.'));
471
+ const errorCode = snapshotReady.timedOut ? 'DB_SNAPSHOT_TIMEOUT' : 'DB_SNAPSHOT_FAILED';
472
+ return failCommand({
473
+ message: `\n✖ Refusing to destroy: pre-destroy snapshot ${snapshotId} ${snapshotReady.timedOut ? 'did not complete in time' : snapshotReady.value.reason} — the database is untouched. Re-run with --allow-data-loss to destroy without a snapshot.`,
474
+ useErrorStream: true,
475
+ event: 'infrastructure_destroyed',
476
+ telemetry: { projectName: projectNameForTelemetry, error_code: errorCode },
477
+ errorCode,
478
+ reason: snapshotReady.timedOut ? 'db-snapshot-timeout' : 'db-snapshot-failed',
479
+ });
480
+ }
481
+ s.stop(`Database snapshot ${snapshotId} ready.`);
482
+ snapshotReadyId = snapshotId;
427
483
  console.log(color.green(`📸 Pre-destroy snapshot: ${snapshotId}`));
428
484
  trackEvent('db_destroy_checkpoint', { projectName: projectNameForTelemetry, db_kind: dbTarget.kind });
429
485
  await flushTelemetry();
@@ -580,8 +636,14 @@ async function destroyStackMain(input = {}) {
580
636
  });
581
637
  if (refused) return refused;
582
638
  }
639
+ // BUG-198: "spin this back up" overstated recovery — apply
640
+ // recreates compute, never the destroyed database. Name the
641
+ // snapshot (or its absence) so the choice is informed.
642
+ const dbRecoveryNote = snapshotReadyId
643
+ ? `\n (The database itself was destroyed — only pre-destroy snapshot ${snapshotReadyId} remains, for manual restore; apply will not bring the data back.)`
644
+ : (dbTarget ? `\n (The database itself was destroyed WITHOUT a snapshot (--allow-data-loss); apply will recreate it empty.)` : '');
583
645
  deleteS3Bucket = shouldAutoApprove(options) ? true : await confirm({
584
- message: color.yellow(`AWS compute resources destroyed. Do you also want to permanently delete the S3 state bucket?\n (Select 'No' if you plan to run 'grada apply' later to spin this back up.)`),
646
+ message: color.yellow(`AWS compute resources destroyed. Do you also want to permanently delete the S3 state bucket?\n (Select 'No' if you plan to run 'grada apply' later to spin this back up.)${dbRecoveryNote}`),
585
647
  initialValue: false,
586
648
  });
587
649
 
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from 'child_process';
2
2
  import { ECSClient, ListTasksCommand, DescribeTasksCommand } from '@aws-sdk/client-ecs';
3
- import { CloudWatchLogsClient, FilterLogEventsCommand } from '@aws-sdk/client-cloudwatch-logs';
3
+ import { CloudWatchLogsClient } from '@aws-sdk/client-cloudwatch-logs';
4
4
  import color from 'picocolors';
5
5
  import { intro, outro, spinner } from '@clack/prompts';
6
6
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
@@ -8,10 +8,15 @@ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized,
8
8
  import { normalizeOptions } from '../utils/args.js';
9
9
  import { truncateSpinnerText } from '../utils/spinner-text.js';
10
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
- import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace } from '../utils/resolvers.js';
12
12
  import { pickNewestRunningTask } from '../utils/ecs.js';
13
+ import { fetchLatestEvents } from './logs.js';
13
14
 
14
15
  export const LOG_FETCH_LIMIT = 50;
16
+ // Stopped-task discovery bounds: 3 ListTasks pages (300 ARNs max),
17
+ // described in DescribeTasks-sized chunks.
18
+ export const STOPPED_LIST_MAX_PAGES = 3;
19
+ export const DESCRIBE_TASKS_ARN_LIMIT = 100;
15
20
 
16
21
  export function extractStoppedReason(task) {
17
22
  return task?.stoppedReason || 'Unknown';
@@ -106,9 +111,10 @@ export async function runLambdaDiagnose(input = {}) {
106
111
  const projectName = options.projectName;
107
112
  const region = options.region;
108
113
  const logGroup = options.logGroup;
114
+ const namespacedProject = resolveNamespacedProject(projectName, options, options.cwd);
109
115
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
110
116
  ? options.functionName.trim()
111
- : `${projectName}${readResourceSuffix(options.cwd)}-fn`;
117
+ : `${namespacedProject}${readResourceSuffix(options.cwd)}-fn`;
112
118
  const runSync = options.spawnSyncImpl || spawnSync;
113
119
 
114
120
  intro(color.bgCyan(color.black(' grada diagnose 🩺 ')));
@@ -180,12 +186,11 @@ export async function runLambdaDiagnose(input = {}) {
180
186
  let logFetchFailed = false;
181
187
  let fetchError = '';
182
188
  try {
183
- const logsResp = await logsClient.send(new FilterLogEventsCommand({
189
+ const { events } = await fetchLatestEvents(logsClient, {
184
190
  logGroupName: logGroup,
185
191
  startTime: Date.now() - 60 * 60 * 1000,
186
- limit: LOG_FETCH_LIMIT,
187
- }));
188
- logs = (logsResp.events || []).slice(-LOG_FETCH_LIMIT).map((e) => e.message);
192
+ }, { tail: LOG_FETCH_LIMIT });
193
+ logs = events.map((e) => e.message);
189
194
  } catch (logsError) {
190
195
  if (handleAuthErrorBranch(logsError, s, options)) return;
191
196
  if (isLogGroupNotFoundError(logsError)) {
@@ -257,8 +262,13 @@ async function runDiagnoseMain(input = {}) {
257
262
  cwd = resolveCwd(options);
258
263
  projectName = resolveProjectName(options, cwd);
259
264
  region = resolveRegion(options, cwd);
260
- cluster = resolveCluster(options, cwd);
261
- logGroup = resolveLogGroup(options, cwd);
265
+ // Workspace-namespaced resources (BUG-90): --workspace (or the
266
+ // local .terraform/environment) targets a preview stack like
267
+ // rollback and db do. Explicit flags/env keep winning; telemetry
268
+ // keeps the raw project name.
269
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
270
+ cluster = resolveCluster(namespacedOptions, cwd);
271
+ logGroup = resolveLogGroup(namespacedOptions, cwd);
262
272
  } catch {
263
273
  return failProjectNotInitialized({ event: 'diagnose_run', noExit });
264
274
  }
@@ -295,16 +305,27 @@ async function runDiagnoseMain(input = {}) {
295
305
  const logsClient = resolveClient(options.logsClient, CloudWatchLogsClient, { region });
296
306
 
297
307
  try {
298
- const listResp = await ecsClient.send(
299
- new ListTasksCommand({
300
- cluster,
301
- desiredStatus: 'STOPPED',
302
- sort: 'DESC',
303
- maxResults: 100
304
- })
305
- );
306
-
307
- const taskArns = listResp.taskArns || [];
308
+ // A crash-looping service exceeds 100 stopped tasks within the ~1h
309
+ // retention, and ListTasks order is arbitrary — one page may miss
310
+ // the true latest crash. Paginate (bounded) before describing.
311
+ const taskArns = [];
312
+ let listToken;
313
+ let truncated = false;
314
+ for (let page = 0; page < STOPPED_LIST_MAX_PAGES; page++) {
315
+ const listResp = await ecsClient.send(
316
+ new ListTasksCommand({
317
+ cluster,
318
+ desiredStatus: 'STOPPED',
319
+ sort: 'DESC',
320
+ maxResults: 100,
321
+ ...(listToken ? { nextToken: listToken } : {}),
322
+ })
323
+ );
324
+ taskArns.push(...(listResp.taskArns || []));
325
+ listToken = listResp.nextToken;
326
+ if (!listToken) break;
327
+ if (page + 1 >= STOPPED_LIST_MAX_PAGES) truncated = true;
328
+ }
308
329
 
309
330
  if (taskArns.length === 0) {
310
331
  s.stop('No stopped tasks found.');
@@ -314,17 +335,21 @@ async function runDiagnoseMain(input = {}) {
314
335
  return { healthy: true, stoppedReason: null, logs: [] };
315
336
  }
316
337
 
317
- // ListTasks order is arbitrary — describe the full batch (up to the
318
- // DescribeTasks 100-ARN limit) and pick the latest stopped task below.
319
- s.message(`Describing ${Math.min(taskArns.length, 100)} stopped task(s)...`);
320
- const descResp = await ecsClient.send(
321
- new DescribeTasksCommand({
322
- cluster,
323
- tasks: taskArns.slice(0, 100)
324
- })
325
- );
326
-
327
- const tasks = descResp.tasks || [];
338
+ // DescribeTasks caps at 100 ARNs per call — chunk the pages.
339
+ s.message(`Describing ${taskArns.length} stopped task(s)...`);
340
+ const tasks = [];
341
+ for (let i = 0; i < taskArns.length; i += DESCRIBE_TASKS_ARN_LIMIT) {
342
+ const descResp = await ecsClient.send(
343
+ new DescribeTasksCommand({
344
+ cluster,
345
+ tasks: taskArns.slice(i, i + DESCRIBE_TASKS_ARN_LIMIT)
346
+ })
347
+ );
348
+ tasks.push(...(descResp.tasks || []));
349
+ }
350
+ if (truncated) {
351
+ console.log(color.dim(` Note: more than ${STOPPED_LIST_MAX_PAGES * 100} stopped tasks exist — diagnosing the latest of the first ${STOPPED_LIST_MAX_PAGES * 100}.`));
352
+ }
328
353
  if (tasks.length === 0) {
329
354
  s.stop('No task details returned.');
330
355
  console.log(color.yellow('⚠ Stopped task ARNs were listed, but ECS returned no task details.'));
@@ -410,8 +435,8 @@ async function runDiagnoseMain(input = {}) {
410
435
  : '';
411
436
 
412
437
  const fetchLogMessages = async (input) => {
413
- const logsResp = await logsClient.send(new FilterLogEventsCommand(input));
414
- return (logsResp.events || []).slice(-LOG_FETCH_LIMIT).map((e) => e.message);
438
+ const { events } = await fetchLatestEvents(logsClient, input, { tail: LOG_FETCH_LIMIT });
439
+ return events.map((e) => e.message);
415
440
  };
416
441
 
417
442
  let logs = [];
@@ -33,7 +33,7 @@ export const PROJECT_CHECKS = [
33
33
  { id: 'state_lock', label: 'Terraform state lock', scope: 'project', severity: 'fail', run: checkStateLock, hint: () => 'If no apply is running, release it with: terraform force-unlock <lock-id> (find the holder via grada doctor --deep).' },
34
34
  { id: 'interrupted_run', label: 'Interrupted Terraform run', scope: 'project', severity: 'warn', run: checkInterruptedRun, hint: () => 'Review the last apply/destroy output before trusting applied state; the next run overwrites the marker.' },
35
35
  { id: 'oidc_trust_scope', label: 'OIDC trust scope', scope: 'project', severity: 'warn', run: checkOidcTrustScope, hint: () => 'Re-scope with: npx grada-run init --github-repo owner/name (or edit the sub claim in terraform/oidc.tf).' },
36
- { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run setup to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
36
+ { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run npx grada-run init to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
37
37
  ];
38
38
 
39
39
  const INSTALL_HINTS = {
@@ -233,7 +233,9 @@ function checkOidcImmutableClaims({ cwd }) {
233
233
  return { ok: true, skipped: 'trust value not parseable (non-literal claim — review by hand)' };
234
234
  }
235
235
  const entries = trust.kind === 'list' ? trust.entries : [trust.value];
236
- const covered = entries.some((entry) => entry === 'repo:*' || /@(\*|\d)/.test(entry));
236
+ // Anchored to owner/name: a bare `@digit` test would count suffix
237
+ // text (`:release@2`) as immutable coverage.
238
+ const covered = entries.some((entry) => entry === 'repo:*' || /^repo:[^/@]+@(?:\*|\d+)\/[^/@:]+@(?:\*|\d+)/.test(entry));
237
239
  if (covered) return { ok: true };
238
240
  return {
239
241
  ok: false,
@@ -367,7 +369,7 @@ async function runDoctorMain(input = {}) {
367
369
  const ranProject = projectResults.filter((result) => !result.skipped);
368
370
  const failedGrade = (result) => !result.ok && result.severity !== 'warn';
369
371
  const passedChecks = [...results, ...ranProject].filter((result) => result.ok).map((result) => result.id);
370
- const failedChecks = [...results, ...ranProject].filter((result) => !result.ok).map((result) => result.id);
372
+ const failedChecks = [...results, ...ranProject].filter(failedGrade).map((result) => result.id);
371
373
 
372
374
  // Enterprise downgrade: a missing `aws` binary with live SDK credentials
373
375
  // is a warning, not a failure — the SDK path provisions fine. Applies
@@ -523,6 +523,16 @@ async function runDomainAdd({ options, projectName, domain, zoneId, domainTfPath
523
523
  const patched = await patchCloudFrontFile(cloudfrontTfPath, domain, previousDomain, 'add', noExit);
524
524
  if (!patched.ok) return patched.failure;
525
525
  cloudfrontPatched = patched.changed;
526
+ } else if (previousDomain && previousDomain !== domain) {
527
+ // External-pending wires nothing new, but a --force replace must
528
+ // still release the previous ACTIVE aliases (BUG-100).
529
+ const read = await readCloudFrontDistribution(cloudfrontTfPath, 'add', noExit);
530
+ if (!read.ok) return read.failure;
531
+ const updated = unpatchCloudFrontDomain(read.content, previousDomain);
532
+ if (updated !== read.content) {
533
+ await atomicWriteFile(cloudfrontTfPath, updated);
534
+ cloudfrontPatched = true;
535
+ }
526
536
  }
527
537
 
528
538
  if (mode === 'route53') {
@@ -543,9 +553,9 @@ async function runDomainAdd({ options, projectName, domain, zoneId, domainTfPath
543
553
  return { ok: true, subcommand: 'add', mode, domain, file: 'terraform/domain.tf', cloudfrontPatched };
544
554
  }
545
555
 
546
- // Patches `cloudfront.tf`, replacing a previous managed domain on --force.
547
- // Returns `{ ok: true, changed }` or `{ ok: false, failure }`.
548
- async function patchCloudFrontFile(cloudfrontTfPath, domain, previousDomain, subcommand, noExit = false) {
556
+ // Reads `cloudfront.tf` for alias patching. Returns `{ ok: true, content }`
557
+ // or `{ ok: false, failure }` when the distribution block is missing.
558
+ async function readCloudFrontDistribution(cloudfrontTfPath, subcommand, noExit = false) {
549
559
  let content;
550
560
  try {
551
561
  content = await fs.readFile(cloudfrontTfPath, 'utf-8');
@@ -565,12 +575,20 @@ async function patchCloudFrontFile(cloudfrontTfPath, domain, previousDomain, sub
565
575
  }),
566
576
  };
567
577
  }
568
- let updated = content;
578
+ return { ok: true, content };
579
+ }
580
+
581
+ // Patches `cloudfront.tf`, replacing a previous managed domain on --force.
582
+ // Returns `{ ok: true, changed }` or `{ ok: false, failure }`.
583
+ async function patchCloudFrontFile(cloudfrontTfPath, domain, previousDomain, subcommand, noExit = false) {
584
+ const read = await readCloudFrontDistribution(cloudfrontTfPath, subcommand, noExit);
585
+ if (!read.ok) return read;
586
+ let updated = read.content;
569
587
  if (previousDomain && previousDomain !== domain) {
570
588
  updated = unpatchCloudFrontDomain(updated, previousDomain);
571
589
  }
572
590
  updated = patchCloudFrontDomain(updated, domain);
573
- const changed = updated !== content;
591
+ const changed = updated !== read.content;
574
592
  if (changed) await atomicWriteFile(cloudfrontTfPath, updated);
575
593
  return { ok: true, changed };
576
594
  }
@@ -663,12 +681,30 @@ async function runDomainStatus({ options, cwd, projectName, domainTfPath, cloudf
663
681
  }
664
682
  const target = outputValue(outputs, 'custom_domain_cname_target') || outputValue(outputs, 'cloudfront_url');
665
683
  if (typeof target === 'string' && target) {
666
- rows.push({ type: 'CNAME', name: domain, value: target.replace(/^https:\/\//, '') });
684
+ // CNAME is invalid at the zone apex: a two-label domain renders
685
+ // an ALIAS row instead. (Longer names keep the CNAME row —
686
+ // multi-part-TLD apexes cannot be told from subdomains without
687
+ // the zone name, so those get a caveat below.)
688
+ const isApex = typeof domain === 'string' && domain.split('.').length === 2;
689
+ rows.push({ type: isApex ? 'ALIAS' : 'CNAME', name: domain, value: target.replace(/^https:\/\//, ''), apex: isApex });
667
690
  }
668
- if (rows.length > 0) {
691
+ if (mode === 'route53') {
692
+ // Validation + alias records all live in terraform/domain.tf —
693
+ // there is nothing to add by hand.
694
+ if (rows.length > 0) {
695
+ console.log(` ${color.dim('DNS records are managed by Terraform in terraform/domain.tf — no manual action needed.')}`);
696
+ } else {
697
+ console.log(` ${color.dim('No DNS outputs yet — run npx grada-run apply first.')}`);
698
+ }
699
+ } else if (rows.length > 0) {
669
700
  console.log('');
670
701
  console.log(` ${color.dim('Add these records at your DNS provider:')}`);
671
702
  printDnsTable(rows);
703
+ if (rows.some((row) => row.apex)) {
704
+ console.log(` ${color.dim('At the zone apex CNAME is invalid — create an ALIAS/ANAME record (or your provider\u2019s CNAME flattening) pointing at the same target.')}`);
705
+ } else if (rows.some((row) => row.name === domain)) {
706
+ console.log(` ${color.dim('If this domain is your zone apex (e.g. under a multi-part TLD), CNAME is invalid there — use an ALIAS/ANAME record instead.')}`);
707
+ }
672
708
  } else {
673
709
  console.log(` ${color.dim('No DNS outputs yet — run npx grada-run apply first.')}`);
674
710
  }
@@ -740,12 +776,14 @@ async function runDomainRemove({ options, projectName, domainTfPath, cloudfrontT
740
776
  }
741
777
  }
742
778
  let remainingAliases = [];
779
+ let unpatched = false;
743
780
  try {
744
781
  if (domain && fsSync.existsSync(cloudfrontTfPath)) {
745
782
  const content = fsSync.readFileSync(cloudfrontTfPath, 'utf-8');
746
783
  const updated = unpatchCloudFrontDomain(content, domain);
747
784
  if (updated !== content) atomicWriteFileSync(cloudfrontTfPath, updated);
748
785
  remainingAliases = getCloudFrontAliases(updated).filter((entry) => entry !== domain);
786
+ unpatched = true;
749
787
  }
750
788
  } catch {
751
789
  // A best-effort unpatch never blocks domain.tf removal.
@@ -755,6 +793,16 @@ async function runDomainRemove({ options, projectName, domainTfPath, cloudfrontT
755
793
  if (remainingAliases.length > 0) {
756
794
  console.log(color.green(`\n✅ Custom domain ${domain || ''} removed.`.replace(' ', ' ')));
757
795
  console.log(color.yellow(`⚠ ${remainingAliases.length} alias(es) remain (${remainingAliases.join(', ')}): the ACM viewer_certificate is kept, but its validation resource is deleted with domain.tf — rewire the certificate by hand before applying.`));
796
+ } else if (!unpatched) {
797
+ // The aliases were never touched: claiming a restore would send
798
+ // the next apply into a stale-alias failure (BUG-99).
799
+ console.log(color.green(`\n✅ Custom domain ${domain || ''} removed.`.replace(' ', ' ')));
800
+ const why = !domain
801
+ ? 'terraform/domain.tf was unparseable, so CloudFront aliases were left untouched'
802
+ : !fsSync.existsSync(cloudfrontTfPath)
803
+ ? 'terraform/cloudfront.tf is missing, so aliases could not be verified'
804
+ : 'the CloudFront unpatch failed';
805
+ console.log(color.yellow(`⚠ CloudFront was NOT restored to the default certificate (${why}) — inspect terraform/cloudfront.tf before applying.`));
758
806
  } else {
759
807
  console.log(color.green(`\n✅ Custom domain ${domain || ''} removed; CloudFront restored to the default certificate.`.replace(' ', ' ')));
760
808
  }
@@ -8,6 +8,7 @@ import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../c
8
8
  import { failCommand, failAwsError, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { resolveRegion, resolveProjectName, resolveCwd, readFileSafe } from '../utils/resolvers.js';
11
+ import { atomicWriteFileSync } from '../utils/atomic-write.js';
11
12
 
12
13
  const __filename = fileURLToPath(import.meta.url);
13
14
  const __dirname = path.dirname(__filename);
@@ -52,7 +53,7 @@ export function scaffoldDriftWorkflow(cwd = process.cwd(), { region, roleArn, fo
52
53
  return { ok: false, reason: 'exists', path: targetPath };
53
54
  }
54
55
  fsSync.mkdirSync(path.dirname(targetPath), { recursive: true });
55
- fsSync.writeFileSync(targetPath, rendered, 'utf8');
56
+ atomicWriteFileSync(targetPath, rendered, 'utf8');
56
57
  return { ok: true, path: targetPath };
57
58
  }
58
59
 
@@ -208,9 +208,20 @@ async function ejectStackMain(input = {}) {
208
208
  const files = fs.readdirSync(dir);
209
209
  for (const file of files) {
210
210
  const fullPath = path.join(dir, file);
211
- if (isGradaBackupName(file)) {
211
+ // lstat, never stat: a symlinked dir pointing outside the
212
+ // tree must neither be descended into nor deleted
213
+ // through. Backup-named links remove the link only.
214
+ let st;
215
+ try {
216
+ st = fs.lstatSync(fullPath);
217
+ } catch {
218
+ continue;
219
+ }
220
+ if (st.isSymbolicLink()) {
221
+ if (isGradaBackupName(file)) fs.rmSync(fullPath, { force: true });
222
+ } else if (isGradaBackupName(file)) {
212
223
  fs.rmSync(fullPath, { recursive: true, force: true });
213
- } else if (fs.statSync(fullPath).isDirectory() && file !== 'node_modules' && file !== '.git') {
224
+ } else if (st.isDirectory() && file !== 'node_modules' && file !== '.git') {
214
225
  cleanBackups(fullPath); // Recursively check subdirectories like .github/workflows
215
226
  }
216
227
  }
@@ -6,7 +6,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
6
6
  import { hasAwsCli, AWS_CLI_INSTALL_URL, isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
7
7
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
8
8
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
9
- import { resolveRegion, resolveProjectName, resolveCluster, resolveService, resolveCwd, guardComputeTarget } from '../utils/resolvers.js';
9
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, resolveCwd, guardComputeTarget, withWorkspaceNamespace } from '../utils/resolvers.js';
10
10
  import {
11
11
  hasSessionManagerPlugin,
12
12
  resolveContainer,
@@ -35,7 +35,7 @@ export function parseExecArgs(argv = []) {
35
35
  const args = normalizeArgv(argv);
36
36
  if (args[0] === 'exec') args.shift();
37
37
  const { options, rest, unknown } = parseFlags(args, {
38
- string: ['cluster', 'service', 'container', { name: 'command', greedy: true }, 'region'],
38
+ string: ['cluster', 'service', 'container', { name: 'command', greedy: true }, 'region', 'workspace'],
39
39
  boolean: ['headless'],
40
40
  });
41
41
  const positionals = rest.filter((arg) => typeof arg === 'string' && !arg.startsWith('-'));
@@ -109,8 +109,13 @@ async function runExecMain(input = {}) {
109
109
  cwd = resolveCwd(options);
110
110
  region = resolveRegion(options, cwd);
111
111
  projectName = resolveProjectName(options, cwd);
112
- cluster = resolveCluster(options, cwd);
113
- service = resolveService(options, cwd);
112
+ // Workspace-namespaced resources (BUG-90): --workspace (or the
113
+ // local .terraform/environment) targets a preview stack like
114
+ // rollback and db do — exec into a preview must not land in
115
+ // production. Explicit flags/env keep winning.
116
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
117
+ cluster = resolveCluster(namespacedOptions, cwd);
118
+ service = resolveService(namespacedOptions, cwd);
114
119
  expectedContainer = resolveContainer(options, cwd);
115
120
  } catch {
116
121
  return failProjectNotInitialized({ event: 'exec_run', noExit });