grada-run 0.42.0 → 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 (59) 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 +61 -9
  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 +76 -72
  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 +4 -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 +224 -57
  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/nestjs.Dockerfile +2 -2
  41. package/templates/docker/nextjs.Dockerfile +3 -3
  42. package/templates/docker/node.Dockerfile +2 -2
  43. package/templates/docker/nuxt.Dockerfile +2 -2
  44. package/templates/docker/static.Dockerfile +1 -1
  45. package/templates/docker/svelte.Dockerfile +2 -2
  46. package/templates/github/deploy-lambda.yml +55 -12
  47. package/templates/github/deploy-static.yml +4 -3
  48. package/templates/github/deploy.yml +96 -13
  49. package/templates/github/drift.yml +74 -5
  50. package/templates/github/preview-lambda.yml +143 -13
  51. package/templates/github/preview.yml +141 -13
  52. package/templates/github/teardown.yml +77 -12
  53. package/templates/terraform/addons/s3.tf +33 -0
  54. package/templates/terraform/backend.tf +7 -0
  55. package/templates/terraform/database-mysql.tf +5 -1
  56. package/templates/terraform/database.tf +5 -1
  57. package/templates/terraform/oidc.tf +3 -2
  58. package/templates/terraform/secrets.tf +6 -4
  59. package/templates/terraform/worker.tf +7 -0
@@ -177,6 +177,9 @@ async function runRollbackMain(input = {}) {
177
177
 
178
178
  let targetTaskDefArn;
179
179
  let targetRevisionNum;
180
+ // Case A only: the requested web revision's image, for worker
181
+ // pairing (BUG-153). Null in Case B and when undescribable.
182
+ let requestedWebImage = null;
180
183
 
181
184
  if (options.revision !== undefined && options.revision !== null && String(options.revision).trim() !== '') {
182
185
  // Case A: explicit revision.
@@ -233,6 +236,22 @@ async function runRollbackMain(input = {}) {
233
236
  exitCode: 1,
234
237
  });
235
238
  }
239
+ // BUG-127: a NEWER explicit revision would silently
240
+ // roll FORWARD — rollback only moves to older revisions.
241
+ if (Number.isInteger(Number(targetRevisionNum)) && Number.isInteger(currentRevNum)
242
+ && Number(targetRevisionNum) > currentRevNum) {
243
+ s.stop(color.red('Revision is newer than deployed.'));
244
+ return failCommand({
245
+ message: `\n✖ Revision ${targetRevisionNum} is newer than the deployed revision ${currentRevNum} — rollback only moves to older revisions.`,
246
+ hint: ' Deploy again to move forward, or request a revision older than the deployed one.\n',
247
+ event: 'rollback_run',
248
+ telemetry: { projectName, error_code: 'NEWER_REVISION_REQUESTED' },
249
+ reason: 'rollback-newer-revision',
250
+ resultExtra: { cluster, service, region },
251
+ exitCode: 1,
252
+ });
253
+ }
254
+ requestedWebImage = descResp.taskDefinition.containerDefinitions?.[0]?.image ?? null;
236
255
  s.stop(`Resolved revision ${targetRevisionNum}.`);
237
256
  } else {
238
257
  // Case B: discover eligible older revisions via the shared seam.
@@ -333,8 +352,38 @@ async function runRollbackMain(input = {}) {
333
352
  exitCode: 1,
334
353
  });
335
354
  }
