@grada-run/grada 0.41.4 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.4",
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"
@@ -478,6 +478,21 @@ resource "aws_subnet" "db_isolated" {
478
478
  }
479
479
  }`;
480
480
 
481
+ // Merges names into the `managed_env_names` collision-guard list in
482
+ // main.tf content. Sorted + deduplicated for deterministic output;
483
+ // idempotent reruns return the content identical. Returns content
484
+ // unchanged when the block is absent (pre-list trees fail open — the
485
+ // CLI preflight still guards local applies).
486
+ export function upsertManagedEnvNames(tfContent, names = []) {
487
+ const content = String(tfContent ?? '');
488
+ const match = /managed_env_names\s*=\s*\[([^\]]*)\]/.exec(content);
489
+ if (!match) return content;
490
+ const existing = [...match[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]);
491
+ const merged = [...new Set([...existing, ...names])].sort();
492
+ if (merged.length === existing.length && merged.every((name, i) => name === existing[i])) return content;
493
+ return content.replace(match[0], `managed_env_names = [${merged.map((name) => JSON.stringify(name)).join(', ')}]`);
494
+ }
495
+
481
496
  // Idempotently appends the isolated-subnet block to network.tf content.
482
497
  // Returns the content unchanged when the block already exists. Uses the
483
498
  // line-anchored lookup so a `#` comment quoting the header never
@@ -1552,6 +1567,8 @@ async function scaffoldDatabaseInner(engine, projectDir, refs) {
1552
1567
  const withVpc = ensureLambdaVpcConfig(updated);
1553
1568
  vpcInjected = withVpc !== updated;
1554
1569
  updated = withVpc;
1570
+ } else {
1571
+ updated = upsertManagedEnvNames(updated, [...env.map((entry) => entry.name), ...secrets.map((entry) => entry.name)]);
1555
1572
  }
1556
1573
  const envInjected = updated !== mainTfContent;
1557
1574
  if (envInjected) await atomicWriteFile(mainTfPath, normalizeBlankLines(updated));
