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
@@ -217,7 +217,12 @@ async function runWakeMain(input = {}) {
217
217
  const foundDb = probedDbSettled && probedDb;
218
218
  if (probedServicesSettled && probedDbSettled && (foundServices.length > 0 || foundDb)) {
219
219
  const servicesAwake = foundServices.every((service) => (service.desiredCount ?? 0) > 0);
220
- const dbAwake = !foundDb || foundDb.status !== 'stopped';
220
+ // `stopped` needs Start and `stopping` needs settle→Start:
221
+ // both must reach the main flow, never the already-awake
222
+ // skip. Every other status (available, starting, …) is
223
+ // started or self-resolving, so there is nothing for wake
224
+ // to do (BUG-152).
225
+ const dbAwake = !foundDb || (foundDb.status !== 'stopped' && foundDb.status !== 'stopping');
221
226
  if (servicesAwake && dbAwake) {
222
227
  return reportSleepWakeSkip({
223
228
  command: 'wake',
@@ -250,6 +255,45 @@ async function runWakeMain(input = {}) {
250
255
  dbIdentifier: target.dbIdentifier,
251
256
  dbClusterIdentifier: target.dbClusterIdentifier,
252
257
  });
258
+ // A transitional database (stopping/starting/…) can neither
259
+ // start nor serve: settle first (mirroring destroy), then
260
+ // start when it lands on `stopped`. Never restore ECS +
261
+ // report success over an unsettled database (BUG-152).
262
+ if (dbTarget && dbTarget.status !== 'stopped' && dbTarget.status !== 'available') {
263
+ const transitional = dbTarget.status;
264
+ const isCluster = dbTarget.kind === 'cluster';
265
+ s.message(truncateSpinnerText(`Database ${dbTarget.id} is ${transitional} — waiting for it to settle...`));
266
+ const settled = await pollUntil({
267
+ intervalMs: pollIntervalMs,
268
+ timeoutMs,
269
+ ...(options.sleepFn ? { sleepFn: options.sleepFn } : {}),
270
+ ...(options.nowFn ? { nowFn: options.nowFn } : {}),
271
+ onTick: async ({ elapsedMs }) => {
272
+ const resp = isCluster
273
+ ? await rdsClient.send(new DescribeDBClustersCommand({ DBClusterIdentifier: dbTarget.id }))
274
+ : await rdsClient.send(new DescribeDBInstancesCommand({ DBInstanceIdentifier: dbTarget.id }));
275
+ const current = isCluster
276
+ ? (resp.DBClusters || [])[0] || null
277
+ : (resp.DBInstances || [])[0] || null;
278
+ const status = dbStatusOf(current, isCluster ? 'cluster' : 'instance');
279
+ if (status === 'stopped' || status === 'available') return { done: true, value: status };
280
+ s.message(truncateSpinnerText(`Database ${dbTarget.id} is ${status || transitional}... [${Math.floor(elapsedMs / 1000)}s]`));
281
+ return { done: false };
282
+ },
283
+ });
284
+ if (settled.timedOut) {
285
+ s.stop(color.yellow('Database still transitioning.'));
286
+ return failCommand({
287
+ message: `\n✖ Database ${dbTarget.id} is still ${transitional} — re-run wake once it settles (ECS left untouched).\n`,
288
+ event: 'wake_run',
289
+ telemetry: { projectName, env_kind: target.envKind, error_code: 'DB_TRANSITION_TIMEOUT' },
290
+ errorCode: 'DB_TRANSITION_TIMEOUT',
291
+ reason: 'db-transition-timeout',
292
+ resultExtra: { cluster: target.cluster, region },
293
+ });
294
+ }
295
+ dbTarget = { ...dbTarget, status: settled.value };
296
+ }
253
297
  if (dbTarget && dbTarget.status === 'stopped') {
254
298
  if (dbTarget.kind === 'cluster') {
255
299
  await rdsClient.send(new StartDBClusterCommand({ DBClusterIdentifier: dbTarget.id }));
@@ -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
 
@@ -500,21 +505,21 @@ export async function generateTemplates(targetDir, config) {
500
505
  // Build the initial HCL map for AWS Secrets Manager
501
506
  let initialSecretMap = `{\n EXAMPLE_API_KEY = "replace_me_in_aws_console"`;
502
507
 
503
- // 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.
504
513
  if (config.finalFramework === 'rails') {
505
514
  secretsArray.push(`{ "name" : "RAILS_MASTER_KEY", "valueFrom" : "\${local.secret_arn}:RAILS_MASTER_KEY::" }`);
506
515
 
507
516
  if (!isLambda) managedEnvNames.push('RAILS_MASTER_KEY');
508
517
 
509
- let initialMasterKey = "1234567890abcdef1234567890abcdef"; // Dummy fallback for CI/CD
510
- const masterKeyPath = path.join(targetDir, 'config', 'master.key');
511
-
512
- if (fsSync.existsSync(masterKeyPath)) {
513
- initialMasterKey = fsSync.readFileSync(masterKeyPath, 'utf-8').trim();
514
- }
515
-
516
518
  // Inject the string literal directly, avoiding Terraform variables entirely
517
- 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
+ }
518
523
  }
519
524
 
520
525
  initialSecretMap += `\n }`;
@@ -528,7 +533,7 @@ export async function generateTemplates(targetDir, config) {
528
533
  config.TASK_SECRETS = isLambda ? '' : secretsArray.join(',\n ');
529
534
  // Collision-guard list for the task-definition precondition. Unused on
530
535
  // Lambda/static targets (their templates carry no task definitions).
531
- 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(', ')}]`;
532
537
  config.INITIAL_SECRET_MAP = initialSecretMap;
533
538
 
534
539
  config.SAFE_ALB_NAME = config.PROJECT_NAME.length > 27
@@ -580,9 +585,12 @@ resource "aws_lb_listener_rule" "vercel_redirect_${index}" {
580
585
  for (const file of filesToProcess) {
581
586
  let content = await fs.readFile(path.join(templatesDir, file.src), 'utf-8');
582
587
 
583
- // 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).
584
591
  for (const [key, value] of Object.entries(config)) {
585
- content = content.replace(new RegExp(`{{${key}}}`, 'g'), value);
592
+ const literal = String(value ?? '');
593
+ content = content.replace(new RegExp(`{{${key}}}`, 'g'), () => literal);
586
594
  }
587
595
 
588
596
  if (isLambda && file.dest === 'Dockerfile') {
@@ -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
  };
@@ -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 dependencies into an isolated venv ---
2
- FROM python:3.12-alpine AS builder
2
+ FROM python:3.12-alpine@sha256:e6dae589c1c05976188fd3bd019afd091445fc533ed2ea29001beddc7368a9c8 AS builder
3
3
 
4
4
  # Prevent Python from writing .pyc files and buffer stdout for cleaner logs
5
5
  ENV PYTHONDONTWRITEBYTECODE=1
@@ -22,7 +22,7 @@ RUN python -m venv /opt/venv && \
22
22
  rm -rf /root/.cache/pip
23
23
 
24
24
  # --- Stage 2: Production runner (no build tools, no pip) ---
25
- FROM python:3.12-alpine AS runner
25
+ FROM python:3.12-alpine@sha256:e6dae589c1c05976188fd3bd019afd091445fc533ed2ea29001beddc7368a9c8 AS runner
26
26
 
27
27
  ENV PYTHONDONTWRITEBYTECODE=1
28
28
  ENV PYTHONUNBUFFERED=1
@@ -1,5 +1,5 @@
1
1
  # Stage 1: Compile
2
- FROM golang:1.26-alpine AS builder
2
+ FROM golang:1.26-alpine@sha256:a2012b4a1d1f9f7e9f44e0d39b805a901e856b1dd80b4e6ee4338db547050308 AS builder
3
3
  WORKDIR /app
4
4
  COPY go.mod go.sum* ./
5
5
  RUN go mod download
@@ -7,7 +7,7 @@ COPY . .
7
7
  RUN CGO_ENABLED=0 GOOS=linux go build -o /main .
8
8
 
9
9
  # Stage 2: Production runner
10
- FROM alpine:3.20
10
+ FROM alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
11
11
  WORKDIR /app
12
12
 
13
13
  # Create unprivileged user
@@ -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
@@ -1,5 +1,5 @@
1
1
  # Stage 1: Build the Nuxt Nitro output
2
- FROM node:22-alpine AS builder
2
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS builder
3
3
  WORKDIR /app
4
4
 
5
5
  # Install native build tools required to compile C++ Node modules (like better-sqlite3)
@@ -16,7 +16,7 @@ COPY . .
16
16
  RUN npm run build
17
17
 
18
18
  # Stage 2: Production runner
19
- FROM node:22-alpine AS runner
19
+ FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS runner
20
20
  WORKDIR /app
21
21
 
22
22
  ENV NODE_ENV=production
@@ -1,5 +1,5 @@
1
1
  # --- Stage 1: Build dependencies into an isolated venv ---
2
- FROM python:3.12-alpine AS builder
2
+ FROM python:3.12-alpine@sha256:e6dae589c1c05976188fd3bd019afd091445fc533ed2ea29001beddc7368a9c8 AS builder
3
3
 
4
4
  # Prevent Python from writing .pyc files and buffer stdout for cleaner logs
5
5
  ENV PYTHONDONTWRITEBYTECODE=1
@@ -22,7 +22,7 @@ RUN python -m venv /opt/venv && \
22
22
  rm -rf /root/.cache/pip
23
23
 
24
24
  # --- Stage 2: Production runner (no build tools, no pip) ---
25
- FROM python:3.12-alpine AS runner
25
+ FROM python:3.12-alpine@sha256:e6dae589c1c05976188fd3bd019afd091445fc533ed2ea29001beddc7368a9c8 AS runner
26
26
 
27
27
  ENV PYTHONDONTWRITEBYTECODE=1
28
28
  ENV PYTHONUNBUFFERED=1