grada-run 0.41.1 → 0.41.3

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/bin/cli.js CHANGED
@@ -34,9 +34,9 @@ const HELP_TEXT = [
34
34
  '',
35
35
  'Commands:',
36
36
  ' init Provision infrastructure and CI/CD pipelines',
37
- ' apply Apply infrastructure changes (--auto-approve, --force, --force-unlock, --force-resume, --destroy-previous-target)',
37
+ ' apply Apply infrastructure changes (--auto-approve, --force, --force-unlock, --force-resume, --destroy-previous-target, --progress)',
38
38
  ' deploy Alias of apply',
39
- ' destroy Tear down infrastructure (--yes, --allow-data-loss, --force-unlock, --force)',
39
+ ' destroy Tear down infrastructure (--yes, --allow-data-loss, --force-unlock, --force, --progress)',
40
40
  ' doctor Run pre-flight dependency checks (--deep)',
41
41
  ' logs [service] Stream CloudWatch logs (--tail, -f/--follow, --error, --since, --region)',
42
42
  ' status Service health dashboard (--region, --json, --watch)',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.41.1",
3
+ "version": "0.41.3",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -4,11 +4,11 @@ import { intro, outro, spinner, log, cancel, confirm, isCancel } from '@clack/pr
4
4
  import color from 'picocolors';
5
5
  import { renderDryRunPreview, parseTerraformConfig, buildCostTelemetryProps } from '../utils/visualizer.js';
6
6
  import { detectFramework } from '../utils/detector.js';
7
- import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
7
+ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName, isCliEntry } from '../core/telemetry.js';
8
8
  import { failCommand, isProgrammaticCall, shouldAutoApprove, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { spawnSync } from 'child_process';
11
- import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, checkOutputsContract, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS } from '../utils/terraform.js';
11
+ import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, checkOutputsContract, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, PROGRESS_MODES } from '../utils/terraform.js';
12
12
  import { classifyTerraformError, countRecreateCollisions, getRunbook, ERROR_CODES } from '../utils/terraform-errors.js';
13
13
  import { readInitManifest, recordAppliedTarget } from '../utils/backup.js';
14
14
  import { requireManagedTree, parseStateBucketBackend, upsertAutoTfvar } from '../utils/terraform-metadata.js';
@@ -26,12 +26,29 @@ export function parseApplyArgs(argv = []) {
26
26
  if (args[0] === 'apply' || args[0] === 'deploy') args.shift();
27
27
  const { options, unknown } = parseFlags(args, {
28
28
  boolean: ['force', 'destroy-previous-target', 'force-resume', 'allow-partial-outputs', 'headless', 'auto-approve', 'dry-run'],
29
- string: ['force-unlock', 'account-id'],
29
+ string: ['force-unlock', 'account-id', 'progress'],
30
30
  });
31
31
  if (unknown.length > 0) options.unknownFlags = unknown;
32
32
  return { force: false, ...options };
33
33
  }
34
34
 
35
+ // Success/cancel paths exit only for real CLI runs: a bare
36
+ // process.exit kills in-process callers (programmatic API, test
37
+ // harnesses, a future MCP tool) along with their finally blocks.
38
+ // Every site below returns its result right after.
39
+ function exitZeroForCli() {
40
+ if (isCliEntry()) process.exit(0);
41
+ }
42
+
43
+ // Manual adopt equivalent, safe to re-run: strip any existing line
44
+ // for the key (indented or not, present or not), then append exactly
45
+ // one copy. A bare `echo … >>` duplicates the key on re-run and
46
+ // Terraform fails hard on the redefinition. The `|| true` keeps the
47
+ // paste alive under `set -e`: grep -v exits 1 when it selects
48
+ // nothing (single-key file), which would otherwise stop the chain
49
+ // before the move and append.
50
+ export const OIDC_ADOPT_MANUAL_COMMAND = `grep -v "^[[:space:]]*create_oidc_provider[[:space:]]*=" terraform/grada.auto.tfvars 2>/dev/null > terraform/grada.auto.tfvars.tmp || true; mv terraform/grada.auto.tfvars.tmp terraform/grada.auto.tfvars; echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`;
51
+
35
52
  // Offline reconcile: an `init --offline` tree carries
36
53
  // YOUR_AWS_ACCOUNT_ID placeholders instead of an account id and has no
37
54
  // state bucket. Resolve the account (explicit flag, else STS ground
@@ -104,7 +121,8 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
104
121
  });
105
122
  if (confirmed !== true) {
106
123
  cancel('Reconcile aborted.');
107
- process.exit(0);
124
+ exitZeroForCli();
125
+ return { proceed: false, result: { ok: false, reason: 'cancelled' } };
108
126
  }
109
127
  }
110
128
  for (const file of files) {
@@ -298,7 +316,7 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
298
316
  return { proceed: true, previousAppliedTarget: appliedTarget };
299
317
  }
300
318
  cancel('Apply cancelled. No infrastructure was changed.');
301
- process.exit(0);
319
+ exitZeroForCli();
302
320
  return { proceed: false, result: { ok: false, reason: 'cancelled' } };
303
321
  }
304
322
 
@@ -334,6 +352,18 @@ async function applyStackMain(input = {}) {
334
352
  const options = normalizeOptions(input);
335
353
  const unknownRefusal = await refuseUnknownFlags(options, { command: 'apply', event: 'infrastructure_applied' });
336
354
  if (unknownRefusal) return unknownRefusal;
355
+ const progressMode = typeof options.progress === 'string' && options.progress.trim() !== '' ? options.progress.trim() : null;
356
+ if (progressMode !== null && !PROGRESS_MODES.includes(progressMode)) {
357
+ return failCommand({
358
+ noExit: isProgrammaticCall(options),
359
+ message: `\n✖ Invalid --progress "${options.progress}". Supported modes: lines, spinner.\n`,
360
+ hint: ' Use --progress lines when the output viewer splits animation frames into lines (harness PTYs, log capture).\n',
361
+ event: 'infrastructure_applied',
362
+ telemetry: { projectName: path.basename(process.cwd()) },
363
+ errorCode: 'INVALID_PROGRESS_MODE',
364
+ reason: 'invalid-progress-mode',
365
+ });
366
+ }
337
367
  intro(color.bgCyan(color.black(' grada apply ☁️ ')));
338
368
 
339
369
  const targetDir = process.cwd();
@@ -413,7 +443,8 @@ async function applyStackMain(input = {}) {
413
443
  framework: detectedConfig.framework,
414
444
  ...costProps,
415
445
  });
