@grada-run/grada 0.41.5 → 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.
package/bin/cli.js CHANGED
@@ -38,10 +38,10 @@ const HELP_TEXT = [
38
38
  ' deploy Alias of apply',
39
39
  ' destroy Tear down infrastructure (--yes, --allow-data-loss, --force-unlock, --force, --progress)',
40
40
  ' doctor Run pre-flight dependency checks (--deep)',
41
- ' logs [service] Stream CloudWatch logs (--tail, -f/--follow, --error, --since, --region)',
42
- ' status Service health dashboard (--region, --json, --watch)',
41
+ ' logs [service] Stream CloudWatch logs (--tail, -f/--follow, --error, --since, --region, --workspace)',
42
+ ' status Service health dashboard (--region, --json, --watch, --workspace)',
43
43
  ' rollback [rev] Roll back ECS service to a previous task revision (ECS only — Lambda uses image tags)',
44
- ' exec Open an interactive shell in a running container (--cluster, --service, --container, --command, --region)',
44
+ ' exec Open an interactive shell in a running container (--cluster, --service, --container, --command, --region, --workspace)',
45
45
  ' db connect Open a secure local tunnel to your database (--port, --show-credentials, --workspace, --region)',
46
46
  ' db enable-vector Enable the pgvector extension via a one-off ECS task (--task-def, --timeout)',
47
47
  ' db import Import a SQL dump into your database (--file, --from, --yes)',
@@ -95,14 +95,24 @@ const { positionalArgs, isHeadless, isDryRun, isPreconfigured, autoApprove, yes:
95
95
  const COMMAND_ALIASES = { deploy: 'apply' };
96
96
  const dispatchCommand = COMMAND_ALIASES[positionalArgs[0]] ?? positionalArgs[0];
97
97
 
98
- function parseRegionFlag(args) {
98
+ function parseStringFlag(args, name) {
99
+ const flag = `--${name}`;
100
+ const prefix = `--${name}=`;
99
101
  for (let i = 0; i < args.length; i++) {
100
- if (args[i] === '--region' && i + 1 < args.length) return args[i + 1];
101
- if (args[i].startsWith('--region=')) return args[i].slice('--region='.length);
102
+ if (args[i] === flag && i + 1 < args.length) return args[i + 1];
103
+ if (args[i].startsWith(prefix)) return args[i].slice(prefix.length);
102
104
  }
103
105
  return undefined;
104
106
  }
105
107
 
108
+ function parseRegionFlag(args) {
109
+ return parseStringFlag(args, 'region');
110
+ }
111
+
112
+ function parseWorkspaceFlag(args) {
113
+ return parseStringFlag(args, 'workspace');
114
+ }
115
+
106
116
  // Dispatch guard: every command promise ends here so an unexpected rejection
107
117
  // prints the error and exits non-zero instead of surfacing as an unhandled
108
118
  // rejection with a stack trace and an unpredictable exit code.
@@ -153,7 +163,7 @@ if (wantsVersion) {
153
163
  } else if (positionalArgs[0] === 'sync-ai') {
154
164
  runCommand(syncAi());
155
165
  } else if (positionalArgs[0] === 'diagnose' || positionalArgs[0] === 'wtf') {
156
- runCommand(runDiagnose(headlessOptions));
166
+ runCommand(runDiagnose({ ...headlessOptions, workspace: parseWorkspaceFlag(rawArgs) }));
157
167
  } else if (positionalArgs[0] === 'logs') {
158
168
  runCommand(runLogs({ ...parseLogsArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
159
169
  } else if (positionalArgs[0] === 'status') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grada-run/grada",
3
- "version": "0.41.5",
3
+ "version": "0.42.0",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -552,7 +552,9 @@ async function runAlertsMain(input = {}) {
552
552
  if (archiveAdded) console.log(color.dim(' Pinned the archive provider in terraform/backend.tf (forwarder packaging).'));
553
553
  console.log(color.dim(' Next steps:'));
554
554
  if (webhook) {
555
- console.log(color.dim(` 1. export TF_VAR_alerts_webhook_url='${webhook}' # ${kind} webhook; never commit it`));
555
+ // The URL is a Bearer [REDACTED] (CI logs are the leak vector): print a
556
+ // redacted placeholder — the operator already holds the real value.
557
+ console.log(color.dim(` 1. export TF_VAR_alerts_webhook_url='<your-${kind}-webhook-url>' # ${kind} webhook; never commit it`));
556
558
  console.log(color.dim(' 2. npx grada-run apply'));
557
559
  if (email) console.log(color.dim(' 3. Click the confirmation link in the email.'));
558
560
  console.log('');
@@ -303,7 +303,7 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
303
303
  telemetry: { projectName },
304
304
  errorCode: 'APPLY_NON_INTERACTIVE',
305
305
  });
306
- if (refused) return refused;
306
+ if (refused) return { proceed: false, previousAppliedTarget: appliedTarget, result: refused };
307
307
  log.warn(color.yellow(`⚠ This tree targets "${diskTarget}" but the last apply recorded "${from}". Applying would destroy the previous stack.`));
308
308
  await renderSwitchPlan({ runTerraform, tfDir, lifecycleOpts });
309
309
  const confirmed = await confirm({
@@ -271,11 +271,7 @@ async function runDbConnectMain(input = {}) {
271
271
  region,
272
272
  });
273
273
 
274
- // Telemetry carries only non-sensitive fields. Credentials never leave this process
275
- // except to the terminal above and the local SSM session below.
276
- await trackSuccess('db_connect_run', { projectName, db_engine: target.engine || 'unknown', db_kind: target.kind });
277
-
278
- await new Promise((resolve) => {
274
+ const { code } = await new Promise((resolve) => {
279
275
  const child = spawnImpl('aws', ssmArgs, { stdio: 'inherit' });
280
276
  child.on('error', (err) => {
281
277
  console.log(color.red(`\n✖ Failed to start AWS CLI: ${err?.message || err}`));
@@ -283,16 +279,27 @@ async function runDbConnectMain(input = {}) {
283
279
  resolve({ code: 1 });
284
280
  });
285
281
  child.on('close', (code) => resolve({ code: code ?? 0 }));
286
- }).then(async ({ code }) => {
287
- if (code === 0) {
288
- outro(color.green('Tunnel closed. 👋'));
289
- } else {
290
- console.log(color.yellow(`\nTunnel exited with code ${code}.`));
291
- console.log(color.dim('If the connection failed, ensure the Session Manager plugin is installed and your AWS session is fresh.'));
292
- outro(color.yellow('Db connect finished.'));
293
- }
294
282
  });
295
283
 
284
+ // Telemetry carries only non-sensitive fields. Credentials never leave this process
285
+ // except to the terminal above and the local SSM session below.
286
+ // Success is recorded only for a clean tunnel exit: a failed tunnel
287
+ // reports the tunnel's own exit code instead of ok:true (BUG-103).
288
+ if (code !== 0) {
289
+ const tunnelCode = Number.isInteger(code) && code > 0 ? Math.min(code, 255) : 1;
290
+ return failCommand({
291
+ message: `\n✖ Database tunnel exited with code ${code}.`,
292
+ hint: ' If the connection failed, ensure the Session Manager plugin is installed and your AWS session is fresh.\n',
293
+ event: 'db_connect_run',
294
+ telemetry: { projectName, error_code: 'TUNNEL_EXIT_NONZERO', exit_code: tunnelCode },
295
+ reason: 'tunnel-exit-nonzero',
296
+ resultExtra: { cluster, service, dbIdentifier, localPort, region },
297
+ exitCode: tunnelCode,
298
+ });
299
+ }
300
+ await trackSuccess('db_connect_run', { projectName, db_engine: target.engine || 'unknown', db_kind: target.kind });
301
+ outro(color.green('Tunnel closed. 👋'));
302
+
296
303
  return { ok: true, cluster, service, dbIdentifier, taskArn: jumpHost.taskArn, localPort, region };
297
304
  } catch (error) {
298
305
  // Only non-sensitive metadata is telemetered here. The password, username, and
@@ -120,7 +120,7 @@ function stripPreviousGateBlock(content) {
120
120
  // (source checkouts report 'unknown').
121
121
  export function buildRunnerInvocation(cliVersion) {
122
122
  const ver = typeof cliVersion === 'string' ? cliVersion.trim() : '';
123
- if (ver === '' || ver === 'unknown') return 'npx grada-run';
123
+ if (ver === '' || ver === 'unknown') return 'npx --yes grada-run';
124
124
  return `npx --yes @grada-run/grada@${ver}`;
125
125
  }
126
126
 
@@ -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
  }
@@ -423,7 +426,49 @@ async function destroyStackMain(input = {}) {
423
426
  reason: 'db-snapshot-failed',
424
427
  });
425
428
  }
426
- s.stop(`Database snapshot ${snapshotId} started.`);
429
+ // Wait for the snapshot to reach `available` before touching the
430
+ // database: deleting while it is still `creating` races snapshot
431
+ // completion on large DBs (BUG-98). A failed snapshot or a timeout
432
+ // refuses the destroy — re-run with --allow-data-loss to skip.
433
+ s.start(truncateSpinnerText(`Waiting for snapshot ${snapshotId} to complete...`));
434
+ const snapshotReady = await pollUntil({
435
+ intervalMs: pollIntervalMs,
436
+ timeoutMs: snapshotTimeoutMs,
437
+ ...pollOverrides,
438
+ onTick: async () => {
439
+ let status = null;
440
+ try {
441
+ if (dbTarget.kind === 'cluster') {
442
+ const resp = await rdsClient.send(new DescribeDBClusterSnapshotsCommand({ DBClusterSnapshotIdentifier: snapshotId }));
443
+ status = resp.DBClusterSnapshots?.[0]?.Status ?? null;
444
+ } else {
445
+ const resp = await rdsClient.send(new DescribeDBSnapshotsCommand({ DBSnapshotIdentifier: snapshotId }));
446
+ status = resp.DBSnapshots?.[0]?.Status ?? null;
447
+ }
448
+ } catch (error) {
449
+ return { done: true, value: { failed: true, reason: `snapshot describe failed (${error.message})` } };
450
+ }
451
+ if (status === 'available') return { done: true, value: { failed: false } };
452
+ if (status === 'failed' || status === 'deleted') {
453
+ return { done: true, value: { failed: true, reason: `snapshot ${status}` } };
454
+ }
455
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId} to complete... (${status || 'pending'})`));
456
+ return { done: false };
457
+ },
458
+ });
459
+ if (snapshotReady.timedOut || snapshotReady.value?.failed) {
460
+ s.stop(color.red('❌ Pre-destroy snapshot did not complete.'));
461
+ const errorCode = snapshotReady.timedOut ? 'DB_SNAPSHOT_TIMEOUT' : 'DB_SNAPSHOT_FAILED';
462
+ return failCommand({
463
+ 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.`,
464
+ useErrorStream: true,
465
+ event: 'infrastructure_destroyed',
466
+ telemetry: { projectName: projectNameForTelemetry, error_code: errorCode },
467
+ errorCode,
468
+ reason: snapshotReady.timedOut ? 'db-snapshot-timeout' : 'db-snapshot-failed',
469
+ });
470
+ }
471
+ s.stop(`Database snapshot ${snapshotId} ready.`);
427
472
  console.log(color.green(`📸 Pre-destroy snapshot: ${snapshotId}`));
428
473
  trackEvent('db_destroy_checkpoint', { projectName: projectNameForTelemetry, db_kind: dbTarget.kind });
429
474
  await flushTelemetry();
@@ -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,8 +8,9 @@ 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;
15
16
 
@@ -106,9 +107,10 @@ export async function runLambdaDiagnose(input = {}) {
106
107
  const projectName = options.projectName;
107
108
  const region = options.region;
108
109
  const logGroup = options.logGroup;
110
+ const namespacedProject = resolveNamespacedProject(projectName, options, options.cwd);
109
111
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
110
112
  ? options.functionName.trim()
111
- : `${projectName}${readResourceSuffix(options.cwd)}-fn`;
113
+ : `${namespacedProject}${readResourceSuffix(options.cwd)}-fn`;
112
114
  const runSync = options.spawnSyncImpl || spawnSync;
113
115
 
114
116
  intro(color.bgCyan(color.black(' grada diagnose 🩺 ')));
@@ -180,12 +182,11 @@ export async function runLambdaDiagnose(input = {}) {
180
182
  let logFetchFailed = false;
181
183
  let fetchError = '';
182
184
  try {
183
- const logsResp = await logsClient.send(new FilterLogEventsCommand({
185
+ const { events } = await fetchLatestEvents(logsClient, {
184
186
  logGroupName: logGroup,
185
187
  startTime: Date.now() - 60 * 60 * 1000,
186
- limit: LOG_FETCH_LIMIT,
187
- }));
188
- logs = (logsResp.events || []).slice(-LOG_FETCH_LIMIT).map((e) => e.message);
188
+ }, { tail: LOG_FETCH_LIMIT });
189
+ logs = events.map((e) => e.message);
189
190
  } catch (logsError) {
190
191
  if (handleAuthErrorBranch(logsError, s, options)) return;
191
192
  if (isLogGroupNotFoundError(logsError)) {
@@ -257,8 +258,13 @@ async function runDiagnoseMain(input = {}) {
257
258
  cwd = resolveCwd(options);
258
259
  projectName = resolveProjectName(options, cwd);
259
260
  region = resolveRegion(options, cwd);
260
- cluster = resolveCluster(options, cwd);
261
- logGroup = resolveLogGroup(options, cwd);
261
+ // Workspace-namespaced resources (BUG-90): --workspace (or the
262
+ // local .terraform/environment) targets a preview stack like
263
+ // rollback and db do. Explicit flags/env keep winning; telemetry
264
+ // keeps the raw project name.
265
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
266
+ cluster = resolveCluster(namespacedOptions, cwd);
267
+ logGroup = resolveLogGroup(namespacedOptions, cwd);
262
268
  } catch {
263
269
  return failProjectNotInitialized({ event: 'diagnose_run', noExit });
264
270
  }
@@ -410,8 +416,8 @@ async function runDiagnoseMain(input = {}) {
410
416
  : '';
411
417
 
412
418
  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);
419
+ const { events } = await fetchLatestEvents(logsClient, input, { tail: LOG_FETCH_LIMIT });
420
+ return events.map((e) => e.message);
415
421
  };
416
422
 
417
423
  let logs = [];
@@ -367,7 +367,7 @@ async function runDoctorMain(input = {}) {
367
367
  const ranProject = projectResults.filter((result) => !result.skipped);
368
368
  const failedGrade = (result) => !result.ok && result.severity !== 'warn';
369
369
  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);
370
+ const failedChecks = [...results, ...ranProject].filter(failedGrade).map((result) => result.id);
371
371
 
372
372
  // Enterprise downgrade: a missing `aws` binary with live SDK credentials
373
373
  // 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
  }
@@ -740,12 +758,14 @@ async function runDomainRemove({ options, projectName, domainTfPath, cloudfrontT
740
758
  }
741
759
  }
742
760
  let remainingAliases = [];
761
+ let unpatched = false;
743
762
  try {
744
763
  if (domain && fsSync.existsSync(cloudfrontTfPath)) {
745
764
  const content = fsSync.readFileSync(cloudfrontTfPath, 'utf-8');
746
765
  const updated = unpatchCloudFrontDomain(content, domain);
747
766
  if (updated !== content) atomicWriteFileSync(cloudfrontTfPath, updated);
748
767
  remainingAliases = getCloudFrontAliases(updated).filter((entry) => entry !== domain);
768
+ unpatched = true;
749
769
  }
750
770
  } catch {
751
771
  // A best-effort unpatch never blocks domain.tf removal.
@@ -755,6 +775,16 @@ async function runDomainRemove({ options, projectName, domainTfPath, cloudfrontT
755
775
  if (remainingAliases.length > 0) {
756
776
  console.log(color.green(`\n✅ Custom domain ${domain || ''} removed.`.replace(' ', ' ')));
757
777
  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.`));
778
+ } else if (!unpatched) {
779
+ // The aliases were never touched: claiming a restore would send
780
+ // the next apply into a stale-alias failure (BUG-99).
781
+ console.log(color.green(`\n✅ Custom domain ${domain || ''} removed.`.replace(' ', ' ')));
782
+ const why = !domain
783
+ ? 'terraform/domain.tf was unparseable, so CloudFront aliases were left untouched'
784
+ : !fsSync.existsSync(cloudfrontTfPath)
785
+ ? 'terraform/cloudfront.tf is missing, so aliases could not be verified'
786
+ : 'the CloudFront unpatch failed';
787
+ console.log(color.yellow(`⚠ CloudFront was NOT restored to the default certificate (${why}) — inspect terraform/cloudfront.tf before applying.`));
758
788
  } else {
759
789
  console.log(color.green(`\n✅ Custom domain ${domain || ''} removed; CloudFront restored to the default certificate.`.replace(' ', ' ')));
760
790
  }
@@ -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 });
@@ -465,8 +465,12 @@ async function removeUntaggedImages({ ecrClient }, images) {
465
465
  }
466
466
  for (const [repositoryName, imageIds] of byRepo) {
467
467
  for (const batch of chunkArray(imageIds, ECR_BATCH_DELETE_LIMIT)) {
468
- await ecrClient.send(new BatchDeleteImageCommand({ repositoryName, imageIds: batch }));
469
- deletedImages += batch.length;
468
+ const resp = await ecrClient.send(new BatchDeleteImageCommand({ repositoryName, imageIds: batch }));
469
+ const failed = resp?.failures?.length ?? 0;
470
+ if (failed > 0) {
471
+ console.log(color.yellow(`⚠ ${failed} of ${batch.length} image(s) in ${repositoryName} failed to delete (${resp.failures[0]?.failureCode || 'unknown'}).`));
472
+ }
473
+ deletedImages += batch.length - failed;
470
474
  }
471
475
  }
472
476
  return deletedImages;
@@ -492,8 +496,22 @@ async function releaseUnattachedEips({ ec2Client }, eips) {
492
496
 
493
497
  export async function deleteDiscoveredResources(clients, discovered) {
494
498
  const summary = {};
499
+ const errors = [];
495
500
  for (const target of GC_TARGETS.filter((entry) => entry.scope === 'standard' && typeof entry.remove === 'function')) {
496
- summary[target.summary] = await target.remove(clients, discovered[target.field] || []);
501
+ try {
502
+ summary[target.summary] = await target.remove(clients, discovered[target.field] || []);
503
+ } catch (error) {
504
+ // One target's API failure must not strand the rest (BUG-105):
505
+ // record it, zero its count, and keep deleting.
506
+ errors.push({ target: target.summary, error });
507
+ summary[target.summary] = 0;
508
+ }
509
+ }
510
+ if (errors.length > 0) {
511
+ const failure = new Error(`gc deletion partially failed: ${errors.map(({ target, error }) => `${target} (${error?.message || error})`).join('; ')}`);
512
+ failure.partialSummary = summary;
513
+ failure.failures = errors;
514
+ throw failure;
497
515
  }
498
516
  return summary;
499
517
  }
@@ -718,7 +736,21 @@ async function runGcMain(input = {}) {
718
736
 
719
737
  const del = spinner();
720
738
  del.start('Deleting orphaned resources...');
721
- const summary = await deleteDiscoveredResources({ ecrClient, logsClient, ec2Client }, discovered);
739
+ let summary;
740
+ try {
741
+ summary = await deleteDiscoveredResources({ ecrClient, logsClient, ec2Client }, discovered);
742
+ } catch (error) {
743
+ del.stop(color.red('❌ Deletion partially failed.'));
744
+ const partial = (error && typeof error === 'object' && error.partialSummary) || {};
745
+ return failCommand({
746
+ message: `\n✖ ${error?.message || error}\n`,
747
+ hint: ' Completed targets stay deleted; fix the cause and re-run to finish the rest.\n',
748
+ event: 'gc_run',
749
+ telemetry: { projectName, error_code: 'GC_PARTIAL_DELETE_FAILED', ...partial },
750
+ reason: 'gc-partial-delete-failed',
751
+ resultExtra: { ...partial },
752
+ });
753
+ }
722
754
  del.stop('Deletion complete.');
723
755
 
724
756
  outro(color.green(`Deleted ${summary.deletedImages} image(s), ${summary.deletedLogGroups} log group(s), released ${summary.releasedEips} Elastic IP(s). ✅`));