336
- const workerTargetArn = pickNewestEligible(workerEligible);
337
- workerTarget = { service: workerService, taskDefArn: workerTargetArn, revision: workerTargetArn.split(':').pop() };
355
+ // BUG-153: in Case A the worker target pairs with the
356
+ // REQUESTED web image (deploys pin both to the same SHA) —
357
+ // newest-previous regardless would skew the pairing. When
358
+ // no eligible worker revision carries the web image, fall
359
+ // back to newest-previous, loudly when both images are
360
+ // known and differ. Case B (newest-previous web) keeps
361
+ // newest-previous worker: paired by construction.
362
+ let workerTargetArn = pickNewestEligible(workerEligible);
363
+ let workerImageMatched = null;
364
+ if (requestedWebImage) {
365
+ const settled = await Promise.allSettled(
366
+ workerEligible.map((workerArn) => ecsClient.send(new DescribeTaskDefinitionCommand({ taskDefinition: workerArn })))
367
+ );
368
+ const withImages = workerEligible.map((workerArn, index) => ({
369
+ workerArn,
370
+ image: settled[index].status === 'fulfilled'
371
+ ? settled[index].value?.taskDefinition?.containerDefinitions?.[0]?.image ?? null
372
+ : null,
373
+ }));
374
+ const match = withImages.find((entry) => entry.image === requestedWebImage);
375
+ if (match) {
376
+ workerTargetArn = match.workerArn;
377
+ workerImageMatched = true;
378
+ } else {
379
+ workerImageMatched = false;
380
+ const newestImage = withImages[0]?.image ?? null;
381
+ if (newestImage && newestImage !== requestedWebImage) {
382
+ console.log(color.yellow(`⚠ No worker revision carries the requested web image ${requestedWebImage} — rolling the worker back to newest-previous (${newestImage}) instead. Web and worker will run different images.`));
383
+ }
384
+ }
385
+ }
386
+ workerTarget = { service: workerService, taskDefArn: workerTargetArn, revision: workerTargetArn.split(':').pop(), imageMatched: workerImageMatched };
338
387
  }
339
388
  }
340
389
 
@@ -358,7 +407,7 @@ async function runRollbackMain(input = {}) {
358
407
  }));
359
408
  }
360
409
 
361
- if (options.skipWait === true) {
410
+ if (options.skipWait === true || options.skipWait === 'true') {
362
411
  const skipLabel = workerTarget
363
412
  ? `revision ${targetRevisionNum} (web) and ${workerTarget.revision} (worker)`
364
413
  : `revision ${targetRevisionNum}`;
@@ -367,7 +416,7 @@ async function runRollbackMain(input = {}) {
367
416
  projectName,
368
417
  targetRevision: String(targetRevisionNum),
369
418
  skipWait: true,
370
- ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision) } : {}),
419
+ ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision), workerImageMatched: workerTarget.imageMatched ?? undefined } : {}),
371
420
  });
372
421
  outro(color.green(`Rollback to ${skipLabel} initiated! 🚀`));
373
422
  return {
@@ -402,7 +451,7 @@ async function runRollbackMain(input = {}) {
402
451
  await trackSuccess('rollback_run', {
403
452
  projectName,
404
453
  targetRevision: String(targetRevisionNum),
405
- ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision) } : {}),
454
+ ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision), workerImageMatched: workerTarget.imageMatched ?? undefined } : {}),
406
455
  });
407
456
  outro(color.green(workerTarget
408
457
  ? `Services successfully rolled back to ${doneLabel}! 🚀`
@@ -9,10 +9,11 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
9
9
  import { failCommand, refuseIfNonInteractive } from '../utils/command.js';
10
10
  import { atomicWriteFile } from '../utils/atomic-write.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
- import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, readRenderedContainerEnvNames } from '../utils/resolvers.js';
12
+ import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, readRenderedContainerEnvNames, readTerraformProjectName } from '../utils/resolvers.js';
13
13
  import { ADDON_ENV_VARS, ADDON_REGISTRY } from '../utils/addons.js';
14
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
15
15
  import { truncateSpinnerText } from '../utils/spinner-text.js';
16
+ import { withProjectLock } from '../utils/file-lock.js';
16
17
 
17
18
  // Static sites provision no secrets vault, so push/pull/audit would fail
18
19
  // obscurely against a Secrets Manager secret that can never exist. One
@@ -63,9 +64,11 @@ function resolveSecretsFile(envFilePath) {
63
64
  }
