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
@@ -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
@@ -170,17 +179,27 @@ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
170
179
  } catch {
171
180
  return [...names].sort();
172
181
  }
173
- const dbFile = tfFiles.find((file) => file.startsWith('database') && file.endsWith('.tf'));
174
- if (dbFile) {
182
+ // NODE_ENV is injected only when the worker renders (the generator
183
+ // scopes it to worker trees): on workerless trees it is a legitimate
184
+ // custom key and must not auto-skip (BUG-95). Unreadable dirs keep
185
+ // the base set above (fail-closed; the TF precondition backstops
186
+ // real collisions there).
187
+ if (!tfFiles.includes('worker.tf')) names.delete('NODE_ENV');
188
+ const dbFiles = tfFiles.filter((file) => file.startsWith('database') && file.endsWith('.tf'));
189
+ if (dbFiles.length > 0) {
175
190
  for (const name of DB_MANAGED_ENV) names.add(name);
176
191
  // DB_ENGINE is rendered only for non-postgres engines: including
177
192
  // it blindly would auto-skip a legitimate custom key on postgres
178
- // 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
179
196
  // files exclude it — the preflights still catch real collisions.
180
197
  try {
181
- const dbContent = await fs.readFile(path.join(cwd, 'terraform', dbFile), 'utf-8');
182
- const engine = /engine\s*=\s*"([^"]+)"/.exec(dbContent)?.[1];
183
- 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');
184
203
  } catch {
185
204
  // Fall through with the base DB set.
186
205
  }
@@ -225,6 +244,96 @@ export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) {
225
244
  return { missingLocally, mismatched, untrackedLocally };
226
245
  }
227
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
+
228
337
  // Shared failure tail for push/pull/audit: identical telemetry stamps,
229
338
  // not-found guidance, auth branch, and spinner/exit routing, so the
230
339
  // three subcommands cannot drift apart again.
@@ -293,6 +402,27 @@ export async function pushSecrets(envFilePath, projectName, options = {}) {
293
402
  }
294
403
 
295
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 = {}) {
296
426
  const refused = await secretsManagedTreeGuard('push', 'secrets_pushed', projectName, options);
297
427
  if (refused) return refused;
298
428
  const pushGuard = secretsTargetGuard('push');
@@ -313,9 +443,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
313
443
  resolvedFilePath = '.env';
314
444
  }
315
445
 
316
- const resolvedProjectName = (typeof explicitProjectName === 'string' && explicitProjectName.trim())
317
- ? explicitProjectName.trim()
318
- : 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);
319
449
 
320
450
  const s = spinner();
321
451
  s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
@@ -371,6 +501,23 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
371
501
 
372
502
  const parsedSecrets = dotenv.parse(envContent);
373
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
+
374
521
  if (Object.keys(parsedSecrets).length === 0) {
375
522
  s.stop('No secrets found in file.');
376
523
  return;
@@ -393,7 +540,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
393
540
  const skippedSet = new Set(skipped);
394
541
  const pushableSecrets = Object.fromEntries(Object.entries(parsedSecrets).filter(([key]) => !skippedSet.has(key)));
395
542
  const needsPreWriteOutput = skipped.length > 0 || wiringHits.length > 0
396
- || (collisions.length > 0 && pushTarget === 'lambda');
543
+ || (collisions.length > 0 && (pushTarget === 'lambda' || skipBypassed));
397
544
  if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
398
545
  for (const { key, indicator } of wiringHits) {
399
546
  console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
@@ -401,12 +548,24 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
401
548
  if (collisions.length > 0 && pushTarget === 'lambda') {
402
549
  console.log(color.yellow(`⚠️ Warning: ${summarizeKeys(collisions)} ${collisions.length === 1 ? 'is' : 'are'} also injected by Grada as plain environment variables — the pushed vault value may be shadowed at runtime.`));
403
550
  }
551
+ if (collisions.length > 0 && skipBypassed && pushTarget !== 'lambda') {
552
+ console.log(color.yellow(`⚠️ Warning: pushing ${summarizeKeys(collisions)} anyway (--yes) though Grada injects ${collisions.length === 1 ? 'it' : 'them'} — the apply preflight refuses until conflicting keys leave .env.`));
553
+ }
404
554
  if (skipped.length > 0) {
405
555
  console.log(color.yellow(`⚠️ Skipping ${skipped.length} colliding ${skipped.length === 1 ? 'key' : 'keys'} (injected by Grada — remove from .env to silence this):`));
406
556
  for (const key of skipped) console.log(color.yellow(`- ${key} (skipped — Grada-managed name)`));
407
557
  }
408
558
  if (Object.keys(pushableSecrets).length === 0) {
409
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
+ }));
410
569
  return;
