grada-run 0.49.11 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.49.11",
3
+ "version": "0.50.1",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -52,6 +52,30 @@ const TARGET_ANCHORS = {
52
52
  static: { resource: 'resource "aws_cloudfront_distribution" "site"', errorCode: 'DISTRIBUTION_NOT_FOUND', reason: 'distribution-not-found' },
53
53
  };
54
54
 
55
+ // Addon alarm anchors. Detection reads the addon FILE CONTENT (not just
56
+ // its presence) so a hand-removed resource can't produce a dangling
57
+ // alarm reference. Several anchors may share one id (either engine
58
+ // file lights up 'db:instance').
59
+ const ADDON_ALARM_ANCHORS = [
60
+ { id: 'queue:sqs', file: 'sqs.tf', resource: 'resource "aws_sqs_queue" "dlq"' },
61
+ { id: 'cron', file: 'cron.tf', resource: 'resource "aws_scheduler_schedule" "cron"' },
62
+ { id: 'db:instance', file: 'database.tf', resource: 'resource "aws_db_instance" "postgres"' },
63
+ { id: 'db:instance', file: 'database-mysql.tf', resource: 'resource "aws_db_instance" "postgres"' },
64
+ { id: 'db:aurora', file: 'database-aurora-postgresql.tf', resource: 'resource "aws_rds_cluster" "postgres"' },
65
+ { id: 'db:redis', file: 'redis.tf', resource: 'resource "aws_elasticache_replication_group" "redis"' },
66
+ { id: 'email:ses', file: 'ses.tf', resource: 'resource "aws_ses_domain_identity" "ses"' },
67
+ ];
68
+
69
+ export function detectAlertAddonFeatures(terraformDir) {
70
+ const features = {};
71
+ for (const anchor of ADDON_ALARM_ANCHORS) {
72
+ if (features[anchor.id]) continue;
73
+ const content = readFileSafe(path.join(terraformDir, anchor.file));
74
+ features[anchor.id] = Boolean(content && content.includes(anchor.resource));
75
+ }
76
+ return features;
77
+ }
78
+
55
79
  export function parseAlertsArgs(argv = []) {
56
80
  const args = normalizeArgv(argv);
57
81
  if (args[0] === 'alerts') args.shift();
@@ -183,7 +207,228 @@ exports.handler = async (event) => {
183
207
  // so every static alert resource is pinned to the aws.us_east_1 alias
184
208
  // (runAlerts ensures main.tf declares it). IAM and archive_file are
185
209
  // region-independent and stay unpinned.
186
- export function buildAlertsTf({ projectName, target = 'ecs', email, webhook, threshold }) {
210
+ // Primary notify-alarm spec per compute target. Addon alarms (DLQ
211
+ // depth, cron health, ...) append as further entries consumed the same
212
+ // way; each spec carries its own baked threshold while --threshold
213
+ // keeps driving the primary alarm only.
214
+ const PRIMARY_NOTIFY_ALARMS = {
215
+ lambda: {
216
+ tfName: 'notify_errors',
217
+ alarmName: 'errors-notify',
218
+ metricName: 'Errors',
219
+ namespace: 'AWS/Lambda',
220
+ statistic: 'Sum',
221
+ describe: ({ projectName, limit, evaluationPeriods }) =>
222
+ `${projectName} reports more than ${limit} Lambda errors in ${evaluationPeriods} minutes.`,
223
+ dimensions: { FunctionName: 'aws_lambda_function.app.function_name' },
224
+ },
225
+ static: {
226
+ tfName: 'notify_5xx_rate',
227
+ alarmName: '5xx-rate-notify',
228
+ metricName: '5xxErrorRate',
229
+ namespace: 'AWS/CloudFront',
230
+ statistic: 'Average',
231
+ describe: ({ projectName, limit, evaluationPeriods }) =>
232
+ `${projectName} serves more than a ${limit}% 5xx error rate over ${evaluationPeriods} minutes.`,
233
+ dimensions: { DistributionId: 'aws_cloudfront_distribution.site.id' },
234
+ },
235
+ ecs: {
236
+ tfName: 'notify_5xx',
237
+ alarmName: '5xx-notify',
238
+ metricName: 'HTTPCode_Target_5XX_Count',
239
+ namespace: 'AWS/ApplicationELB',
240
+ statistic: 'Sum',
241
+ describe: ({ limit, evaluationPeriods }) =>
242
+ `the ALB serves more than ${limit} 5XX errors in ${evaluationPeriods} minutes.`,
243
+ dimensions: { LoadBalancer: 'aws_lb.main.arn_suffix' },
244
+ },
245
+ };
246
+
247
+ // Renders one notify alarm block. Shape is shared by primary and addon
248
+ // alarms so every alarm reads (and diffs) the same way.
249
+ function renderNotifyAlarm(spec, { namePrefix, aliasLine, limit, evaluationPeriods, period, projectName }) {
250
+ const dimensions = spec.dimensions
251
+ ? `\n dimensions = {\n${Object.entries(spec.dimensions).map(([key, value]) => ` ${key} = ${value}`).join('\n')}\n }\n`
252
+ : '';
253
+ return `resource "aws_cloudwatch_metric_alarm" "${spec.tfName}" {
254
+ ${aliasLine} alarm_name = "${namePrefix}-${spec.alarmName}"
255
+ comparison_operator = "${spec.comparison || 'GreaterThanThreshold'}"
256
+ evaluation_periods = "${evaluationPeriods}"
257
+ metric_name = "${spec.metricName}"
258
+ namespace = "${spec.namespace}"
259
+ period = "${period}"
260
+ statistic = "${spec.statistic}"
261
+ threshold = "${limit}"
262
+ alarm_description = "Notifies ${namePrefix}-alerts when ${spec.describe({ projectName, limit, evaluationPeriods })}"
263
+
264
+ alarm_actions = [aws_sns_topic.alerts.arn]
265
+ ${dimensions}}` + '\n';
266
+ }
267
+
268
+ // Addon notify alarms, rendered only when the tree carries the addon
269
+ // (see detectAlertAddonFeatures). Thresholds are baked per alarm;
270
+ // --threshold keeps driving the primary alarm only.
271
+ const ADDON_NOTIFY_ALARMS = [
272
+ {
273
+ id: 'queue:sqs',
274
+ tfName: 'notify_dlq_depth',
275
+ alarmName: 'dlq-depth-notify',
276
+ metricName: 'ApproximateNumberOfMessagesVisible',
277
+ namespace: 'AWS/SQS',
278
+ statistic: 'Maximum',
279
+ threshold: 1,
280
+ evaluationPeriods: 1,
281
+ period: 300,
282
+ describe: () => 'the dead-letter queue holds failed messages (redrive or inspect them).',
283
+ dimensions: { QueueName: 'aws_sqs_queue.dlq.name' },
284
+ },
285
+ {
286
+ id: 'cron',
287
+ tfName: 'notify_cron_target_errors',
288
+ alarmName: 'cron-target-errors-notify',
289
+ metricName: 'TargetErrorCount',
290
+ namespace: 'AWS/Scheduler',
291
+ statistic: 'Sum',
292
+ threshold: 1,
293
+ evaluationPeriods: 1,
294
+ period: 300,
295
+ describe: () => 'a scheduled run fails to invoke its target.',
296
+ dimensions: { ScheduleGroup: 'aws_scheduler_schedule_group.crons.name' },
297
+ },
298
+ {
299
+ id: 'cron',
300
+ tfName: 'notify_cron_dropped',
301
+ alarmName: 'cron-dropped-notify',
302
+ metricName: 'InvocationDroppedCount',
303
+ namespace: 'AWS/Scheduler',
304
+ statistic: 'Sum',
305
+ threshold: 1,
306
+ evaluationPeriods: 1,
307
+ period: 300,
308
+ describe: () => 'a scheduled run is dropped after retry exhaustion.',
309
+ dimensions: { ScheduleGroup: 'aws_scheduler_schedule_group.crons.name' },
310
+ },
311
+ {
312
+ id: 'db:instance',
313
+ tfName: 'notify_rds_storage_low',
314
+ alarmName: 'rds-storage-low-notify',
315
+ metricName: 'FreeStorageSpace',
316
+ namespace: 'AWS/RDS',
317
+ statistic: 'Minimum',
318
+ comparison: 'LessThanThreshold',
319
+ threshold: 2147483648,
320
+ evaluationPeriods: 1,
321
+ period: 300,
322
+ describe: () => 'the database drops below 2 GB of free storage.',
323
+ dimensions: { DBInstanceIdentifier: 'aws_db_instance.postgres.identifier' },
324
+ },
325
+ {
326
+ id: 'db:instance',
327
+ tfName: 'notify_rds_cpu_high',
328
+ alarmName: 'rds-cpu-high-notify',
329
+ metricName: 'CPUUtilization',
330
+ namespace: 'AWS/RDS',
331
+ statistic: 'Average',
332
+ threshold: 80,
333
+ evaluationPeriods: 3,
334
+ period: 300,
335
+ describe: () => 'database CPU stays above 80% for 15 minutes.',
336
+ dimensions: { DBInstanceIdentifier: 'aws_db_instance.postgres.identifier' },
337
+ },
338
+ {
339
+ id: 'db:instance',
340
+ tfName: 'notify_rds_connections_high',
341
+ alarmName: 'rds-connections-high-notify',
342
+ metricName: 'DatabaseConnections',
343
+ namespace: 'AWS/RDS',
344
+ statistic: 'Maximum',
345
+ threshold: 80,
346
+ evaluationPeriods: 2,
347
+ period: 300,
348
+ describe: () => 'database connections exceed 80 (micro exhausts near 112).',
349
+ dimensions: { DBInstanceIdentifier: 'aws_db_instance.postgres.identifier' },
350
+ },
351
+ {
352
+ id: 'db:aurora',
353
+ tfName: 'notify_rds_cpu_high',
354
+ alarmName: 'rds-cpu-high-notify',
355
+ metricName: 'CPUUtilization',
356
+ namespace: 'AWS/RDS',
357
+ statistic: 'Average',
358
+ threshold: 80,
359
+ evaluationPeriods: 3,
360
+ period: 300,
361
+ describe: () => 'database CPU stays above 80% for 15 minutes.',
362
+ dimensions: { DBClusterIdentifier: 'aws_rds_cluster.postgres.id' },
363
+ },
364
+ {
365
+ id: 'db:aurora',
366
+ tfName: 'notify_rds_connections_high',
367
+ alarmName: 'rds-connections-high-notify',
368
+ metricName: 'DatabaseConnections',
369
+ namespace: 'AWS/RDS',
370
+ statistic: 'Maximum',
371
+ threshold: 80,
372
+ evaluationPeriods: 2,
373
+ period: 300,
374
+ describe: () => 'database connections exceed 80.',
375
+ dimensions: { DBClusterIdentifier: 'aws_rds_cluster.postgres.id' },
376
+ },
377
+ {
378
+ id: 'db:redis',
379
+ tfName: 'notify_valkey_evictions',
380
+ alarmName: 'valkey-evictions-notify',
381
+ metricName: 'Evictions',
382
+ namespace: 'AWS/ElastiCache',
383
+ statistic: 'Sum',
384
+ threshold: 1,
385
+ evaluationPeriods: 1,
386
+ period: 300,
387
+ describe: () => 'valkey evicts keys (dedup/rate windows lose entries).',
388
+ dimensions: { ReplicationGroupId: 'aws_elasticache_replication_group.redis.id' },
389
+ },
390
+ {
391
+ id: 'db:redis',
392
+ tfName: 'notify_valkey_cpu_high',
393
+ alarmName: 'valkey-cpu-high-notify',
394
+ metricName: 'EngineCPUUtilization',
395
+ namespace: 'AWS/ElastiCache',
396
+ statistic: 'Average',
397
+ threshold: 80,
398
+ evaluationPeriods: 3,
399
+ period: 300,
400
+ describe: () => 'valkey engine CPU stays above 80% for 15 minutes.',
401
+ dimensions: { ReplicationGroupId: 'aws_elasticache_replication_group.redis.id' },
402
+ },
403
+ {
404
+ id: 'email:ses',
405
+ tfName: 'notify_ses_bounce_rate',
406
+ alarmName: 'ses-bounce-rate-notify',
407
+ metricName: 'Reputation.BounceRate',
408
+ namespace: 'AWS/SES',
409
+ statistic: 'Average',
410
+ threshold: 0.05,
411
+ evaluationPeriods: 1,
412
+ period: 3600,
413
+ describe: () => 'the account bounce rate exceeds 5%.',
414
+ dimensions: null,
415
+ },
416
+ {
417
+ id: 'email:ses',
418
+ tfName: 'notify_ses_complaint_rate',
419
+ alarmName: 'ses-complaint-rate-notify',
420
+ metricName: 'Reputation.ComplaintRate',
421
+ namespace: 'AWS/SES',
422
+ statistic: 'Average',
423
+ threshold: 0.001,
424
+ evaluationPeriods: 1,
425
+ period: 3600,
426
+ describe: () => 'the account complaint rate exceeds 0.1%.',
427
+ dimensions: null,
428
+ },
429
+ ];
430
+
431
+ export function buildAlertsTf({ projectName, target = 'ecs', email, webhook, threshold, addons = {} }) {
187
432
  const defaults = ALERT_TARGET_DEFAULTS[target] || ALERT_TARGET_DEFAULTS.ecs;
188
433
  const limit = threshold ?? defaults.threshold;
189
434
  // All targets use the workspace-aware local: flat ECS names let a
@@ -212,58 +457,29 @@ ${aliasLine} name = "${namePrefix}-alerts"
212
457
  }
213
458
  `;
214
459
 
215
- const alarm = target === 'lambda' ? `resource "aws_cloudwatch_metric_alarm" "notify_errors" {
216
- alarm_name = "${namePrefix}-errors-notify"
217
- comparison_operator = "GreaterThanThreshold"
218
- evaluation_periods = "${defaults.evaluationPeriods}"
219
- metric_name = "Errors"
220
- namespace = "AWS/Lambda"
221
- period = "${defaults.period}"
222
- statistic = "Sum"
223
- threshold = "${limit}"
224
- alarm_description = "Notifies ${namePrefix}-alerts when ${projectName} reports more than ${limit} Lambda errors in ${defaults.evaluationPeriods} minutes."
225
-
226
- alarm_actions = [aws_sns_topic.alerts.arn]
227
-
228
- dimensions = {
229
- FunctionName = aws_lambda_function.app.function_name
230
- }
231
- }
232
- ` : target === 'static' ? `resource "aws_cloudwatch_metric_alarm" "notify_5xx_rate" {
233
- ${aliasLine} alarm_name = "${namePrefix}-5xx-rate-notify"
234
- comparison_operator = "GreaterThanThreshold"
235
- evaluation_periods = "${defaults.evaluationPeriods}"
236
- metric_name = "5xxErrorRate"
237
- namespace = "AWS/CloudFront"
238
- period = "${defaults.period}"
239
- statistic = "Average"
240
- threshold = "${limit}"
241
- alarm_description = "Notifies ${namePrefix}-alerts when ${projectName} serves more than a ${limit}% 5xx error rate over ${defaults.evaluationPeriods} minutes."
242
-
243
- alarm_actions = [aws_sns_topic.alerts.arn]
244
-
245
- dimensions = {
246
- DistributionId = aws_cloudfront_distribution.site.id
247
- }
248
- }
249
- ` : `resource "aws_cloudwatch_metric_alarm" "notify_5xx" {
250
- alarm_name = "${namePrefix}-5xx-notify"
251
- comparison_operator = "GreaterThanThreshold"
252
- evaluation_periods = "${defaults.evaluationPeriods}"
253
- metric_name = "HTTPCode_Target_5XX_Count"
254
- namespace = "AWS/ApplicationELB"
255
- period = "${defaults.period}"
256
- statistic = "Sum"
257
- threshold = "${limit}"
258
- alarm_description = "Notifies ${namePrefix}-alerts when the ALB serves more than ${limit} 5XX errors in ${defaults.evaluationPeriods} minutes."
259
-
260
- alarm_actions = [aws_sns_topic.alerts.arn]
261
-
262
- dimensions = {
263
- LoadBalancer = aws_lb.main.arn_suffix
264
- }
265
- }
266
- `;
460
+ const spec = PRIMARY_NOTIFY_ALARMS[target] || PRIMARY_NOTIFY_ALARMS.ecs;
461
+ const alarm = renderNotifyAlarm(spec, {
462
+ namePrefix,
463
+ aliasLine,
464
+ limit,
465
+ evaluationPeriods: defaults.evaluationPeriods,
466
+ period: defaults.period,
467
+ projectName,
468
+ });
469
+ // Addon alarms are regional metrics (no us-east-1 alias even on
470
+ // static trees) with baked thresholds.
471
+ const addonAlarms = ADDON_NOTIFY_ALARMS
472
+ .filter((entry) => addons && addons[entry.id])
473
+ .map((entry) => renderNotifyAlarm(entry, {
474
+ namePrefix,
475
+ aliasLine: '',
476
+ limit: entry.threshold,
477
+ evaluationPeriods: entry.evaluationPeriods,
478
+ period: entry.period,
479
+ projectName,
480
+ }))
481
+ .join('\n');
482
+ const addonSection = addonAlarms.length > 0 ? `\n${addonAlarms}` : '';
267
483
 
268
484
  // NOTE: the email endpoint lands in git by design (the operator passed
269
485
  // it explicitly); delivery still needs the recipient's confirmation
@@ -283,6 +499,12 @@ ${aliasLine} topic_arn = aws_sns_topic.alerts.arn
283
499
  # (The archive provider constraint lives in backend.tf next to the aws
284
500
  # one — a module may declare required_providers only once.)
285
501
 
502
+ locals {
503
+ # Length-safe forwarder name (role + function both cap at 64):
504
+ # short names render byte-identically, over-cap hash-suffixes.
505
+ forwarder_safe_name = length("${namePrefix}-alerts-forwarder") > 64 ? "\${substr(local.app_name, 0, 64 - 1 - 5 - 17)}-\${substr(md5(local.app_name), 0, 5)}-alerts-forwarder" : "${namePrefix}-alerts-forwarder"
506
+ }
507
+
286
508
  variable "alerts_webhook_url" {
287
509
  description = "Incoming chat webhook URL for alarm notifications. Export TF_VAR_alerts_webhook_url before apply — never commit the URL to git."
288
510
  type = string
@@ -302,7 +524,7 @@ ${buildForwarderJs()} EOT
302
524
  }
303
525
 
304
526
  resource "aws_iam_role" "forwarder" {
305
- name = "${namePrefix}-alerts-forwarder"
527
+ name = local.forwarder_safe_name
306
528
  assume_role_policy = jsonencode({
307
529
  Version = "2012-10-17"
308
530
  Statement = [
@@ -321,7 +543,7 @@ resource "aws_iam_role_policy_attachment" "forwarder_logs" {
321
543
  }
322
544
 
323
545
  resource "aws_lambda_function" "forwarder" {
324
- ${aliasLine} function_name = "${namePrefix}-alerts-forwarder"
546
+ ${aliasLine} function_name = local.forwarder_safe_name
325
547
  role = aws_iam_role.forwarder.arn
326
548
  runtime = "nodejs22.x"
327
549
  handler = "index.handler"
@@ -354,7 +576,7 @@ ${aliasLine} topic_arn = aws_sns_topic.alerts.arn
354
576
 
355
577
  return `${header}
356
578
  ${topic}
357
- ${alarm}${emailSubscription}${forwarder}`;
579
+ ${alarm}${addonSection}${emailSubscription}${forwarder}`;
358
580
  }
359
581
 
360
582
  // Adds the archive provider (used by the forwarder's data.archive_file)
@@ -458,6 +680,8 @@ async function runAlertsMain(input = {}) {
458
680
  resultExtra: { region },
459
681
  });
460
682
  }