416
- process.exit(0);
446
+ exitZeroForCli();
447
+ return { ok: true, dryRun: true };
417
448
  } else if (shouldAutoApprove(options) || options._skipPreview === true) {
418
449
  // Internal lock-retry resumes skip the preview: the user already
419
450
  // confirmed it before the lock failure.
@@ -430,14 +461,15 @@ async function applyStackMain(input = {}) {
430
461
  const confirmed = await renderDryRunPreview(detectedConfig, false);
431
462
  if (!confirmed) {
432
463
  cancel('Apply aborted.');
433
- process.exit(0);
464
+ exitZeroForCli();
465
+ return { ok: false, reason: 'cancelled' };
434
466
  }
435
467
  }
436
468
 
437
469
  const s = spinner();
438
470
  const runTerraform = options.runTerraformImpl || runTerraformCommand;
439
471
  const runSync = options.spawnSyncImpl || spawnSync;
440
- const lifecycleOpts = { markerDir: targetDir, timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS };
472
+ const lifecycleOpts = { markerDir: targetDir, timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, ...(progressMode ? { progress: progressMode } : {}) };
441
473
  const diskTarget = readTerraformComputeTarget(targetDir);
442
474
 
443
475
  try {
@@ -550,7 +582,8 @@ async function applyStackMain(input = {}) {
550
582
  ...costProps
551
583
  });
552
584
 
553
- process.exit(0);
585
+ exitZeroForCli();
586
+ return { ok: true, projectName: actualProjectName, target: diskTarget };
554
587
 
555
588
  } catch (error) {
556
589
  s.stop(color.red('❌ Terraform apply failed.'));
@@ -667,6 +700,7 @@ async function applyStackMain(input = {}) {
667
700
  });
668
701
  }
669
702
 
703
+ let adoptUpsertError = null;
670
704
  if (code === 'OIDC_PROVIDER_CONFLICT' && options._oidcAdopted !== true) {
671
705
  // Adopt the shared provider instead of hand-editing: the
672
706
  // GitHub provider URL is account-singleton, so the existing
@@ -688,12 +722,21 @@ async function applyStackMain(input = {}) {
688
722
  adopt = !isCancel(confirmed) && confirmed === true;
689
723
  }
690
724
  if (adopt) {
691
- upsertAutoTfvar(tfDir, 'create_oidc_provider', false);
692
- trackEvent('oidc_provider_adopted', { projectName: actualProjectName });
693
- log.message(color.cyan('Adopted the existing OIDC provider — retrying apply...'));
694
- return applyStack({ ...options, _skipPreview: true, _oidcAdopted: true });
725
+ try {
726
+ upsertAutoTfvar(tfDir, 'create_oidc_provider', false);
727
+ } catch (error) {
728
+ // A failed write must not crash inside the error
729
+ // handler: fall through to the manual guidance with
730
+ // the write error appended.
731
+ adoptUpsertError = error;
732
+ }
733
+ if (adoptUpsertError === null) {
734
+ trackEvent('oidc_provider_adopted', { projectName: actualProjectName });
735
+ log.message(color.cyan('Adopted the existing OIDC provider — retrying apply...'));
736
+ return applyStack({ ...options, _skipPreview: true, _oidcAdopted: true });
737
+ }
695
738
  }
696
- // Declined: fall through to the manual guidance below.
739
+ // Declined (or unwritable): fall through to the manual guidance below.
697
740
  }
698
741
 
699
742
  if (code === 'OIDC_PROVIDER_CONFLICT') {
@@ -703,8 +746,11 @@ async function applyStackMain(input = {}) {
703
746
  log.message('AWS only allows one GitHub Actions provider per account, and you already have one configured.');
704
747
  log.message('');
705
748
  log.message(`${color.bold('How to fix this:')}`);
706
- log.message(`1. Adopt the shared provider: ${color.cyan(`echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`)}`);
749
+ log.message(`1. Adopt the shared provider (safe to re-run): ${color.cyan(OIDC_ADOPT_MANUAL_COMMAND)}`);
707
750
  log.message(`2. Run ${color.cyan('npx grada-run apply')} again.`);
751
+ if (adoptUpsertError) {
752
+ log.message(color.dim(` (Automatic adoption failed: ${adoptUpsertError.message})`));
753
+ }
708
754
  } else if (code === 'BACKEND_RECONFIGURE_REQUIRED' || code === 'CLOUDFRONT_IN_PROGRESS' || code === 'DELETION_PROTECTION_ACTIVE') {
709
755
  // Named but flow-neutral: runbook guidance with a coded
710
756
  // failure. (RECREATE_COLLISION has its dedicated branch
@@ -8,6 +8,7 @@ import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/a
8
8
  import { resolveRegion, resolveProjectName, resolveAppName, resolveCwd } from '../../utils/resolvers.js';
9
9
  import { findDbTarget, generateSnapshotId, isValidSnapshotId, resolveDbIdentifier, resolveDbClusterIdentifier } from '../../utils/rds.js';
10
10
  import { pollUntil, parseTimeoutSeconds } from '../../utils/system.js';
11
+ import { truncateSpinnerText } from '../../utils/spinner-text.js';
11
12
 
12
13
  export const DEFAULT_BACKUP_TIMEOUT_SECONDS = 900;
13
14
  export const DEFAULT_BACKUP_POLL_INTERVAL_MS = 5000;
@@ -137,7 +138,7 @@ async function runDbBackupMain(input = {}) {
137
138
  ? options.snapshotId.trim()
138
139
  : generateSnapshotId(target.id);
139
140
 
140
- s.message(`Creating snapshot ${snapshotId}...`);
141
+ s.message(truncateSpinnerText(`Creating snapshot ${snapshotId}...`));
141
142
  const snapshotTags = [
142
143
  { Key: 'ManagedBy', Value: 'grada' },
143
144
  { Key: 'Project', Value: projectName },
@@ -165,7 +166,7 @@ async function runDbBackupMain(input = {}) {
165
166
  return { ok: true, snapshotId, status: 'creating' };
166
167
  }
167
168
 
168
- s.message(`Waiting for snapshot ${snapshotId} to become available...`);
169
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId} to become available...`));
169
170
  const outcome = await pollUntil({
170
171
  intervalMs: pollIntervalMs,
171
172
  timeoutMs,
@@ -188,7 +189,7 @@ async function runDbBackupMain(input = {}) {
188
189
  // creation (eventual consistency), so keep polling.
189
190
  const notFoundNames = isCluster ? CLUSTER_SNAPSHOT_NOT_FOUND_NAMES : SNAPSHOT_NOT_FOUND_NAMES;
190
191
  if (error && notFoundNames.has(error.name)) {
191
- s.message(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`);
192
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`));
192
193
  return { done: false };
193
194
  }
194
195
  throw error;
@@ -203,7 +204,7 @@ async function runDbBackupMain(input = {}) {
203
204
  if (snapshot && TERMINAL_SNAPSHOT_STATUSES.has(String(snapshot.Status || '').toLowerCase())) {
204
205
  return { done: true, value: { terminalFailure: true, status: snapshot.Status } };
205
206
  }
206
- s.message(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`);
207
+ s.message(truncateSpinnerText(`Waiting for snapshot ${snapshotId}... [${Math.floor(elapsedMs / 1000)}s]`));
207
208
  return { done: false };
208
209
  },
