grada-run 0.41.0 → 0.41.2

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)',
@@ -73,6 +73,7 @@ const HELP_TEXT = [
73
73
  'Global options:',
74
74
  ' --version, -v Print the CLI version and exit',
75
75
  ' --no-telemetry Disable telemetry for this run only (persistent: grada telemetry off; every run: DO_NOT_TRACK=1)',
76
+ ' --flag=value Use the = form when a flag value itself starts with a dash (e.g. --cmd=--dry-run)',
76
77
  ];
77
78
 
78
79
  const rawArgs = process.argv.slice(2);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.41.0",
3
+ "version": "0.41.2",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -77,7 +77,7 @@ export function parseAddArgs(argv = []) {
77
77
  const args = normalizeArgv(argv);
78
78
  if (args[0] === 'add') args.shift();
79
79
  const { options: parsed, rest, unknown } = parseFlags(args, {
80
- string: ['region', 'project-name', 'partition-key', 'model', 'domain', 'from-email', 'zone-id', 'schedule', { name: 'cmd', key: 'cronCommand' }, { name: 'cron-command', key: 'cronCommand' }, 'name', 'timezone'],
80
+ string: ['region', 'project-name', 'partition-key', 'model', 'domain', 'from-email', 'zone-id', 'schedule', { name: 'cmd', key: 'cronCommand', greedy: true }, { name: 'cron-command', key: 'cronCommand', greedy: true }, 'name', 'timezone'],
81
81
  boolean: ['force', { name: 'headless', key: 'isHeadless' }],
82
82
  bareBoolean: ['list-models', 'refresh'],
83
83
  });
@@ -1,23 +1,23 @@
1
1
  import path from 'path';
2
2
  import fs from 'fs';
3
- import { intro, outro, spinner, log, cancel, confirm } from '@clack/prompts';
3
+ import { intro, outro, spinner, log, cancel, confirm, isCancel } from '@clack/prompts';
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
- import { requireManagedTree, parseStateBucketBackend } from '../utils/terraform-metadata.js';
14
+ import { requireManagedTree, parseStateBucketBackend, upsertAutoTfvar } from '../utils/terraform-metadata.js';
15
15
  import { readTerraformComputeTarget, resolveRegion } from '../utils/resolvers.js';
16
16
  import { requireAwakeEnvironment, resolveSleepTarget, guardSleepingEnv } from '../utils/sleep-state.js';
17
17
  import { promptStateBucketRecovery, recreateStateBucket } from '../utils/recovery.js';
18
18
  import { resolveProjectName, readResourceSuffix } from '../utils/resolvers.js';
19
19
  import { ensureLambdaSeedImage } from '../utils/lambda-ecr.js';
20
- import { checkAwsCredentials, ensureStateBucketExists, printAwsAuthGuidance } from '../utils/aws.js';
20
+ import { checkAwsCredentials, ensureStateBucketExists, isAuthError, printAwsAuthGuidance } from '../utils/aws.js';
21
21
  import { findUnreconciledFiles, isValidAccountId, PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
22
22
  import { runWake } from './wake.js';
23
23
 
@@ -26,12 +26,26 @@ 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.
47
+ 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; mv terraform/grada.auto.tfvars.tmp terraform/grada.auto.tfvars; echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`;
48
+
35
49
  // Offline reconcile: an `init --offline` tree carries
36
50
  // YOUR_AWS_ACCOUNT_ID placeholders instead of an account id and has no
37
51
  // state bucket. Resolve the account (explicit flag, else STS ground
@@ -58,6 +72,19 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
58
72
  }),
59
73
  };
60
74
  }
75
+ // Ping first: the flag resolves the account, but reconciling and
76
+ // provisioning both need live credentials — fail guided with
77
+ // nothing written rather than stamping files and crashing.
78
+ try {
79
+ await checkAwsCredentials(resolveRegion(options, targetDir));
80
+ } catch {
81
+ return {
82
+ proceed: false,
83
+ result: await failCredentialsMissing(options, projectName, {
84
+ message: '\n✖ Could not verify AWS credentials: configure them first — apply cannot reconcile or provision without them.\n',
85
+ }),
86
+ };
87
+ }
61
88
  accountId = flag;
62
89
  source = 'flag';
63
90
  } else {
@@ -65,16 +92,10 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
65
92
  accountId = (await checkAwsCredentials(resolveRegion(options, targetDir))).accountId;
66
93
  source = 'sts';
67
94
  } catch {
68
- printAwsAuthGuidance(options);
69
95
  return {
70
96
  proceed: false,
71
- result: await failCommand({
72
- noExit: isProgrammaticCall(options),
97
+ result: await failCredentialsMissing(options, projectName, {
73
98
  message: '\n✖ Could not resolve the AWS account: configure credentials first — apply cannot provision without them.\n',
74
- event: 'infrastructure_applied',
75
- telemetry: { projectName },
76
- errorCode: 'AWS_CREDENTIALS_MISSING',
77
- reason: 'aws-credentials-missing',
78
99
  }),
79
100
  };
80
101
  }
@@ -97,7 +118,8 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
97
118
  });
98
119
  if (confirmed !== true) {
99
120
  cancel('Reconcile aborted.');
100
- process.exit(0);
121
+ exitZeroForCli();
122
+ return { proceed: false, result: { ok: false, reason: 'cancelled' } };
101
123
  }
102
124
  }
103
125
  for (const file of files) {
@@ -107,10 +129,34 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
107
129
  log.message(color.green(`Rewrote ${files.length} file(s).`));
108
130
  const backend = fs.readFileSync(path.join(targetDir, 'terraform', 'backend.tf'), 'utf8');
109
131
  const { bucket, region: backendRegion } = parseStateBucketBackend(backend);
110
- const ensured = await ensureStateBucketExists({
111
- region: backendRegion ?? resolveRegion(options, targetDir),
112
- bucket,
113
- });
132
+ let ensured;
133
+ try {
134
+ ensured = await ensureStateBucketExists({
135
+ region: backendRegion ?? resolveRegion(options, targetDir),
136
+ bucket,
137
+ });
138
+ } catch (error) {
139
+ if (isAuthError(error) || error?.name === 'CredentialsProviderError') {
140
+ return {
141
+ proceed: false,
142
+ result: await failCredentialsMissing(options, projectName, {
143
+ message: '\n✖ AWS credentials expired during reconciliation.\n',
144
+ hint: ' Placeholders are already rewritten; fix credentials and re-run apply to converge.\n',
145
+ }),
146
+ };
147
+ }
148
+ return {
149
+ proceed: false,
150
+ result: await failCommand({
151
+ noExit: isProgrammaticCall(options),
152
+ message: `\n✖ Could not ensure the state bucket "${bucket}": ${error?.message ?? error}.\n`,
153
+ event: 'infrastructure_applied',
154
+ telemetry: { projectName },
155
+ errorCode: 'RECONCILE_BUCKET_FAILED',
156
+ reason: 'reconcile-bucket-failed',
157
+ }),
158
+ };
159
+ }
114
160
  trackEvent('apply_reconciled', {
115
161
  projectName,
116
162
  account_source: source,
@@ -126,6 +172,22 @@ function describeAccountIdShape(value) {
126
172
  return `expected exactly 12 digits, got ${text.length}`;
127
173
  }
128
174
 
175
+ // Shared credential-failure exit for every reconcile path: the recovery
176
+ // guidance plus a named code, so the shape can't drift between the
177
+ // resolution ping, the STS fallback, and the bucket ensure.
178
+ async function failCredentialsMissing(options, projectName, { message, hint = null }) {
179
+ printAwsAuthGuidance(options);
180
+ return failCommand({
181
+ noExit: isProgrammaticCall(options),
182
+ message,
183
+ ...(hint === null ? {} : { hint }),
184
+ event: 'infrastructure_applied',
185
+ telemetry: { projectName },
186
+ errorCode: 'AWS_CREDENTIALS_MISSING',
187
+ reason: 'aws-credentials-missing',
188
+ });
189
+ }
190
+
129
191
  // Unlock-and-retry flow for a stale Terraform state lock. Headless
130
192
  // refuses unless `--force-unlock <id>` was passed; interactive asks once.
131
193
  // Retries the apply exactly once, skipping the already-confirmed preview.
@@ -251,7 +313,7 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
251
313
  return { proceed: true, previousAppliedTarget: appliedTarget };
252
314
  }
253
315
  cancel('Apply cancelled. No infrastructure was changed.');
254
- process.exit(0);
316
+ exitZeroForCli();
255
317
  return { proceed: false, result: { ok: false, reason: 'cancelled' } };
256
318
  }
257
319
 
@@ -287,6 +349,18 @@ async function applyStackMain(input = {}) {
287
349
  const options = normalizeOptions(input);
288
350
  const unknownRefusal = await refuseUnknownFlags(options, { command: 'apply', event: 'infrastructure_applied' });
289
351
  if (unknownRefusal) return unknownRefusal;
352
+ const progressMode = typeof options.progress === 'string' && options.progress.trim() !== '' ? options.progress.trim() : null;
353
+ if (progressMode !== null && !PROGRESS_MODES.includes(progressMode)) {
354
+ return failCommand({
355
+ noExit: isProgrammaticCall(options),
356
+ message: `\n✖ Invalid --progress "${options.progress}". Supported modes: lines, spinner.\n`,
357
+ hint: ' Use --progress lines when the output viewer splits animation frames into lines (harness PTYs, log capture).\n',
358
+ event: 'infrastructure_applied',
359
+ telemetry: { projectName: path.basename(process.cwd()) },
360
+ errorCode: 'INVALID_PROGRESS_MODE',
361
+ reason: 'invalid-progress-mode',
362
+ });
363
+ }
290
364
  intro(color.bgCyan(color.black(' grada apply ☁️ ')));
291
365
 
292
366
  const targetDir = process.cwd();
@@ -366,7 +440,8 @@ async function applyStackMain(input = {}) {
366
440
  framework: detectedConfig.framework,
367
441
  ...costProps,
368
442
  });
369
- process.exit(0);
443
+ exitZeroForCli();
444
+ return { ok: true, dryRun: true };
370
445
  } else if (shouldAutoApprove(options) || options._skipPreview === true) {
371
446
  // Internal lock-retry resumes skip the preview: the user already
372
447
  // confirmed it before the lock failure.
@@ -383,14 +458,15 @@ async function applyStackMain(input = {}) {
383
458
  const confirmed = await renderDryRunPreview(detectedConfig, false);
384
459
  if (!confirmed) {
385
460
  cancel('Apply aborted.');
386
- process.exit(0);
461
+ exitZeroForCli();
462
+ return { ok: false, reason: 'cancelled' };
387
463
  }
388
464
  }
389
465
 
390
466
  const s = spinner();
391
467
  const runTerraform = options.runTerraformImpl || runTerraformCommand;
392
468
  const runSync = options.spawnSyncImpl || spawnSync;
393
- const lifecycleOpts = { markerDir: targetDir, timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS };
469
+ const lifecycleOpts = { markerDir: targetDir, timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, ...(progressMode ? { progress: progressMode } : {}) };
394
470
  const diskTarget = readTerraformComputeTarget(targetDir);
395
471
 
396
472
  try {
@@ -503,7 +579,8 @@ async function applyStackMain(input = {}) {
503
579
  ...costProps
504
580
  });
505
581
 
506
- process.exit(0);
582
+ exitZeroForCli();
583
+ return { ok: true, projectName: actualProjectName, target: diskTarget };
507
584
 
508
585
  } catch (error) {
509
586
  s.stop(color.red('❌ Terraform apply failed.'));
@@ -620,14 +697,57 @@ async function applyStackMain(input = {}) {
620
697
  });
621
698
  }
622
699
 
700
+ let adoptUpsertError = null;
701
+ if (code === 'OIDC_PROVIDER_CONFLICT' && options._oidcAdopted !== true) {
702
+ // Adopt the shared provider instead of hand-editing: the
703
+ // GitHub provider URL is account-singleton, so the existing
704
+ // provider IS the match — flip the var and retry.
705
+ const refused = await refuseIfNonInteractive(options, {
706
+ message: '\n✖ apply needs approval to adopt the existing GitHub OIDC provider.',
707
+ hint: ' Re-run with --auto-approve to adopt non-interactively.\n',
708
+ event: 'infrastructure_applied',
709
+ telemetry: { projectName: actualProjectName },
710
+ errorCode: 'OIDC_ADOPT_NON_INTERACTIVE',
711
+ });
712
+ if (refused) return refused;
713
+ let adopt = shouldAutoApprove(options);
714
+ if (!adopt) {
715
+ const confirmed = await confirm({
716
+ message: 'Adopt the existing GitHub OIDC provider (writes create_oidc_provider = false) and retry?',
717
+ initialValue: true,
718
+ });
719
+ adopt = !isCancel(confirmed) && confirmed === true;
720
+ }
721
+ if (adopt) {
722
+ try {
723
+ upsertAutoTfvar(tfDir, 'create_oidc_provider', false);
724
+ } catch (error) {
725
+ // A failed write must not crash inside the error
726
+ // handler: fall through to the manual guidance with
727
+ // the write error appended.
728
+ adoptUpsertError = error;
729
+ }
730
+ if (adoptUpsertError === null) {
731
+ trackEvent('oidc_provider_adopted', { projectName: actualProjectName });
732
+ log.message(color.cyan('Adopted the existing OIDC provider — retrying apply...'));
733
+ return applyStack({ ...options, _skipPreview: true, _oidcAdopted: true });
734
+ }
735
+ }
736
+ // Declined (or unwritable): fall through to the manual guidance below.
737
+ }
738
+
623
739
  if (code === 'OIDC_PROVIDER_CONFLICT') {
740
+ // The override lives in grada.auto.tfvars (machine-owned,
741
+ // survives regeneration) — never in the oidc.tf default.
624
742
  log.error(color.red('GitHub OIDC Provider Conflict Detected'));
625
743
  log.message('AWS only allows one GitHub Actions provider per account, and you already have one configured.');
626
744
  log.message('');
627
745
  log.message(`${color.bold('How to fix this:')}`);
628
- log.message(`1. Open ${color.cyan('terraform/oidc.tf')}`);
629
- log.message(`2. Change ${color.green('create_oidc_provider = true')} to ${color.green('create_oidc_provider = false')}`);
630
- log.message(`3. Run ${color.cyan('npx grada-run apply')} again.`);
746
+ log.message(`1. Adopt the shared provider (safe to re-run): ${color.cyan(OIDC_ADOPT_MANUAL_COMMAND)}`);
747
+ log.message(`2. Run ${color.cyan('npx grada-run apply')} again.`);
748
+ if (adoptUpsertError) {
749
+ log.message(color.dim(` (Automatic adoption failed: ${adoptUpsertError.message})`));
750
+ }
631
751
  } else if (code === 'BACKEND_RECONFIGURE_REQUIRED' || code === 'CLOUDFRONT_IN_PROGRESS' || code === 'DELETION_PROTECTION_ACTIVE') {
632
752
  // Named but flow-neutral: runbook guidance with a coded
633
753
  // failure. (RECREATE_COLLISION has its dedicated branch
@@ -60,7 +60,7 @@ export function parseDbMigrateArgs(argv = []) {
60
60
  if (args[0] === 'migrate') args.shift();
61
61
  const { options, rest, unknown } = parseFlags(args, {
62
62
  string: [
63
- { name: 'cmd', key: 'cmd' },
63
+ { name: 'cmd', key: 'cmd', greedy: true },
64
64
  { name: 'task-def', key: 'taskDef' },
65
65
  { name: 'timeout', key: 'timeout' },
66
66
  { name: 'project-name', key: 'projectName' },
@@ -7,8 +7,8 @@ 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';
@@ -40,7 +40,7 @@ export function parseDestroyArgs(argv = []) {
40
40
  const args = normalizeArgv(argv);
41
41
  const { options, unknown } = parseFlags(args, {
42
42
  boolean: ['allow-data-loss', 'force', 'headless', 'yes'],
43
- string: ['force-unlock'],
43
+ string: ['force-unlock', 'progress'],
44
44
  });
45
45
  if (unknown.length > 0) options.unknownFlags = unknown;
46
46
  return { allowDataLoss: false, force: false, ...options };
@@ -148,6 +148,18 @@ async function destroyStackMain(input = {}) {
148
148
  const options = normalizeOptions(input);
149
149
  const unknownRefusal = await refuseUnknownFlags(options, { command: 'destroy', event: 'infrastructure_destroyed' });
150
150
  if (unknownRefusal) return unknownRefusal;
151
+ const progressMode = typeof options.progress === 'string' && options.progress.trim() !== '' ? options.progress.trim() : null;
152
+ if (progressMode !== null && !PROGRESS_MODES.includes(progressMode)) {
153
+ return failCommand({
154
+ noExit: isProgrammaticCall(options),
155
+ message: `\n✖ Invalid --progress "${options.progress}". Supported modes: lines, spinner.\n`,
156
+ hint: ' Use --progress lines when the output viewer splits animation frames into lines (harness PTYs, log capture).\n',
157
+ event: 'infrastructure_destroyed',
158
+ telemetry: { projectName: path.basename(process.cwd()) },
159
+ errorCode: 'INVALID_PROGRESS_MODE',
160
+ reason: 'invalid-progress-mode',
161
+ });
162
+ }
151
163
  intro(color.bgRed(color.white(' grada destroy 🗑️ ')));
152
164
 
153
165
  // Ejected trees are user-owned: refuse unless --force.
@@ -266,7 +278,7 @@ async function destroyStackMain(input = {}) {
266
278
  }
267
279
 
268
280
  const s = spinner();
269
- const lifecycleOpts = { markerDir: process.cwd(), timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS };
281
+ const lifecycleOpts = { markerDir: process.cwd(), timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, ...(progressMode ? { progress: progressMode } : {}) };
270
282
 
271
283
  // 1. Init first (R4): destroy on a fresh checkout or a wiped
272
284
  // .terraform cache must not trip over missing plugins.
@@ -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
 
@@ -35,7 +35,7 @@ export function parseExecArgs(argv = []) {
35
35
  const args = normalizeArgv(argv);
36
36
  if (args[0] === 'exec') args.shift();
37
37
  const { options, rest, unknown } = parseFlags(args, {
38
- string: ['cluster', 'service', 'container', 'command', 'region'],
38
+ string: ['cluster', 'service', 'container', { name: 'command', greedy: true }, 'region'],
39
39
  boolean: ['headless'],
40
40
  });
41
41
  const positionals = rest.filter((arg) => typeof arg === 'string' && !arg.startsWith('-'));
@@ -3,14 +3,14 @@ import path from 'path';
3
3
  import { spawnSync } from 'child_process';
4
4
  import { ECRClient, DescribeRepositoriesCommand, DescribeImagesCommand, BatchDeleteImageCommand } from '@aws-sdk/client-ecr';
5
5
  import { CloudWatchLogsClient, DescribeLogGroupsCommand, DeleteLogGroupCommand } from '@aws-sdk/client-cloudwatch-logs';
6
- import { ECSClient, ListServicesCommand, DescribeServicesCommand } from '@aws-sdk/client-ecs';
6
+ import { ECSClient, ListClustersCommand, ListServicesCommand, DescribeServicesCommand } from '@aws-sdk/client-ecs';
7
7
  import { EC2Client, DescribeAddressesCommand, ReleaseAddressCommand, DescribeVpcsCommand, DescribeSubnetsCommand } from '@aws-sdk/client-ec2';
8
8
  import { SecretsManagerClient, ListSecretsCommand } from '@aws-sdk/client-secrets-manager';
9
9
  import color from 'picocolors';
10
10
  import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
11
11
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
12
12
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
- import { resolveRegion, resolveProjectName, resolveCluster, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
13
+ import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
14
14
  import { resolveClient } from '../utils/aws.js';
15
15
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
16
16
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
@@ -138,15 +138,54 @@ function defaultListLambdaFunctionNames({ region, spawnSyncImpl } = {}) {
138
138
  // trees, Lambda functions for serverless ones. Never throws — any scan
139
139
  // failure resolves to `unknown` so discovery fails closed instead of
140
140
  // proposing live-preview groups.
141
+ // One enumeration feeding every ECS liveness consumer: each workspace
142
+ // provisions its own `<app>-cluster`, so liveness must scan the
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.
149
+ export async function listProjectClusterServices({ ecsClient = null, projectName, resourceSuffix = '' } = {}) {
150
+ const byCluster = new Map();
151
+ try {
152
+ if (!ecsClient) return { byCluster, unknown: false };
153
+ const clusterPattern = new RegExp(`^${escapeRegExp(projectName)}(-[A-Za-z0-9_-]+)?${escapeRegExp(resourceSuffix)}-cluster$`);
154
+ let nextToken;
155
+ const clusters = [];
156
+ do {
157
+ const resp = await ecsClient.send(new ListClustersCommand({ nextToken, maxResults: 100 }));
158
+ for (const arn of resp.clusterArns || []) {
159
+ const name = String(arn).split('/').pop();
160
+ if (clusterPattern.test(name)) clusters.push(name);
161
+ }
162
+ nextToken = resp.nextToken;
163
+ } while (nextToken);
164
+ for (const cluster of clusters) {
165
+ let svcToken;
166
+ const arns = [];
167
+ do {
168
+ const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken: svcToken, maxResults: 100 }));
169
+ arns.push(...(resp.serviceArns || []));
170
+ svcToken = resp.nextToken;
171
+ } while (svcToken);
172
+ byCluster.set(cluster, arns);
173
+ }
174
+ } catch {
175
+ return { byCluster, unknown: true };
176
+ }
177
+ return { byCluster, unknown: false };
178
+ }
179
+
141
180
  export async function discoverLivePreviewLogGroups({
142
181
  ecsClient = null,
143
- cluster = null,
144
182
  projectName,
145
183
  resourceSuffix = '',
146
184
  isLambda = false,
147
185
  listFunctionsImpl = defaultListLambdaFunctionNames,
148
186
  spawnSyncImpl = null,
149
187
  region = null,
188
+ clusterServices = null,
150
189
  } = {}) {
151
190
  const live = new Set();
152
191
  try {
@@ -158,17 +197,15 @@ export async function discoverLivePreviewLogGroups({
158
197
  if (typeof name === 'string' && fnPattern.test(name)) live.add(`/aws/lambda/${name}`);
159
198
  }
160
199
  } else {
161
- if (!ecsClient || !cluster) return { groups: live, unknown: false };
200
+ const enumeration = clusterServices ?? await listProjectClusterServices({ ecsClient, projectName, resourceSuffix });
201
+ if (enumeration.unknown) return { groups: live, unknown: true };
162
202
  const servicePattern = new RegExp(`^${base}-service$`);
163
- let nextToken;
164
- do {
165
- const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken, maxResults: 100 }));
166
- for (const arn of resp.serviceArns || []) {
203
+ for (const arns of enumeration.byCluster.values()) {
204
+ for (const arn of arns || []) {
167
205
  const name = String(arn).split('/').pop();
168
206
  if (servicePattern.test(name)) live.add(`/ecs/${name.slice(0, -'-service'.length)}`);
169
207
  }
170
- nextToken = resp.nextToken;
171
- } while (nextToken);
208
+ }
172
209
  }
173
210
  } catch {
174
211
  return { groups: live, unknown: true };
@@ -227,31 +264,31 @@ async function discoverUnattachedEips({ ec2Client, projectName }) {
227
264
  }
228
265
 
229
266
  // Deep target discovery: VPCs partitioned by the STRICT deletion
230
- // predicate — exact project tag only. Foreign and untagged VPCs land in
231
- // reportOnly, never in deletable, so prefix lookalikes (`myapp-evil`)
232
- // and legacy resources can never enter the deletion set.
267
+ // predicate — exact project tag only, minus live networks. Foreign and
268
+ // untagged VPCs land in reportOnly, never in deletable, so prefix
269
+ // lookalikes (`myapp-evil`) and legacy resources can never enter the
270
+ // deletion set.
233
271
  // Live VPC ids behind running (or desired) ECS services: services →
234
- // awsvpc subnets → VPCs. Fail-closed like the preview-log-group
235
- // liveness: any client error resolves `unknown` instead of guessing.
236
- export async function discoverLiveVpcIds({ ecsClient = null, cluster = null, ec2Client = null } = {}) {
272
+ // awsvpc subnets → VPCs, across every project cluster (each preview
273
+ // workspace runs its own cluster in its own VPC). Fail-closed like the
274
+ // preview-log-group liveness: any client error resolves `unknown`
275
+ // instead of guessing.
276
+ export async function discoverLiveVpcIds({ ecsClient = null, ec2Client = null, projectName, resourceSuffix = '', clusterServices = null } = {}) {
237
277
  const vpcIds = new Set();
238
278
  try {
239
- if (!ecsClient || !cluster || !ec2Client) return { vpcIds, unknown: false };
240
- let nextToken;
241
- const arns = [];
242
- do {
243
- const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken, maxResults: 100 }));
244
- arns.push(...(resp.serviceArns || []));
245
- nextToken = resp.nextToken;
246
- } while (nextToken);
279
+ if (!ecsClient || !ec2Client) return { vpcIds, unknown: false };
280
+ const enumeration = clusterServices ?? await listProjectClusterServices({ ecsClient, projectName, resourceSuffix });
281
+ if (enumeration.unknown) return { vpcIds, unknown: true };
247
282
  const subnetIds = new Set();
248
- for (const batch of chunkArray(arns, 10)) {
249
- const desc = await ecsClient.send(new DescribeServicesCommand({ cluster, services: batch }));
250
- for (const svc of desc.services || []) {
251
- // Desired counts: a crash-looping preview runs nothing
252
- // yet is unambiguously live.
253
- if ((svc.desiredCount ?? 0) <= 0 && (svc.runningCount ?? 0) <= 0) continue;
254
- for (const id of svc.networkConfiguration?.awsvpcConfiguration?.subnets || []) subnetIds.add(id);
283
+ for (const [cluster, arns] of enumeration.byCluster.entries()) {
284
+ for (const batch of chunkArray(arns, 10)) {
285
+ const desc = await ecsClient.send(new DescribeServicesCommand({ cluster, services: batch }));
286
+ for (const svc of desc.services || []) {
287
+ // Desired counts: a crash-looping preview runs nothing
288
+ // yet is unambiguously live.
289
+ if ((svc.desiredCount ?? 0) <= 0 && (svc.runningCount ?? 0) <= 0) continue;
290
+ for (const id of svc.networkConfiguration?.awsvpcConfiguration?.subnets || []) subnetIds.add(id);
291
+ }
255
292
  }
256
293
  }
257
294
  if (subnetIds.size > 0) {
@@ -264,7 +301,7 @@ export async function discoverLiveVpcIds({ ecsClient = null, cluster = null, ec2
264
301
  return { vpcIds, unknown: false };
265
302
  }
266
303
 
267
- async function discoverDeepVpcs({ ec2Client, ecsClient = null, cluster = null, projectName, resourceSuffix = '', isLambda = false }) {
304
+ async function discoverDeepVpcs({ ec2Client, ecsClient = null, projectName, resourceSuffix = '', isLambda = false, clusterServices = null }) {
268
305
  const deletable = [];
269
306
  const reportOnly = [];
270
307
  // The stack's own default-workspace VPC is live by construction —
@@ -274,7 +311,7 @@ async function discoverDeepVpcs({ ec2Client, ecsClient = null, cluster = null, p
274
311
  const defaultVpcName = `${projectName}${resourceSuffix}-vpc`;
275
312
  const live = isLambda
276
313
  ? { vpcIds: new Set(), unknown: false }
277
- : await discoverLiveVpcIds({ ecsClient, cluster, ec2Client });
314
+ : await discoverLiveVpcIds({ ecsClient, ec2Client, projectName, resourceSuffix, clusterServices });
278
315
  let nextToken;
279
316
  do {
280
317
  const resp = await ec2Client.send(new DescribeVpcsCommand({ NextToken: nextToken }));
@@ -542,17 +579,23 @@ async function runGcMain(input = {}) {
542
579
 
543
580
  let discovered;
544
581
  let previewLivenessUnknown = false;
582
+ let previewClusterServices = null;
545
583
  try {
546
584
  const isLambda = isComputeTarget(cwd, 'lambda');
547
585
  const suffix = readResourceSuffix(cwd);
586
+ // One cluster-service enumeration shared by the log-group and
587
+ // (deep) VPC liveness consumers — fetched once, not per scan.
588
+ previewClusterServices = isLambda
589
+ ? null
590
+ : await listProjectClusterServices({ ecsClient, projectName, resourceSuffix: suffix });
548
591
  const liveness = await discoverLivePreviewLogGroups({
549
592
  ecsClient,
550
- cluster: resolveCluster(options, cwd),
551
593
  projectName,
552
594
  resourceSuffix: suffix,
553
595
  isLambda,
554
596
  spawnSyncImpl: options.spawnSyncImpl,
555
597
  region,
598
+ clusterServices: previewClusterServices,
556
599
  });
557
600
  previewLivenessUnknown = liveness.unknown;
558
601
  discovered = await discoverOrphanedResources({
@@ -605,9 +648,9 @@ async function runGcMain(input = {}) {
605
648
  cwd,
606
649
  projectName,
607
650
  ecsClient,
608
- cluster: resolveCluster(options, cwd),
609
651
  resourceSuffix: readResourceSuffix(cwd),
610
652
  isLambda: isComputeTarget(cwd, 'lambda'),
653
+ clusterServices: previewClusterServices,
611
654
  });
612
655
  } catch (error) {
613
656
  ds.stop(color.red('❌ Deep discovery failed.'));
@@ -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 {
@@ -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
  }
package/src/utils/args.js CHANGED
@@ -19,6 +19,19 @@ function normalizeEntries(entries) {
19
19
  return map;
20
20
  }
21
21
 
22
+ // String entries marked `{ name, greedy: true }` consume the next token
23
+ // even when it starts with `--`: flags taking arbitrary shell text
24
+ // (`--cmd`, `--command`) must accept values like `--dry-run`.
25
+ function greedyEntries(entries) {
26
+ const set = new Set();
27
+ for (const entry of entries || []) {
28
+ if (entry && typeof entry === 'object' && typeof entry.name === 'string' && entry.greedy === true) {
29
+ set.add(entry.name);
30
+ }
31
+ }
32
+ return set;
33
+ }
34
+
22
35
  // Guards module entry points against non-object options (direct programmatic
23
36
  // misuse or automated fuzzing): anything that is not an object behaves like
24
37
  // `{}`, so callers always reach structured validation instead of TypeErrors.
@@ -43,7 +56,8 @@ export function normalizeArgv(argv) {
43
56
  // the bare long flag).
44
57
  //
45
58
  // Space-form values never consume a `--like` token (a following flag stays
46
- // a flag). Unknown `--flags` are collected in `unknown` (never silently
59
+ // a flag) — except `greedy` string entries, which take arbitrary shell
60
+ // text. Unknown `--flags` are collected in `unknown` (never silently
47
61
  // dropped) so commands can reject them loud; everything else is returned
48
62
  // in `rest` so each command can apply its own positional rules.
49
63
  export function parseFlags(args, { string = [], number = [], boolean = [], bareBoolean = [], alias = {} } = {}) {
@@ -51,6 +65,7 @@ export function parseFlags(args, { string = [], number = [], boolean = [], bareB
51
65
  const rest = [];
52
66
  const unknown = [];
53
67
  const strings = normalizeEntries(string);
68
+ const greedyStrings = greedyEntries(string);
54
69
  const numbers = normalizeEntries(number);
55
70
  const booleans = normalizeEntries(boolean);
56
71
  const bares = normalizeEntries(bareBoolean);
@@ -73,7 +88,7 @@ export function parseFlags(args, { string = [], number = [], boolean = [], bareB
73
88
  const value = eq === -1 ? undefined : arg.slice(eq + 1);
74
89
  if (strings.has(name)) {
75
90
  if (value !== undefined) options[strings.get(name)] = value;
76
- else if (i + 1 < list.length && !String(list[i + 1]).startsWith('--')) options[strings.get(name)] = list[++i];
91
+ else if (i + 1 < list.length && (greedyStrings.has(name) || !String(list[i + 1]).startsWith('--'))) options[strings.get(name)] = list[++i];
77
92
  continue;
78
93
  }
79
94
  if (numbers.has(name)) {
@@ -63,7 +63,9 @@ export async function refuseUnknownFlags(options = {}, spec = {}) {
63
63
  return failCommand({
64
64
  noExit: isProgrammaticCall(opts),
65
65
  message: `\n✖ Unknown flag "${unknown[0]}" for ${command}.\n`,
66
- hint: ' Check the spelling or run "grada --help" for usage.\n',
66
+ hint: unknown[0] === '--'
67
+ ? ' Bare "--" end-of-flags is not supported; use --flag=value when the value itself starts with a dash.\n'
68
+ : ' Check the spelling or run "grada --help" for usage.\n',
67
69
  event,
68
70
  telemetry,
69
71
  errorCode: 'UNKNOWN_FLAG',
@@ -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.
package/src/utils/hcl.js CHANGED
@@ -98,7 +98,7 @@ function escapeRegExp(raw) {
98
98
  export function findResourceBlock(content, resourceType, resourceName) {
99
99
  const text = String(content ?? '');
100
100
  const pattern = new RegExp(
101
- `^\\s*resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`,
101
+ `^[ \t]*resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`,
102
102
  'm'
103
103
  );
104
104
  const match = pattern.exec(text);
@@ -99,8 +99,8 @@ const RUNBOOKS = {
99
99
  },
100
100
  OIDC_PROVIDER_CONFLICT: {
101
101
  message: 'GitHub OIDC provider already exists in this account.',
102
- headless: 'Set create_oidc_provider = false in terraform/oidc.tf and re-run apply.',
103
- interactive: 'Set create_oidc_provider = false in terraform/oidc.tf and re-run apply.',
102
+ headless: 'Re-run with --auto-approve to adopt it, or set create_oidc_provider = false in terraform/grada.auto.tfvars.',
103
+ interactive: 'Adopt it when prompted, or set create_oidc_provider = false in terraform/grada.auto.tfvars.',
104
104
  },
105
105
  CLOUDFRONT_IN_PROGRESS: {
106
106
  message: 'CloudFront is still converging a previous change.',
@@ -133,6 +133,42 @@ export function parseStateBucketBackend(content) {
133
133
  };
134
134
  }
135
135
 
136
+ // Machine-owned variable overrides live in terraform/grada.auto.tfvars
137
+ // (auto-loaded by Terraform, gitignored, never regenerated) — never in
138
+ // generated .tf defaults, which regeneration would wipe.
139
+ export const GRADA_AUTO_TFVARS_FILENAME = 'grada.auto.tfvars';
140
+
141
+ // Idempotently sets one `key = value` override in grada.auto.tfvars,
142
+ // creating the file with a managed header when absent. Values are
143
+ // booleans only (the file holds machine flags, not secrets). Returns
144
+ // `{ path, created, changed }`.
145
+ export function upsertAutoTfvar(tfDir, key, value) {
146
+ if (typeof value !== 'boolean') throw new Error(`upsertAutoTfvar only supports booleans (got ${typeof value} for ${key})`);
147
+ if (!/^\w+$/.test(key)) throw new Error(`upsertAutoTfvar rejects non-identifier keys (got ${JSON.stringify(key)})`);
148
+ const filePath = path.join(tfDir, GRADA_AUTO_TFVARS_FILENAME);
149
+ let content = '';
150
+ try {
151
+ content = fs.readFileSync(filePath, 'utf8');
152
+ } catch {
153
+ content = '';
154
+ }
155
+ const created = content === '';
156
+ const line = `${key} = ${value ? 'true' : 'false'}`;
157
+ const pattern = new RegExp(`^[ \\t]*${key}\\s*=.*$`, 'm');
158
+ let changed;
159
+ if (pattern.test(content)) {
160
+ const next = content.replace(pattern, line);
161
+ changed = next !== content;
162
+ content = next;
163
+ } else {
164
+ const header = '# Managed by grada: machine-written variable overrides. Safe to delete an entry to restore its default.\n';
165
+ content = `${created ? header : content.replace(/\n*$/, '\n')}${line}\n`;
166
+ changed = true;
167
+ }
168
+ atomicWriteFileSync(filePath, content);
169
+ return { path: filePath, created, changed };
170
+ }
171
+
136
172
  // Central managed-tree gate: mutating commands refuse on ejected trees
137
173
  // unless --force (headless fails, interactive confirms once);
138
174
  // read-only callers pass `mode: 'warn'` to warn and proceed. Returns
@@ -4,6 +4,7 @@ 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';
7
8
 
8
9
  export const LAST_RUN_FILENAME = 'last-run.json';
9
10
  // Generous per-phase ceiling: CloudFront teardown and Aurora provisioning
@@ -53,9 +54,11 @@ export function isInterruptedMarker(marker) {
53
54
  // output would otherwise replace them.
54
55
  const SUMMARY_LINE_RE = /^(Plan:|Apply complete!|Destroy complete!|No changes\.)/;
55
56
 
56
- function notify(spin, text) {
57
- if (spin && typeof spin.message === 'function') spin.message(text);
58
- }
57
+ // Explicit progress modes for `runTerraformCommand` (the --progress flag
58
+ // on apply/destroy): `lines` forces deduped plain lines for viewers that
59
+ // split animation frames into lines (harness PTYs), `spinner` forces the
60
+ // animated spinner. Absent, the terminal sniff below decides.
61
+ export const PROGRESS_MODES = ['lines', 'spinner'];
59
62
 
60
63
  // Runs a terraform command while piping the latest stdout line into a
61
64
  // @clack spinner. Resolves on exit 0; rejects with a structured error
@@ -68,8 +71,40 @@ function notify(spin, text) {
68
71
  // last-run marker records running/completed/failed/interrupted for the
69
72
  // next command to report. `onStdoutLine` observes raw lines (used by
70
73
  // getTerraformOutputs); listeners and timers are always released.
74
+ //
75
+ // Progress display: a live terminal rewrites one spinner line, but the
76
+ // spinner re-renders every ~80ms — wherever cursor movement isn't
77
+ // honored (piped output, log viewers) each tick becomes a line and
78
+ // quiet stretches repeat the same message dozens of times. Non-live
79
+ // runs therefore get deduped plain lines instead, and the caller's
80
+ // spinner is cleared so its tick doesn't spam behind them (the
81
+ // caller's later stop then becomes a silent no-op).
82
+ //
83
+ // `progress` overrides everything (`lines` forces plain lines,
84
+ // `spinner` forces animation). Otherwise an explicit `isTTY` keeps
85
+ // exact legacy semantics, while the default sniff requires a TTY
86
+ // outside CI with a capable TERM — and still can't catch harness
87
+ // PTYs, which is what the flag is for.
71
88
  export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}) {
72
- const { markerDir = null, timeoutMs = 0, onStdoutLine = null } = options || {};
89
+ const opts = options || {};
90
+ const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY, progress = null } = opts;
91
+ const wantsProgress = spin && typeof spin.message === 'function';
92
+ const sniffed = opts.isTTY === undefined
93
+ ? (isTTY === true && !isActiveEnvValue(process.env.CI) && process.env.TERM !== 'dumb')
94
+ : isTTY === true;
95
+ let live;
96
+ if (progress === 'lines') live = false;
97
+ else if (progress === 'spinner') live = true;
98
+ else live = sniffed;
99
+ live = live && wantsProgress;
100
+ let lastEmitted;
101
+ const emit = (text) => {
102
+ if (lastEmitted === text) return;
103
+ lastEmitted = text;
104
+ if (live) spin.message(text);
105
+ else if (wantsProgress) console.log(text);
106
+ };
107
+ if (wantsProgress && !live && typeof spin.clear === 'function') spin.clear();
73
108
  return new Promise((resolve, reject) => {
74
109
  const child = spawn('terraform', args, { cwd });
75
110
  let errorOutput = '';
@@ -191,13 +226,13 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
191
226
  for (const line of lines) {
192
227
  const trimmed = line.trim();
193
228
  if (SUMMARY_LINE_RE.test(trimmed)) {
194
- notify(spin, `${loadingPrefix} - ${color.dim(trimmed)}`);
229
+ emit(`${loadingPrefix} - ${color.dim(trimmed)}`);
195
230
  }
196
231
  }
197
232
  if (lines.length > 0) {
198
233
  const latestLine = lines[lines.length - 1].trim();
199
234
  const display = latestLine.length > 120 ? latestLine.substring(0, 117) + '...' : latestLine;
200
- notify(spin, `${loadingPrefix} - ${color.dim(display)}`);
235
+ emit(`${loadingPrefix} - ${color.dim(display)}`);
201
236
  }
202
237
  });
203
238
 
@@ -41,12 +41,9 @@ Once live, manage the stack without opening the AWS console:
41
41
  * `npx grada-run destroy --yes` — tear down the bucket and distribution
42
42
 
43
43
  ### ⚠️ Troubleshooting: OIDC Provider Already Exists
44
- If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account). Set `create_oidc_provider` to `false` in `terraform/oidc.tf`:
44
+ If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account). `npx grada-run apply` offers to adopt it (one confirm, zero hand-edits); to do it manually instead, add one line to `terraform/grada.auto.tfvars`:
45
45
  ```hcl
46
- variable "create_oidc_provider" {
47
- type = bool
48
- default = false # <--- Change this from true to false
49
- }
46
+ create_oidc_provider = false
50
47
  ```
51
48
  Re-run `npx grada-run apply` to link directly to your existing provider.
52
49
 
@@ -49,12 +49,9 @@ Once live, manage the stack without opening the AWS console:
49
49
  * `npx grada-run add <capability>` — attach S3, DynamoDB, Valkey, SQS, or Bedrock later (`--list-models` shows available AI models)
50
50
 
51
51
  ### ⚠️ Troubleshooting: OIDC Provider Already Exists
52
- If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account). Set `create_oidc_provider` to `false` in `terraform/oidc.tf`:
52
+ If `terraform apply` fails with `EntityAlreadyExists` for the OIDC provider, this AWS account already has a GitHub Actions provider (AWS permits one per account). `npx grada-run apply` offers to adopt it (one confirm, zero hand-edits); to do it manually instead, add one line to `terraform/grada.auto.tfvars`:
53
53
  ```hcl
54
- variable "create_oidc_provider" {
55
- type = bool
56
- default = false # <--- Change this from true to false
57
- }
54
+ create_oidc_provider = false
58
55
  ```
59
56
  Re-run `npx grada-run apply` to link directly to your existing provider.
60
57
 
@@ -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: |