411
570
  }
412
571
  if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
@@ -420,19 +579,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
420
579
 
421
580
  // 4. Fetch the existing secret payload to detect key changes (safe on new vaults)
422
581
  let existingKeys = null;
582
+ let firstSecretString = null;
583
+ const vaultId = `${secretVaultId(resolvedProjectName)}`;
423
584
  try {
424
585
  const existingResp = await client.send(new GetSecretValueCommand({
425
- SecretId: `${secretVaultId(resolvedProjectName)}`,
586
+ SecretId: vaultId,
426
587
  }));
427
- if (existingResp.SecretString) {
428
- try {
429
- existingKeys = Object.keys(JSON.parse(existingResp.SecretString));
430
- } catch {
431
- existingKeys = [];
432
- }
433
- } else {
434
- existingKeys = [];
435
- }
588
+ firstSecretString = existingResp.SecretString ?? null;
589
+ existingKeys = Object.keys(vaultPayloadObject(existingResp, vaultId));
436
590
  } catch (fetchError) {
437
591
  if (fetchError && fetchError.name === 'ResourceNotFoundException') {
438
592
  existingKeys = [];
@@ -448,6 +602,16 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
448
602
  // exclusion from the vault write is covered by the skip notice
449
603
  // above, not by this confirm.
450
604
  const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
605
+ // BUG-89: skipped keys are present in .env (so they never land in
606
+ // `removed`) but excluded from the vault write — a stale vault
607
+ // value for a skipped key is wiped by the full-replace update.
608
+ // Name every such victim loudly. The skip notice above is the
609
+ // acknowledgment, so unlike BUG-80 removals these never confirm.
610
+ const staleSkipped = skipped.filter((key) => (existingKeys ?? []).includes(key));
611
+ if (staleSkipped.length > 0) {
612
+ console.log(color.yellow(`⚠️ ${staleSkipped.length} skipped ${staleSkipped.length === 1 ? 'key' : 'keys'} still ${staleSkipped.length === 1 ? 'has' : 'have'} a stale vault value that this push deletes (no longer pushed):`));
613
+ for (const key of staleSkipped) console.log(color.red(`- ${key} (stale vault value deleted — key is skipped)`));
614
+ }
451
615
  if (removed.length > 0) {
452
616
  s.stop('Pre-flight checks done.');
453
617
  console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`));
@@ -475,9 +639,32 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
475
639
  s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
476
640
  }
477
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
+
478
665
  // 5. Update the secret string in AWS
479
666
  const command = new UpdateSecretCommand({
480
- SecretId: `${secretVaultId(resolvedProjectName)}`,
667
+ SecretId: vaultId,
481
668
  SecretString: JSON.stringify(pushableSecrets),
482
669
  });
483
670
 
@@ -486,7 +673,18 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
486
673
  const keys = Object.keys(pushableSecrets);
487
674
  const keysFilePath = path.join(process.cwd(), 'terraform', 'secret_keys.json');
488
675
 
489
- 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
+ }
490
688
 
491
689
  s.stop(`✅ Successfully pushed ${Object.keys(pushableSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`);
492
690
 
@@ -512,7 +710,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
512
710
  ecs_restart: false,
513
711
  removed_count: removed.length,
514
712
  managed_collisions: collisions.length,
515
- skipped_count: skipped.length
713
+ skipped_count: skipped.length,
714
+ stale_skipped_count: staleSkipped.length
516
715
  });
517
716
  return { keysChanged: false, restarted: false, skipped };
518
717
  }
@@ -528,7 +727,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
528
727
  ecs_restart: false,
529
728
  removed_count: removed.length,
530
729
  managed_collisions: collisions.length,
531
- skipped_count: skipped.length
730
+ skipped_count: skipped.length,
731
+ stale_skipped_count: staleSkipped.length
532
732
  });
533
733
  return { keysChanged: false, restarted: false, skipped };
534
734
  }
@@ -544,7 +744,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
544
744
  message: 'Keys are unchanged. Trigger a rolling ECS restart to apply new values immediately?',
545
745
  initialValue: false,
546
746
  });
547
- if (shouldRestart) {
747
+ if (shouldRestart === true) {
548
748
  const cluster = resolveEcsCluster(resolvedProjectName, opts);
549
749
  const service = resolveEcsService(resolvedProjectName, opts);
550
750
  const ecsClient = resolveClient(opts.ecsClient ?? opts.ecs, ECSClient, targetRegion ? { region: targetRegion } : {});
@@ -569,7 +769,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
569
769
  ecs_restart: true,
570
770
  removed_count: removed.length,
571
771
  managed_collisions: collisions.length,
572
- skipped_count: skipped.length
772
+ skipped_count: skipped.length,
773
+ stale_skipped_count: staleSkipped.length
573
774
  });
574
775
  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')}`));
575
776
  return { keysChanged: false, restarted: true, cluster, service, skipped };
@@ -577,14 +778,15 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
577
778
  }
578
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')}`));
579
780
 
580
- await trackSuccess('secrets_pushed', {
781
+ await trackSuccess('secrets_pushed', pushSuccessTelemetry({
581
782
  projectName: resolvedProjectName,
582
- secret_count: Object.keys(pushableSecrets).length,
583
- keys_changed: keysChanged,
584
- removed_count: removed.length,
585
- managed_collisions: collisions.length,
586
- skipped_count: skipped.length
587
- });
783
+ pushableSecrets,
784
+ keysChanged,
785
+ removed,
786
+ collisions,
787
+ skipped,
788
+ staleSkipped,
789
+ }));
588
790
  return { keysChanged, skipped };
589
791
 
590
792
  } catch (error) {
@@ -639,16 +841,7 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
639
841
  SecretId: `${secretVaultId(resolvedProjectName)}`,
640
842
  }));
