grada-run 0.42.0 → 0.43.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.
Files changed (63) hide show
  1. package/bin/cli.js +1 -1
  2. package/package.json +1 -1
  3. package/src/commands/add.js +93 -11
  4. package/src/commands/alerts.js +66 -30
  5. package/src/commands/apply.js +65 -10
  6. package/src/commands/db/backup.js +1 -2
  7. package/src/commands/db/connect.js +10 -4
  8. package/src/commands/db/enable-vector.js +19 -6
  9. package/src/commands/db/import.js +114 -22
  10. package/src/commands/db/migrate.js +82 -74
  11. package/src/commands/db/restore.js +38 -6
  12. package/src/commands/destroy.js +20 -3
  13. package/src/commands/diagnose.js +40 -21
  14. package/src/commands/doctor.js +27 -2
  15. package/src/commands/domain.js +20 -2
  16. package/src/commands/drift.js +2 -1
  17. package/src/commands/eject.js +13 -2
  18. package/src/commands/gc.js +100 -3
  19. package/src/commands/init.js +75 -9
  20. package/src/commands/logs.js +3 -1
  21. package/src/commands/mcp.js +2 -1
  22. package/src/commands/rollback.js +54 -5
  23. package/src/commands/secrets.js +260 -64
  24. package/src/commands/status.js +4 -1
  25. package/src/commands/sync-ai.js +4 -3
  26. package/src/commands/wake.js +45 -1
  27. package/src/data/action-pins.js +26 -0
  28. package/src/utils/addons.js +9 -6
  29. package/src/utils/ai-rules.js +3 -2
  30. package/src/utils/backup.js +16 -2
  31. package/src/utils/command.js +20 -0
  32. package/src/utils/db-tunnel.js +15 -5
  33. package/src/utils/detector.js +8 -0
  34. package/src/utils/ecs-runner.js +16 -3
  35. package/src/utils/frameworks.js +14 -2
  36. package/src/utils/generator.js +21 -13
  37. package/src/utils/prompts.js +20 -4
  38. package/src/utils/resolvers.js +9 -7
  39. package/src/utils/revision-discovery.js +19 -7
  40. package/templates/docker/django.Dockerfile +2 -2
  41. package/templates/docker/go.Dockerfile +2 -2
  42. package/templates/docker/nestjs.Dockerfile +2 -2
  43. package/templates/docker/nextjs.Dockerfile +3 -3
  44. package/templates/docker/node.Dockerfile +2 -2
  45. package/templates/docker/nuxt.Dockerfile +2 -2
  46. package/templates/docker/python.Dockerfile +2 -2
  47. package/templates/docker/rails.Dockerfile +2 -2
  48. package/templates/docker/static.Dockerfile +2 -2
  49. package/templates/docker/svelte.Dockerfile +2 -2
  50. package/templates/github/deploy-lambda.yml +55 -12
  51. package/templates/github/deploy-static.yml +24 -6
  52. package/templates/github/deploy.yml +96 -13
  53. package/templates/github/drift.yml +68 -5
  54. package/templates/github/preview-lambda.yml +137 -13
  55. package/templates/github/preview.yml +135 -13
  56. package/templates/github/teardown.yml +71 -12
  57. package/templates/terraform/addons/s3.tf +35 -0
  58. package/templates/terraform/backend.tf +7 -0
  59. package/templates/terraform/database-mysql.tf +9 -1
  60. package/templates/terraform/database.tf +9 -1
  61. package/templates/terraform/oidc.tf +3 -2
  62. package/templates/terraform/secrets.tf +6 -4
  63. package/templates/terraform/worker.tf +7 -0
@@ -13,6 +13,10 @@ import { pickNewestRunningTask } from '../utils/ecs.js';
13
13
  import { fetchLatestEvents } from './logs.js';
14
14
 
15
15
  export const LOG_FETCH_LIMIT = 50;
16
+ // Stopped-task discovery bounds: 3 ListTasks pages (300 ARNs max),
17
+ // described in DescribeTasks-sized chunks.
18
+ export const STOPPED_LIST_MAX_PAGES = 3;
19
+ export const DESCRIBE_TASKS_ARN_LIMIT = 100;
16
20
 
