grada-run 0.40.11 → 0.40.13

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.40.11",
3
+ "version": "0.40.13",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -11,7 +11,7 @@ import { ADDON_REGISTRY, ADDON_UPSERT_KEYS, resolveAddonEnvVars, addonTargetDisp
11
11
  import { stripTerraformMetadata, readEjectedMarker } from '../utils/terraform-metadata.js';
12
12
  import { normalizeDomain, isValidDomain, normalizeZoneId, isValidFromEmail, parseDomainTf } from '../utils/domains.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
- import { failCommand, failProjectNotInitialized, isProgrammaticCall } from '../utils/command.js';
14
+ import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive } from '../utils/command.js';
15
15
  import { findArrayBounds, findMapBounds, findNestedBlock, findResourceBlock, enclosingBraceBounds, normalizeBlankLines, realignAssignmentRuns } from '../utils/hcl.js';
16
16
  import { syncDocCostEstimate } from '../utils/visualizer.js';
17
17
  import { withProjectLock } from '../utils/file-lock.js';
@@ -810,11 +810,33 @@ function invalidModelFailure(model) {
810
810
  };
811
811
  }
812
812
 
813
+ // Armed non-interactive gate for the resolveAddonOptions prompt sites.
814
+ // `gateProject` is non-null only for runAddMain (which threads its
815
+ // projectName through ctx), so init and direct callers keep their
816
+ // historical missing-value failures byte-identical. Returns the
817
+ // `{ ok: false, nonInteractiveRefusal }` marker for runAddMain to
818
+ // propagate verbatim, or null when the prompt may proceed.
819
+ async function refuseHeadlessAddonPrompt(opts, gateProject, { message, hint }) {
820
+ if (gateProject === null || gateProject === undefined) return null;
821
+ const refused = await refuseIfNonInteractive(opts, {
822
+ message,
823
+ hint,
824
+ event: 'add_run',
825
+ telemetry: { projectName: gateProject },
826
+ errorCode: 'ADD_NON_INTERACTIVE',
827
+ });
828
+ if (!refused) return null;
829
+ return { ok: false, nonInteractiveRefusal: refused };
830
+ }
831
+
813
832
  // Post-guard option resolution per capability: interactive prompts,
814
833
  // auto-detection, and template/env assembly. `ctx` carries
815
- // `{ cwd, region, isInteractive, heldCatalog }`. Returns
816
- // `{ ok: true, templateVars, conditionalBlocks, envVars, upsertKeys, meta }`,
817
- // `{ ok: false, cancelled: true }`, or a structured validation failure.
834
+ // `{ cwd, region, isInteractive, heldCatalog, projectName? }` —
835
+ // `projectName` (runAddMain only) arms the non-interactive gates.
836
+ // Returns `{ ok: true, templateVars, conditionalBlocks, envVars,
837
+ // upsertKeys, meta }`, `{ ok: false, cancelled: true }`,
838
+ // `{ ok: false, nonInteractiveRefusal }` (runAddMain propagates the
839
+ // refused result verbatim), or a structured validation failure.
818
840
  export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
819
841
  const opts = normalizeOptions(options);
820
842
  const context = normalizeOptions(ctx);
@@ -822,6 +844,7 @@ export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
822
844
  const region = context.region || resolveRegion(opts, cwd);
823
845
  const isInteractive = context.isInteractive === true;
824
846
  const heldCatalog = context.heldCatalog || null;
847
+ const gateProject = context.projectName ?? null;
825
848
  const upsertKeys = [...(ADDON_UPSERT_KEYS[capability] || [])];
826
849
 
827
850
  const flagError = validateAddonFlags(capability, opts);
@@ -844,6 +867,11 @@ export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
844
867
  let selectedInteractively = false;
845
868
  let customTypedModel = false;