209
210
  });
@@ -7,13 +7,14 @@ 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, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
11
- import { runTerraformCommand, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, getTerraformStateBuckets, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS } from '../utils/terraform.js';
10
+ import { failCommand, shouldAutoApprove, refuseIfNonInteractive, refuseUnknownFlags, isProgrammaticCall } from '../utils/command.js';
11
+ import { runTerraformCommand, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, getTerraformStateBuckets, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, PROGRESS_MODES } 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';
14
14
  import { requireManagedTree, parseStateBucketBackend } from '../utils/terraform-metadata.js';
15
15
  import { guardSleepingEnv } from '../utils/sleep-state.js';
16
16
  import { normalizeOptions, parseFlags, normalizeArgv } from '../utils/args.js';
17
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
17
18
 
18
19
  export const DEFAULT_DESTROY_DB_TIMEOUT_MS = 600000;
19
20
  export const DEFAULT_DESTROY_DB_SETTLE_TIMEOUT_MS = 1800000;
@@ -40,7 +41,7 @@ export function parseDestroyArgs(argv = []) {
40
41
  const args = normalizeArgv(argv);
41
42
  const { options, unknown } = parseFlags(args, {
42
43
  boolean: ['allow-data-loss', 'force', 'headless', 'yes'],
43
- string: ['force-unlock'],
44
+ string: ['force-unlock', 'progress'],
44
45
  });
45
46
  if (unknown.length > 0) options.unknownFlags = unknown;
46
47
  return { allowDataLoss: false, force: false, ...options };
@@ -148,6 +149,18 @@ async function destroyStackMain(input = {}) {
148
149
  const options = normalizeOptions(input);
149
150
  const unknownRefusal = await refuseUnknownFlags(options, { command: 'destroy', event: 'infrastructure_destroyed' });
150
151
  if (unknownRefusal) return unknownRefusal;
152
+ const progressMode = typeof options.progress === 'string' && options.progress.trim() !== '' ? options.progress.trim() : null;
153
+ if (progressMode !== null && !PROGRESS_MODES.includes(progressMode)) {
154
+ return failCommand({
155
+ noExit: isProgrammaticCall(options),
156
+ message: `\n✖ Invalid --progress "${options.progress}". Supported modes: lines, spinner.\n`,
157
+ hint: ' Use --progress lines when the output viewer splits animation frames into lines (harness PTYs, log capture).\n',
158
+ event: 'infrastructure_destroyed',
159
+ telemetry: { projectName: path.basename(process.cwd()) },
160
+ errorCode: 'INVALID_PROGRESS_MODE',
161
+ reason: 'invalid-progress-mode',
162
+ });
163
+ }
151
164
  intro(color.bgRed(color.white(' grada destroy 🗑️ ')));
152
165
 
153
166
  // Ejected trees are user-owned: refuse unless --force.
@@ -266,7 +279,7 @@ async function destroyStackMain(input = {}) {
266
279
  }
267
280
 
268
281
  const s = spinner();
269
- const lifecycleOpts = { markerDir: process.cwd(), timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS };
282
+ const lifecycleOpts = { markerDir: process.cwd(), timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, ...(progressMode ? { progress: progressMode } : {}) };
270
283
 
271
284
  // 1. Init first (R4): destroy on a fresh checkout or a wiped
272
285
  // .terraform cache must not trip over missing plugins.
@@ -311,7 +324,7 @@ async function destroyStackMain(input = {}) {
311
324
  if (status === 'stopped' || status === 'available' || status === null) {
312
325
  return { done: true, value: status };
313
326
  }
314
- s.message(`Waiting for ${dbTarget.id} to settle (${status})... [${Math.floor(elapsedMs / 1000)}s]`);
327
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} to settle (${status})... [${Math.floor(elapsedMs / 1000)}s]`));
315
328
  return { done: false };
316
329
  },
317
330
  });
@@ -322,7 +335,7 @@ async function destroyStackMain(input = {}) {
322
335
  onTick: async ({ elapsedMs }) => {
323
336
  const status = await readStatus();
324
337
  if (status === 'available' || status === null) return { done: true, value: status };
325
- s.message(`Waiting for ${dbTarget.id} to become available... [${Math.floor(elapsedMs / 1000)}s]`);
338
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} to become available... [${Math.floor(elapsedMs / 1000)}s]`));
326
339
  return { done: false };
327
340
  },
328
341
  });
