grada-run 0.41.5 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/bin/cli.js +18 -8
  2. package/package.json +1 -1
  3. package/src/commands/add.js +93 -11
  4. package/src/commands/alerts.js +69 -31
  5. package/src/commands/apply.js +62 -10
  6. package/src/commands/db/backup.js +1 -2
  7. package/src/commands/db/connect.js +27 -14
  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 +77 -73
  11. package/src/commands/db/restore.js +38 -6
  12. package/src/commands/destroy.js +68 -6
  13. package/src/commands/diagnose.js +57 -32
  14. package/src/commands/doctor.js +5 -3
  15. package/src/commands/domain.js +55 -7
  16. package/src/commands/drift.js +2 -1
  17. package/src/commands/eject.js +13 -2
  18. package/src/commands/exec.js +9 -4
  19. package/src/commands/gc.js +135 -6
  20. package/src/commands/init.js +75 -9
  21. package/src/commands/logs.js +127 -38
  22. package/src/commands/mcp.js +3 -2
  23. package/src/commands/rollback.js +230 -74
  24. package/src/commands/secrets.js +251 -61
  25. package/src/commands/status.js +17 -8
  26. package/src/commands/sync-ai.js +4 -3
  27. package/src/commands/wake.js +45 -1
  28. package/src/data/action-pins.js +26 -0
  29. package/src/utils/addons.js +9 -6
  30. package/src/utils/ai-rules.js +3 -2
  31. package/src/utils/backup.js +16 -2
  32. package/src/utils/command.js +20 -0
  33. package/src/utils/db-tunnel.js +15 -5
  34. package/src/utils/detector.js +8 -0
  35. package/src/utils/ecs-runner.js +16 -3
  36. package/src/utils/frameworks.js +14 -2
  37. package/src/utils/generator.js +33 -16
  38. package/src/utils/prompts.js +20 -4
  39. package/src/utils/resolvers.js +74 -11
  40. package/src/utils/revision-discovery.js +19 -7
  41. package/templates/docker/nestjs.Dockerfile +2 -2
  42. package/templates/docker/nextjs.Dockerfile +3 -3
  43. package/templates/docker/node.Dockerfile +2 -2
  44. package/templates/docker/nuxt.Dockerfile +2 -2
  45. package/templates/docker/static.Dockerfile +1 -1
  46. package/templates/docker/svelte.Dockerfile +2 -2
  47. package/templates/github/deploy-lambda.yml +73 -11
  48. package/templates/github/deploy-static.yml +4 -3
  49. package/templates/github/deploy.yml +114 -12
  50. package/templates/github/drift.yml +74 -5
  51. package/templates/github/preview-lambda.yml +143 -13
  52. package/templates/github/preview.yml +141 -13
  53. package/templates/github/teardown.yml +77 -12
  54. package/templates/terraform/addons/bedrock.tf +6 -2
  55. package/templates/terraform/addons/s3.tf +33 -0
  56. package/templates/terraform/backend.tf +7 -0
  57. package/templates/terraform/cloudfront-lambda.tf +125 -6
  58. package/templates/terraform/cloudfront.tf +137 -10
  59. package/templates/terraform/database-mysql.tf +5 -1
  60. package/templates/terraform/database.tf +5 -1
  61. package/templates/terraform/main.tf +36 -1
  62. package/templates/terraform/network.tf +5 -2
  63. package/templates/terraform/oidc.tf +3 -2
  64. package/templates/terraform/secrets.tf +6 -4
  65. package/templates/terraform/worker.tf +7 -0