17
21
  export function extractStoppedReason(task) {
18
22
  return task?.stoppedReason || 'Unknown';
@@ -301,16 +305,27 @@ async function runDiagnoseMain(input = {}) {
301
305
  const logsClient = resolveClient(options.logsClient, CloudWatchLogsClient, { region });
302
306
 
303
307
  try {
304
- const listResp = await ecsClient.send(
305
- new ListTasksCommand({
306
- cluster,
307
- desiredStatus: 'STOPPED',
308
- sort: 'DESC',
309
- maxResults: 100
310
- })
311
- );
312
-
313
- const taskArns = listResp.taskArns || [];
308
+ // A crash-looping service exceeds 100 stopped tasks within the ~1h
309
+ // retention, and ListTasks order is arbitrary — one page may miss
310
+ // the true latest crash. Paginate (bounded) before describing.
311
+ const taskArns = [];
312
+ let listToken;
313
+ let truncated = false;
314
+ for (let page = 0; page < STOPPED_LIST_MAX_PAGES; page++) {
315
+ const listResp = await ecsClient.send(
316
+ new ListTasksCommand({
317
+ cluster,
318
+ desiredStatus: 'STOPPED',
319
+ sort: 'DESC',
320
+ maxResults: 100,
321
+ ...(listToken ? { nextToken: listToken } : {}),
322
+ })
323
+ );
324
+ taskArns.push(...(listResp.taskArns || []));
325
+ listToken = listResp.nextToken;
326
+ if (!listToken) break;
327
+ if (page + 1 >= STOPPED_LIST_MAX_PAGES) truncated = true;
328
+ }
314
329
 
315
330
  if (taskArns.length === 0) {
316
331
  s.stop('No stopped tasks found.');
@@ -320,17 +335,21 @@ async function runDiagnoseMain(input = {}) {
320
335
  return { healthy: true, stoppedReason: null, logs: [] };
321
336
  }
322
337
 
323
- // ListTasks order is arbitrary — describe the full batch (up to the
324
- // DescribeTasks 100-ARN limit) and pick the latest stopped task below.
325
- s.message(`Describing ${Math.min(taskArns.length, 100)} stopped task(s)...`);
326
- const descResp = await ecsClient.send(
327
- new DescribeTasksCommand({
328
- cluster,
329
- tasks: taskArns.slice(0, 100)
330
- })
331
- );
332
-
333
- const tasks = descResp.tasks || [];
338
+ // DescribeTasks caps at 100 ARNs per call — chunk the pages.
339
+ s.message(`Describing ${taskArns.length} stopped task(s)...`);
340
+ const tasks = [];
341
+ for (let i = 0; i < taskArns.length; i += DESCRIBE_TASKS_ARN_LIMIT) {
342
+ const descResp = await ecsClient.send(
343
+ new DescribeTasksCommand({
344
+ cluster,
345
+ tasks: taskArns.slice(i, i + DESCRIBE_TASKS_ARN_LIMIT)
346
+ })
347
+ );
348
+ tasks.push(...(descResp.tasks || []));
349
+ }
350
+ if (truncated) {
351
+ console.log(color.dim(` Note: more than ${STOPPED_LIST_MAX_PAGES * 100} stopped tasks exist — diagnosing the latest of the first ${STOPPED_LIST_MAX_PAGES * 100}.`));
352
+ }
334
353
  if (tasks.length === 0) {
335
354
  s.stop('No task details returned.');
336
355
  console.log(color.yellow('⚠ Stopped task ARNs were listed, but ECS returned no task details.'));
@@ -33,7 +33,8 @@ export const PROJECT_CHECKS = [
33
33
  { id: 'state_lock', label: 'Terraform state lock', scope: 'project', severity: 'fail', run: checkStateLock, hint: () => 'If no apply is running, release it with: terraform force-unlock <lock-id> (find the holder via grada doctor --deep).' },
34
34
  { id: 'interrupted_run', label: 'Interrupted Terraform run', scope: 'project', severity: 'warn', run: checkInterruptedRun, hint: () => 'Review the last apply/destroy output before trusting applied state; the next run overwrites the marker.' },
35
35
  { id: 'oidc_trust_scope', label: 'OIDC trust scope', scope: 'project', severity: 'warn', run: checkOidcTrustScope, hint: () => 'Re-scope with: npx grada-run init --github-repo owner/name (or edit the sub claim in terraform/oidc.tf).' },
36
- { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run setup to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
36
+ { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run npx grada-run init to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
37
+ { id: 'origin_restriction', label: 'ALB origin restriction', scope: 'project', severity: 'warn', run: checkOriginRestriction, hint: () => 'Re-run npx grada-run init to add the CloudFront origin-secret wiring, then apply.' },
37
38
  ];
38
39
 
39
40
  const INSTALL_HINTS = {
@@ -207,6 +208,28 @@ function workspaceSuffix(lockKey) {
207
208
  // by default): surfaces yellow without flipping the verdict red. List
208
209
  // trusts flag when any entry is open; non-literal claims (var/ref)
209
210
  // skip honestly as not parseable rather than as missing.
211
+ // Project check: the apply-time Direct URL only bypasses the CDN on
212
+ // trees predating the CloudFront origin-secret restriction (listener
213
+ // rule 403ing hits without the header). Warning-grade: the URL still
214
+ // prints, but on unwired trees it misleads. Non-ECS targets have no
215
+ // ALB — skip.
216
+ function checkOriginRestriction({ cwd }) {
217
+ let mainTf;
218
+ try {
219
+ mainTf = fs.readFileSync(path.join(cwd, 'terraform', 'main.tf'), 'utf8');
220
+ } catch {
221
+ return { ok: true, skipped: 'no terraform/main.tf found' };
222
+ }
223
+ if (!mainTf.includes('aws_lb_listener')) {
224
+ return { ok: true, skipped: 'no ALB in this tree (non-ECS target)' };
225
+ }
226
+ if (mainTf.includes('X-Grada-Origin-Secret')) return { ok: true };
227
+ return {
228
+ ok: false,
229
+ detailLines: ['ALB accepts direct traffic (no CloudFront origin-secret restriction) — the apply-time Direct URL bypasses the CDN on this tree.'],
230
+ };
231
+ }
232
+
210
233
  function checkOidcTrustScope({ cwd }) {
211
234
  const trust = readTerraformOidcTrust(cwd);
212
235
  if (trust === null) return { ok: true, skipped: 'no oidc.tf trust found' };
@@ -233,7 +256,9 @@ function checkOidcImmutableClaims({ cwd }) {
233
256
  return { ok: true, skipped: 'trust value not parseable (non-literal claim — review by hand)' };
234
257
  }
235
258
  const entries = trust.kind === 'list' ? trust.entries : [trust.value];
236
- const covered = entries.some((entry) => entry === 'repo:*' || /@(\*|\d)/.test(entry));
259
+ // Anchored to owner/name: a bare `@digit` test would count suffix
260
+ // text (`:release@2`) as immutable coverage.
261
+ const covered = entries.some((entry) => entry === 'repo:*' || /^repo:[^/@]+@(?:\*|\d+)\/[^/@:]+@(?:\*|\d+)/.test(entry));
237
262
  if (covered) return { ok: true };
238
263
  return {
239
264
  ok: false,
@@ -681,12 +681,30 @@ async function runDomainStatus({ options, cwd, projectName, domainTfPath, cloudf
681
681
  }
682
682
  const target = outputValue(outputs, 'custom_domain_cname_target') || outputValue(outputs, 'cloudfront_url');
683
683
  if (typeof target === 'string' && target) {
684
- rows.push({ type: 'CNAME', name: domain, value: target.replace(/^https:\/\//, '') });
684
+ // CNAME is invalid at the zone apex: a two-label domain renders
685
+ // an ALIAS row instead. (Longer names keep the CNAME row —
686
+ // multi-part-TLD apexes cannot be told from subdomains without
687
+ // the zone name, so those get a caveat below.)
688
+ const isApex = typeof domain === 'string' && domain.split('.').length === 2;
689
+ rows.push({ type: isApex ? 'ALIAS' : 'CNAME', name: domain, value: target.replace(/^https:\/\//, ''), apex: isApex });
685
690
  }
686
- if (rows.length > 0) {
691
+ if (mode === 'route53') {
692
+ // Validation + alias records all live in terraform/domain.tf —
693
+ // there is nothing to add by hand.
694
+ if (rows.length > 0) {
695
+ console.log(` ${color.dim('DNS records are managed by Terraform in terraform/domain.tf — no manual action needed.')}`);
696
+ } else {
697
+ console.log(` ${color.dim('No DNS outputs yet — run npx grada-run apply first.')}`);
698
+ }
699
+ } else if (rows.length > 0) {
687
700
  console.log('');
688
701
  console.log(` ${color.dim('Add these records at your DNS provider:')}`);
689
702
  printDnsTable(rows);
703
+ if (rows.some((row) => row.apex)) {
704
+ console.log(` ${color.dim('At the zone apex CNAME is invalid — create an ALIAS/ANAME record (or your provider\u2019s CNAME flattening) pointing at the same target.')}`);
705
+ } else if (rows.some((row) => row.name === domain)) {
706
+ console.log(` ${color.dim('If this domain is your zone apex (e.g. under a multi-part TLD), CNAME is invalid there — use an ALIAS/ANAME record instead.')}`);
707
+ }
690
708
  } else {
691
709
  console.log(` ${color.dim('No DNS outputs yet — run npx grada-run apply first.')}`);
692
710
  }
@@ -8,6 +8,7 @@ import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../c
8
8
  import { failCommand, failAwsError, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { resolveRegion, resolveProjectName, resolveCwd, readFileSafe } from '../utils/resolvers.js';
11
+ import { atomicWriteFileSync } from '../utils/atomic-write.js';
11
12
 
12
13
  const __filename = fileURLToPath(import.meta.url);
13
14
  const __dirname = path.dirname(__filename);
@@ -52,7 +53,7 @@ export function scaffoldDriftWorkflow(cwd = process.cwd(), { region, roleArn, fo
52
53
  return { ok: false, reason: 'exists', path: targetPath };
53
54
  }
54
55
  fsSync.mkdirSync(path.dirname(targetPath), { recursive: true });
55
- fsSync.writeFileSync(targetPath, rendered, 'utf8');
56
+ atomicWriteFileSync(targetPath, rendered, 'utf8');
56
57
  return { ok: true, path: targetPath };
57
58
  }
58
59
 
@@ -208,9 +208,20 @@ async function ejectStackMain(input = {}) {
208
208
  const files = fs.readdirSync(dir);
209
209
  for (const file of files) {
210
210
  const fullPath = path.join(dir, file);
211
- if (isGradaBackupName(file)) {
211
+ // lstat, never stat: a symlinked dir pointing outside the
212
+ // tree must neither be descended into nor deleted
213
+ // through. Backup-named links remove the link only.
214
+ let st;
215
+ try {
216
+ st = fs.lstatSync(fullPath);
217
+ } catch {
218
+ continue;
219
+ }
220
+ if (st.isSymbolicLink()) {
221
+ if (isGradaBackupName(file)) fs.rmSync(fullPath, { force: true });
222
+ } else if (isGradaBackupName(file)) {
212
223
  fs.rmSync(fullPath, { recursive: true, force: true });
213
- } else if (fs.statSync(fullPath).isDirectory() && file !== 'node_modules' && file !== '.git') {
224
+ } else if (st.isDirectory() && file !== 'node_modules' && file !== '.git') {
214
225
  cleanBackups(fullPath); // Recursively check subdirectories like .github/workflows
215
226
  }
216
227
  }
@@ -6,6 +6,7 @@ import { CloudWatchLogsClient, DescribeLogGroupsCommand, DeleteLogGroupCommand }
6
6
  import { ECSClient, ListClustersCommand, ListServicesCommand, DescribeServicesCommand } from '@aws-sdk/client-ecs';
7
7
  import { EC2Client, DescribeAddressesCommand, ReleaseAddressCommand, DescribeVpcsCommand, DescribeSubnetsCommand } from '@aws-sdk/client-ec2';
8
8
  import { SecretsManagerClient, ListSecretsCommand } from '@aws-sdk/client-secrets-manager';
9
+ import { RDSClient, DescribeDBSnapshotsCommand, DescribeDBClusterSnapshotsCommand, DeleteDBSnapshotCommand, DeleteDBClusterSnapshotCommand } from '@aws-sdk/client-rds';
9
10
  import color from 'picocolors';
10
11
  import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
11
12
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
@@ -14,16 +15,23 @@ import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readRes
14
15
  import { resolveClient } from '../utils/aws.js';
15
16
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
16
17
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
18
+ import { resolveDbIdentifier, resolveDbClusterIdentifier } from '../utils/rds.js';
17
19
 
18
20
  export const CONFIRM_MESSAGE = 'Are you sure you want to permanently delete these orphaned resources? (y/N)';
19
21
 
22
+ // Pre-destroy manual snapshots younger than this are never proposed:
23
+ // recent destroys stay restorable until the threshold passes.
24
+ export const DEFAULT_SNAPSHOT_MAX_AGE_DAYS = 30;
25
+
20
26
  export function parseGcArgs(argv = []) {
21
27
  const args = normalizeArgv(argv);
22
28
  if (args[0] === 'gc') args.shift();
23
29
  // --yes auto-confirms the delete prompt (explicit opt-in; the default
24
30
  // path still prompts). --deep adds the report-only deep scan.
31
+ // --snapshot-max-age-days retires pre-destroy manual snapshots older
32
+ // than N days (default 30).
25
33
  const { options, unknown } = parseFlags(args, {
26
- string: ['region', 'project-name'],
34
+ string: ['region', 'project-name', { name: 'snapshot-max-age-days', key: 'snapshotMaxAgeDays' }],
27
35
  boolean: ['deep', 'yes', 'headless'],
28
36
  });
29
37
  if (unknown.length > 0) options.unknownFlags = unknown;
@@ -263,6 +271,50 @@ async function discoverUnattachedEips({ ec2Client, projectName }) {
263
271
  return unattachedEips;
264
272
  }
265
273
 
274
+ // Standard target discovery: pre-destroy manual snapshots older than
275
+ // the age threshold. Scoped by the exact `<db>-manual-<stamp>` naming
276
+ // pattern destroy writes (instance AND cluster snapshots) — foreign,
277
+ // automated, non-available, and young snapshots are never proposed.
278
+ // Tolerant of missing clients/identifiers (programmatic callers without
279
+ // RDS context discover nothing instead of throwing).
280
+ async function discoverOldManualSnapshots({ rdsClient, dbIdentifier, dbClusterIdentifier, snapshotMaxAgeDays } = {}) {
281
+ if (!rdsClient || (!dbIdentifier && !dbClusterIdentifier)) return [];
282
+ const maxAgeDays = Number(snapshotMaxAgeDays ?? DEFAULT_SNAPSHOT_MAX_AGE_DAYS);
283
+ const cutoffMs = Date.now() - (Number.isFinite(maxAgeDays) ? maxAgeDays : DEFAULT_SNAPSHOT_MAX_AGE_DAYS) * 86400000;
284
+ const patterns = [dbIdentifier, dbClusterIdentifier]
285
+ .filter((id) => typeof id === 'string' && id.trim())
286
+ .map((id) => new RegExp(`^${escapeRegExp(id.trim().toLowerCase())}-manual-\\d{8}-\\d{6}$`));
287
+ if (patterns.length === 0) return [];
288
+ const isRetirable = (snapshotId, status, type, createTime) => {
289
+ if (status !== 'available' || type !== 'manual') return false;
290
+ const createdMs = createTime ? new Date(createTime).getTime() : NaN;
291
+ if (!Number.isFinite(createdMs) || createdMs > cutoffMs) return false;
292
+ return patterns.some((pattern) => pattern.test(String(snapshotId).toLowerCase()));
293
+ };
294
+ const snapshots = [];
295
+ let marker;
296
+ do {
297
+ const resp = await rdsClient.send(new DescribeDBSnapshotsCommand({ Marker: marker, MaxRecords: 100 }));
298
+ for (const snap of resp.DBSnapshots || []) {
299
+ if (isRetirable(snap.DBSnapshotIdentifier, snap.Status, snap.SnapshotType, snap.SnapshotCreateTime)) {
300
+ snapshots.push({ id: snap.DBSnapshotIdentifier, kind: 'instance', createTime: snap.SnapshotCreateTime });
301
+ }
302
+ }
303
+ marker = resp.Marker;
304
+ } while (marker);
305
+ marker = undefined;
306
+ do {
307
+ const resp = await rdsClient.send(new DescribeDBClusterSnapshotsCommand({ Marker: marker, MaxRecords: 100 }));
308
+ for (const snap of resp.DBClusterSnapshots || []) {
309
+ if (isRetirable(snap.DBClusterSnapshotIdentifier, snap.Status, snap.SnapshotType, snap.SnapshotCreateTime)) {
310
+ snapshots.push({ id: snap.DBClusterSnapshotIdentifier, kind: 'cluster', createTime: snap.SnapshotCreateTime });
311
+ }
312
+ }
313
+ marker = resp.Marker;
314
+ } while (marker);
315
+ return snapshots;
316
+ }
317
+
266
318
  // Deep target discovery: VPCs partitioned by the STRICT deletion
267
319
  // predicate — exact project tag only, minus live networks. Foreign and
268
320
  // untagged VPCs land in reportOnly, never in deletable, so prefix
@@ -406,6 +458,13 @@ export const GC_TARGETS = [
406
458
  format: (eip) => eip.PublicIp || eip.AllocationId,
407
459
  listCap: Infinity,
408
460
  },
461
+ {
462
+ id: 'db-snapshots', label: 'Old manual DB snapshots', scope: 'standard',
463
+ field: 'oldManualSnapshots', summary: 'deletedSnapshots',
464
+ discover: discoverOldManualSnapshots, remove: removeOldManualSnapshots,
465
+ format: (snap) => snap.id,
466
+ listCap: 10,
467
+ },
409
468
  {
410
469
  id: 'vpcs', label: 'VPCs', kind: 'vpc', scope: 'deep',
411
470
  discover: discoverDeepVpcs, remove: null,
@@ -494,6 +553,19 @@ async function releaseUnattachedEips({ ec2Client }, eips) {
494
553
  return releasedEips;
495
554
  }
496
555
 
556
+ async function removeOldManualSnapshots({ rdsClient }, snapshots) {
557
+ let deletedSnapshots = 0;
558
+ for (const snap of snapshots || []) {
559
+ if (snap.kind === 'cluster') {
560
+ await rdsClient.send(new DeleteDBClusterSnapshotCommand({ DBClusterSnapshotIdentifier: snap.id }));
561
+ } else {
562
+ await rdsClient.send(new DeleteDBSnapshotCommand({ DBSnapshotIdentifier: snap.id }));
563
+ }
564
+ deletedSnapshots += 1;
565
+ }
566
+ return deletedSnapshots;
567
+ }
568
+
497
569
  export async function deleteDiscoveredResources(clients, discovered) {
498
570
  const summary = {};
499
571
  const errors = [];
@@ -588,8 +660,26 @@ async function runGcMain(input = {}) {
588
660
  const ec2Client = resolveClient(options.ec2Client, EC2Client, { region });
589
661
  const ecsClient = resolveClient(options.ecsClient, ECSClient, { region });
590
662
  const secretsClient = resolveClient(options.secretsClient, SecretsManagerClient, { region });
663
+ const rdsClient = resolveClient(options.rdsClient, RDSClient, { region });
591
664
  const deep = options.deep === true || options.deep === 'true';
592
665
 
666
+ let snapshotMaxAgeDays = DEFAULT_SNAPSHOT_MAX_AGE_DAYS;
667
+ if (options.snapshotMaxAgeDays !== undefined && options.snapshotMaxAgeDays !== null && String(options.snapshotMaxAgeDays).trim() !== '') {
668
+ const parsed = Number(options.snapshotMaxAgeDays);
669
+ if (!Number.isFinite(parsed) || parsed < 0) {
670
+ return failCommand({
671
+ noExit: isProgrammaticCall(options),
672
+ message: `\n✖ Invalid --snapshot-max-age-days "${options.snapshotMaxAgeDays}". Use a non-negative number of days (default ${DEFAULT_SNAPSHOT_MAX_AGE_DAYS}).\n`,
673
+ event: 'gc_run',
674
+ telemetry: { projectName },
675
+ errorCode: 'INVALID_SNAPSHOT_MAX_AGE_DAYS',
676
+ reason: 'invalid-snapshot-max-age-days',
677
+ resultExtra: { projectName, region },
678
+ });
679
+ }
680
+ snapshotMaxAgeDays = parsed;
681
+ }
682
+
593
683
  intro(color.bgCyan(color.black(' grada gc 🧹 ')));
594
684
 
595
685
  const s = spinner();
@@ -600,6 +690,9 @@ async function runGcMain(input = {}) {
600
690
  let previewClusterServices = null;
601
691
  try {
602
692
  const isLambda = isComputeTarget(cwd, 'lambda');
693
+ // Static projects cannot have a database: snapshot discovery is
694
+ // skipped entirely (no identifiers, no RDS calls).
695
+ const isStatic = isComputeTarget(cwd, 'static');
603
696
  const suffix = readResourceSuffix(cwd);
604
697
  // One cluster-service enumeration shared by the log-group and
605
698
  // (deep) VPC liveness consumers — fetched once, not per scan.
@@ -620,7 +713,11 @@ async function runGcMain(input = {}) {
620
713
  ecrClient,
621
714
  logsClient,
622
715
  ec2Client,
716
+ rdsClient,
623
717
  projectName,
718
+ dbIdentifier: isStatic ? undefined : resolveDbIdentifier(options, cwd),
719
+ dbClusterIdentifier: isStatic ? undefined : resolveDbClusterIdentifier(options, cwd),
720
+ snapshotMaxAgeDays,
624
721
  resourceSuffix: suffix,
625
722
  isLambda,
626
723
  logGroupPrefix: isLambda ? `/aws/lambda/${projectName}-` : undefined,
@@ -738,7 +835,7 @@ async function runGcMain(input = {}) {
738
835
  del.start('Deleting orphaned resources...');
739
836
  let summary;
740
837
  try {
741
- summary = await deleteDiscoveredResources({ ecrClient, logsClient, ec2Client }, discovered);
838
+ summary = await deleteDiscoveredResources({ ecrClient, logsClient, ec2Client, rdsClient }, discovered);
742
839
  } catch (error) {
743
840
  del.stop(color.red('❌ Deletion partially failed.'));
744
841
  const partial = (error && typeof error === 'object' && error.partialSummary) || {};
@@ -753,7 +850,7 @@ async function runGcMain(input = {}) {
753
850
  }
754
851
  del.stop('Deletion complete.');
755
852
 
756
- outro(color.green(`Deleted ${summary.deletedImages} image(s), ${summary.deletedLogGroups} log group(s), released ${summary.releasedEips} Elastic IP(s). ✅`));
853
+ outro(color.green(`Deleted ${summary.deletedImages} image(s), ${summary.deletedLogGroups} log group(s), released ${summary.releasedEips} Elastic IP(s), deleted ${summary.deletedSnapshots} snapshot(s). ✅`));
757
854
  await trackSuccess('gc_run', { projectName, deleted: true, ...summary, total: discovered.totalCount });
758
855
  return { ...discovered, ...summary, deleted: true, confirmed: true };
759
856
  }
@@ -21,7 +21,7 @@ import {
21
21
  SUPPORTED_FRAMEWORKS
22
22
  } from '../utils/detector.js';
23
23
  import { detectProjectCapabilities } from '../utils/capabilities.js';
24
- import { ADDON_REGISTRY } from '../utils/addons.js';
24
+ import { ADDON_REGISTRY, addonTargetDisposition, addonSupportedTargets } from '../utils/addons.js';
25
25
  import { validateAddonFlags, resolveAddonOptions, scaffoldAddon, DEFAULT_BEDROCK_MODEL } from './add.js';
26
26
  import { injectMigrationGate, injectPreviewMigrationGate } from './db/migrate.js';
27
27
  import { scaffoldDriftWorkflow } from './drift.js';
@@ -38,7 +38,7 @@ import { getTargetDirectory, getProjectConfig, promptWorkerCommand, promptGitHub
38
38
  import { resolveDjangoWsgi, handleRailsCI } from '../utils/frameworks.js';
39
39
  import { parseDockerCompose, selectComposeWebService } from '../utils/dockerCompose.js';
40
40
  import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-rules.js';
41
- import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust } from '../utils/resolvers.js';
41
+ import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust, guardComputeTarget } from '../utils/resolvers.js';
42
42
  import { readGitHubRepoFromRemote, isValidGitHubRepoSlug } from '../utils/git.js';
43
43
  import { parseDomainTf } from '../utils/domains.js';
44
44
  import { PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
@@ -53,15 +53,16 @@ export const OFFLINE_ACCOUNT_PLACEHOLDER = PLACEHOLDER_ACCOUNT_ID;
53
53
  // so it lands in CI logs as well as terminals. Mirrors every call
54
54
  // provisionStateBucket makes (create + tag + versioning), including its
55
55
  // us-east-1 LocationConstraint exception.
56
- export function printOfflineChecklist({ bucket, region }) {
56
+ export function printOfflineChecklist({ bucket, region, workflows = ['deploy', 'preview', 'teardown', 'drift'] }) {
57
57
  const locationArg = region === 'us-east-1' ? '' : ` --create-bucket-configuration LocationConstraint=${region}`;
58
+ const rendered = Array.isArray(workflows) && workflows.length > 0 ? workflows : ['deploy'];
58
59
  console.log('');
59
60
  console.log(color.yellow('⚠️ Offline scaffold: no AWS resources were created. Reconcile before applying:'));
60
61
  console.log(` 1. Create the state bucket (replace ${OFFLINE_ACCOUNT_PLACEHOLDER} with yours):`);
61
62
  console.log(color.cyan(` aws s3api create-bucket --bucket ${bucket} --region ${region}${locationArg}`));
62
63
  console.log(color.cyan(` aws s3api put-bucket-tagging --bucket ${bucket} --tagging 'TagSet=[{Key=ManagedBy,Value=grada}]'`));
63
64
  console.log(color.cyan(` aws s3api put-bucket-versioning --bucket ${bucket} --versioning-configuration Status=Enabled`));
64
- console.log(` 2. Replace every ${OFFLINE_ACCOUNT_PLACEHOLDER} with your account ID: the bucket name in terraform/backend.tf plus every role-to-assume ARN in .github/workflows/*.yml (deploy, preview, teardown, drift).`);
65
+ console.log(` 2. Replace every ${OFFLINE_ACCOUNT_PLACEHOLDER} with your account ID: the bucket name in terraform/backend.tf plus every role-to-assume ARN in .github/workflows/*.yml (${rendered.join(', ')}).`);
65
66
  console.log(` 3. Run ${color.cyan('terraform init')} in terraform/, then ${color.cyan('grada apply')}.`);
66
67
  }
67
68
 
@@ -394,6 +395,30 @@ async function mainStackMain(input = {}) {
394
395
  target = targetAnswer;
395
396
  }
396
397
 
398
+ // Capability-vs-target policy for --with (BUG-157): refuse fast when
399
+ // the requested capability cannot render on this target (static has
400
+ // no task role or VPC), before any prompt/AWS call/write. Interactive
401
+ // multiselect offers only compatible targets' caps; this covers --with.
402
+ for (const cap of withList) {
403
+ if (!ADDON_REGISTRY[cap]) continue;
404
+ if (addonTargetDisposition(cap, target) === 'refuse') {
405
+ const targetGuard = guardComputeTarget({
406
+ actual: target,
407
+ command: `init --with ${cap}`,
408
+ supported: addonSupportedTargets(cap),
409
+ hint: 'Static sites run no containers — this capability needs a compute target (--target ecs or lambda).',
410
+ });
411
+ return failCommand({
412
+ message: targetGuard.message,
413
+ hint: targetGuard.hint,
414
+ event: 'cli-error',
415
+ telemetry: { step: 'init_validation', error_code: targetGuard.errorCode },
416
+ reason: targetGuard.reason,
417
+ resultExtra: { capability: cap },
418
+ });
419
+ }
420
+ }
421
+
397
422
  const detectedFramework = detectFramework(dirConfig.targetDir);
398
423
  const procfile = parseProcfile(dirConfig.targetDir);
399
424
  const vercelRules = parseVercelConfig(dirConfig.targetDir);
@@ -446,7 +471,7 @@ async function mainStackMain(input = {}) {
446
471
  config.dbEngine = 'postgres';
447
472
  }
448
473
  const djangoWsgi = await resolveDjangoWsgi(dirConfig.targetDir, procfile, config.framework, isHeadless);
449
- const disableDefaultCI = await handleRailsCI(dirConfig.targetDir, config.framework, isHeadless);
474
+ const disableDefaultCI = await handleRailsCI(dirConfig.targetDir, config.framework, isHeadless, { force: initOptions.force === true });
450
475
 
451
476
  // 3b. Dependency-aware composition (worker, migration gate, addons).
452
477
  // Everything here resolves before backups, AWS calls, or file writes.
@@ -503,6 +528,14 @@ async function mainStackMain(input = {}) {
503
528
  workerCommandHcl = `command = ${toHclStringArray(splitProcfileCommand(workerAnswer.trim()))}`;
504
529
  }
505
530
  }
531
+ if (!isInteractive && !isStaticSite && target !== 'lambda' && target !== 'static' && !procfile?.worker && capabilities.worker.detected) {
532
+ // The suggested command is an npm shim (broken on stripped
533
+ // runners), so headless never scaffolds it blindly — but the
534
+ // detection must not vanish silently either.
535
+ const evidence = (capabilities.worker.evidence || []).join(', ') || 'worker signals';
536
+ const suggested = capabilities.worker.suggestedCommand || 'none';
537
+ log.warn(color.yellow(`⚠️ Skipping the background worker: detection found ${evidence} but no Procfile worker process, and the suggested command ("${suggested}") needs interactive confirmation. Re-run init interactively to configure the worker command.`));
538
+ }
506
539
  if (target === 'lambda' && (procfile?.worker || capabilities.worker.detected)) {
507
540
  log.warn(color.yellow('⚠️ Skipping the background worker: Lambda targets run a single scale-to-zero function with no ECS worker service.'));
508
541
  }
@@ -547,14 +580,14 @@ async function mainStackMain(input = {}) {
547
580
  if (!isInteractive) {
548
581
  return failCommand({
549
582
  message: `\n✖ Refusing to wire the pre-deploy migration gate with "${migrationCmd}": the generated ${config.framework} Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" on every deploy.\n`,
550
- hint: ' Re-run with an explicit node-based command, e.g. `--setup-ci-migrate="node ./dist/migrate.cjs"`, or wire the gate later with `grada db migrate --cmd "node ./dist/migrate.cjs" --setup-ci`.\n',
583
+ hint: ' Re-run with an explicit node-based command, e.g. `--setup-ci-migrate="node ./dist/migrate.cjs"`, or wire the gate later with `grada db migrate --cmd "node ./dist/migrate.cjs" --setup-ci`. Ensure your Dockerfile builds the bundle and copies it into the runner image.\n',
551
584
  event: 'cli-error',
552
585
  telemetry: { step: 'init_setup', cmd_source: migrationCmdSource, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
553
586
  errorCode: 'NPM_CMD_STRIPPED_RUNNER',
554
587
  reason: 'npm-cmd-stripped-runner',
555
588
  });
556
589
  }
557
- console.log(color.yellow(`⚠️ The ${migrationCmdSource} migration command ("${migrationCmd}") starts with npm/npx but the generated ${config.framework} Dockerfile strips those binaries from the runner image — the gate will fail unless you switch to a node-based command (e.g. "node ./dist/migrate.cjs").`));
590
+ console.log(color.yellow(`⚠️ The ${migrationCmdSource} migration command ("${migrationCmd}") starts with npm/npx but the generated ${config.framework} Dockerfile strips those binaries from the runner image — the gate will fail unless you switch to a node-based command (e.g. "node ./dist/migrate.cjs"). Ensure your Dockerfile builds the bundle and copies it into the runner image.`));
558
591
  trackEvent('npm_cmd_stripped_runner', { projectName: dirConfig.actualProjectName, cmd_source: migrationCmdSource, ci_setup: true });
559
592
  }
560
593
 
@@ -680,6 +713,22 @@ async function mainStackMain(input = {}) {
680
713
  log.warn(color.yellow(`⚠️ vercel.json redirects were detected, but ${target === 'static' ? 'static' : 'Lambda'} targets have no ALB listener rules to translate them into. ${remedy}`));
681
714
  }
682
715
 
716
+ // Headers/rewrites have no translator on any target — name the dropped
717
+ // counts loudly, or the "Migrating edge network rules" success line
718
+ // reads as if everything migrated.
719
+ {
720
+ const migratedRedirects = (target === 'lambda' || target === 'static') ? 0 : (vercelRules?.redirects?.length || 0);
721
+ const droppedHeaders = vercelRules?.headers?.length || 0;
722
+ const droppedRewrites = vercelRules?.rewrites?.length || 0;
723
+ if (droppedHeaders > 0 || droppedRewrites > 0) {
724
+ const dropped = [
725
+ droppedHeaders > 0 ? `${droppedHeaders} header rule${droppedHeaders === 1 ? '' : 's'}` : null,
726
+ droppedRewrites > 0 ? `${droppedRewrites} rewrite${droppedRewrites === 1 ? '' : 's'}` : null,
727
+ ].filter(Boolean).join(' and ');
728
+ log.warn(color.yellow(`⚠️ vercel.json ${dropped} were detected but are not migrated (only redirects translate to ALB listener rules — ${migratedRedirects} migrated). Recreate them as CloudFront Functions or ALB listener rules after provisioning.`));
729
+ }
730
+ }
731
+
683
732
  if (config.framework === 'nestjs') {
684
733
  const nestAnalysis = analyzeNestApp(dirConfig.targetDir);
685
734
  if (nestAnalysis.hasMain && !nestAnalysis.listensOnAllInterfaces) {
@@ -871,9 +920,14 @@ async function mainStackMain(input = {}) {
871
920
  }
872
921
 
873
922
  if (driftEnabled) {
923
+ // drift.yml rides the manifest + backup like deploy.yml now
924
+ // (BUG-158): re-init backs the old file up and regenerates fresh
925
+ // (current role ARN) instead of silently keeping a stale copy.
926
+ // Hand edits trip refuse-dirty before this point; --force regenerates.
874
927
  const drifted = scaffoldDriftWorkflow(dirConfig.targetDir, {
875
928
  region: config.region,
876
929
  roleArn: `arn:aws:iam::${awsAccountId}:role/${dirConfig.actualProjectName}${resourceSuffix}-github-actions-role`,
930
+ force: initOptions.force,
877
931
  });
878
932
  if (drifted.ok) {
879
933
  console.log(color.green('✅ Scaffolded .github/workflows/drift.yml (scheduled IaC drift detection)'));
@@ -1033,7 +1087,9 @@ async function mainStackMain(input = {}) {
1033
1087
  if (upcoming.vector) {
1034
1088
  console.log(color.dim(' 💡 Vector-search dependencies detected: managed pgvector support is coming soon.'));
1035
1089
  }
1036
- if (upcoming.cron) {
1090
+ // Static targets refuse `add cron` (no compute) — don't send
1091
+ // static users down a dead end (BUG-157).
1092
+ if (upcoming.cron && target !== 'static') {
1037
1093
  console.log(color.dim(' 💡 Scheduled-task dependencies detected: scaffold a schedule with "grada add cron".'));
1038
1094
  }
1039
1095
  if (upcoming.mysql) {
@@ -1065,7 +1121,17 @@ async function mainStackMain(input = {}) {
1065
1121
  if (offlineScaffold) {
1066
1122
  // Pass the exact backend bucket (suffix included) — recomputing
1067
1123
  // from the bare project name prints a bucket terraform never uses.
1068
- printOfflineChecklist({ bucket: stateBucketName, region: config.region });
1124
+ // Step 2 names only emitted workflows: preview/teardown render
1125
+ // with PR previews, drift only when enabled.
1126
+ printOfflineChecklist({
1127
+ bucket: stateBucketName,
1128
+ region: config.region,
1129
+ workflows: [
1130
+ 'deploy',
1131
+ ...(config.enablePrPreviews ? ['preview', 'teardown'] : []),
1132
+ ...(driftEnabled ? ['drift'] : []),
1133
+ ],
1134
+ });
1069
1135
  }
1070
1136
 
1071
1137
  await flushTelemetry();
@@ -238,7 +238,9 @@ async function runLogsMain(input = {}) {
238
238
  });
239
239
  }
240
240
 
241
- const sinceRaw = options.since ?? options.sinceDuration ?? (follow ? undefined : DEFAULT_SINCE);
241
+ // Follow defaults to the same bounded window: an unbounded initial
242
+ // scan walks every page of history before printing the live edge.
243
+ const sinceRaw = options.since ?? options.sinceDuration ?? DEFAULT_SINCE;
242
244
  const startTime = sinceRaw === undefined ? undefined : Date.now() - parseSinceDuration(sinceRaw);
243
245
 
244
246
  const pollIntervalMs = options.pollIntervalMs ?? FOLLOW_POLL_INTERVAL_MS;
@@ -8,6 +8,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
8
8
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
9
9
  import { z } from 'zod';
10
10
  import { getCliVersion, trackSuccess, setActiveCommandName, resetActiveCommandName, rotateRunId } from '../core/telemetry.js';
11
+ import { atomicWriteFileSync } from '../utils/atomic-write.js';
11
12
  import { safeHomedir } from '../core/homedir.js';
12
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
14
  import { failCommand, refuseUnknownFlags } from '../utils/command.js';
@@ -629,7 +630,7 @@ export function installMcpConfig(editor, { homeDir = safeHomedir(), platform = o
629
630
  }
630
631
  try {
631
632
  fsSync.mkdirSync(path.dirname(target.path), { recursive: true });
632
- fsSync.writeFileSync(
633
+ atomicWriteFileSync(
633
634
  target.path,
634
635
  `${JSON.stringify({ ...existing, [target.key]: { ...servers, grada: { ...MCP_SERVER_CONFIG, args: [...MCP_SERVER_CONFIG.args] } } }, null, 4)}\n`,
635
636
  'utf-8'