@@ -392,7 +405,7 @@ async function destroyStackMain(input = {}) {
392
405
  // (nothing left to protect).
393
406
  if (dbNeedsProtection) {
394
407
  const snapshotId = generateSnapshotId(dbTarget.id);
395
- s.start(`Snapshotting database ${dbTarget.id} before destruction...`);
408
+ s.start(truncateSpinnerText(`Snapshotting database ${dbTarget.id} before destruction...`));
396
409
  try {
397
410
  if (dbTarget.kind === 'cluster') {
398
411
  await rdsClient.send(new CreateDBClusterSnapshotCommand({ DBClusterSnapshotIdentifier: snapshotId, DBClusterIdentifier: dbTarget.id }));
@@ -429,7 +442,7 @@ async function destroyStackMain(input = {}) {
429
442
  // warns and proceeds — terraform reports the authoritative outcome.
430
443
  if (dbTarget && dbTarget.status !== 'deleting') {
431
444
  const isCluster = dbTarget.kind === 'cluster';
432
- s.start(`Lifting RDS deletion protection on ${dbTarget.id}...`);
445
+ s.start(truncateSpinnerText(`Lifting RDS deletion protection on ${dbTarget.id}...`));
433
446
  let lifted = false;
434
447
  try {
435
448
  if (isCluster) {
@@ -462,7 +475,7 @@ async function destroyStackMain(input = {}) {
462
475
  status = null;
463
476
  }
464
477
  if (status === 'available' || status === null || status === 'deleting') return { done: true, value: status };
465
- s.message(`Waiting for ${dbTarget.id} after lifting protection (${status})... [${Math.floor(elapsedMs / 1000)}s]`);
478
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} after lifting protection (${status})... [${Math.floor(elapsedMs / 1000)}s]`));
466
479
  return { done: false };
467
480
  },
468
481
  });
@@ -573,7 +586,7 @@ async function destroyStackMain(input = {}) {
573
586
  });
574
587
 
575
588
  if (deleteS3Bucket && typeof deleteS3Bucket !== 'symbol') {
576
- s.start(`Emptying and deleting S3 state bucket: ${bucketName}...`);
589
+ s.start(truncateSpinnerText(`Emptying and deleting S3 state bucket: ${bucketName}...`));
577
590
  try {
578
591
  const bucketResult = await teardownStateBucket(region, bucketName);
579
592
  const remaining = bucketResult && typeof bucketResult === 'object' && Array.isArray(bucketResult.remaining)
@@ -6,6 +6,7 @@ import { intro, outro, spinner } from '@clack/prompts';
6
6
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
7
7
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, isProgrammaticCall } from '../utils/command.js';
8
8
  import { normalizeOptions } from '../utils/args.js';
9
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
9
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
10
11
  import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
11
12
  import { pickNewestRunningTask } from '../utils/ecs.js';
@@ -173,7 +174,7 @@ export async function runLambdaDiagnose(input = {}) {
173
174
  const lastUpdateStatus = configuration.LastUpdateStatus || 'UNKNOWN';
174
175
  const configUnhealthy = state !== 'Active' || lastUpdateStatus === 'Failed';
175
176
 
176
- s.message(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${functionName}"...`);
177
+ s.message(truncateSpinnerText(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${functionName}"...`));
177
178
  let logs = [];
178
179
  let logGroupMissing = false;
179
180
  let logFetchFailed = false;
@@ -400,7 +401,7 @@ async function runDiagnoseMain(input = {}) {
400
401
  };
401
402
  }
402
403
 
403
- s.message(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${containerName}"...`);
404
+ s.message(truncateSpinnerText(`Fetching last ${LOG_FETCH_LIMIT} log lines for "${containerName}"...`));
404
405
 
405
406
  // CloudWatch stream names follow `ecs/<containerName>/<taskId>`.
406
407
  const taskId = extractTaskIdFromArn(failedTask.taskArn);
@@ -231,6 +231,20 @@ async function runDriftMain(input = {}) {
231
231
  return { ok: true, action: 'check', drift: false, region };
232
232
  }
233
233
  if (status === 2) {
234
+ // A plan on never-applied infrastructure also exits 2
235
+ // (everything "to add"). Empty state means nothing exists yet —
236
+ // report that instead of crying drift. A failed state lookup
237
+ // falls through to DRIFT_DETECTED: never mask real drift
238
+ // behind a broken check.
239
+ const stateResult = runSync('terraform', ['state', 'list', '-no-color'], { cwd: tfDir, encoding: 'utf8' });
240
+ const stateOk = stateResult?.status === 0;
241
+ if (stateOk && String(stateResult?.stdout ?? '').trim() === '') {
242
+ s.stop(color.green('Not provisioned yet.'));
243
+ console.log(color.green('\n✅ Nothing provisioned yet — run "npx grada-run apply" first, then check drift.\n'));
244
+ await trackSuccess('drift_run', { projectName, action: 'check', drift: false, provisioned: false });
245
+ outro(color.green('Done.'));
246
+ return { ok: true, action: 'check', drift: false, provisioned: false, region };
247
+ }
234
248
  s.stop(color.yellow('Drift detected.'));
235
249
  const summary = extractPlanSummary(planResult?.stdout);
236
250
  return failCommand({
@@ -241,10 +255,10 @@ async function runDriftMain(input = {}) {
241
255
  console.log(` Reconcile with ${color.green('npx grada-run apply')}, or adopt the live resource with ${color.green('terraform import')}.\n`);
242
256
  },
243
257
  event: 'drift_run',
244
- telemetry: { projectName, action: 'check', drift: true },
258
+ telemetry: { projectName, action: 'check', drift: true, ...(stateOk ? { provisioned: true } : {}) },
245
259
  errorCode: 'DRIFT_DETECTED',
246
260
  reason: 'drift-detected',
247
- resultExtra: { region },
261
+ resultExtra: { region, ...(stateOk ? { provisioned: true } : {}) },
248
262
  exitCode: 2,
249
263
  });
250
264
  }
@@ -11,9 +11,10 @@ import {
11
11
  writeEjectedMarker,
12
12
  writeEjectedSentinel,
13
13
  parseStateBucketBackend,
14
+ GRADA_AUTO_TFVARS_FILENAME,
14
15
  } from '../utils/terraform-metadata.js';
15
16
  import { readSleepState, writeSleepState, LEDGER_LOCK_SCOPE } from '../utils/sleep-state.js';
16
- import { ensureGitignoreRules, GITIGNORE_RULE_GRADA_DIR } from '../utils/gitignore.js';
17
+ import { ensureGitignoreRules, applyGitignoreRules, GITIGNORE_RULE_GRADA_DIR } from '../utils/gitignore.js';
17
18
  import { withProjectLock } from '../utils/file-lock.js';
18
19
  import { atomicWriteFileSync } from '../utils/atomic-write.js';
19
20
  import { runWake } from './wake.js';
@@ -180,6 +181,24 @@ async function ejectStackMain(input = {}) {
180
181
  let gitignore = fs.readFileSync(gitignorePath, 'utf8');
181
182
  // Remove the exact block we injected in backup.js
182
183
  gitignore = stripGitignoreMetadata(gitignore);
184
+ // 2b. Adopted trees must keep the adoption committed: the
185
+ // scaffolded `terraform/*.auto.tfvars` ignore would drop
186
+ // grada.auto.tfvars from fresh clones, breaking them on
187
+ // OIDC with no Grada left to adopt. Negate just that file
188
+ // (sleep.auto.tfvars stays ignored). No file, no rule to
189
+ // negate, or already negated: leave the file untouched.
190
+ const autoTfvarsPath = path.join(tfDir, GRADA_AUTO_TFVARS_FILENAME);
191
+ const hasIgnoreRule = gitignore.split('\n').some((line) => {
192
+ const trimmed = line.trim();
193
+ return trimmed !== '' && !trimmed.startsWith('#') && !trimmed.startsWith('!') && trimmed.includes('auto.tfvars');
194
+ });
195
+ if (hasIgnoreRule && fs.existsSync(autoTfvarsPath)) {
196
+ const negation = `!terraform/${GRADA_AUTO_TFVARS_FILENAME}`;
197
+ gitignore = applyGitignoreRules(gitignore, [{
198
+ contains: negation,
199
+ block: `# Ejected tree: keep the adopted OIDC override committed\n${negation}\n`,
200
+ }]).content;
201
+ }
183
202
  atomicWriteFileSync(gitignorePath, gitignore.trim() + '\n');
184
203
  }
185
204
 
@@ -140,14 +140,17 @@ function defaultListLambdaFunctionNames({ region, spawnSyncImpl } = {}) {
140
140
  // proposing live-preview groups.
141
141
  // One enumeration feeding every ECS liveness consumer: each workspace
142
142
  // provisions its own `<app>-cluster`, so liveness must scan the
143
- // default cluster AND every preview cluster — never just one.
144
- // Returns service ARNs per project cluster; any client error resolves
145
- // `unknown` (fail closed) instead of a partial set.
143
+ // default cluster AND every workspace cluster — Grada-minted `pr-N`
144
+ // and hand-made (`staging`) alike, never just one. The segment is
145
+ // deliberately workspace-wide: over-matching only ADDS live marks
146
+ // (gc skips more), while a missed live cluster proposes a live VPC
147
+ // for deletion. Returns service ARNs per project cluster; any client
148
+ // error resolves `unknown` (fail closed) instead of a partial set.
146
149
  export async function listProjectClusterServices({ ecsClient = null, projectName, resourceSuffix = '' } = {}) {
147
150
  const byCluster = new Map();
148
151
  try {
149
152
  if (!ecsClient) return { byCluster, unknown: false };
150
- const clusterPattern = new RegExp(`^${escapeRegExp(projectName)}(-pr-\\d+)?${escapeRegExp(resourceSuffix)}-cluster$`);
153
+ const clusterPattern = new RegExp(`^${escapeRegExp(projectName)}(-[A-Za-z0-9_-]+)?${escapeRegExp(resourceSuffix)}-cluster$`);
151
154
  let nextToken;
152
155
  const clusters = [];
153
156
  do {
@@ -7,7 +7,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
7
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
8
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
9
9
  import { z } from 'zod';
10
- import { getCliVersion, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
10
+ import { getCliVersion, trackSuccess, setActiveCommandName, resetActiveCommandName, rotateRunId } from '../core/telemetry.js';
11
11
  import { safeHomedir } from '../core/homedir.js';
12
12
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
13
  import { failCommand, refuseUnknownFlags } from '../utils/command.js';
@@ -151,6 +151,7 @@ export function runGuardedToolCall(fn) {
151
151
  // safe, while setting it outside would race pipelined tool calls.
152
152
  export async function withMcpCommand(commandName, fn) {
153
153
  setActiveCommandName(commandName);
154
+ rotateRunId();
154
155
  try {
155
156
  return await fn();
156
157
  } finally {
@@ -13,6 +13,7 @@ import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
13
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
14
14
  import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, resolveWorkspaceSuffix, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
15
  import { requireManagedTree } from '../utils/terraform-metadata.js';
16
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
16
17
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
17
18
  import {
18
19
  discoverEligibleRevisions as discoverWithAdapter,
@@ -301,7 +302,7 @@ async function runRollbackMain(input = {}) {
301
302
  }
302
303
 
303
304
  // 2. Trigger the rollback.
304
- s.start(`Rolling back ${service} to revision ${targetRevisionNum}...`);
305
+ s.start(truncateSpinnerText(`Rolling back ${service} to revision ${targetRevisionNum}...`));
305
306
  await ecsClient.send(new UpdateServiceCommand({
306
307
  cluster,
307
308
  service,
@@ -353,19 +354,23 @@ async function runRollbackMain(input = {}) {
353
354
  }
354
355
 
355
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]`;
356
361
  if (!primary) {
357
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (registering deployment...)`);
362
+ s.message(truncateSpinnerText(`${progressStem} (registering deployment...)`));
358
363
  } else {
359
364
  const runningCount = primary.runningCount ?? 0;
360
365
  const desiredCount = primary.desiredCount ?? 0;
361
366
  const pendingCount = primary.pendingCount ?? 0;
362
367
  const failedTasks = primary.failedTasks ?? 0;
363
368
  if (failedTasks > 0) {
364
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`);
369
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending, ${failedTasks} failed ⚠️ — container crashing)`));
365
370
  } else if (runningCount >= desiredCount && desiredCount > 0 && pendingCount === 0) {
366
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (${runningCount}/${desiredCount} running — draining previous tasks)`);
371
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running — draining previous tasks)`));
367
372
  } else {
368
- s.message(`Rolling back ${service} to revision ${targetRevisionNum}... [${elapsedSec}s] (${runningCount}/${desiredCount} running, ${pendingCount} pending)`);
373
+ s.message(truncateSpinnerText(`${progressStem} (${runningCount}/${desiredCount} running, ${pendingCount} pending)`));
369
374
  }
370
375
  }
371
376
 
@@ -11,6 +11,7 @@ import { atomicWriteFile } from '../utils/atomic-write.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
12
  import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
13
13
  import { requireManagedTree } from '../utils/terraform-metadata.js';
14
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
14
15
 
15
16
  // Static sites provision no secrets vault, so push/pull/audit would fail
16
17
  // obscurely against a Secrets Manager secret that can never exist. One
@@ -242,7 +243,7 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
242
243
  : path.basename(process.cwd());
243
244
 
244
245
  const s = spinner();
245
- s.start(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`);
246
+ s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
246
247
 
247
248
  try {
248
249
  // 1. Read and parse the local .env file
@@ -7,6 +7,7 @@ import { intro, outro, spinner, confirm, cancel } from '@clack/prompts';
7
7
  import { trackEvent, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
8
  import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
10
11
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
12
  import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget } from '../utils/resolvers.js';
12
13
  import { requireManagedTree } from '../utils/terraform-metadata.js';
@@ -219,7 +220,7 @@ async function runSleepMain(input = {}) {
219
220
  const runSync = options.spawnSyncImpl || spawnSync;
220
221
 
221
222
  const s = spinner();
222
- s.start(`Putting ${target.envKey} to sleep...`);
223
+ s.start(truncateSpinnerText(`Putting ${target.envKey} to sleep...`));
223
224
 
224
225
  try {
225
226
  // Read-only probes first: the fast-path check below must see live
@@ -13,6 +13,7 @@ import { requireManagedTree } from '../utils/terraform-metadata.js';
13
13
  import { findDbTarget, dbStatusOf } from '../utils/rds.js';
14
14
  import { fetchActiveService, detectTaskFailure } from '../utils/ecs.js';
15
15
  import { pollUntil } from '../utils/system.js';
16
+ import { truncateSpinnerText } from '../utils/spinner-text.js';
16
17
  import {
17
18
  resolveSleepTarget,
18
19
  readSleepState,
@@ -231,7 +232,7 @@ async function runWakeMain(input = {}) {
231
232
  }
232
233
 
233
234
  const s = spinner();
234
- s.start(`Waking ${target.envKey}...`);
235
+ s.start(truncateSpinnerText(`Waking ${target.envKey}...`));
235
236
 
236
237
  try {
237
238
  // 1. Start the database first so booting containers never
@@ -261,7 +262,7 @@ async function runWakeMain(input = {}) {
261
262
 
262
263
  if (!noWait && dbTarget && dbStarted) {
263
264
  const isCluster = dbTarget.kind === 'cluster';
264
- s.message(`Waiting for ${dbTarget.id} to become available...`);
265
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id} to become available...`));
265
266
  const outcome = await pollUntil({
266
267
  intervalMs: pollIntervalMs,
267
268
  timeoutMs,
@@ -275,7 +276,7 @@ async function runWakeMain(input = {}) {
275
276
  ? (resp.DBClusters || [])[0] || null
276
277
  : (resp.DBInstances || [])[0] || null;
277
278
  if (dbStatusOf(current, isCluster ? 'cluster' : 'instance') === 'available') return { done: true, value: current };
278
- s.message(`Waiting for ${dbTarget.id}... [${Math.floor(elapsedMs / 1000)}s]`);
279
+ s.message(truncateSpinnerText(`Waiting for ${dbTarget.id}... [${Math.floor(elapsedMs / 1000)}s]`));
279
280
  return { done: false };
280
281
  },
281
282
  });
@@ -11,6 +11,14 @@ const pendingRequests = [];
11
11
 
12
12
  const CLI_ENTRY_BASENAMES = ['cli.js', 'grada', 'grada-run', 'deploy-stack'];
13
13
 
14
+ // True when this process is a real CLI invocation (as opposed to a
15
+ // programmatic import, test harness, or MCP host): success/cancel
16
+ // paths exit only here, so in-process callers get results instead of
17
+ // a dead host. Argv injectable for tests.
18
+ export function isCliEntry(argv = process.argv) {
19
+ return CLI_ENTRY_BASENAMES.includes(path.basename(argv?.[1] || ''));
20
+ }
21
+
14
22
  // Base props trackEvent stamps on every payload. Callers may override them
15
23
  // with real values, but never with `undefined` (see step 3b below).
16
24
  const RESERVED_BASE_PROPS = [
@@ -24,6 +32,7 @@ const RESERVED_BASE_PROPS = [
24
32
  'is_cli_entry',
25
33
  'cli_command',
26
34
  'project_id',
35
+ 'run_id',
27
36
  'framework',
28
37
  ];
29
38
 
@@ -33,6 +42,24 @@ export function resetTelemetryIdentityCache() {
33
42
  cachedDistinctId = null;
34
43
  }
35
44
 
45
+ // Per-invocation correlation id: stable across every event one CLI run
46
+ // emits, unique across runs. Parallel runners share distinct_id (baked
47
+ // image) and project_id (same fixture dirname), so without this their
48
+ // bursts are indistinguishable from one run emitting many events.
49
+ let cachedRunId = null;
50
+
51
+ export function currentRunId() {
52
+ if (!cachedRunId) cachedRunId = crypto.randomUUID();
53
+ return cachedRunId;
54
+ }
55
+
56
+ // Long-lived hosts (the MCP server) invoke many commands in one process:
57
+ // rotate per tool call so each keeps a distinct correlation id.
58
+ export function rotateRunId() {
59
+ cachedRunId = crypto.randomUUID();
60
+ return cachedRunId;
61
+ }
62
+
36
63
  // Active command for programmatic (non-CLI) entrypoints. Wrappers such as
37
64
  // the MCP server set this around the command they invoke so `cli_command`
38
65
  // names the real command instead of falling back to 'module_import'.
@@ -430,7 +457,7 @@ export function trackEvent(eventName, properties) {
430
457
  const ciProvider = detectCiProvider();
431
458
  const testEnv = isTestEnv();
432
459
  const isCi = isActiveEnvValue(process.env.CI) || ciProvider !== 'none';
433
- const isCliEntry = CLI_ENTRY_BASENAMES.includes(path.basename(process.argv?.[1] || ''));
460
+ const cliEntry = isCliEntry();
434
461
 
435
462
  // 5. Machine-scoped Person identity, stable across commands in this env.
436
463
  const distinctId = resolveDistinctId({ ciProvider, testEnv });
@@ -447,6 +474,9 @@ export function trackEvent(eventName, properties) {
447
474
  // 7. Strip the raw name out of the payload
448
475
  delete eventProps.projectName;
449
476
 
477
+ // 7b. Invocation correlation, resolved lazily so imports never pay.
478
+ const runId = currentRunId();
479
+
450
480
  const payload = {
451
481
  api_key: POSTHOG_API_KEY,
452
482
  event: normalizedEvent,
@@ -459,11 +489,12 @@ export function trackEvent(eventName, properties) {
459
489
  ci_provider: ciProvider,
460
490
  is_test_env: testEnv,
461
491
  is_tty: Boolean(process.stdout && process.stdout.isTTY),
462
- is_cli_entry: isCliEntry,
463
- cli_command: isCliEntry
492
+ is_cli_entry: cliEntry,
493
+ cli_command: cliEntry
464
494
  ? (process.env.CLI_COMMAND || process.argv.slice(2).join(' ') || 'unknown')
465
495
  : (currentCommandName() || 'module_import'),
466
496
  project_id: projectId,
497
+ run_id: runId,
467
498
  framework: process.env.GRADA_FRAMEWORK || process.env.DEPLOY_STACK_FRAMEWORK || frameworkOverride || undefined,
468
499
  ...eventProps
469
500
  }
@@ -8,6 +8,7 @@ import { FilterLogEventsCommand, GetLogEventsCommand } from '@aws-sdk/client-clo
8
8
  import color from 'picocolors';
9
9
  import { fetchActiveService, pickRuntimeContainer } from './ecs.js';
10
10
  import { sleep, pollUntil } from './system.js';
11
+ import { truncateSpinnerText } from './spinner-text.js';
11
12
  import { isNotFoundError, buildLogStreamName } from '../commands/logs.js';
12
13
 
13
14
  export const DEFAULT_RUNNER_POLL_INTERVAL_MS = 2000;
@@ -259,7 +260,7 @@ export async function runEphemeralEcsTask({
259
260
  console.log(color.dim(` task ${taskId} — press Ctrl+C to abort and stop the remote task.\n`));
260
261
  } else if (!streaming && status && status !== lastPhase) {
261
262
  lastPhase = status;
262
- spinner?.message(phaseMessage(status));
263
+ spinner?.message(truncateSpinnerText(phaseMessage(status)));
263
264
  }
264
265
  return { done: false };
265
266
  },
@@ -20,6 +20,21 @@ export const GITIGNORE_RULE_BACKUPS = {
20
20
  block: '\n# grada backups\n*.bak.*\n',
21
21
  };
22
22
 
23
+ // Content-level twin of `ensureGitignoreRules` for read-modify-write
24
+ // flows that already hold the file content (eject strips stanzas in
25
+ // memory under the project lock, so the file-based helper can't be
26
+ // used). Pure: returns the amended content plus whether it changed.
27
+ export function applyGitignoreRules(content, rules = []) {
28
+ const text = typeof content === 'string' ? content : '';
29
+ const missing = rules.filter(
30
+ (rule) => !(typeof text === 'string' && text.includes(rule.contains))
31
+ );
32
+ if (missing.length === 0) return { content: text, changed: false };
33
+ const addition = missing.map((rule) => rule.block).join('').replace(/^\n+/, '');
34
+ const separator = text === '' ? '' : (text.endsWith('\n') ? '\n' : '\n\n');
35
+ return { content: `${text}${separator}${addition}`, changed: true };
36
+ }
37
+
23
38
  // Ensures every rule's block is present in `<cwd>/.gitignore`. Returns
24
39
  // true when the file was created or amended, false when every rule
25
40
  // already matched or the write failed.
@@ -0,0 +1,30 @@
1
+ // Terminal-width truncation for spinner frames. Clack re-renders the
2
+ // current frame every ~80ms, and any frame wider than the terminal
3
+ // wraps — on viewers that split frames into lines (harness PTYs, log
4
+ // capture) each wrapped frame fossilizes as extra scrollback lines.
5
+ // Every dynamic spinner message goes through here so over-width
6
+ // frames can never wall, on any terminal width.
7
+
8
+ // Spinner chrome around the message: glyph + animated dots + padding.
9
+ export const SPINNER_FRAME_OVERHEAD = 9;
10
+
11
+ // Wide terminals keep the historical 120-column cap.
12
+ export const SPINNER_TEXT_MAX = 120;
13
+
14
+ // Visible columns available for spinner text: the terminal width
15
+ // minus caller-reserved fixed text (e.g. a `Prefix - ` stem, counted
16
+ // via fixedOverhead) and spinner chrome. Floored so tiny terminals
17
+ // still show something; falls back to 80 when piped.
18
+ export function spinnerTextBudget({ columns = process.stdout?.columns ?? 80, fixedOverhead = SPINNER_FRAME_OVERHEAD } = {}) {
19
+ return Math.max(20, Math.min(SPINNER_TEXT_MAX, columns - fixedOverhead));
20
+ }
21
+
22
+ // Cuts text to the spinner budget (with `...`), code-point safe so
23
+ // emoji survive. Pass uncolored text and color after: ANSI escapes
24
+ // would count as visible columns and slicing could split them.
25
+ export function truncateSpinnerText(text, options = {}) {
26
+ const chars = Array.from(String(text ?? ''));
27
+ const budget = spinnerTextBudget(options);
28
+ if (chars.length <= budget) return chars.join('');
29
+ return `${chars.slice(0, budget - 3).join('')}...`;
30
+ }
@@ -154,12 +154,21 @@ export function upsertAutoTfvar(tfDir, key, value) {
154
154
  }
155
155
  const created = content === '';
156
156
  const line = `${key} = ${value ? 'true' : 'false'}`;
157
- const pattern = new RegExp(`^${key}\\s*=.*$`, 'm');
157
+ const pattern = new RegExp(`^[ \\t]*${key}\\s*=.*$`, 'm');
158
+ const matches = content.match(new RegExp(`^[ \\t]*${key}\\s*=.*$`, 'gm')) || [];
158
159
  let changed;
159
- if (pattern.test(content)) {
160
+ if (matches.length === 1) {
160
161
  const next = content.replace(pattern, line);
161
162
  changed = next !== content;
162
163
  content = next;
164
+ } else if (matches.length > 1) {
165
+ // Pre-existing duplicates (the old single-echo guidance ran
166
+ // twice): first-match replace would keep the dup and report
167
+ // unchanged while Terraform fails hard. Collapse to one copy.
168
+ const stripped = content.replace(new RegExp(`^[ \\t]*${key}\\s*=.*$\\n?`, 'gm'), '');
169
+ const next = `${stripped === '' ? '' : stripped.replace(/\n*$/, '\n')}${line}\n`;
170
+ changed = next !== content;
171
+ content = next;
163
172
  } else {
164
173
  const header = '# Managed by grada: machine-written variable overrides. Safe to delete an entry to restore its default.\n';
165
174
  content = `${created ? header : content.replace(/\n*$/, '\n')}${line}\n`;
@@ -4,6 +4,8 @@ import { spawn } from 'child_process';
4
4
  import color from 'picocolors';
5
5
  import { classifyTerraformError } from './terraform-errors.js';
6
6
  import { SLEEP_STATE_DIRNAME } from './sleep-state.js';
7
+ import { isActiveEnvValue } from '../core/telemetry.js';
8
+ import { truncateSpinnerText, SPINNER_FRAME_OVERHEAD } from './spinner-text.js';
7
9
 
8
10
  export const LAST_RUN_FILENAME = 'last-run.json';
9
11
  // Generous per-phase ceiling: CloudFront teardown and Aurora provisioning
@@ -53,6 +55,12 @@ export function isInterruptedMarker(marker) {
53
55
  // output would otherwise replace them.
54
56
  const SUMMARY_LINE_RE = /^(Plan:|Apply complete!|Destroy complete!|No changes\.)/;
55
57
 
58
+ // Explicit progress modes for `runTerraformCommand` (the --progress flag
59
+ // on apply/destroy): `lines` forces deduped plain lines for viewers that
60
+ // split animation frames into lines (harness PTYs), `spinner` forces the
61
+ // animated spinner. Absent, the terminal sniff below decides.
62
+ export const PROGRESS_MODES = ['lines', 'spinner'];
63
+
56
64
  // Runs a terraform command while piping the latest stdout line into a
57
65
  // @clack spinner. Resolves on exit 0; rejects with a structured error
58
66
  // (`{ code, stderr, lockId? }` classified via terraform-errors.js)
@@ -68,15 +76,28 @@ const SUMMARY_LINE_RE = /^(Plan:|Apply complete!|Destroy complete!|No changes\.)
68
76
  // Progress display: a live terminal rewrites one spinner line, but the
69
77
  // spinner re-renders every ~80ms — wherever cursor movement isn't
70
78
  // honored (piped output, log viewers) each tick becomes a line and
71
- // quiet stretches repeat the same message dozens of times. Non-TTY
79
+ // quiet stretches repeat the same message dozens of times. Non-live
72
80
  // runs therefore get deduped plain lines instead, and the caller's
73
81
  // spinner is cleared so its tick doesn't spam behind them (the
74
- // caller's later stop then becomes a silent no-op). `isTTY` overrides
75
- // the terminal sniff for tests.
82
+ // caller's later stop then becomes a silent no-op).
83
+ //
84
+ // `progress` overrides everything (`lines` forces plain lines,
85
+ // `spinner` forces animation). Otherwise an explicit `isTTY` keeps
86
+ // exact legacy semantics, while the default sniff requires a TTY
87
+ // outside CI with a capable TERM — and still can't catch harness
88
+ // PTYs, which is what the flag is for.
76
89
  export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}) {
77
- const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY } = options || {};
90
+ const opts = options || {};
91
+ const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY, progress = null } = opts;
78
92
  const wantsProgress = spin && typeof spin.message === 'function';
79
- const live = isTTY === true && wantsProgress;
93
+ const sniffed = opts.isTTY === undefined
94
+ ? (isTTY === true && !isActiveEnvValue(process.env.CI) && process.env.TERM !== 'dumb')
95
+ : isTTY === true;
96
+ let live;
97
+ if (progress === 'lines') live = false;
98
+ else if (progress === 'spinner') live = true;
99
+ else live = sniffed;
100
+ live = live && wantsProgress;
80
101
  let lastEmitted;
81
102
  const emit = (text) => {
82
103
  if (lastEmitted === text) return;
@@ -203,16 +224,18 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
203
224
  if (typeof onStdoutLine === 'function') {
204
225
  for (const line of lines) onStdoutLine(line);
205
226
  }
227
+ // Both emits cut the line to the terminal budget (truncate
228
+ // before coloring so ANSI escapes never count as columns).
229
+ const lineOverhead = `${loadingPrefix} - `.length + SPINNER_FRAME_OVERHEAD;
206
230
  for (const line of lines) {
207
231
  const trimmed = line.trim();
208
232
  if (SUMMARY_LINE_RE.test(trimmed)) {
209
- emit(`${loadingPrefix} - ${color.dim(trimmed)}`);
233
+ emit(`${loadingPrefix} - ${color.dim(truncateSpinnerText(trimmed, { fixedOverhead: lineOverhead }))}`);
210
234
  }
211
235
  }
212
236
  if (lines.length > 0) {
213
237
  const latestLine = lines[lines.length - 1].trim();
214
- const display = latestLine.length > 120 ? latestLine.substring(0, 117) + '...' : latestLine;
215
- emit(`${loadingPrefix} - ${color.dim(display)}`);
238
+ emit(`${loadingPrefix} - ${color.dim(truncateSpinnerText(latestLine, { fixedOverhead: lineOverhead }))}`);
216
239
  }
217
240
  });
218
241
 
@@ -55,8 +55,24 @@ jobs:
55
55
  echo "### Drift plan (exit $EXITCODE)" >> "$GITHUB_STEP_SUMMARY"
56
56
  head -50 plan.txt >> "$GITHUB_STEP_SUMMARY"
57
57
 
58
+ # A plan on never-applied infrastructure also exits 2 (everything
59
+ # "to add") — that is not drift. Skip the issue/Slack alarm when
60
+ # the state tracks no resources yet. A failed lookup emits no
61
+ # output, so real drift is never masked by a broken check.
62
+ - name: Check provisioned state
63
+ id: state
64
+ if: steps.plan.outputs.exitcode == '2'
65
+ working-directory: ./terraform
66
+ run: |
67
+ if STATE_OUT=$(terraform state list -no-color 2>/dev/null); then
68
+ if [ -z "$STATE_OUT" ]; then
69
+ echo "empty=true" >> "$GITHUB_OUTPUT"
70
+ echo "### Not provisioned yet — skipping drift alarm (state tracks no resources)" >> "$GITHUB_STEP_SUMMARY"
71
+ fi
72
+ fi
73
+
58
74
  - name: Report drift as GitHub Issue
59
- if: steps.plan.outputs.exitcode == '2' || steps.plan.outputs.exitcode == '0'
75
+ if: (steps.plan.outputs.exitcode == '2' || steps.plan.outputs.exitcode == '0') && steps.state.outputs.empty != 'true'
60
76
  uses: actions/github-script@v7
61
77
  with:
62
78
  script: |
@@ -99,7 +115,7 @@ jobs:
99
115
  }
100
116
 
101
117
  - name: Notify Slack
102
- if: steps.plan.outputs.exitcode == '2'
118
+ if: steps.plan.outputs.exitcode == '2' && steps.state.outputs.empty != 'true'
103
119
  env:
104
120
  SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
105
121
  run: |