@@ -0,0 +1,26 @@
1
+ // Single source of truth for third-party GitHub Action pins used by the
2
+ // generated workflows (see tests/github-workflows.test.js: every `uses:`
3
+ // in templates/github/*.yml must match this map). Bump a SHA here, run
4
+ // the workflow test to find every template site, and keep the `# tag`
5
+ // comment in sync so humans can still read the major version at a
6
+ // glance. Verified against the GitHub API; SHAs are commit SHAs, never
7
+ // tag objects.
8
+ export const ACTION_PINS = {
9
+ 'actions/checkout': { sha: '11d5960a326750d5838078e36cf38b85af677262', tag: 'v4' },
10
+ 'actions/github-script': { sha: 'f28e40c7f34bde8b3046d885e986cb6290c5673b', tag: 'v7' },
11
+ 'actions/setup-node': { sha: '49933ea5288caeca8642d1e84afbd3f7d6820020', tag: 'v4' },
12
+ 'aquasecurity/trivy-action': { sha: 'ed142fd0673e97e23eac54620cfb913e5ce36c25', tag: 'v0.36.0' },
13
+ 'aws-actions/amazon-ecr-login': { sha: '03f1aad4c6c7ffd436567f42f9384779290529bd', tag: 'v2' },
14
+ 'aws-actions/configure-aws-credentials': { sha: '7474bc4690e29a8392af63c5b98e7449536d5c3a', tag: 'v4' },
15
+ 'grada-run/grada-action': { sha: '12227808ae4caafaec1041319645586a1132fc57', tag: 'v1' },
16
+ 'hashicorp/setup-terraform': { sha: 'b9cd54a3c349d3f38e8881555d616ced269862dd', tag: 'v3' },
17
+ };
18
+
19
+ // Renders a pinned `uses:` value (`owner/name@sha # tag`) for generated
20
+ // workflow content. Throws on unknown actions — a typo must fail the
21
+ // unit suite, not ship a broken step.
22
+ export function pinnedActionUse(action) {
23
+ const pin = ACTION_PINS[action];
24
+ if (!pin) throw new Error(`Unknown action pin: ${action}`);
25
+ return `${action}@${pin.sha} # ${pin.tag}`;
26
+ }
@@ -81,12 +81,15 @@ export const ADDON_REGISTRY = {
81
81
  // warning), `refuse` (fail STATIC_TARGET_UNSUPPORTED). Consulted once at
82
82
  // the top of runAdd/runAddDatabase, before the TOCTOU guards.
83
83
  export const ADDON_TARGET_POLICY = {
84
- 'storage:s3': { ecs: 'allow', lambda: 'allow', static: 'allow' },
85
- 'db:dynamodb': { ecs: 'allow', lambda: 'allow', static: 'allow' },
86
- 'db:redis': { ecs: 'allow', lambda: 'allow', static: 'allow' },
87
- 'queue:sqs': { ecs: 'allow', lambda: 'warn', static: 'warn' },
88
- 'ai:bedrock': { ecs: 'allow', lambda: 'allow', static: 'allow' },
89
- 'email:ses': { ecs: 'allow', lambda: 'allow', static: 'allow' },
84
+ // Static trees have no task role or VPC: every one of these renders
85
+ // a dangling aws_iam_role.task_role / aws_vpc reference on static
86
+ // (BUG-157) — refuse fast instead of emitting unplannable TF.
87
+ 'storage:s3': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
88
+ 'db:dynamodb': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
89
+ 'db:redis': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
90
+ 'queue:sqs': { ecs: 'allow', lambda: 'warn', static: 'refuse' },
91
+ 'ai:bedrock': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
92
+ 'email:ses': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
90
93
  'cron': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
91
94
  'db:postgres': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
92
95
  'db:mysql': { ecs: 'allow', lambda: 'allow', static: 'refuse' },
@@ -1,4 +1,5 @@
1
1
  import fsSync from 'fs';
2
+ import { atomicWriteFileSync } from './atomic-write.js';
2
3
 
3
4
  // Per-target architecture lines so generated rules describe the actual
4
5
  // topology instead of hardcoding ECS. Unknown/legacy contexts fall back
@@ -89,9 +90,9 @@ export function injectManagedBlock(filePath, content, isMarkdown = true) {
89
90
  } else {
90
91
  fileContent = fileContent.trim() + '\n' + block; // Append to bottom
91
92
  }
92
- fsSync.writeFileSync(filePath, fileContent);
93
+ atomicWriteFileSync(filePath, fileContent);
93
94
  } else {
94
95
  // File doesn't exist, create it cleanly
95
- fsSync.writeFileSync(filePath, block.trim() + '\n');
96
+ atomicWriteFileSync(filePath, block.trim() + '\n');
96
97
  }
97
98
  }
@@ -29,7 +29,13 @@ function collectManifestFiles(targetDir) {
29
29
  }
30
30
  };
31
31
  walk(tfDir);