846
869
  if (isInteractive && !explicitModel) {
870
+ const refused = await refuseHeadlessAddonPrompt(opts, gateProject, {
871
+ message: `\n✖ add needs a model before scaffolding Bedrock.`,
872
+ hint: ' Re-run with --model <model-id> to scaffold non-interactively.\n',
873
+ });
874
+ if (refused) return refused;
847
875
  const catalog = heldCatalog || loadBedrockCatalog({ cachePath: opts.cachePath });
848
876
  const providerChoice = await promptBedrockProvider(catalog);
849
877
  if (isCancel(providerChoice)) return { ok: false, cancelled: true };
@@ -915,6 +943,11 @@ export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
915
943
  }
916
944
  let selectedInteractively = false;
917
945
  if (domain === null) {
946
+ const refused = await refuseHeadlessAddonPrompt(opts, gateProject, {
947
+ message: `\n✖ add needs a domain before scaffolding Amazon SES.`,
948
+ hint: ' Re-run with --domain <domain> to scaffold non-interactively.\n',
949
+ });
950
+ if (refused) return refused;
918
951
  if (!isInteractive) {
919
952
  return {
920
953
  ok: false,
@@ -997,6 +1030,11 @@ export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
997
1030
  timezone = typeof timezone === 'string' ? timezone.trim() : 'UTC';
998
1031
 
999
1032
  if (!schedule && isInteractive) {
1033
+ const refused = await refuseHeadlessAddonPrompt(opts, gateProject, {
1034
+ message: `\n✖ add needs a schedule before scaffolding cron.`,
1035
+ hint: ' Re-run with --schedule <expression> to scaffold non-interactively.\n',
1036
+ });
1037
+ if (refused) return refused;
1000
1038
  const choice = await promptCronSchedule();
1001
1039
  if (isCancel(choice)) return { ok: false, cancelled: true };
1002
1040
  if (choice === CRON_CUSTOM_VALUE) {
@@ -1020,6 +1058,11 @@ export async function resolveAddonOptions(capability, options = {}, ctx = {}) {
1020
1058
 
1021
1059
  let cronCommandPrompted = false;
1022
1060
  if (!cronCommand && isInteractive) {
1061
+ const refused = await refuseHeadlessAddonPrompt(opts, gateProject, {
1062
+ message: `\n✖ add needs a command before scaffolding cron.`,
1063
+ hint: ' Re-run with --cmd <command> to scaffold non-interactively.\n',
1064
+ });
1065
+ if (refused) return refused;
1023
1066
  const answer = await promptCronCommand();
1024
1067
  if (isCancel(answer)) return { ok: false, cancelled: true };
1025
1068
  cronCommand = String(answer).trim();
@@ -1327,7 +1370,8 @@ async function runAddMain(input = {}) {
1327
1370
  Boolean(process.stdout?.isTTY)
1328
1371
  );
1329
1372
 
1330
- const resolved = await resolveAddonOptions(capability, options, { cwd, region, isInteractive, heldCatalog });
1373
+ const resolved = await resolveAddonOptions(capability, options, { cwd, region, isInteractive, heldCatalog, projectName });
1374
+ if (!resolved.ok && resolved.nonInteractiveRefusal) return resolved.nonInteractiveRefusal;
1331
1375
  if (!resolved.ok && resolved.cancelled) return cancelSelection();
1332
1376
  if (!resolved.ok) return failResolved(resolved);
1333
1377
 
@@ -3,7 +3,7 @@ import path from 'path';
3
3
  import color from 'picocolors';
4
4
  import { intro, outro, select, text, cancel, isCancel } from '@clack/prompts';
5
5
  import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
6
- import { failCommand, failProjectNotInitialized } from '../utils/command.js';
6
+ import { failCommand, failProjectNotInitialized, refuseIfNonInteractive } from '../utils/command.js';
7
7
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
8
8
  import { resolveRegion, resolveProjectName, resolveCwd, resolveHeadless, readFileSafe, readTerraformComputeTarget } from '../utils/resolvers.js';
9
9
  import { findNestedBlock } from '../utils/hcl.js';
@@ -490,14 +490,28 @@ async function runAlertsMain(input = {}) {
490
490
  }
491
491
 
492
492
  const headless = resolveHeadless(options);
493
- if (email === undefined && webhook === undefined && !headless) {
494
- const prompted = await promptDestinations();
495
- if (prompted.cancelled) {
496
- cancel('Alerts scaffolding cancelled.');
497
- return { ok: false, cancelled: true };
493
+ if (email === undefined && webhook === undefined) {
494
+ // One gate covers all three destination prompts (they live in a
495
+ // single promptDestinations call with no flag-bypass between
496
+ // them); explicit --email/--webhook flags bypass via the outer
497
+ // condition, and explicit --headless scaffolds the manual path.
498
+ const refused = await refuseIfNonInteractive(options, {
499
+ message: `\n✖ alerts needs a destination before scaffolding notifications.`,
500
+ hint: ' Re-run with --email <address> and/or --webhook <url> to scaffold non-interactively.\n',
501
+ event: 'alerts_run',
502
+ telemetry: { projectName },
503
+ errorCode: 'ALERTS_NON_INTERACTIVE',
504
+ });
505
+ if (refused) return refused;
506
+ if (!headless) {
507
+ const prompted = await promptDestinations();
508
+ if (prompted.cancelled) {
509
+ cancel('Alerts scaffolding cancelled.');
510
+ return { ok: false, cancelled: true };
511
+ }
512
+ email = prompted.email;
513
+ webhook = prompted.webhook;
498
514
  }
499
- email = prompted.email;
500
- webhook = prompted.webhook;
501
515
  }
502
516
 
503
517
  const alertsPath = path.join(cwd, ALERTS_TF_FILE);
@@ -5,7 +5,7 @@ import color from 'picocolors';
5
5
  import { renderDryRunPreview, parseTerraformConfig, buildCostTelemetryProps } from '../utils/visualizer.js';
6
6
  import { detectFramework } from '../utils/detector.js';
7
7
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
- import { failCommand, shouldAutoApprove } from '../utils/command.js';
8
+ import { failCommand, shouldAutoApprove, refuseIfNonInteractive } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { spawnSync } from 'child_process';
11
11
  import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, checkOutputsContract, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS } from '../utils/terraform.js';
@@ -69,6 +69,14 @@ async function handleApplyStateLock({ options, tfDir, runTerraform, lockId, proj
69
69
 
70
70
  if (approvedByFlag) return unlockAndRetry('flag');
71
71
  if (!shouldAutoApprove(options)) {
72
+ const refused = await refuseIfNonInteractive(options, {
73
+ message: `\n✖ apply needs approval to force-unlock the Terraform state lock.`,
74
+ hint: ` Re-run with --force-unlock ${unlockId} to unlock non-interactively.\n`,
75
+ event: 'infrastructure_applied',
76
+ telemetry: { projectName },
77
+ errorCode: 'APPLY_NON_INTERACTIVE',
78
+ });
79
+ if (refused) return refused;
72
80
  const runbook = getRunbook('STATE_LOCK_HELD', { headless: false, lockId });
73
81
  log.error(color.red(`✖ ${runbook.message}`));
74
82
  log.message(` ${runbook.hint}\n`);
@@ -126,6 +134,14 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
126
134
  }
127
135
 
128
136
  if (!shouldAutoApprove(options)) {
137
+ const refused = await refuseIfNonInteractive(options, {
138
+ message: `\n✖ apply needs review before destroying the previous compute target (${from} → ${diskTarget}).`,
139
+ hint: ' Run "cd terraform && terraform plan" to review the destroys, then re-run with --destroy-previous-target.\n',
140
+ event: 'infrastructure_applied',
141
+ telemetry: { projectName },
142
+ errorCode: 'APPLY_NON_INTERACTIVE',
143
+ });
144
+ if (refused) return refused;
129
145
  log.warn(color.yellow(`⚠ This tree targets "${diskTarget}" but the last apply recorded "${from}". Applying would destroy the previous stack.`));
130
146
  await renderSwitchPlan({ runTerraform, tfDir, lifecycleOpts });
131
147
  const confirmed = await confirm({
@@ -245,6 +261,14 @@ async function applyStackMain(input = {}) {
245
261
  // confirmed it before the lock failure.
246
262
  await renderDryRunPreview(detectedConfig, true);
247
263
  } else {
264
+ const refused = await refuseIfNonInteractive(options, {
265
+ message: `\n✖ apply needs approval before provisioning infrastructure.`,
266
+ hint: ' Re-run with --auto-approve to apply non-interactively.\n',
267
+ event: 'infrastructure_applied',
268
+ telemetry: { projectName: detectedConfig.projectName },
269
+ errorCode: 'APPLY_NON_INTERACTIVE',
270
+ });
271
+ if (refused) return refused;
248
272
  const confirmed = await renderDryRunPreview(detectedConfig, false);
249
273
  if (!confirmed) {
250
274
  cancel('Apply aborted.');
@@ -402,7 +426,11 @@ async function applyStackMain(input = {}) {
402
426
 
403
427
  trackEvent('recovery_prompted', { type: 'state_bucket_missing' });
404
428
 
405
- const shouldRecreate = await promptStateBucketRecovery({ autoApprove: shouldAutoApprove(options) });
429
+ const shouldRecreate = await promptStateBucketRecovery({ autoApprove: shouldAutoApprove(options), options, projectName: actualProjectName });
430
+
431
+ // A refused non-interactive run propagates as-is (object
432
+ // result); otherwise the util answers boolean.
433
+ if (typeof shouldRecreate === 'object' && shouldRecreate !== null) return shouldRecreate;
406
434
 
407
435
  if (!shouldRecreate) {
408
436
  return failCommand({
@@ -14,6 +14,9 @@ export const DEFAULT_BACKUP_POLL_INTERVAL_MS = 5000;
14
14
 
15
15
  const SNAPSHOT_NOT_FOUND_NAMES = new Set(['DBSnapshotNotFound', 'DBSnapshotNotFoundFault']);
16
16
  const CLUSTER_SNAPSHOT_NOT_FOUND_NAMES = new Set(['DBClusterSnapshotNotFound', 'DBClusterSnapshotNotFoundFault']);
17
+ // Snapshot states that never become available: polling past them only
18
+ // wastes the timeout and misreports.
19
+ const TERMINAL_SNAPSHOT_STATUSES = new Set(['failed', 'deleted', 'deleting']);
17
20
 
18
21
  export function parseDbBackupArgs(argv = []) {
19
22
  const args = normalizeArgv(argv);
@@ -191,11 +194,33 @@ async function runDbBackupMain(input = {}) {
191
194
  if (snapshot && snapshot.Status === 'available') {
192
195
  return { done: true, value: snapshot };
193
196
  }
197
+ // Terminal states never become available: fail fast naming
198
+ // the actual state instead of waiting out the timeout and
199
+ // misreporting "still creating".
200
+ if (snapshot && TERMINAL_SNAPSHOT_STATUSES.has(String(snapshot.Status || '').toLowerCase())) {
201
+ return { done: true, value: { terminalFailure: true, status: snapshot.Status } };
202
+ }
194
203
  s.message(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`);
195
204
  return { done: false };
196
205
  },
197
206
  });
198
207
 
208
+ if (outcome.value?.terminalFailure) {
209
+ const failedStatus = outcome.value.status;
210
+ s.stop(color.red(`❌ Snapshot ${failedStatus}.`));
211
+ return failCommand({
212
+ print: () => {
213
+ console.log(color.red(`\n✖ Snapshot ${snapshotId} reached a terminal state (${failedStatus}) and will never become available.`));
214
+ console.log(' Check the failure cause in the RDS console, then retry the backup.\n');
215
+ },
216
+ event: 'db_backup_run',
217
+ telemetry: { projectName, waited: true },
218
+ errorCode: 'SNAPSHOT_FAILED',
219
+ reason: 'snapshot-failed',
220
+ resultExtra: { dbIdentifier, region, snapshotId },
221
+ });
222
+ }
223
+
199
224
  if (outcome.timedOut) {
200
225
  s.stop(color.yellow('Snapshot still creating.'));
201
226
  return failCommand({
@@ -7,7 +7,7 @@ import { S3Client } from '@aws-sdk/client-s3';
7
7
  import { teardownStateBucket, drainBucketObjects, resolveClient } from '../utils/aws.js';
8
8
  import { checkDependency, pollUntil } from '../utils/system.js';
9
9
  import { trackEvent, flushTelemetry, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
10
- import { failCommand, shouldAutoApprove } from '../utils/command.js';
10
+ import { failCommand, shouldAutoApprove, refuseIfNonInteractive } from '../utils/command.js';
11
11
  import { runTerraformCommand, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, getTerraformStateBuckets, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS } from '../utils/terraform.js';
12
12
  import { classifyTerraformError, getRunbook, ERROR_CODES } from '../utils/terraform-errors.js';
13
13
  import { findDbTarget, dbStatusOf, resolveDbIdentifier, resolveDbClusterIdentifier, generateSnapshotId } from '../utils/rds.js';
@@ -96,6 +96,14 @@ async function handleDestroyTerraformError({ options, tfDirPath, attemptDestroy,
96
96
 
97
97
  if (unlockId && approvedByFlag) return unlockAndRetry('flag');
98
98
  if (unlockId && !shouldAutoApprove(options)) {
99
+ const refused = await refuseIfNonInteractive(options, {
100
+ message: `\n✖ destroy needs approval to force-unlock the Terraform state lock.`,
101
+ hint: ` Re-run with --force-unlock ${unlockId} to unlock non-interactively.\n`,
102
+ event: 'infrastructure_destroyed',
103
+ telemetry: { projectName: actualProjectName },
104
+ errorCode: 'DESTROY_NON_INTERACTIVE',
105
+ });
106
+ if (refused) return refused;
99
107
  const runbook = getRunbook('STATE_LOCK_HELD', { headless: false, lockId });
100
108
  console.error(color.red(`✖ ${runbook.message}`));
101
109
  console.log(` ${runbook.hint}`);
@@ -214,7 +222,7 @@ async function destroyStackMain(input = {}) {
214
222
  if (dbNeedsProtection && shouldAutoApprove(options)) {
215
223
  return failCommand({
216
224
  message: `\n✖ Refusing to destroy: database ${dbTarget.id} is still provisioned and --allow-data-loss was not passed.`,
217
- hint: ` Re-run with --allow-data-loss to snapshot it first and then destroy, or delete the database by hand.\n`,
225
+ hint: ` Re-run with --allow-data-loss to destroy without a snapshot, or run interactively (a pre-destroy snapshot is taken first), or delete the database by hand.\n`,
218
226
  event: 'infrastructure_destroyed',
219
227
  telemetry: { projectName: projectNameForTelemetry, error_code: 'DATA_LOSS_UNCONFIRMED' },
220
228
  errorCode: 'DATA_LOSS_UNCONFIRMED',
@@ -222,6 +230,19 @@ async function destroyStackMain(input = {}) {
222
230
  });
223
231
  }
224
232
 
233
+ if (!shouldAutoApprove(options)) {
234
+ const refused = await refuseIfNonInteractive(options, {
235
+ message: `\n✖ destroy needs confirmation before tearing down infrastructure.`,
236
+ hint: dbNeedsProtection
237
+ ? ' Re-run with --yes --allow-data-loss to destroy non-interactively (no pre-destroy snapshot), or run interactively to snapshot first.\n'
238
+ : ' Re-run with --yes to destroy non-interactively.\n',
239
+ event: 'infrastructure_destroyed',
240
+ telemetry: { projectName: projectNameForTelemetry },
241
+ errorCode: 'DESTROY_NON_INTERACTIVE',
242
+ });
243
+ if (refused) return refused;
244
+ }
245
+
225
246
  const proceed = shouldAutoApprove(options) ? true : await confirm({
226
247
  message: dbNeedsProtection
227
248
  ? color.red(`⚠️ WARNING: This will permanently destroy all AWS resources including database ${dbTarget.id} (a pre-destroy snapshot will be taken first). Are you absolutely sure?`)
@@ -533,6 +554,16 @@ async function destroyStackMain(input = {}) {
533
554
  let deleteS3Bucket = false;
534
555
 
535
556
  if (bucketName) {
557
+ if (!shouldAutoApprove(options)) {
558
+ const refused = await refuseIfNonInteractive(options, {
559
+ message: `\n✖ destroy needs confirmation before deleting the S3 state bucket.`,
560
+ hint: ' Re-run with --yes to delete the state bucket non-interactively.\n',
561
+ event: 'infrastructure_destroyed',
562
+ telemetry: { projectName: projectNameForTelemetry },
563
+ errorCode: 'DESTROY_NON_INTERACTIVE',
564
+ });
565
+ if (refused) return refused;
566
+ }
536
567
  deleteS3Bucket = shouldAutoApprove(options) ? true : await confirm({
537
568
  message: color.yellow(`AWS compute resources destroyed. Do you also want to permanently delete the S3 state bucket?\n (Select 'No' if you plan to run 'grada apply' later to spin this back up.)`),
538
569
  initialValue: false,
@@ -8,6 +8,7 @@ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized,
8
8
  import { normalizeOptions } from '../utils/args.js';
9
9
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
10
10
  import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
11
+ import { pickNewestRunningTask } from '../utils/ecs.js';
11
12
 
12
13
  export const LOG_FETCH_LIMIT = 50;
13
14
 
@@ -76,6 +77,25 @@ function isLogGroupNotFoundError(error) {
76
77
  return !!error && error.name === 'ResourceNotFoundException';
77
78
  }
78
79
 
80
+ // Shared log tail for the ECS and Lambda paths: fetched lines, the honest
81
+ // fetch-failure warning (never "no events" when the fetch failed), the
82
+ // missing-group hint, or the genuine empty line — in that order.
83
+ function printLogTail({ logGroup, logs, logGroupMissing, logFetchFailed, fetchError, listPrefix, region }) {
84
+ if (logs.length > 0) {
85
+ console.log(`\n ${color.bold(`Last ${logs.length} log lines (${color.cyan(logGroup)}):`)}`);
86
+ for (const line of logs) {
87
+ console.log(` ${color.dim('│')} ${highlightErrorLine(line)}`);
88
+ }
89
+ } else if (logFetchFailed) {
90
+ console.log(color.yellow(`\n⚠ Could not fetch recent logs from ${logGroup} (${fetchError}). Log health is unverified.`));
91
+ } else if (logGroupMissing) {
92
+ console.log(color.yellow(`\n⚠ Log group not found (expected ${logGroup}).`));
93
+ console.log(color.dim(`List matching groups with: aws logs describe-log-groups --log-group-name-prefix "${listPrefix}" --region ${region}`));
94
+ } else {
95
+ console.log(color.dim(`\n No recent log events found in ${logGroup}.`));
96
+ }
97
+ }
98
+
79
99
  // Lambda diagnosis without new dependencies: function configuration comes
80
100
  // from the AWS CLI (`get-function`), recent output from the CloudWatch Logs
81
101
  // SDK client the ECS path already uses.
@@ -156,6 +176,8 @@ export async function runLambdaDiagnose(input = {}) {
156
176
  s.message(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${functionName}"...`);
157
177
  let logs = [];
158
178
  let logGroupMissing = false;
179
+ let logFetchFailed = false;
180
+ let fetchError = '';
159
181
  try {
160
182
  const logsResp = await logsClient.send(new FilterLogEventsCommand({
161
183
  logGroupName: logGroup,
@@ -169,12 +191,14 @@ export async function runLambdaDiagnose(input = {}) {
169
191
  logGroupMissing = true;
170
192
  logs = [];
171
193
  } else {
194
+ logFetchFailed = true;
195
+ fetchError = `${logsError?.name || 'Error'}: ${logsError?.message || logsError}`;
172
196
  logs = [];
173
197
  }
174
198
  }
175
199
 
176
200
  const errorLines = logs.filter((line) => /error|exception|failed|fatal|outofmemory|killed/i.test(String(line ?? '')));
177
- const healthy = !configUnhealthy && errorLines.length === 0;
201
+ const healthy = !configUnhealthy && !logFetchFailed && errorLines.length === 0;
178
202
 
179
203
  s.stop('Diagnosis complete.\n');
180
204
 
@@ -185,27 +209,28 @@ export async function runLambdaDiagnose(input = {}) {
185
209
  console.log(` ${color.dim('State:')} ${state === 'Active' ? color.green(state) : color.yellow(state)} ${color.dim(`/ ${lastUpdateStatus}`)}`);
186
210
  if (configuration.LastModified) console.log(` ${color.dim('Modified:')} ${configuration.LastModified}`);
187
211
 
188
- if (logs.length > 0) {
189
- console.log(`\n ${color.bold(`Last ${logs.length} log lines (${color.cyan(logGroup)}):`)}`);
190
- for (const line of logs) {
191
- console.log(` ${color.dim('│')} ${highlightErrorLine(line)}`);
192
- }
193
- } else if (logGroupMissing) {
194
- console.log(color.yellow(`\n⚠ Log group not found (expected ${logGroup}).`));
195
- console.log(color.dim(`List matching groups with: aws logs describe-log-groups --log-group-name-prefix "/aws/lambda/" --region ${region}`));
196
- } else {
197
- console.log(color.dim(`\n No recent log events found in ${logGroup}.`));
198
- }
212
+ printLogTail({ logGroup, logs, logGroupMissing, logFetchFailed, fetchError, listPrefix: '/aws/lambda/', region });
199
213
 
200
214
  if (healthy) {
201
215
  outro(color.green('Diagnose complete. Nothing to fix!'));
202
- await trackSuccess('diagnose_run', { healthy: true, log_source: logs.length > 0 ? 'group-fallback' : 'none' });
216
+ await trackSuccess('diagnose_run', { healthy: true, log_source: logs.length > 0 ? 'log-group' : 'none' });
203
217
  return { healthy: true, functionName, state, lastUpdateStatus, logs: [] };
204
218
  }
205
219
 
206
- outro(color.green('Diagnose complete. Fix the error above, then redeploy. 🚀'));
207
- await trackSuccess('diagnose_run', { healthy: false, log_source: logs.length > 0 ? 'group-fallback' : 'none' });
208
- return { healthy: false, functionName, state, lastUpdateStatus, logs };
220
+ if (logFetchFailed && !configUnhealthy && errorLines.length === 0) {
221
+ outro(color.yellow('Diagnose complete. Log health unverified — retry shortly or check CloudWatch directly.'));
222
+ } else {
223
+ outro(color.green('Diagnose complete. Fix the error above, then redeploy. 🚀'));
224
+ }
225
+ await trackSuccess('diagnose_run', {
226
+ healthy: false,
227
+ log_source: logs.length > 0 ? 'log-group' : 'none',
228
+ ...(logFetchFailed ? { log_fetch_failed: true } : {}),
229
+ });
230
+ return {
231
+ healthy: false, functionName, state, lastUpdateStatus, logs,
232
+ ...(logFetchFailed ? { logFetchFailed: true } : {}),
233
+ };
209
234
  }
210
235
 
211
236
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
@@ -336,17 +361,8 @@ async function runDiagnoseMain(input = {}) {
336
361
  tasks: runningArns.slice(0, 100)
337
362
  })
338
363
  );
339
- const runningTasks = runningDescResp.tasks || [];
340
- for (const task of runningTasks) {
341
- // ListTasks({ desiredStatus: 'RUNNING' }) also returns tasks
342
- // still PROVISIONING/PENDING toward that goal. Only a task
343
- // whose actual lastStatus is RUNNING — and which isn't
344
- // UNHEALTHY — proves the service recovered.
345
- if (task?.lastStatus !== 'RUNNING' || task?.healthStatus === 'UNHEALTHY') continue;
346
- if (!newestRunning || taskStartTime(task) > taskStartTime(newestRunning)) {
347
- newestRunning = task;
348
- }
349
- }
364
+ // Only a healthy RUNNING task proves the service recovered.
365
+ newestRunning = pickNewestRunningTask(runningDescResp.tasks || [], { excludeUnhealthy: true });
350
366
  }
351
367
  const latestRunningStart = newestRunning ? taskStartTime(newestRunning) : 0;
352
368
 
@@ -399,6 +415,8 @@ async function runDiagnoseMain(input = {}) {
399
415
 
400
416
  let logs = [];
401
417
  let logGroupMissing = false;
418
+ let logFetchFailed = false;
419
+ let fetchError = '';
402
420
  let logSource = 'none';
403
421
  if (streamPrefix) {
404
422
  try {
@@ -425,7 +443,12 @@ async function runDiagnoseMain(input = {}) {
425
443
  });
426
444
  if (logs.length > 0) logSource = 'group-fallback';
427
445
  } catch (fallbackError) {
428
- if (isLogGroupNotFoundError(fallbackError)) logGroupMissing = true;
446
+ if (isLogGroupNotFoundError(fallbackError)) {
447
+ logGroupMissing = true;
448
+ } else {
449
+ logFetchFailed = true;
450
+ fetchError = `${fallbackError?.name || 'Error'}: ${fallbackError?.message || fallbackError}`;
451
+ }
429
452
  logs = [];
430
453
  }
431
454
  }
@@ -440,21 +463,15 @@ async function runDiagnoseMain(input = {}) {
440
463
  console.log(` ${color.dim('Container reason:')} ${color.yellow(containerReason)}`);
441
464
  }
442
465
 
443
- if (logs.length > 0) {
444
- console.log(`\n ${color.bold(`Last ${logs.length} log lines (${color.cyan(logGroup)}):`)}`);
445
- for (const line of logs) {
446
- console.log(` ${color.dim('│')} ${highlightErrorLine(line)}`);
447
- }
448
- } else if (logGroupMissing) {
449
- console.log(color.yellow(`\n⚠ Log group not found (expected ${logGroup}).`));
450
- console.log(color.dim(`List matching groups with: aws logs describe-log-groups --log-group-name-prefix "/ecs/" --region ${region}`));
451
- } else {
452
- console.log(color.dim(`\n No recent log events found in ${logGroup}.`));
453
- }
466
+ printLogTail({ logGroup, logs, logGroupMissing, logFetchFailed, fetchError, listPrefix: '/ecs/', region });
454
467
 
455
468
  outro(color.green('Diagnose complete. Fix the error above, then redeploy. 🚀'));
456
469
 
457
- await trackSuccess('diagnose_run', { healthy: false, log_source: logSource });
470
+ await trackSuccess('diagnose_run', {
471
+ healthy: false,
472
+ log_source: logSource,
473
+ ...(logFetchFailed ? { log_fetch_failed: true } : {}),
474
+ });
458
475
 
459
476
  return {
460
477
  healthy: false,
@@ -464,7 +481,8 @@ async function runDiagnoseMain(input = {}) {
464
481
  containerName,
465
482
  exitCode,
466
483
  containerReason,
467
- logs
484
+ logs,
485
+ ...(logFetchFailed ? { logFetchFailed: true } : {}),
468
486
  };
469
487
  } catch (error) {
470
488
  if (isAuthError(error)) {