@@ -1735,10 +1752,11 @@ async function scaffoldAddonInner(capability, resolvedOpts, { cwd, region } = {}
1735
1752
  // ElastiCache lives inside the VPC: attach the function on first Redis
1736
1753
  // provisioning when the project was generated without a database.
1737
1754
  const withVpc = capability === 'db:redis' ? ensureLambdaVpcConfig(updated) : updated;
1738
- const envInjected = withVpc !== mainTfContent;
1755
+ const withManaged = isLambda ? withVpc : upsertManagedEnvNames(withVpc, envVars.map((entry) => entry.name));
1756
+ const envInjected = withManaged !== mainTfContent;
1739
1757
  const vpcInjected = withVpc !== updated;
1740
1758
  if (envInjected) {
1741
- await atomicWriteFile(mainTfPath, normalizeBlankLines(withVpc));
1759
+ await atomicWriteFile(mainTfPath, normalizeBlankLines(withManaged));
1742
1760
  }
1743
1761
 
1744
1762
  let workerEnvInjected = false;
@@ -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('');
@@ -12,7 +12,7 @@ import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterrup
12
12
  import { classifyTerraformError, countRecreateCollisions, getRunbook, ERROR_CODES } from '../utils/terraform-errors.js';
13
13
  import { readInitManifest, recordAppliedTarget } from '../utils/backup.js';
14
14
  import { requireManagedTree, parseStateBucketBackend, upsertAutoTfvar } from '../utils/terraform-metadata.js';
15
- import { readTerraformComputeTarget, resolveRegion } from '../utils/resolvers.js';
15
+ import { readTerraformComputeTarget, resolveRegion, readRenderedContainerEnvNames } from '../utils/resolvers.js';
16
16
  import { requireAwakeEnvironment, resolveSleepTarget, guardSleepingEnv } from '../utils/sleep-state.js';
17
17
  import { promptStateBucketRecovery, recreateStateBucket } from '../utils/recovery.js';
18
18
  import { resolveProjectName, readResourceSuffix } from '../utils/resolvers.js';
@@ -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({
@@ -339,6 +339,34 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
339
339
 
340
340
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
341
341
  // invocation path, including direct imports that bypass bin/cli.js and MCP.
342
+ // Intersects secret_keys.json with the RENDERED container env names so
343
+ // stale, confirmed-through, or hand-edited keys files fail here instead
344
+ // of late on the raw ECS 400. Returns null when clean or inapplicable
345
+ // (non-ECS target, unreadable inputs — those surface through their own
346
+ // errors), else { kind, keys, detail? } for the failCommand call site.
347
+ function preflightSecretEnvCollisions({ targetDir }) {
348
+ if (readTerraformComputeTarget(targetDir) !== 'ecs') return null;
349
+ let keysRaw;
350
+ try {
351
+ keysRaw = fs.readFileSync(path.join(targetDir, 'terraform', 'secret_keys.json'), 'utf-8');
352
+ } catch {
353
+ return null;
354
+ }
355
+ let keys;
356
+ try {
357
+ keys = JSON.parse(keysRaw);
358
+ } catch {
359
+ return { kind: 'malformed', keys: [], detail: 'is not valid JSON.' };
360
+ }
361
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== 'string' || key === '')) {
362
+ return { kind: 'malformed', keys: [], detail: 'must be a JSON array of non-empty key names.' };
363
+ }
364
+ const rendered = readRenderedContainerEnvNames(targetDir);
365
+ const collisions = [...new Set(keys.filter((key) => rendered.includes(key)))];
366
+ if (collisions.length === 0) return null;
367
+ return { kind: 'collision', keys: collisions };
368
+ }
369
+
342
370
  export async function applyStack(input = {}) {
343
371
  setActiveCommandName('apply');
344
372
  try {
@@ -426,6 +454,34 @@ async function applyStackMain(input = {}) {
426
454
  if (!sleepGuard.proceed) return sleepGuard.result;
427
455
  }
428
456
 
457
+ // 1d. Preflight secret/env collisions (BUG-81): stale,
458
+ // confirmed-through, or hand-edited keys files would die late on
459
+ // the raw ECS 400 — fail here naming the key and the fix. ECS-only
460
+ // (Lambda maps no secrets into env), unconditional (a collision is
461
+ // deterministic breakage no flag can fix), and fail-open on
462
+ // unreadable inputs. Runs on dry runs too: previews should
463
+ // surface deterministic breakage, not hide it.
464
+ const secretPreflight = preflightSecretEnvCollisions({ targetDir });
465
+ if (secretPreflight !== null) {
466
+ const shown = secretPreflight.keys.length <= 8
467
+ ? secretPreflight.keys.join(', ')
468
+ : `${secretPreflight.keys.slice(0, 8).join(', ')} (+${secretPreflight.keys.length - 8} more)`;
469
+ const isCollision = secretPreflight.kind === 'collision';
470
+ return failCommand({
471
+ noExit: isProgrammaticCall(options),
472
+ message: isCollision
473
+ ? `\n✖ ${secretPreflight.keys.length} secret ${secretPreflight.keys.length === 1 ? 'key' : 'keys'} in terraform/secret_keys.json ${secretPreflight.keys.length === 1 ? 'collides' : 'collide'} with container environment names: ${shown}.\n`
474
+ : `\n✖ terraform/secret_keys.json ${secretPreflight.detail}\n`,
475
+ hint: isCollision
476
+ ? ' ECS rejects task definitions where a secret shares a name with an environment variable. Remove the key(s) from .env and re-push (colliding keys are skipped automatically), then re-run apply.\n'
477
+ : ' Re-push your secrets to regenerate it: npx grada-run secrets push .env\n',
478
+ event: 'infrastructure_applied',
479
+ telemetry: { projectName: path.basename(targetDir), collision_count: secretPreflight.keys.length },
480
+ errorCode: 'SECRETS_ENV_COLLISION',
481
+ reason: isCollision ? 'secrets-env-collision' : 'malformed-keys-file',
482
+ });
483
+ }
484
+
429
485
  // 2. Read the actual AWS configuration from disk (CPU, Memory, Region, Database)
430
486
  const detectedConfig = parseTerraformConfig(tfDir);
431
487
  detectedConfig.projectName = path.basename(process.cwd());
@@ -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 = [];
@@ -33,6 +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
37
  ];
37
38
 
38
39
  const INSTALL_HINTS = {
@@ -220,6 +221,26 @@ function checkOidcTrustScope({ cwd }) {
220
221
  };
221
222
  }
222
223
 
224
+ // Project check: a trust covering classic subject claims only rejects
225
+ // every repo created after 2026-07-15 (immutable `repo:<owner>@<id>/`
226
+ // `<name>@<id>:...` subjects). Warning-grade like the scope check: the
227
+ // open trust matches all formats, and any `@*`/`@<id>` entry counts as
228
+ // immutable coverage.
229
+ function checkOidcImmutableClaims({ cwd }) {
230
+ const trust = readTerraformOidcTrust(cwd);
231
+ if (trust === null) return { ok: true, skipped: 'no oidc.tf trust found' };
232
+ if (trust.kind === 'unparseable') {
233
+ return { ok: true, skipped: 'trust value not parseable (non-literal claim — review by hand)' };
234
+ }
235
+ const entries = trust.kind === 'list' ? trust.entries : [trust.value];
236
+ const covered = entries.some((entry) => entry === 'repo:*' || /@(\*|\d)/.test(entry));
237
+ if (covered) return { ok: true };
238
+ return {
239
+ ok: false,
240
+ detailLines: ['CI trust covers classic subject claims only — workflows in repos created after 2026-07-15 use immutable claims this trust rejects, failing every deploy with an OIDC assume-role error.'],
241
+ };
242
+ }
243
+
223
244
  // Project check: a leftover interrupted/running marker means the last
224
245
  // Terraform run never settled. Warning-grade (apply proceeds with its own
225
246
  // warning): surfaces yellow without flipping the verdict red.
@@ -346,7 +367,7 @@ async function runDoctorMain(input = {}) {
346
367
  const ranProject = projectResults.filter((result) => !result.skipped);
347
368
  const failedGrade = (result) => !result.ok && result.severity !== 'warn';
348
369
  const passedChecks = [...results, ...ranProject].filter((result) => result.ok).map((result) => result.id);
349
- const failedChecks = [...results, ...ranProject].filter((result) => !result.ok).map((result) => result.id);
370
+ const failedChecks = [...results, ...ranProject].filter(failedGrade).map((result) => result.id);
350
371
 
351
372
  // Enterprise downgrade: a missing `aws` binary with live SDK credentials
352
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 });