32
- for (const rel of ['Dockerfile', path.join('.github', 'workflows', 'deploy.yml')]) {
32
+ // Preview/teardown/drift carry project names + role ARNs and invite
33
+ // hand edits like deploy.yml — manifest them so re-init refuses
34
+ // dirty trees and backs them up instead of silently overwriting or
35
+ // leaving them stale (BUG-158).
36
+ for (const rel of ['Dockerfile', 'preview.yml', 'teardown.yml', 'drift.yml'].map((name) => (
37
+ name === 'Dockerfile' ? name : path.join('.github', 'workflows', name)
38
+ ))) {
33
39
  if (fs.existsSync(path.join(targetDir, rel))) relPaths.push(rel);
34
40
  }
35
41
  return relPaths.sort();
@@ -220,12 +226,15 @@ export async function planExistingFiles(targetDir, { isHeadless = false, force =
220
226
  const tfPath = path.join(targetDir, 'terraform');
221
227
  const dockerfilePath = path.join(targetDir, 'Dockerfile');
222
228
  const wfPath = path.join(targetDir, '.github', 'workflows', 'deploy.yml');
229
+ const extraWorkflows = ['preview.yml', 'teardown.yml', 'drift.yml']
230
+ .map((workflow) => path.join('.github', 'workflows', workflow))
231
+ .filter((rel) => fs.existsSync(path.join(targetDir, rel)));
223
232
 
224
233
  const tfExists = fs.existsSync(tfPath);
225
234
  const dockerfileExists = fs.existsSync(dockerfilePath);
226
235
  const wfExists = fs.existsSync(wfPath);
227
236
 
228
- if (!tfExists && !dockerfileExists && !wfExists) {
237
+ if (!tfExists && !dockerfileExists && !wfExists && extraWorkflows.length === 0) {
229
238
  return { decision: 'clean', foundFiles: [], dirty: [] };
230
239
  }
231
240
 
@@ -233,6 +242,7 @@ export async function planExistingFiles(targetDir, { isHeadless = false, force =
233
242
  if (tfExists) foundFiles.push('terraform/');
234
243
  if (dockerfileExists) foundFiles.push('Dockerfile');
235
244
  if (wfExists) foundFiles.push('.github/workflows/deploy.yml');
245
+ foundFiles.push(...extraWorkflows);
236
246
 
237
247
  const treeStatus = detectModifiedTree(targetDir);
238
248
  const dirty = treeStatus ? [...treeStatus.modified, ...treeStatus.missing] : [];
@@ -293,6 +303,10 @@ export async function executeBackup(targetDir, plan = {}) {
293
303
  ['terraform/', path.join(targetDir, 'terraform')],
294
304
  ['Dockerfile', path.join(targetDir, 'Dockerfile')],
295
305
  ['.github/workflows/deploy.yml', path.join(targetDir, '.github', 'workflows', 'deploy.yml')],
306
+ ...['preview.yml', 'teardown.yml', 'drift.yml'].map((workflow) => {
307
+ const rel = path.join('.github', 'workflows', workflow);
308
+ return [rel, path.join(targetDir, rel)];
309
+ }),
296
310
  ];
297
311
  for (const [rel, fullPath] of renames) {
298
312
  if (!foundFiles.includes(rel)) continue;
@@ -192,3 +192,23 @@ export async function failProjectNotInitialized({ event, noExit = false }) {
192
192
  noExit,
193
193
  });
194
194
  }
195
+
196
+ // Shared loud failure for the ecs-runner NAMED_CONTAINER_MISSING
197
+ // outcome: the stopped task has no such container, so no exit code can
198
+ // be attributed. `noun` names the task kind for the spinner line.
199
+ export async function failNamedContainerMissing({ spinner, outcome, cluster, service, region, event, telemetry, noun = 'Task' }) {
200
+ try {
201
+ spinner.stop(color.red(`${noun} container missing from stopped task.`));
202
+ } catch {
203
+ // The spinner may already be stopped; the message below carries it.
204
+ }
205
+ return failCommand({
206
+ message: `\n✖ The stopped task has no "${outcome.containerName}" container (found: ${outcome.available.join(', ') || 'none'}). Task stopped: ${outcome.stoppedReason}.\n`,
207
+ hint: 'The task definition may have changed mid-run; retry, or pin --task-def to the service revision.\n',
208
+ event,
209
+ telemetry,
210
+ errorCode: 'NAMED_CONTAINER_MISSING',
211
+ reason: 'named-container-missing',
212
+ resultExtra: { cluster, service, region, taskArn: outcome.taskArn },
213
+ });
214
+ }
@@ -2,7 +2,7 @@ import { ListTasksCommand, DescribeTasksCommand } from '@aws-sdk/client-ecs';
2
2
  import { GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
3
3
  import { spawnSync } from 'child_process';
4
4
  import net from 'node:net';
5
- import { pickRuntimeContainer } from './ecs.js';
5
+ import { pickRuntimeContainer, pickNewestRunningTask } from './ecs.js';
6
6
  import { pollUntil } from './system.js';
7
7
 
8
8
  // SSM port-forwarding session arguments for tunneling to a database
@@ -46,14 +46,24 @@ export async function findJumpHostTarget(ecsClient, { cluster, service, expected
46
46
  );
47
47
  const taskArns = listResp.taskArns || [];
48
48
  if (taskArns.length === 0) return { error: 'NO_RUNNING_TASKS' };
49
+ // ListTasks order is arbitrary and desiredStatus RUNNING still
50
+ // returns tasks PROVISIONING/PENDING toward that goal — describe the
51
+ // batch and pick the newest actually-RUNNING task with a runtimeId
52
+ // instead of trusting arns[0].
49
53
  const descResp = await ecsClient.send(
50
- new DescribeTasksCommand({ cluster, tasks: taskArns.slice(0, 1) })
54
+ new DescribeTasksCommand({ cluster, tasks: taskArns.slice(0, 10) })
51
55
  );
52
- const task = (descResp.tasks || [])[0] || null;
53
- if (!task?.taskArn) return { error: 'NO_RUNNING_TASKS' };
56
+ const described = descResp.tasks || [];
57
+ const withRuntime = described.filter(
58
+ (candidate) => pickRuntimeContainer(candidate, expectedContainer)?.runtimeId
59
+ );
60
+ const task = pickNewestRunningTask(withRuntime);
61
+ if (!task?.taskArn) {
62
+ const anyRunning = described.some((candidate) => candidate?.lastStatus === 'RUNNING');
63
+ return { error: anyRunning ? 'NO_RUNTIME_ID' : 'NO_RUNNING_TASKS' };
64
+ }
54
65
  const container = pickRuntimeContainer(task, expectedContainer);
55
66
  const runtimeId = container?.runtimeId;
56
- if (!runtimeId) return { error: 'NO_RUNTIME_ID' };
57
67
  return {
58
68
  taskArn: task.taskArn,
59
69
  taskId: task.taskArn.split('/').pop(),
@@ -319,6 +319,14 @@ export function detectMigrationCommand(cwd = process.cwd()) {
319
319
  }
320
320
  };
321
321
 
322
+ // 0. Prescribed migration bundle first: a built dist/migrate.cjs
323
+ // (then .mjs, then scripts/) is the stripped-runner-safe convention,
324
+ // so a bundle-ready tree must never detect a runner-refused npx shim.
325
+ if (exists(path.join('dist', 'migrate.cjs'))) return 'node ./dist/migrate.cjs';
326
+ if (exists(path.join('dist', 'migrate.mjs'))) return 'node ./dist/migrate.mjs';
327
+ if (exists(path.join('scripts', 'migrate.cjs'))) return 'node ./scripts/migrate.cjs';
328
+ if (exists(path.join('scripts', 'migrate.mjs'))) return 'node ./scripts/migrate.mjs';
329
+
322
330
  // 1. Explicit package.json migration scripts win over framework markers.
323
331
  const pkg = readJson('package.json');
324
332
  const scripts = pkg && typeof pkg === 'object' ? pkg.scripts || {} : {};
@@ -97,6 +97,7 @@ async function flushRemainingLogs({ logsClient, logGroupName, logStreamName, see
97
97
  // { ok: false, code: 'CONTAINER_NOT_FOUND', targetTaskDef, available: [names] }
98
98
  // { ok: false, code: 'RUN_TASK_FAILED', reason }
99
99
  // { ok: false, code: 'TIMEOUT', taskArn } (task stop attempted best-effort)
100
+ // { ok: false, code: 'NAMED_CONTAINER_MISSING', taskArn, containerName, available, stoppedReason }
100
101
  //
101
102
  // `command` is the container override: either the array itself or a builder
102
103
  // `(containerDef) => string[]` invoked with the selected task-definition
@@ -283,8 +284,20 @@ export async function runEphemeralEcsTask({
283
284
  }
284
285
 
285
286
  const containers = finalTask?.containers || [];
286
- const match = containers.find((c) => c.name === containerName) || containers[0];
287
- const exitCode = match?.exitCode;
288
- const stoppedReason = match?.reason || finalTask?.stoppedReason || 'unknown';
287
+ const match = containers.find((c) => c.name === containerName) || null;
288
+ if (!match) {
289
+ // Strict by name only — never the containers[0] fallback: a
290
+ // sidecar's exit 0 must not masquerade as the named container's.
291
+ return {
292
+ ok: false,
293
+ code: 'NAMED_CONTAINER_MISSING',
294
+ taskArn,
295
+ containerName,
296
+ available: containers.map((c) => c.name),
297
+ stoppedReason: finalTask?.stoppedReason || 'unknown',
298
+ };
299
+ }
300
+ const exitCode = match.exitCode;
301
+ const stoppedReason = match.reason || finalTask?.stoppedReason || 'unknown';
289
302
  return { ok: true, taskArn, exitCode, stoppedReason };
290
303
  }
@@ -24,20 +24,32 @@ export async function resolveDjangoWsgi(targetDir, procfile, framework, isHeadle
24
24
  message: 'What is the Python module path to your Django wsgi.py?',
25
25
  placeholder: 'core.wsgi',
26
26
  initialValue: 'core.wsgi',
27
+ validate: (value) => {
28
+ if (/^[A-Za-z0-9_.]+$/.test(String(value ?? ''))) return undefined;
29
+ return 'Enter a Python module path with letters, numbers, dots, and underscores only (e.g. core.wsgi).';
30
+ },
27
31
  });
28
32
 
29
33
  if (typeof djangoWsgi === 'symbol') process.exit(0);
30
34
  return djangoWsgi;
31
35
  }
32
36
 
33
- export async function handleRailsCI(targetDir, framework, isHeadless) {
37
+ export async function handleRailsCI(targetDir, framework, isHeadless, { force = false } = {}) {
34
38
  if (framework !== 'rails') return false;
35
39
 
36
40
  const ciPath = path.join(targetDir, '.github', 'workflows', 'ci.yml');
37
41
  const dependabotPath = path.join(targetDir, '.github', 'dependabot.yml');
38
42
 
39
43
  if (fsSync.existsSync(ciPath) || fsSync.existsSync(dependabotPath)) {
40
- if (isHeadless) return true;
44
+ // Headless renames user files only with explicit --force;
45
+ // otherwise warn and keep them like the interactive decline path.
46
+ if (isHeadless) {
47
+ if (force !== true) {
48
+ log.warn(color.yellow('⚠️ Detected default Rails GitHub Actions (ci.yml, dependabot.yml) that usually crash in isolated CI environments without a database — keeping them. Re-run with --force to let grada rename them to .bak.'));
49
+ return false;
50
+ }
51
+ return true;
52
+ }
41
53
 
42
54
  console.log('');
43
55
  const disable = await confirm({
@@ -17,6 +17,9 @@ const __dirname = path.dirname(__filename);
17
17
  // name stays a writable candidate so pre-rebrand docs keep updating.
18
18
  export const MANAGED_DOC_FALLBACK = 'GRADA.md';
19
19
  export const LEGACY_MANAGED_DOC_FALLBACK = 'DEPLOY-STACK.md';
20
+ // Greppable, boot-failing Rails master-key seed (BUG-146): Rails cannot
21
+ // boot on it, so a tree that never pushes the real key fails closed.
22
+ export const RAILS_MASTER_KEY_PLACEHOLDER = 'REPLACE_ME_PUSH_REAL_RAILS_MASTER_KEY';
20
23
 
21
24
  // A doc is ours when it carries our cost-estimate marker (current or legacy).
22
25
  export function isManagedDoc(content) {
@@ -27,7 +30,9 @@ export function isManagedDoc(content) {
27
30
  export function buildReadmeNotice(docFile, target = 'ecs') {
28
31
  const what = target === 'static'
29
32
  ? 'Static site infrastructure (S3 + CloudFront) is managed'
30
- : 'AWS Fargate infrastructure is managed';
33
+ : target === 'lambda'
34
+ ? 'AWS Lambda infrastructure is managed'
35
+ : 'AWS Fargate infrastructure is managed';
31
36
  return `\n## 🚀 Deployment\n${what} via [grada](./${docFile}).\n`;
32
37
  }
33
38
 
@@ -213,8 +218,17 @@ export function buildDbEntries(engine, target = 'ecs') {
213
218
  };
214
219
  }
215
220
 
216
- // Adds the `random` provider to a rendered backend.tf (Lambda + database
217
- // projects only, for `random_password.db_password`). No-op when present.
221
+ // Whether a target's rendered backend.tf needs the `random` provider:
222
+ // always on ECS (the ALB origin secret), on Lambda only with a database
223
+ // (`random_password.db_password`), never on static.
224
+ export function backendNeedsRandomProvider(target, needsDatabase = false) {
225
+ if (target === 'static') return false;
226
+ if (target === 'lambda') return needsDatabase === true;
227
+ return true;
228
+ }
229
+
230
+ // Adds the `random` provider to a rendered backend.tf (see
231
+ // backendNeedsRandomProvider for which trees need it). No-op when present.
218
232
  // Resolves the compose service to merge for a render config. init
219
233
  // pre-selects through DOCKER_COMPOSE_WEB (a service name, or null when
220
234
  // init already warned and declined the merge); direct callers run the
@@ -491,21 +505,21 @@ export async function generateTemplates(targetDir, config) {
491
505
  // Build the initial HCL map for AWS Secrets Manager
492
506
  let initialSecretMap = `{\n EXAMPLE_API_KEY = "replace_me_in_aws_console"`;
493
507
 
494
- // 4.1. Inject Rails Master Key if applicable
508
+ // 4.1. Seed a placeholder for the Rails master key (BUG-146): the
509
+ // live key must never render into committed .tf (or linger in
510
+ // state), and no constant dummy may boot prod. The placeholder is
511
+ // greppable and boot-failing; the loud instruction tells the
512
+ // operator to push the real key before going live.
495
513
  if (config.finalFramework === 'rails') {
496
514
  secretsArray.push(`{ "name" : "RAILS_MASTER_KEY", "valueFrom" : "\${local.secret_arn}:RAILS_MASTER_KEY::" }`);
497
515
 
498
516
  if (!isLambda) managedEnvNames.push('RAILS_MASTER_KEY');
499
517
 
500
- let initialMasterKey = "1234567890abcdef1234567890abcdef"; // Dummy fallback for CI/CD
501
- const masterKeyPath = path.join(targetDir, 'config', 'master.key');
502
-
503
- if (fsSync.existsSync(masterKeyPath)) {
504
- initialMasterKey = fsSync.readFileSync(masterKeyPath, 'utf-8').trim();
505
- }
506
-
507
518
  // Inject the string literal directly, avoiding Terraform variables entirely
508
- initialSecretMap += `,\n RAILS_MASTER_KEY = "${initialMasterKey}"`;
519
+ initialSecretMap += `,\n RAILS_MASTER_KEY = "${RAILS_MASTER_KEY_PLACEHOLDER}"`;
520
+ if (!isLambda) {
521
+ console.log(color.yellow(`⚠️ Rails app detected: terraform/secrets.tf seeds RAILS_MASTER_KEY with the placeholder "${RAILS_MASTER_KEY_PLACEHOLDER}" — push the real key before going live: npx grada-run secrets push .env (with RAILS_MASTER_KEY set from config/master.key).`));
522
+ }
509
523
  }
510
524
 
511
525
  initialSecretMap += `\n }`;
@@ -519,7 +533,7 @@ export async function generateTemplates(targetDir, config) {
519
533
  config.TASK_SECRETS = isLambda ? '' : secretsArray.join(',\n ');
520
534
  // Collision-guard list for the task-definition precondition. Unused on
521
535
  // Lambda/static targets (their templates carry no task definitions).
522
- config.MANAGED_ENV_NAMES = `[${[...new Set(managedEnvNames)].map((name) => JSON.stringify(name)).join(', ')}]`;
536
+ config.MANAGED_ENV_NAMES = `[${[...new Set(managedEnvNames)].sort().map((name) => JSON.stringify(name)).join(', ')}]`;
523
537
  config.INITIAL_SECRET_MAP = initialSecretMap;
524
538
 
525
539
  config.SAFE_ALB_NAME = config.PROJECT_NAME.length > 27
@@ -571,9 +585,12 @@ resource "aws_lb_listener_rule" "vercel_redirect_${index}" {
571
585
  for (const file of filesToProcess) {
572
586
  let content = await fs.readFile(path.join(templatesDir, file.src), 'utf-8');
573
587
 
574
- // Inject variables
588
+ // Inject variables. Replacement FUNCTION (not string): `$&`/`$'`/
589
+ // `$$` in values (Procfile commands, compose env vars) must land
590
+ // byte-identical, not interpolate match text (BUG-156).
575
591
  for (const [key, value] of Object.entries(config)) {
576
- content = content.replace(new RegExp(`{{${key}}}`, 'g'), value);
592
+ const literal = String(value ?? '');
593
+ content = content.replace(new RegExp(`{{${key}}}`, 'g'), () => literal);
577
594
  }
578
595
 
579
596
  if (isLambda && file.dest === 'Dockerfile') {
@@ -584,7 +601,7 @@ resource "aws_lb_listener_rule" "vercel_redirect_${index}" {
584
601
  content = convertDatabaseTfForLambda(content);
585
602
  }
586
603
 
587
- if (isLambda && config.NEEDS_DATABASE && file.dest === 'terraform/backend.tf') {
604
+ if (file.dest === 'terraform/backend.tf' && backendNeedsRandomProvider(target, config.NEEDS_DATABASE)) {
588
605
  content = addRandomProvider(content);
589
606
  }
590
607
 
@@ -27,15 +27,31 @@ function resolveActualProjectName(rawName) {
27
27
  return actualProjectName;
28
28
  }
29
29
 
30
+ function resolveTargetDir(projectName) {
31
+ if (projectName === '.') return process.cwd();
32
+ // path.join does not reset on absolute segments — an absolute --dir
33
+ // would scaffold under $PWD/<abs> instead of exactly there.
34
+ if (path.isAbsolute(projectName)) return path.normalize(projectName);
35
+ return path.join(process.cwd(), projectName);
36
+ }
37
+
38
+ function deriveRawName(projectName, explicitName) {
39
+ if (explicitName !== '') return explicitName;
40
+ if (projectName === '.') return path.basename(process.cwd());
41
+ // An absolute dir derives from its own basename, never the whole path.
42
+ if (path.isAbsolute(projectName)) return path.basename(projectName);
43
+ return projectName;
44
+ }
45
+
30
46
  export async function getTargetDirectory(isHeadless, headlessOptions, overrides = {}) {
31
47
  const explicitName = typeof overrides.projectName === 'string' ? overrides.projectName.trim() : '';
32
48
  if (isHeadless) {
33
49
  const projectName = headlessOptions.dir || '.';
34
- const rawName = explicitName !== '' ? explicitName : (projectName === '.' ? path.basename(process.cwd()) : projectName);
50
+ const rawName = deriveRawName(projectName, explicitName);
35
51
  return {
36
52
  projectName,
37
53
  actualProjectName: resolveActualProjectName(rawName),
38
- targetDir: projectName === '.' ? process.cwd() : path.join(process.cwd(), projectName)
54
+ targetDir: resolveTargetDir(projectName)
39
55
  };
40
56
  }
41
57
 
@@ -54,11 +70,11 @@ export async function getTargetDirectory(isHeadless, headlessOptions, overrides
54
70
  process.exit(0);
55
71
  }
56
72
 
57
- const rawName = explicitName !== '' ? explicitName : (projectName === '.' ? path.basename(process.cwd()) : projectName);
73
+ const rawName = deriveRawName(projectName, explicitName);
58
74
  return {
59
75
  projectName,
60
76
  actualProjectName: resolveActualProjectName(rawName),
61
- targetDir: projectName === '.' ? process.cwd() : path.join(process.cwd(), projectName)
77
+ targetDir: resolveTargetDir(projectName)
62
78
  };
63
79
  }
64
80
 
@@ -61,17 +61,19 @@ function prettyTargetName(target) {
61
61
  // to failCommand ({ actual, reason, errorCode, message, hint }).
62
62
  // The message names every unsupported target ("…is not supported on
63
63
  // Lambda or Static targets.") so one call site covers all of them.
64
- export function guardComputeTarget({ cwd = process.cwd(), command, supported = ['ecs'], hint = null } = {}) {
65
- const actual = readTerraformComputeTarget(cwd);
66
- if (supported.includes(actual)) return null;
64
+ export function guardComputeTarget({ cwd = process.cwd(), command, supported = ['ecs'], hint = null, actual = null } = {}) {
65
+ // `actual` overrides the disk read for callers validating a REQUESTED
66
+ // target (init --with on a fresh dir has no main.tf to read).
67
+ const resolved = actual ?? readTerraformComputeTarget(cwd);
68
+ if (supported.includes(resolved)) return null;
67
69
  const unsupported = COMPUTE_TARGETS.filter((target) => !supported.includes(target)).map(prettyTargetName);
68
70
  const targetList = unsupported.length > 1
69
71
  ? `${unsupported.slice(0, -1).join(', ')} or ${unsupported[unsupported.length - 1]} targets`
70
- : `${unsupported[0] ?? prettyTargetName(actual)} targets`;
72
+ : `${unsupported[0] ?? prettyTargetName(resolved)} targets`;
71
73
  return {
72
- actual,
73
- reason: `${actual}-target-unsupported`,
74
- errorCode: `${actual.toUpperCase()}_TARGET_UNSUPPORTED`,
74
+ actual: resolved,
75
+ reason: `${resolved}-target-unsupported`,
76
+ errorCode: `${resolved.toUpperCase()}_TARGET_UNSUPPORTED`,
75
77
  message: `\n✖ ${command} is not supported on ${targetList}.`,
76
78
  hint,
77
79
  };
@@ -148,6 +150,30 @@ export function readTerraformOidcTrust(cwd = process.cwd()) {
148
150
  return { kind: 'string', value: raw.slice(1, -1) };
149
151
  }
150
152
 
153
+ // Index just past the `]` matching the `[` at openIdx (quoted regions
154
+ // skipped, so bracket-bearing strings can't mis-close it), or -1 when
155
+ // the block never closes.
156
+ function scanBracketBlock(content, openIdx) {
157
+ let depth = 0;
158
+ let i = openIdx;
159
+ while (i < content.length) {
160
+ const ch = content[i];
161
+ if (ch === '"') {
162
+ i += 1;
163
+ while (i < content.length && content[i] !== '"') i += content[i] === '\\' ? 2 : 1;
164
+ i += 1;
165
+ continue;
166
+ }
167
+ if (ch === '[') depth += 1;
168
+ else if (ch === ']') {
169
+ depth -= 1;
170
+ if (depth === 0) return i + 1;
171
+ }
172
+ i += 1;
173
+ }
174
+ return -1;
175
+ }
176
+
151
177
  // Reads container environment + static-secret names from the rendered
152
178
  // task definitions (main.tf + worker.tf). Covers every injection path —
153
179
  // scaffold DB/compose entries (`{ "name" : "X" }`), addon entries
@@ -156,19 +182,41 @@ export function readTerraformOidcTrust(cwd = process.cwd()) {
156
182
  // dynamic `for key in local.secret_keys` loop carries an unquoted key
157
183
  // reference, so it never matches; the shape filter drops resource names
158
184
  // (`${...}`, hyphens, paths). Sorted, deduplicated, [] when unreadable.
185
+ //
186
+ // Scoped to secret-receiving containers (BUG-93): ECS collides secrets
187
+ // with environment per container definition, so sidecar `environment`
188
+ // arrays (whose containers get no secrets) must not contribute names —
189
+ // parsing them would falsely render same-named secrets undeployable.
190
+ // An environment block counts when a `secrets =` assignment follows it
191
+ // before the next environment block (the app/worker shape); hand-added
192
+ // entries inside those blocks stay covered.
159
193
  export function readRenderedContainerEnvNames(cwd = process.cwd()) {
160
194
  const base = resolveCwd({}, cwd);
161
195
  const names = new Set();
162
- const patterns = [/"name"\s*:\s*"([^"]+)"/g, /\bname\s*=\s*"([^"]+)"/g];
163
196
  const shape = /^[A-Za-z_][A-Za-z0-9_]*$/;
164
197
  for (const file of ['main.tf', 'worker.tf']) {
165
198
  const content = readFileSafe(path.join(base, 'terraform', file));
166
199
  if (!content) continue;
167
- for (const pattern of patterns) {
168
- for (const match of content.matchAll(pattern)) {
169
- if (shape.test(match[1])) names.add(match[1]);
200
+ const envStarts = [...content.matchAll(/environment\s*=\s*\[/g)];
201
+ for (let bi = 0; bi < envStarts.length; bi += 1) {
202
+ const match = envStarts[bi];
203
+ const openIdx = match.index + match[0].length - 1;
204
+ const closeIdx = scanBracketBlock(content, openIdx);
205
+ if (closeIdx === -1) continue;
206
+ const nextEnvIdx = bi + 1 < envStarts.length ? envStarts[bi + 1].index : content.length;
207
+ if (!/\bsecrets\s*=/.test(content.slice(closeIdx, nextEnvIdx))) continue;
208
+ const block = content.slice(openIdx, closeIdx);
209
+ for (const pattern of [/"name"\s*:\s*"([^"]+)"/g, /\bname\s*=\s*"([^"]+)"/g]) {
210
+ for (const m of block.matchAll(pattern)) {
211
+ if (shape.test(m[1])) names.add(m[1]);
212
+ }
170
213
  }
171
214
  }
215
+ // Static secret entries (`{ "name" : "X", "valueFrom" : ... }`):
216
+ // quoted names reached by a valueFrom within the same object.
217
+ for (const m of content.matchAll(/"name"\s*:\s*"([^"]+)"(?=[^}]{0,300}"valueFrom")/g)) {
218
+ if (shape.test(m[1])) names.add(m[1]);
219
+ }
172
220
  }
173
221
  return [...names].sort();
174
222
  }
@@ -275,6 +323,21 @@ export function resolveAppName(projectName, workspace, cwd = process.cwd()) {
275
323
  return `${projectName}${resolveWorkspaceSuffix({ workspace, cwd }, cwd)}`;
276
324
  }
277
325
 
326
+ // Workspace-namespaced project name for resource derivation: --workspace
327
+ // (or the local .terraform/environment) targets a preview stack. Telemetry
328
+ // keeps the raw project name; explicit --cluster/--service/--log-group
329
+ // flags still win inside the resolvers.
330
+ export function resolveNamespacedProject(projectName, options = {}, cwd = process.cwd()) {
331
+ return `${projectName}${resolveWorkspaceSuffix(options, cwd)}`;
332
+ }
333
+
334
+ // `options` with the project name workspace-namespaced, for commands that
335
+ // derive several resource names (cluster/service/log group) at once.
336
+ export function withWorkspaceNamespace(options = {}, cwd = process.cwd()) {
337
+ const opts = normalizeOptions(options);
338
+ return { ...opts, projectName: resolveNamespacedProject(resolveProjectName(opts, cwd), opts, cwd) };
339
+ }
340
+
278
341
  // Reads the local Terraform workspace (e.g. a PR-preview environment).
279
342
  // Returns '' for the default workspace so names stay un-suffixed.
280
343
  export function resolveWorkspaceSuffix(options = {}, cwd = process.cwd()) {
@@ -31,16 +31,28 @@ export function pickNewestEligible(eligibleArns) {
31
31
  return eligibleArns.length > 0 ? eligibleArns[0] : null;
32
32
  }
33
33
 
34
+ // Discovery horizon: 5 pages × 10 ACTIVE revisions. Past it, Case B
35
+ // still refuses — but only after a genuine look, not a one-page peek.
36
+ export const REVISION_DISCOVERY_MAX_PAGES = 5;
37
+
34
38
  export function createEcsRevisionAdapter(ecsClient) {
35
39
  return {
36
40
  listRevisionArns: async (family) => {
37
- const listResp = await ecsClient.send(new ListTaskDefinitionsCommand({
38
- familyPrefix: family,
39
- status: 'ACTIVE',
40
- sort: 'DESC',
41
- maxResults: 10,
42
- }));
43
- return listResp.taskDefinitionArns || [];
41
+ const arns = [];
42
+ let nextToken;
43
+ for (let page = 0; page < REVISION_DISCOVERY_MAX_PAGES; page += 1) {
44
+ const listResp = await ecsClient.send(new ListTaskDefinitionsCommand({
45
+ familyPrefix: family,
46
+ status: 'ACTIVE',
47
+ sort: 'DESC',
48
+ maxResults: 10,
49
+ ...(nextToken ? { nextToken } : {}),
50
+ }));
51
+ arns.push(...(listResp.taskDefinitionArns || []));
52
+ nextToken = listResp.nextToken;
53
+ if (!nextToken) break;
54
+ }
55
+ return arns;
44
56
  },
45
57
  };
46
58
  }
@@ -1,5 +1,5 @@
1
1
  # --- Stage 1: Build ---
2
- FROM node:22-alpine AS builder
2
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS builder
3
3
  WORKDIR /app
4
4
  COPY package*.json ./
5
5
  RUN npm ci
@@ -7,7 +7,7 @@ COPY . .
7
7
  RUN npm run build
8
8
 
9
9
  # --- Stage 2: Production ---
10
- FROM node:22-alpine
10
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914
11
11
 
12
12
  # 1. DevSecOps: Patch Alpine OS
13
13
  RUN apk update && apk upgrade --no-cache
@@ -1,10 +1,10 @@
1
1
  # Stage 1: Install dependencies and build the app
2
- FROM node:22-alpine AS builder
2
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS builder
3
3
  WORKDIR /app
4
4
 
5
5
  # FIX 1: Upgrade Alpine system packages & upgrade global NPM to patch 'tar' and 'pacote' CVEs
6
6
  RUN apk upgrade --no-cache && \
7
- npm install -g npm@latest
7
+ npm install -g npm@12.2.1
8
8
 
9
9
  # Copy package files and install dependencies
10
10
  COPY package.json package-lock.json* ./
@@ -18,7 +18,7 @@ COPY . .
18
18
  RUN npm run build
19
19
 
20
20
  # Stage 2: Production environment
21
- FROM node:22-alpine AS runner
21
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS runner
22
22
  WORKDIR /app
23
23
 
24
24
  # FIX 2: Upgrade Alpine packages and absolutely destroy npm, yarn, and corepack
@@ -1,5 +1,5 @@
1
1
  # --- Stage 1: Install production dependencies ---
2
- FROM node:22-alpine AS builder
2
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS builder
3
3
  WORKDIR /app
4
4
  COPY package*.json ./
5
5
  # Guarantee node_modules exists for zero-dependency projects (npm ci with
@@ -7,7 +7,7 @@ COPY package*.json ./
7
7
  RUN npm ci --omit=dev && npm cache clean --force && mkdir -p node_modules
8
8
 
9
9
  # --- Stage 2: Production runner (no package managers) ---
10
- FROM node:22-alpine AS runner
10
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS runner
11
11
 
12
12
  # 1. DevSecOps: Patch underlying Alpine OS vulnerabilities
13
13
  RUN apk update && apk upgrade --no-cache