683
+ const addons = detectAlertAddonFeatures(path.join(cwd, 'terraform'));
684
+ const addonAlarmIds = ADDON_NOTIFY_ALARMS.filter((entry) => addons[entry.id]).map((entry) => entry.id);
461
685
  const anchor = TARGET_ANCHORS[target] || TARGET_ANCHORS.ecs;
462
686
  if (!mainTf.includes(anchor.resource)) {
463
687
  const anchorName = target === 'lambda' ? 'aws_lambda_function.app'
@@ -573,7 +797,7 @@ async function runAlertsMain(input = {}) {
573
797
  archiveAdded = ensureArchiveProvider(path.join(cwd, 'terraform', 'backend.tf'));
574
798
  }
575
799
 
576
- await atomicWriteFile(alertsPath, buildAlertsTf({ projectName, target, email, webhook, threshold }));
800
+ await atomicWriteFile(alertsPath, buildAlertsTf({ projectName, target, email, webhook, threshold, addons }));
577
801
  if (webhook) {
578
802
  await ensureForwarderZipIgnored(cwd);
579
803
  }
@@ -583,7 +807,7 @@ async function runAlertsMain(input = {}) {
583
807
  const { aliasAdded, archiveAdded } = scaffolded;
584
808
  const destinations = email && webhook ? 'both' : webhook ? 'webhook' : email ? 'email' : 'manual';
585
809
  const kind = webhook ? detectWebhookKind(webhook) : undefined;
586
- console.log(color.green(`\n✅ Created ${ALERTS_TF_FILE} (SNS topic + ${target} notify alarm${webhook ? ' + chat forwarder' : ''}).`));
810
+ console.log(color.green(`\n✅ Created ${ALERTS_TF_FILE} (SNS topic + ${target} notify alarm${addonAlarmIds.length > 0 ? ` + ${addonAlarmIds.length} addon alarm${addonAlarmIds.length === 1 ? '' : 's'}` : ''}${webhook ? ' + chat forwarder' : ''}).`));
587
811
  if (aliasAdded) console.log(color.dim(' Added the aws.us_east_1 provider alias to terraform/main.tf (CloudFront alarms only exist there).'));
588
812
  if (archiveAdded) console.log(color.dim(' Pinned the archive provider in terraform/backend.tf (forwarder packaging).'));
589
813
  console.log(color.dim(' Next steps:'));
@@ -605,7 +829,7 @@ async function runAlertsMain(input = {}) {
605
829
  }
606
830
  // Telemetry carries destination *kinds* only — never the email
607
831
  // address or webhook URL (PII / bearer secret).
608
- await trackSuccess('alerts_run', { projectName, action: 'scaffold', target, destinations, thresholdCustom: threshold !== undefined });
832
+ await trackSuccess('alerts_run', { projectName, action: 'scaffold', target, destinations, thresholdCustom: threshold !== undefined, addonAlarms: addonAlarmIds });
609
833
  outro(color.green('Done.'));
610
834
  return { ok: true, action: 'scaffold', projectName, region, target, destinations, file: ALERTS_TF_FILE };
611
835
  }
@@ -93,7 +93,7 @@ function renderGateBlock({ includeSetupNode, steps }) {
93
93
  ' - name: Setup Node.js for migrations',
94
94
  ` uses: ${pinnedActionUse('actions/setup-node')}`,
95
95
  ' with:',
96
- " node-version: '20'",
96
+ " node-version: '22'",
97
97
  ''
98
98
  );
99
99
  }
