grada-run 0.41.5 → 0.42.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.
@@ -3,7 +3,7 @@ import color from 'picocolors';
3
3
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
4
4
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
5
5
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
6
- import { resolveRegion, resolveProjectName, resolveLogGroup, resolveCwd, isComputeTarget } from '../utils/resolvers.js';
6
+ import { resolveRegion, resolveProjectName, resolveLogGroup, resolveCwd, isComputeTarget, withWorkspaceNamespace } from '../utils/resolvers.js';
7
7
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
8
8
  import { sleep } from '../utils/system.js';
9
9
 
@@ -40,6 +40,18 @@ export function normalizeTailLines(value) {
40
40
  return n;
41
41
  }
42
42
 
43
+ function isValidTailLines(value) {
44
+ if (typeof value === 'number') return Number.isInteger(value) && value >= 1;
45
+ if (typeof value === 'string') return /^\d+$/.test(value.trim()) && parseInt(value, 10) >= 1;
46
+ return false;
47
+ }
48
+
49
+ function isValidSinceDuration(value) {
50
+ if (typeof value === 'number') return Number.isFinite(value);
51
+ if (typeof value === 'string') return SINCE_RE.test(value.trim());
52
+ return false;
53
+ }
54
+
43
55
  export function parseSinceDuration(input) {
44
56
  if (input === undefined || input === null || input === '') return UNIT_MS.h;
45
57
  if (typeof input === 'number' && Number.isFinite(input)) return Math.max(0, input * 1000);
@@ -86,7 +98,7 @@ export function parseLogsArgs(argv = []) {
86
98
  const args = normalizeArgv(argv);
87
99
  if (args[0] === 'logs') args.shift();
88
100
  const { options, rest, unknown } = parseFlags(args, {
89
- string: ['since', 'region'],
101
+ string: ['since', 'region', 'workspace'],
90
102
  number: ['tail'],
91
103
  boolean: ['headless'],
92
104
  bareBoolean: ['follow', 'error'],
@@ -103,6 +115,44 @@ function eventKey(event) {
103
115
  return `${event.timestamp}:${event.message}`;
104
116
  }
105
117
 
118
+ // Fetches the most recent matching events from a log group.
119
+ // FilterLogEvents pages oldest-first, so slicing the first page shows the
120
+ // OLDEST N on groups larger than one page (BUG-87). This probes with a
121
+ // small page (cheap when the group fits), and only multi-page groups pay
122
+ // for a wide-page scan to the live edge; a rolling window keeps memory
123
+ // O(tail). Returns `{ events, nextToken }` — the trailing window plus the
124
+ // last valid page token (for follow-mode continuation).
125
+ export async function fetchLatestEvents(logsClient, baseInput = {}, { tail = DEFAULT_TAIL_LINES, onlyErrors = false } = {}) {
126
+ const want = Math.max(1, tail);
127
+ const probeSize = Math.min(want, 10000);
128
+ const first = await logsClient.send(new FilterLogEventsCommand({ ...baseInput, limit: probeSize }));
129
+ if (!first.nextToken) {
130
+ const events = first.events || [];
131
+ return {
132
+ events: (onlyErrors ? events.filter((e) => isErrorLine(e.message)) : events).slice(-want),
133
+ nextToken: undefined,
134
+ };
135
+ }
136
+ const window = [];
137
+ let nextToken;
138
+ let lastToken;
139
+ do {
140
+ const resp = await logsClient.send(new FilterLogEventsCommand({
141
+ ...baseInput,
142
+ limit: 10000,
143
+ ...(nextToken ? { nextToken } : {}),
144
+ }));
145
+ const events = onlyErrors ? (resp.events || []).filter((e) => isErrorLine(e.message)) : (resp.events || []);
146
+ for (const event of events) {
147
+ window.push(event);
148
+ if (window.length > want) window.shift();
149
+ }
150
+ if (resp.nextToken) lastToken = resp.nextToken;
151
+ nextToken = resp.nextToken;
152
+ } while (nextToken);
153
+ return { events: window, nextToken: lastToken };
154
+ }
155
+
106
156
  export function isNotFoundError(error) {
107
157
  return error && (
108
158
  error.name === 'ResourceNotFoundException' ||
@@ -145,8 +195,12 @@ async function runLogsMain(input = {}) {
145
195
  try {
146
196
  cwd = resolveCwd(options);
147
197
  region = resolveRegion(options, cwd);
148
- service = resolveServiceName(options, cwd);
149
- logGroup = resolveLogGroup(options, cwd);
198
+ // Workspace-namespaced resources (BUG-90): --workspace (or the
199
+ // local .terraform/environment) targets a preview stack like
200
+ // rollback and db do. Explicit flags/env keep winning.
201
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
202
+ service = resolveServiceName(namespacedOptions, cwd);
203
+ logGroup = resolveLogGroup(namespacedOptions, cwd);
150
204
  } catch {
151
205
  return failProjectNotInitialized({ event: 'logs_streamed' });
152
206
  }
@@ -158,6 +212,32 @@ async function runLogsMain(input = {}) {
158
212
  const isLambda = isComputeTarget(cwd, 'lambda');
159
213
  const explicitService = hasExplicitService(options) && !isLambda;
160
214
 
215
+ // Explicit garbage fails loud (BUG-107): silently substituting defaults
216
+ // for a mistyped --tail/--since shows logs the user never asked for.
217
+ // Absent flags still default via the normalizers below.
218
+ const rawTail = options.tail ?? options.tailLines ?? options.lines;
219
+ if (rawTail !== undefined && !isValidTailLines(rawTail)) {
220
+ return failCommand({
221
+ noExit: isProgrammaticCall(options),
222
+ message: `\n✖ Invalid --tail "${rawTail}". Pass a positive integer (line count).\n`,
223
+ event: 'logs_streamed',
224
+ telemetry: { projectName: resolveProjectName(options, cwd) },
225
+ errorCode: 'INVALID_TAIL',
226
+ reason: 'invalid-tail',
227
+ });
228
+ }
229
+ const rawSince = options.since ?? options.sinceDuration;
230
+ if (rawSince !== undefined && !isValidSinceDuration(rawSince)) {
231
+ return failCommand({
232
+ noExit: isProgrammaticCall(options),
233
+ message: `\n✖ Invalid --since "${rawSince}". Pass a duration like 30s, 5m, 1h, or 7d.\n`,
234
+ event: 'logs_streamed',
235
+ telemetry: { projectName: resolveProjectName(options, cwd) },
236
+ errorCode: 'INVALID_SINCE',
237
+ reason: 'invalid-since',
238
+ });
239
+ }
240
+
161
241
  const sinceRaw = options.since ?? options.sinceDuration ?? (follow ? undefined : DEFAULT_SINCE);
162
242
  const startTime = sinceRaw === undefined ? undefined : Date.now() - parseSinceDuration(sinceRaw);
163
243
 
@@ -194,40 +274,47 @@ async function runLogsMain(input = {}) {
194
274
 
195
275
  const seen = new Set();
196
276
  const collected = [];
197
- let nextToken;
198
- let polls = 0;
199
- let firstPoll = true;
200
-
201
- do {
202
- const input = { logGroupName: logGroup, limit: Math.min(Math.max(tail, 1), 10000) };
203
- if (startTime !== undefined) input.startTime = startTime;
204
- if (explicitService) input.logStreamNamePrefix = service;
205
- if (nextToken) input.nextToken = nextToken;
206
-
207
- const resp = await logsClient.send(new FilterLogEventsCommand(input));
208
- if (resp.nextToken) nextToken = resp.nextToken;
209
-
210
- if (seen.size > 5000) seen.clear();
211
-
212
- let fresh = (resp.events || []).filter((e) => {
213
- const key = eventKey(e);
214
- if (seen.has(key)) return false;
215
- seen.add(key);
216
- return true;
217
- });
218
- if (onlyErrors) fresh = fresh.filter((e) => isErrorLine(e.message));
219
- if (firstPoll) fresh = fresh.slice(-tail);
220
-
221
- for (const event of fresh) {
222
- console.log(formatLogLine(event));
223
- collected.push(String(event.message ?? ''));
224
- }
277
+ const dedupe = (e) => {
278
+ const key = eventKey(e);
279
+ if (seen.has(key)) return false;
280
+ seen.add(key);
281
+ return true;
282
+ };
283
+ const baseInput = { logGroupName: logGroup };
284
+ if (startTime !== undefined) baseInput.startTime = startTime;
285
+ if (explicitService) baseInput.logStreamNamePrefix = service;
286
+
287
+ // First poll starts at the live edge (see fetchLatestEvents):
288
+ // slicing an unscanned first page would show the OLDEST N.
289
+ const edge = await fetchLatestEvents(logsClient, baseInput, { tail, onlyErrors });
290
+ let nextToken = edge.nextToken;
291
+ let polls = 1;
292
+ for (const event of edge.events.filter(dedupe)) {
293
+ console.log(formatLogLine(event));
294
+ collected.push(String(event.message ?? ''));
295
+ }
296
+ if (follow && !stopped && polls < maxPolls) {
297
+ do {
298
+ await sleep(pollIntervalMs);
299
+ const input = { ...baseInput, limit: Math.min(Math.max(tail, 1), 10000) };
300
+ if (nextToken) input.nextToken = nextToken;
301
+
302
+ const resp = await logsClient.send(new FilterLogEventsCommand(input));
303
+ if (resp.nextToken) nextToken = resp.nextToken;
304
+
305
+ if (seen.size > 5000) seen.clear();
225
306
 
226
- firstPoll = false;
227
- polls += 1;
228
- if (!follow || stopped || polls >= maxPolls) break;
229
- await sleep(pollIntervalMs);
230
- } while (true);
307
+ let fresh = (resp.events || []).filter(dedupe);
308
+ if (onlyErrors) fresh = fresh.filter((e) => isErrorLine(e.message));
309
+
310
+ for (const event of fresh) {
311
+ console.log(formatLogLine(event));
312
+ collected.push(String(event.message ?? ''));
313
+ }
314
+
315
+ polls += 1;
316
+ } while (!stopped && polls < maxPolls);
317
+ }
231
318
 
232
319
  if (collected.length === 0) {
233
320
  console.log(color.cyan(`\nℹ Waiting for logs...`));
@@ -452,7 +452,7 @@ export function resolveMcpTransport(input = {}) {
452
452
  // every OS layout from one machine.
453
453
  export const MCP_INSTALL_EDITORS = ['windsurf', 'zed', 'cursor', 'vscode', 'claude-desktop', 'gemini-cli'];
454
454
 
455
- export const MCP_SERVER_CONFIG = { command: 'npx', args: ['grada-run', 'mcp'] };
455
+ export const MCP_SERVER_CONFIG = { command: 'npx', args: ['--yes', 'grada-run', 'mcp'] };
456
456
 
457
457
  export function mcpInstallTarget(editor, homeDir = safeHomedir(), platform = os.platform()) {
458
458
  // No home, no target: null reads as "unresolvable" like an unknown
@@ -6,12 +6,13 @@ import {
6
6
  UpdateServiceCommand,
7
7
  } from '@aws-sdk/client-ecs';
8
8
  import color from 'picocolors';
9
+ import path from 'path';
9
10
  import { intro, outro, spinner, select, isCancel } from '@clack/prompts';
10
11
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
11
12
  import { failCommand, failAwsError, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
12
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
14
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
14
- import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, resolveWorkspaceSuffix, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
16
  import { requireManagedTree } from '../utils/terraform-metadata.js';
16
17
  import { truncateSpinnerText } from '../utils/spinner-text.js';
17
18
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
@@ -82,6 +83,7 @@ async function runRollbackMain(input = {}) {
82
83
  let projectName;
83
84
  let cluster;
84
85
  let service;
86
+ let namespacedProject;
85
87
  try {
86
88
  cwd = resolveCwd(options);
87
89
  region = resolveRegion(options, cwd);
@@ -89,8 +91,8 @@ async function runRollbackMain(input = {}) {
89
91
 
90
92
  // Namespace cluster/service for PR-preview workspaces; explicit
91
93
  // --cluster/--service flags still win inside the resolvers.
92
- const namespacedProject = `${projectName}${resolveWorkspaceSuffix(options, cwd)}`;
93
- const namespacedOptions = { ...options, projectName: namespacedProject };
94
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
95
+ namespacedProject = namespacedOptions.projectName;
94
96
  cluster = resolveCluster(namespacedOptions, cwd);
95
97
  service = resolveService(namespacedOptions, cwd);
96
98
  } catch {
@@ -301,48 +303,164 @@ async function runRollbackMain(input = {}) {
301
303
  }
302
304
  }
303
305
 
306
+ // 1b. Worker rollback (BUG-85): deploys advance web AND worker,
307
+ // so a rollback must move both — otherwise the worker keeps the bad
308
+ // image. Explicit --service keeps single-service semantics (the
309
+ // escape hatch); workerless trees (no worker.tf) skip. Resolved
310
+ // BEFORE any update so a worker with no rollback history fails
311
+ // loud with zero half-state.
312
+ let workerTarget = null;
313
+ const explicitService = (typeof options.service === 'string' && options.service.trim() !== '')
314
+ || (typeof options.serviceName === 'string' && options.serviceName.trim() !== '');
315
+ if (!explicitService && readFileSafe(path.join(cwd, 'terraform', 'worker.tf')) !== null) {
316
+ const workerService = `${namespacedProject}${readResourceSuffix(cwd)}-worker-service`;
317
+ const workerResp = await ecsClient.send(new DescribeServicesCommand({ cluster, services: [workerService] }));
318
+ const workerDesc = (workerResp.services || [])[0] || null;
319
+ if (!workerDesc || workerDesc.status !== 'ACTIVE') {
320
+ console.log(color.yellow(`⚠ Worker service ${workerService} not found or inactive — rolling back ${service} only.`));
321
+ } else {
322
+ const { family: workerFamily, revNum: workerCurrentRev } = parseFamilyAndRevision(workerDesc.taskDefinition);
323
+ const workerEligible = await discoverWithAdapter(createEcsRevisionAdapter(ecsClient), workerFamily, workerCurrentRev);
324
+ if (workerEligible.length === 0) {
325
+ s.stop(color.yellow('No previous worker revisions.'));
326
+ return failCommand({
327
+ message: `\n⚠ Family ${workerFamily} is on revision ${workerCurrentRev} with no previous ACTIVE revisions — refusing to roll back ${service} alone (the worker would keep the bad image).\n Deploy again to create worker rollback history, or re-run with --service ${service} to roll back the web service only.\n`,
328
+ tone: 'yellow',
329
+ event: 'rollback_run',
330
+ telemetry: { projectName, error_code: 'WORKER_NO_PRIOR_REVISIONS' },
331
+ reason: 'worker-no-prior-revisions',
332
+ resultExtra: { cluster, service, region },
333
+ exitCode: 1,
334
+ });
335
+ }
336
+ const workerTargetArn = pickNewestEligible(workerEligible);
337
+ workerTarget = { service: workerService, taskDefArn: workerTargetArn, revision: workerTargetArn.split(':').pop() };
338
+ }
339
+ }
340
+
304
341
  // 2. Trigger the rollback.
305
- s.start(truncateSpinnerText(`Rolling back ${service} to revision ${targetRevisionNum}...`));
342
+ const triggerLabel = workerTarget
343
+ ? `${service} to revision ${targetRevisionNum} and ${workerTarget.service} to revision ${workerTarget.revision}`
344
+ : `${service} to revision ${targetRevisionNum}`;
345
+ s.start(truncateSpinnerText(`Rolling back ${triggerLabel}...`));
306
346
  await ecsClient.send(new UpdateServiceCommand({
307
347
  cluster,
308
348
  service,
309
349
  taskDefinition: targetTaskDefArn,
310
350
  forceNewDeployment: true,
311
351
  }));
352
+ if (workerTarget) {
353
+ await ecsClient.send(new UpdateServiceCommand({
354
+ cluster,
355
+ service: workerTarget.service,
356
+ taskDefinition: workerTarget.taskDefArn,
357
+ forceNewDeployment: true,
358
+ }));
359
+ }
312
360
 
313
361
  if (options.skipWait === true) {
314
- s.stop(`Rollback to revision ${targetRevisionNum} triggered.`);
315
- await trackSuccess('rollback_run', { projectName, targetRevision: String(targetRevisionNum), skipWait: true });
316
- outro(color.green(`Rollback to revision ${targetRevisionNum} initiated! 🚀`));
317
- return { ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region };
362
+ const skipLabel = workerTarget
363
+ ? `revision ${targetRevisionNum} (web) and ${workerTarget.revision} (worker)`
364
+ : `revision ${targetRevisionNum}`;
365
+ s.stop(`Rollback to ${skipLabel} triggered.`);
366
+ await trackSuccess('rollback_run', {
367
+ projectName,
368
+ targetRevision: String(targetRevisionNum),
369
+ skipWait: true,
370
+ ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision) } : {}),
371
+ });
372
+ outro(color.green(`Rollback to ${skipLabel} initiated! 🚀`));
373
+ return {
374
+ ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region,
375
+ ...(workerTarget ? { worker: { service: workerTarget.service, targetTaskDefArn: workerTarget.taskDefArn, targetRevision: workerTarget.revision } } : {}),
376
+ };
318
377
  }
319
378
 
320
- // 3. Monitor the deployment until it stabilizes or times out,
321
- // with live spinner updates on every non-terminal tick.
322
- const startTime = Date.now();
323
- const deadline = startTime + timeoutMs;
324
- while (true) {
325
- const pollResp = await ecsClient.send(new DescribeServicesCommand({ cluster, services: [service] }));
326
- const svc = (pollResp.services || [])[0] || null;
327
- const primary = svc?.deployments?.find(
328
- (d) => d.status === 'PRIMARY' && d.taskDefinition === targetTaskDefArn
329
- );
330
-
331
- if (primary && (primary.rolloutState === 'COMPLETED'
332
- || (primary.runningCount === primary.desiredCount
333
- && primary.desiredCount > 0
334
- && (svc.deployments || []).length === 1))) {
335
- s.stop(color.green(`Rolled back to revision ${targetRevisionNum}.`));
336
- await trackSuccess('rollback_run', { projectName, targetRevision: String(targetRevisionNum) });
337
- outro(color.green(`Service successfully rolled back to revision ${targetRevisionNum}! 🚀`));
338
- return { ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region };
339
- }
379
+ // 3. Monitor each deployment until it stabilizes or times out,
380
+ // with live spinner updates on every non-terminal tick. Web
381
+ // first, then the worker; a worker failure names the completed
382
+ // web rollback so the half-state is never a mystery.
383
+ const webWait = await waitForPrimaryStable({
384
+ s, ecsClient, cluster, service, targetTaskDefArn, targetRevisionNum,
385
+ pollIntervalMs, timeoutMs, projectName, region,
386
+ });
387
+ if (!webWait.ok) return webWait.failure;
388
+ if (workerTarget) {
389
+ const workerWait = await waitForPrimaryStable({
390
+ s, ecsClient, cluster, service: workerTarget.service,
391
+ targetTaskDefArn: workerTarget.taskDefArn, targetRevisionNum: workerTarget.revision,
392
+ pollIntervalMs, timeoutMs, projectName, region,
393
+ doneNote: `${service} already rolled back to revision ${targetRevisionNum}`,
394
+ });
395
+ if (!workerWait.ok) return workerWait.failure;
396
+ }
340
397
 
341
- if (primary?.rolloutState === 'FAILED') {
342
- s.stop(color.red('❌ Rollback deployment failed.'));
343
- return failCommand({
398
+ const doneLabel = workerTarget
399
+ ? `revision ${targetRevisionNum} (web) and ${workerTarget.revision} (worker)`
400
+ : `revision ${targetRevisionNum}`;
401
+ s.stop(color.green(`Rolled back to ${doneLabel}.`));
402
+ await trackSuccess('rollback_run', {
403
+ projectName,
404
+ targetRevision: String(targetRevisionNum),
405
+ ...(workerTarget ? { workerTargetRevision: String(workerTarget.revision) } : {}),
406
+ });
407
+ outro(color.green(workerTarget
408
+ ? `Services successfully rolled back to ${doneLabel}! 🚀`
409
+ : `Service successfully rolled back to revision ${targetRevisionNum}! 🚀`));
410
+ return {
411
+ ok: true, targetTaskDefArn, targetRevision: targetRevisionNum, cluster, service, region,
412
+ ...(workerTarget ? { worker: { service: workerTarget.service, targetTaskDefArn: workerTarget.taskDefArn, targetRevision: workerTarget.revision } } : {}),
413
+ };
414
+ } catch (error) {
415
+ if (isAuthError(error)) {
416
+ await trackFailure('rollback_run', { projectName, error_code: 'AUTH_EXPIRED' });
417
+ handleAwsAuthError(error, s, options);
418
+ return { ok: false, reason: 'auth-error', cluster, service, region };
419
+ }
420
+ s.stop(color.red('❌ Rollback failed.'));
421
+ return failAwsError({
422
+ event: 'rollback_run',
423
+ error,
424
+ telemetry: { projectName },
425
+ reason: 'error',
426
+ resultExtra: { cluster, service, region },
427
+ exitCode: 1,
428
+ });
429
+ }
430
+ }
431
+
432
+ // Polls one service until its PRIMARY deployment settles on the target
433
+ // revision (or fails/times out). Shared by the web and worker waits;
434
+ // `doneNote` names already-completed work on the failure prints so a
435
+ // late worker failure never hides the finished web rollback.
436
+ async function waitForPrimaryStable({
437
+ s, ecsClient, cluster, service, targetTaskDefArn, targetRevisionNum,
438
+ pollIntervalMs, timeoutMs, projectName, region, doneNote = null,
439
+ }) {
440
+ const startTime = Date.now();
441
+ const deadline = startTime + timeoutMs;
442
+ while (true) {
443
+ const pollResp = await ecsClient.send(new DescribeServicesCommand({ cluster, services: [service] }));
444
+ const svc = (pollResp.services || [])[0] || null;
445
+ const primary = svc?.deployments?.find(
446
+ (d) => d.status === 'PRIMARY' && d.taskDefinition === targetTaskDefArn
447
+ );
448
+
449
+ if (primary && (primary.rolloutState === 'COMPLETED'
450
+ || (primary.runningCount === primary.desiredCount
451
+ && primary.desiredCount > 0
452
+ && (svc.deployments || []).length === 1))) {
453
+ return { ok: true };
454
+ }
455
+
456
+ if (primary?.rolloutState === 'FAILED') {
457
+ s.stop(color.red('❌ Rollback deployment failed.'));
458
+ return {
459
+ ok: false,
460
+ failure: await failCommand({
344
461
  print: () => {
345
462
  console.log(color.red('\n✖ The rollback deployment failed to stabilize.'));
463
+ if (doneNote) console.log(color.yellow(` Note: ${doneNote}.`));
346
464
  console.log(` Check service health with ${color.green('npx grada-run status')} and recent output with ${color.green('npx grada-run logs')}.\n`);
347
465
  },
348
466
  event: 'rollback_run',
@@ -350,35 +468,39 @@ async function runRollbackMain(input = {}) {
350
468
  reason: 'rollout-failed',
351
469
  resultExtra: { cluster, service, region },
352
470
  exitCode: 1,
353
- });
354
- }
471
+ }),
472
+ };
473
+ }
355
474
 
356
- const elapsedSec = Math.floor((Date.now() - startTime) / 1000);
357
- // Every poll frame goes through the width budget: the
358
- // crashing-container variant walls past 131 columns on long
359
- // service names without it.
360
- const progressStem = `Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s]`;
361
- if (!primary) {
362
- s.message(truncateSpinnerText(`${progressStem} (registering deployment...)`));
475
+ const elapsedSec = Math.floor((Date.now() - startTime) / 1000);
476
+ // Every poll frame goes through the width budget: the
477
+ // crashing-container variant walls past 131 columns on long
478
+ // service names without it.
479
+ const progressStem = `Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s]`;
480
+ if (!primary) {
481
+ s.message(truncateSpinnerText(`${progressStem} (registering deployment...)`));
482
+ } else {
483
+ const runningCount = primary.runningCount ?? 0;
484
+ const desiredCount = primary.desiredCount ?? 0;
485
+ const pendingCount = primary.pendingCount ?? 0;
486
+ const failedTasks = primary.failedTasks ?? 0;
487
+ if (failedTasks > 0) {
488
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`));
489
+ } else if (runningCount >= desiredCount && desiredCount > 0 && pendingCount === 0) {
490
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running — draining previous tasks)`));
363
491
  } else {
364
- const runningCount = primary.runningCount ?? 0;
365
- const desiredCount = primary.desiredCount ?? 0;
366
- const pendingCount = primary.pendingCount ?? 0;
367
- const failedTasks = primary.failedTasks ?? 0;
368
- if (failedTasks > 0) {
369
- s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`));
370
- } else if (runningCount >= desiredCount && desiredCount > 0 && pendingCount === 0) {
371
- s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running — draining previous tasks)`));
372
- } else {
373
- s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending)`));
374
- }
492
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending)`));
375
493
  }
494
+ }
376
495
 
377
- if (Date.now() >= deadline) {
378
- s.stop(color.yellow('⚠ Rollback timed out waiting for ECS stabilization.'));
379
- return failCommand({
496
+ if (Date.now() >= deadline) {
497
+ s.stop(color.yellow('⚠ Rollback timed out waiting for ECS stabilization.'));
498
+ return {
499
+ ok: false,
500
+ failure: await failCommand({
380
501
  print: () => {
381
502
  console.log(color.yellow('\n⚠ The rollback is still in progress.'));
503
+ if (doneNote) console.log(color.yellow(` Note: ${doneNote}.`));
382
504
  console.log(` Check progress with ${color.green('npx grada-run status')}.\n`);
383
505
  },
384
506
  event: 'rollback_run',
@@ -386,26 +508,11 @@ async function runRollbackMain(input = {}) {
386
508
  reason: 'rollout-timeout',
387
509
  resultExtra: { cluster, service, region },
388
510
  exitCode: 1,
389
- });
390
- }
391
-
392
- await sleep(pollIntervalMs);
511
+ }),
512
+ };
393
513
  }
394
- } catch (error) {
395
- if (isAuthError(error)) {
396
- await trackFailure('rollback_run', { projectName, error_code: 'AUTH_EXPIRED' });
397
- handleAwsAuthError(error, s, options);
398
- return { ok: false, reason: 'auth-error', cluster, service, region };
399
- }
400
- s.stop(color.red('❌ Rollback failed.'));
401
- return failAwsError({
402
- event: 'rollback_run',
403
- error,
404
- telemetry: { projectName },
405
- reason: 'error',
406
- resultExtra: { cluster, service, region },
407
- exitCode: 1,
408
- });
514
+
515
+ await sleep(pollIntervalMs);
409
516
  }
410
517
  }
411
518
 
@@ -170,6 +170,12 @@ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
170
170
  } catch {
171
171
  return [...names].sort();
172
172
  }
173
+ // NODE_ENV is injected only when the worker renders (the generator
174
+ // scopes it to worker trees): on workerless trees it is a legitimate
175
+ // custom key and must not auto-skip (BUG-95). Unreadable dirs keep
176
+ // the base set above (fail-closed; the TF precondition backstops
177
+ // real collisions there).
178
+ if (!tfFiles.includes('worker.tf')) names.delete('NODE_ENV');
173
179
  const dbFile = tfFiles.find((file) => file.startsWith('database') && file.endsWith('.tf'));
174
180
  if (dbFile) {
175
181
  for (const name of DB_MANAGED_ENV) names.add(name);
@@ -393,7 +399,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
393
399
  const skippedSet = new Set(skipped);
394
400
  const pushableSecrets = Object.fromEntries(Object.entries(parsedSecrets).filter(([key]) => !skippedSet.has(key)));
395
401
  const needsPreWriteOutput = skipped.length > 0 || wiringHits.length > 0
396
- || (collisions.length > 0 && pushTarget === 'lambda');
402
+ || (collisions.length > 0 && (pushTarget === 'lambda' || skipBypassed));
397
403
  if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
398
404
  for (const { key, indicator } of wiringHits) {
399
405
  console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
@@ -401,6 +407,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
401
407
  if (collisions.length > 0 && pushTarget === 'lambda') {
402
408
  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
409
  }
410
+ if (collisions.length > 0 && skipBypassed && pushTarget !== 'lambda') {
411
+ 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.`));
412
+ }
404
413
  if (skipped.length > 0) {
405
414
  console.log(color.yellow(`⚠️ Skipping ${skipped.length} colliding ${skipped.length === 1 ? 'key' : 'keys'} (injected by Grada — remove from .env to silence this):`));
406
415
  for (const key of skipped) console.log(color.yellow(`- ${key} (skipped — Grada-managed name)`));
@@ -448,6 +457,16 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
448
457
  // exclusion from the vault write is covered by the skip notice
449
458
  // above, not by this confirm.
450
459
  const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
460
+ // BUG-89: skipped keys are present in .env (so they never land in
461
+ // `removed`) but excluded from the vault write — a stale vault
462
+ // value for a skipped key is wiped by the full-replace update.
463
+ // Name every such victim loudly. The skip notice above is the
464
+ // acknowledgment, so unlike BUG-80 removals these never confirm.
465
+ const staleSkipped = skipped.filter((key) => (existingKeys ?? []).includes(key));
466
+ if (staleSkipped.length > 0) {
467
+ 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):`));
468
+ for (const key of staleSkipped) console.log(color.red(`- ${key} (stale vault value deleted — key is skipped)`));
469
+ }
451
470
  if (removed.length > 0) {
452
471
  s.stop('Pre-flight checks done.');
453
472
  console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`));
@@ -512,7 +531,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
512
531
  ecs_restart: false,
513
532
  removed_count: removed.length,
514
533
  managed_collisions: collisions.length,
515
- skipped_count: skipped.length
534
+ skipped_count: skipped.length,
535
+ stale_skipped_count: staleSkipped.length
516
536
  });
517
537
  return { keysChanged: false, restarted: false, skipped };
518
538
  }
@@ -528,7 +548,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
528
548
  ecs_restart: false,
529
549
  removed_count: removed.length,
530
550
  managed_collisions: collisions.length,
531
- skipped_count: skipped.length
551
+ skipped_count: skipped.length,
552
+ stale_skipped_count: staleSkipped.length
532
553
  });
533
554
  return { keysChanged: false, restarted: false, skipped };
534
555
  }
@@ -544,7 +565,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
544
565
  message: 'Keys are unchanged. Trigger a rolling ECS restart to apply new values immediately?',
545
566
  initialValue: false,
546
567
  });
547
- if (shouldRestart) {
568
+ if (shouldRestart === true) {
548
569
  const cluster = resolveEcsCluster(resolvedProjectName, opts);
549
570
  const service = resolveEcsService(resolvedProjectName, opts);
550
571
  const ecsClient = resolveClient(opts.ecsClient ?? opts.ecs, ECSClient, targetRegion ? { region: targetRegion } : {});
@@ -569,7 +590,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
569
590
  ecs_restart: true,
570
591
  removed_count: removed.length,
571
592
  managed_collisions: collisions.length,
572
- skipped_count: skipped.length
593
+ skipped_count: skipped.length,
594
+ stale_skipped_count: staleSkipped.length
573
595
  });
574
596
  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
597
  return { keysChanged: false, restarted: true, cluster, service, skipped };
@@ -583,7 +605,8 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
583
605
  keys_changed: keysChanged,
584
606
  removed_count: removed.length,
585
607
  managed_collisions: collisions.length,
586
- skipped_count: skipped.length
608
+ skipped_count: skipped.length,
609
+ stale_skipped_count: staleSkipped.length
587
610
  });
588
611
  return { keysChanged, skipped };
589
612