64
65
 
65
66
  function resolveSecretsProject(projectName) {
66
- return (typeof projectName === 'string' && projectName.trim())
67
- ? projectName.trim()
68
- : path.basename(process.cwd());
67
+ // BUG-162: the terraform project name (what provisioned the vault)
68
+ // outranks the directory basename — a renamed directory otherwise
69
+ // silently aims at a missing vault.
70
+ if (typeof projectName === 'string' && projectName.trim()) return projectName.trim();
71
+ return readTerraformProjectName(process.cwd()) || path.basename(process.cwd());
69
72
  }
70
73
 
71
74
  // Vault identifiers carry the tree's resource suffix (matching the
@@ -84,9 +87,15 @@ export async function resolveSecretsRegion(options = {}) {
84
87
  try {
85
88
  const backendTfPath = path.join(process.cwd(), 'terraform', 'backend.tf');
86
89
  const backendTfContent = await fs.readFile(backendTfPath, 'utf-8');
87
- const regionMatch = backendTfContent.match(/region\s*=\s*"([^"]+)"/);
88
- if (regionMatch && !regionMatch[1].includes('{{')) {
89
- return regionMatch[1];
90
+ // BUG-164: scan line-wise skipping comments — the old whole-file
91
+ // regex resolved commented-out regions (or legacy lines) as live.
92
+ for (const rawLine of backendTfContent.split('\n')) {
93
+ const line = rawLine.trim();
94
+ if (line === '' || line.startsWith('#')) continue;
95
+ const regionMatch = line.match(/region\s*=\s*"([^"]+)"/);
96
+ if (regionMatch && !regionMatch[1].includes('{{')) {
97
+ return regionMatch[1];
98
+ }
90
99
  }
91
100
  } catch {
92
101
  // Fall through to the product default region if the file is missing or unreadable
@@ -176,17 +185,21 @@ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
176
185
  // the base set above (fail-closed; the TF precondition backstops
177
186
  // real collisions there).
178
187
  if (!tfFiles.includes('worker.tf')) names.delete('NODE_ENV');
179
- const dbFile = tfFiles.find((file) => file.startsWith('database') && file.endsWith('.tf'));
180
- if (dbFile) {
188
+ const dbFiles = tfFiles.filter((file) => file.startsWith('database') && file.endsWith('.tf'));
189
+ if (dbFiles.length > 0) {
181
190
  for (const name of DB_MANAGED_ENV) names.add(name);
182
191
  // DB_ENGINE is rendered only for non-postgres engines: including
183
192
  // it blindly would auto-skip a legitimate custom key on postgres
184
- // trees with a false "injected by Grada" notice. Unparseable
193
+ // trees with a false "injected by Grada" notice. Every database
194
+ // file is sniffed — a stale database.tf sorting before the live
195
+ // database-mysql.tf must not hide the engine. Unparseable
185
196
  // files exclude it — the preflights still catch real collisions.
186
197
  try {
187
- const dbContent = await fs.readFile(path.join(cwd, 'terraform', dbFile), 'utf-8');
188
- const engine = /engine\s*=\s*"([^"]+)"/.exec(dbContent)?.[1];
189
- if (engine && engine !== 'postgres') names.add('DB_ENGINE');
198
+ const contents = await Promise.all(
199
+ dbFiles.map((dbFile) => fs.readFile(path.join(cwd, 'terraform', dbFile), 'utf-8'))
200
+ );
201
+ const engines = contents.map((dbContent) => /engine\s*=\s*"([^"]+)"/.exec(dbContent)?.[1]);
202
+ if (engines.some((engine) => engine && engine !== 'postgres')) names.add('DB_ENGINE');
190
203
  } catch {
191
204
  // Fall through with the base DB set.
192
205
  }
@@ -231,6 +244,96 @@ export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) {
231
244
  return { missingLocally, mismatched, untrackedLocally };
232
245
  }
233
246
 