@@ -8,7 +8,7 @@ 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, resolveNamespacedProject, withWorkspaceNamespace } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace, safeSuffixedName } from '../utils/resolvers.js';
12
12
  import { pickNewestRunningTask } from '../utils/ecs.js';
13
13
  import { fetchLatestEvents } from './logs.js';
14
14
 
@@ -127,7 +127,7 @@ export async function runLambdaDiagnose(input = {}) {
127
127
  const namespacedProject = resolveNamespacedProject(projectName, options, options.cwd);
128
128
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
129
129
  ? options.functionName.trim()
130
- : `${namespacedProject}${readResourceSuffix(options.cwd)}-fn`;
130
+ : safeSuffixedName(`${namespacedProject}${readResourceSuffix(options.cwd)}`, '-fn', 64);
131
131
  const runSync = options.spawnSyncImpl || spawnSync;
132
132
 
133
133
  intro(color.bgCyan(color.black(' grada diagnose 🩺 ')));
@@ -11,7 +11,7 @@ import color from 'picocolors';
11
11
  import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
12
12
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
- import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
14
+ import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix, safeSuffixedName } from '../utils/resolvers.js';
15
15
  import { resolveClient } from '../utils/aws.js';
16
16
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
17
17
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
@@ -85,6 +85,9 @@ function projectRepoName(projectName, resourceSuffix = '') {
85
85
  // lookalikes (`myapp-evil-pr-2`) never match.
86
86
  function previewLogGroupPattern({ projectName, resourceSuffix = '', isLambda = false }) {
87
87
  const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
88
+ // Plain-form only by design: over-cap preview names hash-suffix in
89
+ // Terraform, so they never match here — fail closed (never proposed)
90
+ // and the 30-day group retention self-cleans them instead.
88
91
  return isLambda ? new RegExp(`^/aws/lambda/${base}-fn$`) : new RegExp(`^/ecs/${base}$`);
89
92
  }
90
93
 
@@ -199,6 +202,9 @@ export async function discoverLivePreviewLogGroups({
199
202
  try {
200
203
  const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
201
204
  if (isLambda) {
205
+ // Plain-form only (see previewLogGroupPattern): hashed
206
+ // over-cap functions are invisible here, and invisible to
207
+ // the orphan candidate pattern too — consistently skipped.
202
208
  const fnPattern = new RegExp(`^${base}-fn$`);
203
209
  const names = await listFunctionsImpl({ region, spawnSyncImpl });
204
210
  for (const name of names || []) {
@@ -740,7 +746,7 @@ async function runGcMain(input = {}) {
740
746
  // Exact match: the live group carries the suffix on suffixed
741
747
  // trees, and proposing it for deletion would be catastrophic.
742
748
  excludeLogGroup: isLambda
743
- ? `/aws/lambda/${projectName}${suffix}-fn`
749
+ ? `/aws/lambda/${safeSuffixedName(`${projectName}${suffix}`, '-fn', 64)}`
744
750
  : `/ecs/${projectName}${suffix}`,
745
751
  livePreviewGroups: liveness.groups,
746
752
  previewLivenessUnknown: liveness.unknown,
@@ -12,7 +12,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
12
12
  import { failCommand, failAwsError, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
14
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
15
- import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix, safeSuffixedName } from '../utils/resolvers.js';
16
16
  import { requireManagedTree } from '../utils/terraform-metadata.js';
17
17
  import { truncateSpinnerText } from '../utils/spinner-text.js';
18
18
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
@@ -131,7 +131,7 @@ async function runRollbackMain(input = {}) {
131
131
 
132
132
  const targetGuard = guardComputeTarget({ cwd, command: 'Rollback', supported: ['ecs'] });
133
133
  if (targetGuard) {
134
- const functionName = `${projectName}${readResourceSuffix(cwd)}-fn`;
134
+ const functionName = safeSuffixedName(`${projectName}${readResourceSuffix(cwd)}`, '-fn', 64);
135
135
  trackEvent('rollback_target_unsupported', { projectName, actual: targetGuard.actual });
136
136
  return failCommand({
137
137
  message: targetGuard.message,