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
package/bin/cli.js CHANGED
@@ -48,7 +48,7 @@ const HELP_TEXT = [
48
48
  ' db migrate Run database migrations in a one-off ECS task (--cmd, --task-def, --timeout, --setup-ci)',
49
49
  ' db backup Create an RDS snapshot checkpoint (--id, --timeout, --no-wait)',
50
50
  ' db restore Restore the database from a snapshot ([snapshot-id], --yes)',
51
- ' gc Discover and delete orphaned ECR images, log groups, and Elastic IPs (--region, --deep, --yes)',
51
+ ' gc Discover and delete orphaned ECR images, log groups, Elastic IPs, and old manual DB snapshots (--region, --deep, --yes, --snapshot-max-age-days)',
52
52
  ' sleep [env] Scale ECS services to zero and stop RDS to save costs (--skip-db, --yes, --strict)',
53
53
  ' wake [env] Start RDS and restore ECS desired counts (--skip-db, --no-wait, --strict)',
54
54
  ' drift Detect Terraform drift locally or scaffold scheduled checks (--setup)',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.42.0",
3
+ "version": "0.43.1",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'url';
5
5
  import color from 'picocolors';
6
6
  import { intro, outro, select, text, spinner, log, cancel, isCancel } from '@clack/prompts';
7
7
  import { trackEvent, flushTelemetry, trackSuccess, isActiveEnvValue, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
- import { resolveRegion, resolveProjectName, resolveCwd, readFileSafe, detectComputeTargetFromMainTf, readTerraformComputeTarget, guardComputeTarget } from '../utils/resolvers.js';
8
+ import { resolveRegion, resolveProjectName, resolveAppName, resolveCwd, readFileSafe, readResourceSuffix, detectComputeTargetFromMainTf, readTerraformComputeTarget, guardComputeTarget } from '../utils/resolvers.js';
9
9
  import { resolveDbEngineRefs, buildDbEntries, convertDatabaseTfForLambda, addRandomProvider } from '../utils/generator.js';
10
10
  import { ADDON_REGISTRY, ADDON_UPSERT_KEYS, resolveAddonEnvVars, addonTargetDisposition, addonSupportedTargets } from '../utils/addons.js';
11
11
  import { stripTerraformMetadata, readEjectedMarker } from '../utils/terraform-metadata.js';
@@ -42,7 +42,9 @@ export const CUSTOM_MODEL_VALUE = '__custom__';
42
42
  // EventBridge Scheduler expressions (`cron(...)`, `rate(...)`, `at(...)`)
43
43
  // plus safe IANA timezone characters. Single schedule per project: `--name`
44
44
  // customizes it, `--force` replaces it in place.
45
- export const CRON_SCHEDULE_RE = /^(cron|rate|at)\(.+\)$/;
45
+ // The expression renders raw inside quoted HCL, so `"` and control
46
+ // characters are rejected here — never escaped downstream.
47
+ export const CRON_SCHEDULE_RE = /^(cron|rate|at)\([^"\x00-\x1f\x7f]+\)$/;
46
48
  export const CRON_TIMEZONE_RE = /^[A-Za-z0-9/_+-]{1,64}$/;
47
49
  export const CRON_CUSTOM_VALUE = '__custom__';
48
50
  export const DEFAULT_CRON_SCHEDULE = 'cron(0 0 * * ? *)';
@@ -493,6 +495,63 @@ export function upsertManagedEnvNames(tfContent, names = []) {
493
495
  return content.replace(match[0], `managed_env_names = [${merged.map((name) => JSON.stringify(name)).join(', ')}]`);
494
496
  }
495
497
 
498
+ // Removes names from the `managed_env_names` collision-guard list,
499
+ // preserving the surviving order. Returns content unchanged when the
500
+ // block is absent or no name matched.
501
+ export function removeManagedEnvNames(tfContent, names = []) {
502
+ const content = String(tfContent ?? '');
503
+ const match = /managed_env_names\s*=\s*\[([^\]]*)\]/.exec(content);
504
+ if (!match) return content;
505
+ const remove = new Set(names);
506
+ const existing = [...match[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]);
507
+ const kept = existing.filter((name) => !remove.has(name));
508
+ if (kept.length === existing.length) return content;
509
+ return content.replace(match[0], `managed_env_names = [${kept.map((name) => JSON.stringify(name)).join(', ')}]`);
510
+ }
511
+
512
+ // Removes one `{ name = "<name>", value = ... }` entry from the first
513
+ // `environment = [...]` array of `aws_ecs_task_definition."<taskName>"`,
514
+ // repairing the surrounding separators (`, ,`, dangling edge commas,
515
+ // orphaned blank lines) so the array stays valid. Returns the content
516
+ // unchanged when the resource, array, or entry cannot be found.
517
+ export function removeContainerEnvVar(tfContent, name, taskDefinitionName = 'app') {
518
+ if (typeof taskDefinitionName === 'object' && taskDefinitionName !== null) {
519
+ taskDefinitionName = taskDefinitionName.taskDefinitionName || 'app';
520
+ }
521
+ const content = String(tfContent ?? '');
522
+ const bounds = findEnvBlockBounds(content, taskDefinitionName || 'app');
523
+ if (!bounds) return content;
524
+ const block = content.slice(bounds.openIdx, bounds.closeIdx + 1);
525
+ const namePattern = new RegExp(`(?:"name"|name)\\s*[:=]\\s*"${escapeRegExp(name)}"`);
526
+ const nameMatch = namePattern.exec(block);
527
+ if (!nameMatch) return content;
528
+ const objBounds = enclosingBraceBounds(block, nameMatch.index);
529
+ if (!objBounds) return content;
530
+ const updated = (block.slice(0, objBounds.openIdx) + block.slice(objBounds.closeIdx + 1))
531
+ .replace(/,\s*,/g, ',')
532
+ .replace(/\[\s*,/g, '[')
533
+ .replace(/,\s*\]/g, ']')
534
+ .replace(/\n[ \t]*\n/g, '\n');
535
+ return content.slice(0, bounds.openIdx) + updated + content.slice(bounds.closeIdx + 1);
536
+ }
537
+
538
+ // Removes one `NAME = ...` line from the `variables = {...}` map of
539
+ // `aws_lambda_function."app"`, realigning the surviving run so
540
+ // `terraform fmt` stays clean. Returns the content unchanged when the
541
+ // resource, map, or entry cannot be found.
542
+ export function removeLambdaEnvVar(tfContent, name) {
543
+ const content = String(tfContent ?? '');
544
+ if (!/^[A-Za-z0-9_]+$/.test(String(name))) return content;
545
+ const bounds = findLambdaVariablesBounds(content);
546
+ if (!bounds) return content;
547
+ const linePattern = new RegExp(`^[^\\n]*?\\b${escapeRegExp(name)}\\s*=[^\\n]*\\n?`, 'm');
548
+ const mapBlock = content.slice(bounds.openIdx, bounds.closeIdx + 1);
549
+ if (!linePattern.test(mapBlock)) return content;
550
+ return content.slice(0, bounds.openIdx + 1)
551
+ + realignAssignmentRuns(content.slice(bounds.openIdx + 1, bounds.closeIdx).replace(linePattern, ''))
552
+ + content.slice(bounds.closeIdx);
553
+ }
554
+
496
555
  // Idempotently appends the isolated-subnet block to network.tf content.
497
556
  // Returns the content unchanged when the block already exists. Uses the
498
557
  // line-anchored lookup so a `#` comment quoting the header never
@@ -646,11 +705,15 @@ export function renderWorkerAutoscalingBlock(hasWorker) {
646
705
  // no-ops, so callers pass the full maps unconditionally.
647
706
  function renderAddonTemplate(templateContent, templateVars = {}, conditionalBlocks = {}) {
648
707
  let rendered = String(templateContent ?? '');
708
+ // Replacement FUNCTIONS (not strings): `$` patterns in values (cron
709
+ // commands, ARNs) land byte-identical (BUG-156).
649
710
  for (const [key, value] of Object.entries(templateVars)) {
650
- rendered = rendered.replaceAll(`{{${key}}}`, value ?? '');
711
+ const literal = String(value ?? '');
712
+ rendered = rendered.replaceAll(`{{${key}}}`, () => literal);
651
713
  }
652
714
  for (const [key, value] of Object.entries(conditionalBlocks)) {
653
- rendered = rendered.replaceAll(`{{${key}}}`, value ?? '');
715
+ const literal = String(value ?? '');
716
+ rendered = rendered.replaceAll(`{{${key}}}`, () => literal);
654
717
  }
655
718
  return rendered;
656
719
  }
@@ -1179,14 +1242,19 @@ export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
1179
1242
  hint: ' Use a lowercase slug with letters, numbers, and hyphens (e.g. --name nightly-cleanup).\n',
1180
1243
  };
1181
1244
  }
1182
- const scheduleName = `${resolveProjectName(opts, cwd)}-cron-${name}`;
1245
+ // The rendered schedule name is `${local.app_name}-cron-<name>`
1246
+ // where app_name carries the workspace env_suffix AND the
1247
+ // always-present resource suffix — validate the rendered length,
1248
+ // not the bare base, or apply-time EventBridge rejects it.
1249
+ const appName = resolveAppName(resolveProjectName(opts, cwd), opts.workspace, cwd);
1250
+ const scheduleName = `${appName}${readResourceSuffix(cwd)}-cron-${name}`;
1183
1251
  if (scheduleName.length > MAX_SCHEDULE_NAME_LENGTH) {
1184
1252
  return {
1185
1253
  ok: false,
1186
1254
  errorCode: 'INVALID_CRON_NAME',
1187
1255
  reason: 'invalid-cron-name',
1188
- message: `\nāœ– Schedule name "${scheduleName}" exceeds the ${MAX_SCHEDULE_NAME_LENGTH}-character EventBridge Scheduler limit.`,
1189
- hint: ' Use a shorter --name (PR-preview workspaces add a suffix on top).\n',
1256
+ message: `\nāœ– Schedule name "${scheduleName}" (${scheduleName.length} chars) exceeds the ${MAX_SCHEDULE_NAME_LENGTH}-character EventBridge Scheduler limit.`,
1257
+ hint: ' Use a shorter --name (PR-preview workspaces and the stack resource suffix count toward the limit).\n',
1190
1258
  };
1191
1259
  }
1192
1260
 
@@ -1570,17 +1638,28 @@ async function scaffoldDatabaseInner(engine, projectDir, refs) {
1570
1638
  } else {
1571
1639
  updated = upsertManagedEnvNames(updated, [...env.map((entry) => entry.name), ...secrets.map((entry) => entry.name)]);
1572
1640
  }
1641
+ // Switches TO postgres must also remove DB_ENGINE: the new entry set
1642
+ // has no such key, so add-only injection would leave the stale
1643
+ // aurora/mysql value (plus its guard-list entry) behind.
1644
+ if (refs.engine === 'postgres') {
1645
+ updated = isLambda
1646
+ ? removeLambdaEnvVar(updated, 'DB_ENGINE')
1647
+ : removeManagedEnvNames(removeContainerEnvVar(updated, 'DB_ENGINE', 'app'), ['DB_ENGINE']);
1648
+ }
1573
1649
  const envInjected = updated !== mainTfContent;
1574
1650
  if (envInjected) await atomicWriteFile(mainTfPath, normalizeBlankLines(updated));
1575
1651
 
1576
1652
  let workerEnvInjected = false;
1577
1653
  if (!isLambda && fsSync.existsSync(workerTfPath)) {
1578
1654
  const workerTfContent = await fs.readFile(workerTfPath, 'utf-8');
1579
- const updatedWorker = injectContainerSecrets(
1655
+ let updatedWorker = injectContainerSecrets(
1580
1656
  injectContainerEnvVars(workerTfContent, env, 'worker', injectOptions),
1581
1657
  secrets,
1582
1658
  'worker'
1583
1659
  );
1660
+ if (refs.engine === 'postgres') {
1661
+ updatedWorker = removeContainerEnvVar(updatedWorker, 'DB_ENGINE', 'worker');
1662
+ }
1584
1663
  workerEnvInjected = updatedWorker !== workerTfContent;
1585
1664
  if (workerEnvInjected) await atomicWriteFile(workerTfPath, normalizeBlankLines(updatedWorker));
1586
1665
  }
@@ -1670,7 +1749,7 @@ export async function runAddDatabase({ cwd, projectName, region, force = false,
1670
1749
  if (guarded.guardFailed === 'referenced') {
1671
1750
  return failCommand({
1672
1751
  noExit,
1673
- message: '\n⚠ main.tf already references a Postgres database. Pass --force to overwrite.\n',
1752
+ message: '\n⚠ main.tf already references a relational database. Pass --force to overwrite.\n',
1674
1753
  tone: 'yellow',
1675
1754
  event: 'add_run',
1676
1755
  telemetry: { projectName, capability, error_code: 'DB_ALREADY_REFERENCED' },
@@ -1753,9 +1832,12 @@ async function scaffoldAddonInner(capability, resolvedOpts, { cwd, region } = {}
1753
1832
  // provisioning when the project was generated without a database.
1754
1833
  const withVpc = capability === 'db:redis' ? ensureLambdaVpcConfig(updated) : updated;
1755
1834
  const withManaged = isLambda ? withVpc : upsertManagedEnvNames(withVpc, envVars.map((entry) => entry.name));
1756
- const envInjected = withManaged !== mainTfContent;
1835
+ // The write gate covers the guard list too, but envInjected (the
1836
+ // banner flag) tracks injection only — a guard-list-only or VPC-only
1837
+ // update must not claim container env injection.
1838
+ const envInjected = updated !== mainTfContent;
1757
1839
  const vpcInjected = withVpc !== updated;
1758
- if (envInjected) {
1840
+ if (withManaged !== mainTfContent) {
1759
1841
  await atomicWriteFile(mainTfPath, normalizeBlankLines(withManaged));
1760
1842
  }
1761
1843
 
@@ -7,9 +7,31 @@ import { failCommand, failProjectNotInitialized, refuseIfNonInteractive, refuseU
7
7
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
8
8
  import { resolveRegion, resolveProjectName, resolveCwd, resolveHeadless, readFileSafe, readTerraformComputeTarget } from '../utils/resolvers.js';
9
9
  import { findNestedBlock } from '../utils/hcl.js';
10
+ import { atomicWriteFile, atomicWriteFileSync } from '../utils/atomic-write.js';
11
+ import { withProjectLock } from '../utils/file-lock.js';
10
12
  import { ensureUsEast1Provider } from './domain.js';
11
13
 
12
14
  export const ALERTS_TF_FILE = path.join('terraform', 'alerts.tf');
15
+ // data.archive_file materializes the forwarder zip at apply time; it is
16
+ // build output and must never be committed.
17
+ export const FORWARDER_ZIP_GITIGNORE_ENTRY = 'terraform/.grada-alerts-forwarder.zip';
18
+
19
+ // Appends the forwarder-zip ignore entry idempotently (atomically).
20
+ // Returns true when the file changed. Covered by the alerts command
21
+ // tests.
22
+ export async function ensureForwarderZipIgnored(cwd) {
23
+ const gitignorePath = path.join(cwd, '.gitignore');
24
+ let content = '';
25
+ try {
26
+ content = fsSync.readFileSync(gitignorePath, 'utf8');
27
+ } catch {
28
+ content = '';
29
+ }
30
+ if (content.split('\n').some((line) => line.trim() === FORWARDER_ZIP_GITIGNORE_ENTRY)) return false;
31
+ const suffix = content === '' || content.endsWith('\n') ? '' : '\n';
32
+ await atomicWriteFile(gitignorePath, `${content}${suffix}${FORWARDER_ZIP_GITIGNORE_ENTRY}\n`);
33
+ return true;
34
+ }
13
35
 
14
36
  // Per-target alarm defaults: { threshold, evaluationPeriods, period }.
15
37
  // ECS mirrors the dashboard alarm in templates/terraform/main.tf
@@ -164,10 +186,10 @@ exports.handler = async (event) => {
164
186
  export function buildAlertsTf({ projectName, target = 'ecs', email, webhook, threshold }) {
165
187
  const defaults = ALERT_TARGET_DEFAULTS[target] || ALERT_TARGET_DEFAULTS.ecs;
166
188
  const limit = threshold ?? defaults.threshold;
167
- // ECS keeps the historical flat naming (existing topic/alarm names
168
- // are unchanged); lambda/static use the workspace-aware local for
169
- // preview isolation.
170
- const namePrefix = target === 'ecs' ? projectName : '${local.app_name}';
189
+ // All targets use the workspace-aware local: flat ECS names let a
190
+ // preview apply clobber the prod alarm (BUG-132). Existing trees
191
+ // migrate on the next `grada alerts` + apply (topic/alarm recreate).
192
+ const namePrefix = '${local.app_name}';
171
193
  const aliasLine = target === 'static' ? ' provider = aws.us_east_1\n' : '';
172
194
 
173
195
  const destinations = [];
@@ -350,7 +372,7 @@ export function ensureArchiveProvider(backendTfPath) {
350
372
  const closingIndent = /(\n[ \t]*)$/.exec(head)?.[1] ?? '\n';
351
373
  const entry = ' archive = {\n source = "hashicorp/archive"\n version = "~> 2.0"\n }\n';
352
374
  const updated = `${head.replace(/\s+$/, '\n')}${entry}${closingIndent.slice(1)}${content.slice(bounds.closeIdx)}`;
353
- fsSync.writeFileSync(backendTfPath, updated);
375
+ atomicWriteFileSync(backendTfPath, updated);
354
376
  return true;
355
377
  }
356
378
 
@@ -517,34 +539,48 @@ async function runAlertsMain(input = {}) {
517
539
  }
518
540
  }
519
541
 
542
+ // Mutations (main.tf, backend.tf, alerts.tf, .gitignore) run under
543
+ // the terraform project lock like every other scaffolding family —
544
+ // the exists-check rides along so concurrent scaffolds cannot both
545
+ // pass it and interleave the read-modify-write helpers.
520
546
  const alertsPath = path.join(cwd, ALERTS_TF_FILE);
521
- if (fsSync.existsSync(alertsPath) && !force) {
522
- return failCommand({
523
- message: `\n⚠ ${ALERTS_TF_FILE} already exists. Pass --force to overwrite.\n`,
524
- tone: 'yellow',
525
- event: 'alerts_run',
526
- telemetry: { projectName, error_code: 'ALERTS_FILE_EXISTS' },
527
- reason: 'alerts-file-exists',
528
- resultExtra: { projectName, region },
529
- exitCode: null,
530
- });
531
- }
547
+ const scaffolded = await withProjectLock(cwd, async () => {
548
+ if (fsSync.existsSync(alertsPath) && !force) {
549
+ return {
550
+ refused: failCommand({
551
+ message: `\n⚠ ${ALERTS_TF_FILE} already exists. Pass --force to overwrite.\n`,
552
+ tone: 'yellow',
553
+ event: 'alerts_run',
554
+ telemetry: { projectName, error_code: 'ALERTS_FILE_EXISTS' },
555
+ reason: 'alerts-file-exists',
556
+ resultExtra: { projectName, region },
557
+ exitCode: null,
558
+ }),
559
+ };
560
+ }
532
561
 
533
- // Static alarms + topics must live in us-east-1 (CloudFront metrics
534
- // are only visible there); ensure main.tf declares the alias the
535
- // generated file references. No-op when already present.
536
- let aliasAdded = false;
537
- if (target === 'static') {
538
- aliasAdded = ensureUsEast1Provider(path.join(cwd, 'terraform', 'main.tf'));
539
- }
540
- // The forwarder's data.archive_file needs its provider pinned next
541
- // to the aws one (required_providers may only appear once).
542
- let archiveAdded = false;
543
- if (webhook) {
544
- archiveAdded = ensureArchiveProvider(path.join(cwd, 'terraform', 'backend.tf'));
545
- }
562
+ // Static alarms + topics must live in us-east-1 (CloudFront metrics
563
+ // are only visible there); ensure main.tf declares the alias the
564
+ // generated file references. No-op when already present.
565
+ let aliasAdded = false;
566
+ if (target === 'static') {
567
+ aliasAdded = ensureUsEast1Provider(path.join(cwd, 'terraform', 'main.tf'));
568
+ }
569
+ // The forwarder's data.archive_file needs its provider pinned next
570
+ // to the aws one (required_providers may only appear once).
571
+ let archiveAdded = false;
572
+ if (webhook) {
573
+ archiveAdded = ensureArchiveProvider(path.join(cwd, 'terraform', 'backend.tf'));
574
+ }
546
575
 
547
- fsSync.writeFileSync(alertsPath, buildAlertsTf({ projectName, target, email, webhook, threshold }));
576
+ await atomicWriteFile(alertsPath, buildAlertsTf({ projectName, target, email, webhook, threshold }));
577
+ if (webhook) {
578
+ await ensureForwarderZipIgnored(cwd);
579
+ }
580
+ return { aliasAdded, archiveAdded };
581
+ }, { scope: 'terraform' });
582
+ if (scaffolded.refused) return scaffolded.refused;
583
+ const { aliasAdded, archiveAdded } = scaffolded;
548
584
  const destinations = email && webhook ? 'both' : webhook ? 'webhook' : email ? 'email' : 'manual';
549
585
  const kind = webhook ? detectWebhookKind(webhook) : undefined;
550
586
  console.log(color.green(`\nāœ… Created ${ALERTS_TF_FILE} (SNS topic + ${target} notify alarm${webhook ? ' + chat forwarder' : ''}).`));
@@ -125,13 +125,51 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
125
125
  return { proceed: false, result: { ok: false, reason: 'cancelled' } };
126
126
  }
127
127
  }
128
- for (const file of files) {
129
- const abs = path.join(targetDir, file);
130
- fs.writeFileSync(abs, fs.readFileSync(abs, 'utf8').split(PLACEHOLDER_ACCOUNT_ID).join(accountId));
128
+ // Pre-validate everything before stamping anything: a missing or
129
+ // bucket-less backend.tf must fail BEFORE the first placeholder is
130
+ // rewritten, or the tree is left half-stamped with a raw throw.
131
+ const failBackendInvalid = async (message, hint = ' Restore terraform/backend.tf from version control and re-run apply.\n') => ({
132
+ proceed: false,
133
+ result: await failCommand({
134
+ noExit: isProgrammaticCall(options),
135
+ message,
136
+ hint,
137
+ event: 'infrastructure_applied',
138
+ telemetry: { projectName },
139
+ errorCode: 'RECONCILE_BACKEND_INVALID',
140
+ reason: 'reconcile-backend-invalid',
141
+ }),
142
+ });
143
+ let backend;
144
+ try {
145
+ backend = fs.readFileSync(path.join(targetDir, 'terraform', 'backend.tf'), 'utf8');
146
+ } catch (error) {
147
+ return failBackendInvalid(`\nāœ– Cannot reconcile: terraform/backend.tf is unreadable (${error?.message ?? error}). Nothing was rewritten.\n`);
148
+ }
149
+ const parsedBackend = parseStateBucketBackend(backend);
150
+ const backendRegion = parsedBackend.region;
151
+ // The bucket may still carry the placeholder (we now read before
152
+ // stamping): resolve it to the account being reconciled with.
153
+ const bucket = parsedBackend.bucket ? parsedBackend.bucket.split(PLACEHOLDER_ACCOUNT_ID).join(accountId) : null;
154
+ if (!bucket) {
155
+ return failBackendInvalid('\nāœ– Cannot reconcile: terraform/backend.tf has no state bucket. Nothing was rewritten.\n');
156
+ }
157
+ let staged;
158
+ try {
159
+ staged = files.map((file) => {
160
+ const abs = path.join(targetDir, file);
161
+ return { abs, content: fs.readFileSync(abs, 'utf8').split(PLACEHOLDER_ACCOUNT_ID).join(accountId) };
162
+ });
163
+ } catch (error) {
164
+ return failBackendInvalid(
165
+ `\nāœ– Cannot reconcile: a placeholder file is unreadable (${error?.message ?? error}). Nothing was rewritten.\n`,
166
+ ' Restore the tree from version control and re-run apply.\n'
167
+ );
168
+ }
169
+ for (const { abs, content } of staged) {
170
+ fs.writeFileSync(abs, content);
131
171
  }
132
172
  log.message(color.green(`Rewrote ${files.length} file(s).`));
133
- const backend = fs.readFileSync(path.join(targetDir, 'terraform', 'backend.tf'), 'utf8');
134
- const { bucket, region: backendRegion } = parseStateBucketBackend(backend);
135
173
  let ensured;
136
174
  try {
137
175
  ensured = await ensureStateBucketExists({
@@ -476,8 +514,13 @@ async function applyStackMain(input = {}) {
476
514
  ? ' 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
515
  : ' Re-push your secrets to regenerate it: npx grada-run secrets push .env\n',
478
516
  event: 'infrastructure_applied',
479
- telemetry: { projectName: path.basename(targetDir), collision_count: secretPreflight.keys.length },
480
- errorCode: 'SECRETS_ENV_COLLISION',
517
+ // A malformed keys file is not a collision: it gets its own
518
+ // code and no collision_count (0 would lie).
519
+ telemetry: {
520
+ projectName: path.basename(targetDir),
521
+ ...(isCollision ? { collision_count: secretPreflight.keys.length } : {}),
522
+ },
523
+ errorCode: isCollision ? 'SECRETS_ENV_COLLISION' : 'MALFORMED_KEYS_FILE',
481
524
  reason: isCollision ? 'secrets-env-collision' : 'malformed-keys-file',
482
525
  });
483
526
  }
@@ -613,7 +656,10 @@ async function applyStackMain(input = {}) {
613
656
  });
614
657
  }
615
658
  if (outputsCheck.missing.length > 0 || outputsCheck.empty) {
616
- console.log(color.yellow(`⚠ Partial outputs: expected [${expectedList}] for ${diskTarget}, got ${gotList} — proceeding; pass --allow-partial-outputs to silence this.`));
659
+ const tail = allowPartialOutputs
660
+ ? 'proceeding per --allow-partial-outputs.'
661
+ : 'proceeding; pass --allow-partial-outputs to silence this.';
662
+ console.log(color.yellow(`⚠ Partial outputs: expected [${expectedList}] for ${diskTarget}, got ${gotList} — ${tail}`));
617
663
  }
618
664
 
619
665
  const cfUrl = outputs.cloudfront_url?.value;
@@ -623,8 +669,17 @@ async function applyStackMain(input = {}) {
623
669
 
624
670
  let finalMessage = color.green('āœ… Infrastructure is live!');
625
671
  if (cfUrl) finalMessage += `\n šŸŒ App URL: ${color.cyan(cfUrl)} ${color.dim('(global CDN — share this link)')}`;
626
- if (albUrl) finalMessage += `\n 🚦 Direct URL: ${color.gray(albUrl)} ${color.dim('(bypasses the CDN — for debugging)')}`;
627
- if (apiUrl) finalMessage += `\n šŸ”Œ API URL: ${color.gray(apiUrl)} ${color.dim('(bypasses the CDN — for debugging)')}`;
672
+ // The origin only answers CloudFront (listener rule 403s direct
673
+ // hits without the origin-secret header) — label the URL as
674
+ // unreachable instead of a working bypass (BUG-136).
675
+ if (albUrl) finalMessage += `\n 🚦 Direct URL: ${color.gray(albUrl)} ${color.dim('(CloudFront-only origin — direct hits 403)')}`;
676
+ // Lambda stacks have no CDN: without a CloudFront URL the API
677
+ // URL is the primary link, not a debug bypass.
678
+ if (apiUrl) {
679
+ finalMessage += cfUrl
680
+ ? `\n šŸ”Œ API URL: ${color.gray(apiUrl)} ${color.dim('(bypasses the CDN — for debugging)')}`
681
+ : `\n šŸ”Œ API URL: ${color.cyan(apiUrl)} ${color.dim('(share this link)')}`;
682
+ }
628
683
  if (siteUrl) finalMessage += `\n šŸŒ Site URL: ${color.cyan(siteUrl)} ${color.dim('(global CDN — share this link)')}`;
629
684
 
630
685
  outro(`${finalMessage}\n\n ${color.yellow('Push code to deploy your app and clear the 503 error:')}\n ${color.cyan('git add . && git commit -m "ci: infra" && git push origin main')}`);
@@ -5,7 +5,7 @@ import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../.
5
5
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../../utils/command.js';
6
6
  import { parseFlags, normalizeOptions, normalizeArgv } from '../../utils/args.js';
7
7
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/aws.js';
8
- import { resolveRegion, resolveProjectName, resolveAppName, resolveCwd } from '../../utils/resolvers.js';
8
+ import { resolveRegion, resolveProjectName, resolveCwd } from '../../utils/resolvers.js';
9
9
  import { findDbTarget, generateSnapshotId, isValidSnapshotId, resolveDbIdentifier, resolveDbClusterIdentifier } from '../../utils/rds.js';
10
10
  import { pollUntil, parseTimeoutSeconds } from '../../utils/system.js';
11
11
  import { truncateSpinnerText } from '../../utils/spinner-text.js';
@@ -64,7 +64,6 @@ async function runDbBackupMain(input = {}) {
64
64
  cwd = resolveCwd(options);
65
65
  region = resolveRegion(options, cwd);
66
66
  projectName = resolveProjectName(options, cwd);
67
- const appName = resolveAppName(projectName, options.workspace, cwd);
68
67
  dbIdentifier = resolveDbIdentifier({ ...options, projectName }, cwd);
69
68
  dbClusterIdentifier = resolveDbClusterIdentifier({ ...options, projectName }, cwd);
70
69
  } catch {
@@ -271,14 +271,18 @@ async function runDbConnectMain(input = {}) {
271
271
  region,
272
272
  });
273
273
 
274
- const { code } = await new Promise((resolve) => {
274
+ // Node reports signal death as code null — a killed tunnel is a
275
+ // failure naming the signal, never `?? 0` success (BUG-149).
276
+ const { code, signal } = await new Promise((resolve) => {
275
277
  const child = spawnImpl('aws', ssmArgs, { stdio: 'inherit' });
276
278
  child.on('error', (err) => {
277
279
  console.log(color.red(`\nāœ– Failed to start AWS CLI: ${err?.message || err}`));
278
280
  console.log(color.dim(`Install help: ${AWS_CLI_INSTALL_URL}`));
279
281
  resolve({ code: 1 });
280
282
  });
281
- child.on('close', (code) => resolve({ code: code ?? 0 }));
283
+ child.on('close', (closeCode, closeSignal) => resolve(closeSignal
284
+ ? { code: 1, signal: closeSignal }
285
+ : { code: closeCode ?? 0 }));
282
286
  });
283
287
 
284
288
  // Telemetry carries only non-sensitive fields. Credentials never leave this process
@@ -288,10 +292,12 @@ async function runDbConnectMain(input = {}) {
288
292
  if (code !== 0) {
289
293
  const tunnelCode = Number.isInteger(code) && code > 0 ? Math.min(code, 255) : 1;
290
294
  return failCommand({
291
- message: `\nāœ– Database tunnel exited with code ${code}.`,
295
+ message: signal
296
+ ? `\nāœ– Database tunnel was killed by ${signal}.`
297
+ : `\nāœ– Database tunnel exited with code ${code}.`,
292
298
  hint: ' If the connection failed, ensure the Session Manager plugin is installed and your AWS session is fresh.\n',
293
299
  event: 'db_connect_run',
294
- telemetry: { projectName, error_code: 'TUNNEL_EXIT_NONZERO', exit_code: tunnelCode },
300
+ telemetry: { projectName, error_code: 'TUNNEL_EXIT_NONZERO', exit_code: tunnelCode, ...(signal ? { signal } : {}) },
295
301
  reason: 'tunnel-exit-nonzero',
296
302
  resultExtra: { cluster, service, dbIdentifier, localPort, region },
297
303
  exitCode: tunnelCode,
@@ -3,7 +3,7 @@ import { CloudWatchLogsClient } from '@aws-sdk/client-cloudwatch-logs';
3
3
  import color from 'picocolors';
4
4
  import { intro, outro, spinner } from '@clack/prompts';
5
5
  import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../../core/telemetry.js';
6
- import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../../utils/command.js';
6
+ import { failCommand, failAwsError, failNamedContainerMissing, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../../utils/command.js';
7
7
  import { parseFlags, normalizeOptions, normalizeArgv } from '../../utils/args.js';
8
8
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/aws.js';
9
9
  import {
@@ -74,9 +74,9 @@ export function buildVectorExtensionCommand() {
74
74
  'if command -v psql >/dev/null 2>&1; then',
75
75
  ' psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "$VECTOR_SQL" -c "SELECT extversion FROM pg_extension WHERE extname = \'vector\';"',
76
76
  'elif command -v node >/dev/null 2>&1 && node -e "require.resolve(\'pg\')" >/dev/null 2>&1; then',
77
- ' node -e "const{Client}=require(\'pg\');(async()=>{const c=new Client({connectionString:process.env.DATABASE_URL,ssl:{rejectUnauthorized:false}});await c.connect();await c.query(\'CREATE EXTENSION IF NOT EXISTS vector\');const r=await c.query(\\"SELECT extversion FROM pg_extension WHERE extname=\'vector\'\\");console.log(\'pgvector extension version: \'+(r.rows[0]&&r.rows[0].extversion));await c.end();})().catch(e=>{console.error(e&&e.message||e);process.exit(1);})"',
77
+ ' node -e "const{Client}=require(\'pg\');(async()=>{const c=new Client({connectionString:process.env.DATABASE_URL,ssl:{rejectUnauthorized:false}});await c.connect();await c.query(\'CREATE EXTENSION IF NOT EXISTS vector\');const r=await c.query(\\"SELECT extversion FROM pg_extension WHERE extname=\'vector\'\\");console.log(\'pgvector extension version: \'+(r.rows[0]&&r.rows[0].extversion));await c.end();})().catch(e=>{console.error(e&&e.stack||e);process.exit(1);})"',
78
78
  'elif command -v node >/dev/null 2>&1 && node -e "require.resolve(\'@prisma/client\')" >/dev/null 2>&1; then',
79
- ' node -e "const{PrismaClient}=require(\'@prisma/client\');(async()=>{let U=process.env.DATABASE_URL;if(!/[?&]sslmode=/i.test(U))U+=U.includes(\'?\')?\'&sslmode=require\':\'?sslmode=require\';process.env.DATABASE_URL=U;const p=new PrismaClient();await p.\\$executeRawUnsafe(\'CREATE EXTENSION IF NOT EXISTS vector\');const r=await p.\\$queryRawUnsafe(\\"SELECT extversion FROM pg_extension WHERE extname=\'vector\'\\");console.log(\'pgvector extension ready: \'+JSON.stringify(r));await p.\\$disconnect();})().catch(e=>{console.error(e&&e.message||e);process.exit(1);})"',
79
+ ' node -e "const{PrismaClient}=require(\'@prisma/client\');(async()=>{let U=process.env.DATABASE_URL;if(!/[?&]sslmode=/i.test(U))U+=U.includes(\'?\')?\'&sslmode=require\':\'?sslmode=require\';process.env.DATABASE_URL=U;const p=new PrismaClient();await p.\\$executeRawUnsafe(\'CREATE EXTENSION IF NOT EXISTS vector\');const r=await p.\\$queryRawUnsafe(\\"SELECT extversion FROM pg_extension WHERE extname=\'vector\'\\");console.log(\'pgvector extension ready: \'+JSON.stringify(r));await p.\\$disconnect();})().catch(e=>{console.error(e&&e.stack||e);process.exit(1);})"',
80
80
  'elif [ -n "$PYBIN" ] && "$PYBIN" -c "import psycopg" >/dev/null 2>&1; then',
81
81
  ' "$PYBIN" -c "import os,psycopg;c=psycopg.connect(os.environ[\'DATABASE_URL\'],autocommit=True);c.execute(\'CREATE EXTENSION IF NOT EXISTS vector\');print(\'pgvector extension version:\',c.execute(\\"SELECT extversion FROM pg_extension WHERE extname=\'vector\'\\").fetchone()[0])"',
82
82
  'elif [ -n "$PYBIN" ] && "$PYBIN" -c "import psycopg2" >/dev/null 2>&1; then',
@@ -101,7 +101,10 @@ function detectDatabaseEngine(cwd) {
101
101
  const databaseTf = path.join(cwd, 'terraform', 'database.tf');
102
102
  if (!fsSync.existsSync(databaseTf)) return { present: false, engine: 'unknown' };
103
103
  const hcl = fsSync.readFileSync(databaseTf, 'utf8');
104
- if (hcl.includes('resource "aws_rds_cluster"')) return { present: true, engine: 'aurora-postgresql' };
104
+ if (hcl.includes('resource "aws_rds_cluster"')) {
105
+ if (/engine\s*=\s*"aurora-mysql"/.test(hcl)) return { present: true, engine: 'aurora-mysql' };
106
+ return { present: true, engine: 'aurora-postgresql' };
107
+ }
105
108
  if (/engine\s*=\s*"mysql"/.test(hcl)) return { present: true, engine: 'mysql' };
106
109
  return { present: true, engine: 'postgres' };
107
110
  } catch {
@@ -185,9 +188,10 @@ async function runDbEnableVectorMain(input = {}) {
185
188
 
186
189
  // Engine & prerequisite guards (before any AWS calls).
187
190
  const { present: hasDatabaseTf, engine } = detectDatabaseEngine(cwd);
188
- if (hasDatabaseTf && engine === 'mysql') {
191
+ if (hasDatabaseTf && (engine === 'mysql' || engine === 'aurora-mysql')) {
192
+ const engineLabel = engine === 'aurora-mysql' ? 'Aurora MySQL' : 'MySQL';
189
193
  return failCommand({
190
- message: '\nāœ– pgvector requires PostgreSQL or Aurora PostgreSQL. This project provisions MySQL.\n',
194
+ message: `\nāœ– pgvector requires PostgreSQL or Aurora PostgreSQL. This project provisions ${engineLabel}.\n`,
191
195
  event: 'db_enable_vector_run',
192
196
  telemetry: { projectName, engine },
193
197
  errorCode: 'UNSUPPORTED_VECTOR_ENGINE',
@@ -295,6 +299,15 @@ async function runDbEnableVectorMain(input = {}) {
295
299
  });
296
300
  }
297
301
 
302
+ if (!outcome.ok && outcome.code === 'NAMED_CONTAINER_MISSING') {
303
+ return failNamedContainerMissing({
304
+ spinner: s, outcome, cluster, service, region,
305
+ event: 'db_enable_vector_run',
306
+ telemetry: { projectName },
307
+ noun: 'Vector',
308
+ });
309
+ }
310
+
298
311
  if (!outcome.ok && outcome.code === 'TIMEOUT') {
299
312
  try { s.stop(color.yellow('Vector task timed out.')); } catch { /* already stopped */ }
300
313
  return failCommand({