247
+ // Names the shape of a non-object vault payload for refusal messages.
248
+ function vaultPayloadShape(parsed) {
249
+ if (parsed === null) return 'null';
250
+ if (Array.isArray(parsed)) return 'array';
251
+ return typeof parsed;
252
+ }
253
+
254
+ // Validates a GetSecretValue response into the managed JSON object.
255
+ // Refuses binary payloads (BUG-145: they read as "empty" and a push
256
+ // would full-replace them away without the removal confirm) and
257
+ // non-object/non-string payloads (BUG-159: phantom `0,1` removals,
258
+ // garbage pull keys, TypeError crashes). A response carrying neither
259
+ // field means an empty/new vault — live AWS never returns that shape
260
+ // for a valued secret.
261
+ function vaultPayloadObject(resp, secretId) {
262
+ if (resp.SecretBinary != null) {
263
+ const binaryError = new Error(`Refusing to operate on "${secretId}": the vault payload is binary, not the JSON object secrets commands manage. Migrate it to a JSON string payload first.`);
264
+ binaryError.code = 'REMOTE_SECRET_BINARY';
265
+ throw binaryError;
266
+ }
267
+ if (resp.SecretString == null) return {};
268
+ let parsed;
269
+ try {
270
+ parsed = JSON.parse(resp.SecretString);
271
+ } catch {
272
+ const jsonError = new Error('Remote secret payload is not valid JSON.');
273
+ jsonError.code = 'REMOTE_SECRET_MALFORMED';
274
+ throw jsonError;
275
+ }
276
+ const valuesOk = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
277
+ && Object.values(parsed).every((value) => typeof value === 'string');
278
+ if (!valuesOk) {
279
+ const shapeError = new Error(`Remote secret payload must be a JSON object of string values, found ${vaultPayloadShape(parsed)}.`);
280
+ shapeError.code = 'REMOTE_SECRET_MALFORMED';
281
+ throw shapeError;
282
+ }
283
+ return parsed;
284
+ }
285
+
286
+ // Lenient key-attempt extractor for drop accounting: what key did this
287
+ // line TRY to define? Calibrated against the real dotenv parse — a line
288
+ // is dropped only when its attempted key is absent from it.
289
+ const ATTEMPTED_KEY_RE = /^\s*([^=:#\s][^=:]*?)\s*[=:]/;
290
+
291
+ // Finds .env input lines dotenv silently dropped plus duplicate keys
292
+ // (BUG-143). Multiline double-quoted values span lines — continuation
293
+ // lines are value text, not dropped lines. Pure and unit-tested via
294
+ // push output.
295
+ function analyzeEnvLines(envContent, parsedSecrets) {
296
+ const dropped = [];
297
+ const seen = new Map();
298
+ const lines = String(envContent ?? '').split('\n');
299
+ let continuation = false;
300
+ lines.forEach((rawLine, index) => {
301
+ const line = rawLine.replace(/\r$/, '');
302
+ const wasContinuation = continuation;
303
+ // Track unescaped double quotes across lines (backslash escapes).
304
+ let open = continuation;
305
+ for (let i = 0; i < line.length; i += 1) {
306
+ if (line[i] === '\\') {
307
+ i += 1;
308
+ } else if (line[i] === '"') {
309
+ open = !open;
310
+ }
311
+ }
312
+ continuation = open;
313
+ if (wasContinuation) return;
314
+ const trimmed = line.trim();
315
+ if (trimmed === '' || trimmed.startsWith('#')) return;
316
+ const effective = line.replace(/^\s*export\s+/, '');
317
+ const match = ATTEMPTED_KEY_RE.exec(effective);
318
+ if (!match) {
319
+ dropped.push({ line: index + 1, content: trimmed });
320
+ return;
321
+ }
322
+ const attempted = match[1].trim();
323
+ if (!Object.hasOwn(parsedSecrets, attempted)) {
324
+ dropped.push({ line: index + 1, content: trimmed });
325
+ return;
326
+ }
327
+ if (!seen.has(attempted)) seen.set(attempted, []);
328
+ seen.get(attempted).push(index + 1);
329
+ });
330
+ const duplicates = [];
331
+ for (const [key, dupLines] of seen) {
332
+ if (dupLines.length > 1) duplicates.push({ key, lines: dupLines });
333
+ }
334
+ return { dropped, duplicates };
335
+ }
336
+
234
337
  // Shared failure tail for push/pull/audit: identical telemetry stamps,
235
338
  // not-found guidance, auth branch, and spinner/exit routing, so the
236
339
  // three subcommands cannot drift apart again.
@@ -299,6 +402,27 @@ export async function pushSecrets(envFilePath, projectName, options = {}) {
299
402
  }
300
403
 
301
404
  async function pushSecretsMain(envFilePath, projectName, options = {}) {
405
+ // BUG-144: push is read-modify-full-replace — serialize local
406
+ // concurrent pushes like every other mutating family (the re-read
407
+ // before UpdateSecret below covers cross-machine second writers).
408
+ return withProjectLock(process.cwd(), () => pushSecretsInner(envFilePath, projectName, options));
409
+ }
410
+
411
+ // Builds the secrets_pushed success payload shared by the full-push and
412
+ // all-skipped early-return paths, so the two can never skew key names.
413
+ function pushSuccessTelemetry({ projectName, pushableSecrets, keysChanged, removed, collisions, skipped, staleSkipped }) {
414
+ return {
415
+ projectName,
416
+ secret_count: Object.keys(pushableSecrets).length,
417
+ keys_changed: keysChanged,
418
+ removed_count: removed.length,
419
+ managed_collisions: collisions.length,
420
+ skipped_count: skipped.length,
421
+ stale_skipped_count: staleSkipped.length,
422
+ };
423
+ }
424
+
425
+ async function pushSecretsInner(envFilePath, projectName, options = {}) {
302
426
  const refused = await secretsManagedTreeGuard('push', 'secrets_pushed', projectName, options);
303
427
  if (refused) return refused;
304
428
  const pushGuard = secretsTargetGuard('push');
@@ -319,9 +443,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
319
443
  resolvedFilePath = '.env';
320
444
  }
321
445
 
322
- const resolvedProjectName = (typeof explicitProjectName === 'string' && explicitProjectName.trim())
323
- ? explicitProjectName.trim()
324
- : path.basename(process.cwd());
446
+ // BUG-162: shared helper — the terraform project name outranks the
447
+ // directory basename (a renamed directory must not aim at a phantom).
448
+ const resolvedProjectName = resolveSecretsProject(explicitProjectName);
325
449
 
326
450
  const s = spinner();
327
451
  s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
@@ -377,6 +501,23 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
377
501
 
378
502
  const parsedSecrets = dotenv.parse(envContent);
379
503
 
504
+ // BUG-143: dotenv silently drops lines it cannot parse (and
505
+ // last-wins duplicates) — name them so the success count below
506
+ // reconciles with the file. Runs before the empty early-return
507
+ // so an all-dropped file explains itself.
508
+ const { dropped: droppedLines, duplicates: duplicateKeys } = analyzeEnvLines(envContent, parsedSecrets);
509
+ if (droppedLines.length > 0 || duplicateKeys.length > 0) {
510
+ s.stop('Pre-flight checks done.');
511
+ if (droppedLines.length > 0) {
512
+ console.log(color.yellow(`⚠️ Warning: ${droppedLines.length} ${droppedLines.length === 1 ? 'line' : 'lines'} in ${resolvedFilePath} could not be parsed and ${droppedLines.length === 1 ? 'was' : 'were'} ignored:`));
513
+ for (const { line, content } of droppedLines) console.log(color.yellow(`- line ${line}: ${content}`));
514
+ }
515
+ for (const { key, lines } of duplicateKeys) {
516
+ console.log(color.yellow(`⚠️ Warning: duplicate key "${key}" (lines ${lines.join(', ')}) — last value wins.`));
517
+ }
518
+ s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
519
+ }
520
+
380
521
  if (Object.keys(parsedSecrets).length === 0) {
381
522
  s.stop('No secrets found in file.');
382
523
  return;
@@ -416,6 +557,15 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
416
557
  }
417
558
  if (Object.keys(pushableSecrets).length === 0) {
418
559
  console.log(color.dim('Nothing left to push — the vault and secret_keys.json are unchanged.'));
560
+ await trackSuccess('secrets_pushed', pushSuccessTelemetry({
561
+ projectName: resolvedProjectName,
562
+ pushableSecrets,
563
+ keysChanged: [],
564
+ removed: [],
565
+ collisions,
566
+ skipped,
567
+ staleSkipped: [],
568
+ }));
419
569
  return;
420
570
  }
421
571
  if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
@@ -429,19 +579,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
429
579
 
430
580
  // 4. Fetch the existing secret payload to detect key changes (safe on new vaults)
431
581
  let existingKeys = null;
582
+ let firstSecretString = null;
583
+ const vaultId = `${secretVaultId(resolvedProjectName)}`;
432
584
  try {
433
585
  const existingResp = await client.send(new GetSecretValueCommand({
434
- SecretId: `${secretVaultId(resolvedProjectName)}`,
586
+ SecretId: vaultId,
435
587
  }));
436
- if (existingResp.SecretString) {
437
- try {
438
- existingKeys = Object.keys(JSON.parse(existingResp.SecretString));
439
- } catch {
440
- existingKeys = [];
441
- }
442
- } else {
443
- existingKeys = [];
444
- }
588
+ firstSecretString = existingResp.SecretString ?? null;
589
+ existingKeys = Object.keys(vaultPayloadObject(existingResp, vaultId));
445
590
  } catch (fetchError) {
446
591
  if (fetchError && fetchError.name === 'ResourceNotFoundException') {
447
592
  existingKeys = [];
@@ -494,9 +639,32 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
494
639
  s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
495
640
  }
496
641
 
642
+ // BUG-144: the confirm above can wait unboundedly — re-read the
643
+ // vault immediately before the full-replace write and abort when
644
+ // a second writer moved the payload since the first read.
645
+ let rereadSecretString = null;
646
+ let rereadBinary = false;
647
+ try {
648
+ const rereadResp = await client.send(new GetSecretValueCommand({ SecretId: vaultId }));
649
+ rereadSecretString = rereadResp.SecretString ?? null;
650
+ rereadBinary = rereadResp.SecretBinary != null;
651
+ } catch (rereadError) {
652
+ if (!rereadError || rereadError.name !== 'ResourceNotFoundException') throw rereadError;
653
+ }
654
+ if (rereadBinary || rereadSecretString !== firstSecretString) {
655
+ s.stop('Pre-flight checks done.');
656
+ return failCommand({
657
+ message: `\n✖ The vault changed while this push was waiting (a second writer updated it) — refusing to overwrite. Re-run the push to merge with the latest vault content.\n`,
658
+ event: 'secrets_pushed',
659
+ telemetry: { projectName: resolvedProjectName, error_code: 'SECRETS_VAULT_CHANGED' },
660
+ errorCode: 'SECRETS_VAULT_CHANGED',
661
+ reason: 'secrets-vault-changed',
662
+ });
663
+ }
664
+
497
665
  // 5. Update the secret string in AWS
498
666
  const command = new UpdateSecretCommand({
499
- SecretId: `${secretVaultId(resolvedProjectName)}`,
667
+ SecretId: vaultId,
500
668
  SecretString: JSON.stringify(pushableSecrets),
501
669
  });
502
670
 
@@ -505,7 +673,18 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
505
673
  const keys = Object.keys(pushableSecrets);
506
674
  const keysFilePath = path.join(process.cwd(), 'terraform', 'secret_keys.json');
507
675
 
508
- await atomicWriteFile(keysFilePath, JSON.stringify(keys, null, 2));
676
+ // BUG-160: skip the write when the file is already byte-identical
677
+ // so unchanged pushes don't dirty `git status`.
678
+ const nextKeysContent = JSON.stringify(keys, null, 2);
679
+ let keysUnchanged = false;
680
+ try {
681
+ keysUnchanged = (await fs.readFile(keysFilePath, 'utf-8')) === nextKeysContent;
682
+ } catch {
683
+ keysUnchanged = false;
684
+ }
685
+ if (!keysUnchanged) {
686
+ await atomicWriteFile(keysFilePath, nextKeysContent);
687
+ }
509
688
 
510
689
  s.stop(`✅ Successfully pushed ${Object.keys(pushableSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`);
511
690
 
@@ -599,15 +778,15 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
599
778
  }
600
779
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
601
780
 
602
- await trackSuccess('secrets_pushed', {
781
+ await trackSuccess('secrets_pushed', pushSuccessTelemetry({
603
782
  projectName: resolvedProjectName,
604
- secret_count: Object.keys(pushableSecrets).length,
605
- keys_changed: keysChanged,
606
- removed_count: removed.length,
607
- managed_collisions: collisions.length,
608
- skipped_count: skipped.length,
609
- stale_skipped_count: staleSkipped.length
610
- });
783
+ pushableSecrets,
784
+ keysChanged,
785
+ removed,
786
+ collisions,
787
+ skipped,
788
+ staleSkipped,
789
+ }));
611
790
  return { keysChanged, skipped };
612
791
 
613
792
  } catch (error) {
@@ -662,16 +841,7 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
662
841
  SecretId: `${secretVaultId(resolvedProjectName)}`,
663
842
  }));