641
843
 
642
- let remoteSecrets = {};
643
- if (resp.SecretString) {
644
- try {
645
- remoteSecrets = JSON.parse(resp.SecretString);
646
- } catch {
647
- const jsonError = new Error('Remote secret payload is not valid JSON.');
648
- jsonError.code = 'REMOTE_SECRET_MALFORMED';
649
- throw jsonError;
650
- }
651
- }
844
+ const remoteSecrets = vaultPayloadObject(resp, `${secretVaultId(resolvedProjectName)}`);
652
845
  const remoteKeys = Object.keys(remoteSecrets);
653
846
  s.stop('Remote secrets fetched.');
654
847
  remoteFetched = true;
@@ -703,6 +896,12 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
703
896
  ...Object.keys(localSecrets),
704
897
  ...remoteKeys.filter((k) => !Object.hasOwn(localSecrets, k)),
705
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
+ }
706
905
  const unrepresentable = orderedKeys.filter((key) =>
707
906
  key === '__proto__' || quoteEnvValue(merged[key]) === null
708
907
  );
@@ -725,7 +924,7 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
725
924
  });
726
925
  await flushTelemetry();
727
926
 
728
- return { synced: remoteKeys.length, file: resolvedFilePath, overwritten: overwrite, conflicts: mismatched };
927
+ return { synced: remoteKeys.length, file: resolvedFilePath, overwritten: overwrite, conflicts: mismatched, appended };
729
928
  } catch (error) {
730
929
  return handleSecretsCatch({
731
930
  error,
@@ -776,16 +975,7 @@ async function auditSecretsMain(envFilePath, projectName, options = {}) {
776
975
  SecretId: `${secretVaultId(resolvedProjectName)}`,
777
976
  }));
778
977
 
779
- let remoteSecrets = {};
780
- if (resp.SecretString) {
781
- try {
782
- remoteSecrets = JSON.parse(resp.SecretString);
783
- } catch {
784
- const jsonError = new Error('Remote secret payload is not valid JSON.');
785
- jsonError.code = 'REMOTE_SECRET_MALFORMED';
786
- throw jsonError;
787
- }
788
- }
978
+ const remoteSecrets = vaultPayloadObject(resp, `${secretVaultId(resolvedProjectName)}`);
789
979
 
790
980
  const envPath = path.resolve(process.cwd(), resolvedFilePath);
791
981
  let localSecrets = {};
@@ -8,7 +8,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
8
8
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
- import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix, resolveNamespacedProject } from '../utils/resolvers.js';
12
12
  import { runDiagnose } from './diagnose.js';