664
843
 
665
- let remoteSecrets = {};
666
- if (resp.SecretString) {
667
- try {
668
- remoteSecrets = JSON.parse(resp.SecretString);
669
- } catch {
670
- const jsonError = new Error('Remote secret payload is not valid JSON.');
671
- jsonError.code = 'REMOTE_SECRET_MALFORMED';
672
- throw jsonError;
673
- }
674
- }
844
+ const remoteSecrets = vaultPayloadObject(resp, `${secretVaultId(resolvedProjectName)}`);
675
845
  const remoteKeys = Object.keys(remoteSecrets);
676
846
  s.stop('Remote secrets fetched.');
677
847
  remoteFetched = true;
@@ -726,6 +896,12 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
726
896
  ...Object.keys(localSecrets),
727
897
  ...remoteKeys.filter((k) => !Object.hasOwn(localSecrets, k)),
728
898
  ];
899
+ // BUG-161: the merge appends remote-only keys (reviving local
900
+ // deletions) — name what came back instead of syncing silently.
901
+ const appended = localExists ? remoteKeys.filter((k) => !Object.hasOwn(localSecrets, k)) : [];
902
+ if (appended.length > 0) {
903
+ console.log(color.yellow(`⚠️ Pulled ${appended.length} key${appended.length === 1 ? '' : 's'} not present locally (revived deletions?): ${appended.join(', ')}`));
904
+ }
729
905
  const unrepresentable = orderedKeys.filter((key) =>
730
906
  key === '__proto__' || quoteEnvValue(merged[key]) === null
731
907
  );
@@ -748,7 +924,7 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
748
924
  });
749
925
  await flushTelemetry();
750
926
 
751
- return { synced: remoteKeys.length, file: resolvedFilePath, overwritten: overwrite, conflicts: mismatched };
927
+ return { synced: remoteKeys.length, file: resolvedFilePath, overwritten: overwrite, conflicts: mismatched, appended };
752
928
  } catch (error) {
753
929
  return handleSecretsCatch({
754
930
  error,
@@ -799,16 +975,7 @@ async function auditSecretsMain(envFilePath, projectName, options = {}) {
799
975
  SecretId: `${secretVaultId(resolvedProjectName)}`,
800
976
  }));
801
977
 
802
- let remoteSecrets = {};
803
- if (resp.SecretString) {
804
- try {
805
- remoteSecrets = JSON.parse(resp.SecretString);
806
- } catch {
807
- const jsonError = new Error('Remote secret payload is not valid JSON.');
808
- jsonError.code = 'REMOTE_SECRET_MALFORMED';
809
- throw jsonError;
810
- }
811
- }
978
+ const remoteSecrets = vaultPayloadObject(resp, `${secretVaultId(resolvedProjectName)}`);
812
979
 
813
980
  const envPath = path.resolve(process.cwd(), resolvedFilePath);
814
981
  let localSecrets = {};
@@ -502,7 +502,10 @@ async function runStatusMain(input = {}) {
502
502
  return;
503
503
  }
504
504
 
505
- const alarmsResp = await cloudWatchClient.send(new DescribeAlarmsCommand({ AlarmNamePrefix: projectName, MaxRecords: 100 }));
505
+ // Namespaced stem (BUG-151): the raw project prefix merged prod
506
+ // + preview alarms into one verdict and could auto-diagnose the
507
+ // wrong cluster. Paired with workspace-aware alarm names (BUG-132).
508
+ const alarmsResp = await cloudWatchClient.send(new DescribeAlarmsCommand({ AlarmNamePrefix: `${namespacedProject}${resourceSuffix}`, MaxRecords: 100 }));
506
509
  const rawAlarms = [...(alarmsResp.MetricAlarms || []), ...(alarmsResp.CompositeAlarms || [])];
507
510
 
508
511
  const health = getServiceHealth(serviceDesc, rawAlarms);
@@ -7,6 +7,7 @@ import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-ru
7
7
  import { readTerraformComputeTarget, resolveHeadless } from '../utils/resolvers.js';
8
8
  import { trackEvent, flushTelemetry, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
9
9
  import { failCommand } from '../utils/command.js';
10
+ import { atomicWriteFile } from '../utils/atomic-write.js';
10
11
 
11
12
  function getProjectContext(cwd) {
12
13
  const context = { region: '', port: '', target: readTerraformComputeTarget(cwd) };
@@ -72,13 +73,13 @@ async function syncAiMain(options = {}) {
72
73
  if (assistants.includes('cursor')) {
73
74
  const cursorDir = path.join(cwd, '.cursor', 'rules');
74
75
  if (!fsSync.existsSync(cursorDir)) fsSync.mkdirSync(cursorDir, { recursive: true });
75
- fsSync.writeFileSync(path.join(cursorDir, 'grada.mdc'), getCursorRules(context));
76
+ await atomicWriteFile(path.join(cursorDir, 'grada.mdc'), getCursorRules(context));
76
77
  }
77
78
 
78
79
  if (assistants.includes('roo')) {
79
80
  const rooDir = path.join(cwd, '.roo', 'rules');
80
81
  if (!fsSync.existsSync(rooDir)) fsSync.mkdirSync(rooDir, { recursive: true });
81
- fsSync.writeFileSync(path.join(rooDir, 'grada.md'), getBaseRules(context));
82
+ await atomicWriteFile(path.join(rooDir, 'grada.md'), getBaseRules(context));
82
83
  }
83
84
 
84
85
  if (assistants.includes('trae')) {
@@ -90,7 +91,7 @@ async function syncAiMain(options = {}) {
90
91
  if (assistants.includes('continue')) {
91
92
  const promptsDir = path.join(cwd, '.prompts');
92
93
  if (!fsSync.existsSync(promptsDir)) fsSync.mkdirSync(promptsDir, { recursive: true });
93
- fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(context));
94
+ await atomicWriteFile(path.join(promptsDir, 'grada.prompt'), getBaseRules(context));
94
95
  }
95
96
 
96
97
  if (assistants.includes('windsurf')) {
@@ -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
+ }