13
13
  import { fetchGoldenSignals } from '../utils/golden-signals.js';
14
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
@@ -38,7 +38,7 @@ export function parseStatusArgs(argv = []) {
38
38
  const args = normalizeArgv(argv);
39
39
  if (args[0] === 'status') args.shift();
40
40
  const { options, unknown } = parseFlags(args, {
41
- string: ['region'],
41
+ string: ['region', 'workspace'],
42
42
  boolean: ['headless'],
43
43
  bareBoolean: ['json', 'watch'],
44
44
  });
@@ -128,9 +128,10 @@ export async function runLambdaStatus(input = {}) {
128
128
  const cwd = options.cwd || process.cwd();
129
129
  const region = options.region;
130
130
  const projectName = options.projectName;
131
+ const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
131
132
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
132
133
  ? options.functionName.trim()
133
- : `${projectName}${readResourceSuffix(cwd)}-fn`;
134
+ : `${namespacedProject}${readResourceSuffix(cwd)}-fn`;
134
135
  const asJson = Boolean(options.json);
135
136
  const runSync = options.spawnSyncImpl || spawnSync;
136
137
 
@@ -260,7 +261,8 @@ export async function runStaticStatus(input = {}) {
260
261
  const cwd = options.cwd || process.cwd();
261
262
  const region = options.region;
262
263
  const projectName = options.projectName;
263
- const comment = `${projectName}${readResourceSuffix(cwd)}-cdn`;
264
+ const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
265
+ const comment = `${namespacedProject}${readResourceSuffix(cwd)}-cdn`;
264
266
  const asJson = Boolean(options.json);
265
267
  const cloudFrontClient = resolveClient(options.cloudFrontClient, CloudFrontClient, { region });
266
268
 
@@ -451,9 +453,13 @@ async function runStatusMain(input = {}) {
451
453
  return runStaticStatus({ ...options, cwd, region, projectName });
452
454
  }
453
455
  const resourceSuffix = readResourceSuffix(cwd);
454
- const cluster = options.cluster || process.env.ECS_CLUSTER || `${projectName}${resourceSuffix}-cluster`;
455
- const serviceName = options.service || process.env.ECS_SERVICE || `${projectName}${resourceSuffix}-service`;
456
- const logGroup = options.logGroup || process.env.ECS_LOG_GROUP || `/ecs/${projectName}${resourceSuffix}`;
456
+ // Workspace-namespaced resources (BUG-90): --workspace (or the local
457
+ // .terraform/environment) targets a preview stack like rollback and db
458
+ // do. Explicit flags/env keep winning; telemetry keeps the raw name.
459
+ const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
460
+ const cluster = options.cluster || process.env.ECS_CLUSTER || `${namespacedProject}${resourceSuffix}-cluster`;
461
+ const serviceName = options.service || process.env.ECS_SERVICE || `${namespacedProject}${resourceSuffix}-service`;
462
+ const logGroup = options.logGroup || process.env.ECS_LOG_GROUP || `/ecs/${namespacedProject}${resourceSuffix}`;
457
463
 
458
464
  // --watch repaints the human dashboard; --json stays a single shot.
459
465
  if (Boolean(options.watch) && !asJson) {
@@ -496,7 +502,10 @@ async function runStatusMain(input = {}) {
496
502
  return;
497
503
  }
498
504
 
499
- 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 }));
500
509
  const rawAlarms = [...(alarmsResp.MetricAlarms || []), ...(alarmsResp.CompositeAlarms || [])];
501
510
 
502
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 }));