grada-run 0.41.1 → 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)',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.41.1",
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"
@@ -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,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
@@ -104,7 +118,8 @@ export async function reconcileOfflineTree({ targetDir, options = {}, projectNam
104
118
  });
105
119
  if (confirmed !== true) {
106
120
  cancel('Reconcile aborted.');
107
- process.exit(0);
121
+ exitZeroForCli();
122
+ return { proceed: false, result: { ok: false, reason: 'cancelled' } };
108
123
  }
109
124
  }
110
125
  for (const file of files) {
@@ -298,7 +313,7 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
298
313
  return { proceed: true, previousAppliedTarget: appliedTarget };
299
314
  }
300
315
  cancel('Apply cancelled. No infrastructure was changed.');
301
- process.exit(0);
316
+ exitZeroForCli();
302
317
  return { proceed: false, result: { ok: false, reason: 'cancelled' } };
303
318
  }
304
319
 
@@ -334,6 +349,18 @@ async function applyStackMain(input = {}) {
334
349
  const options = normalizeOptions(input);
335
350
  const unknownRefusal = await refuseUnknownFlags(options, { command: 'apply', event: 'infrastructure_applied' });
336
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
+ }
337
364
  intro(color.bgCyan(color.black(' grada apply ☁️ ')));
338
365
 
339
366
  const targetDir = process.cwd();
@@ -413,7 +440,8 @@ async function applyStackMain(input = {}) {
413
440
  framework: detectedConfig.framework,
414
441
  ...costProps,
415
442
  });
416
- process.exit(0);
443
+ exitZeroForCli();
444
+ return { ok: true, dryRun: true };
417
445
  } else if (shouldAutoApprove(options) || options._skipPreview === true) {
418
446
  // Internal lock-retry resumes skip the preview: the user already
419
447
  // confirmed it before the lock failure.
@@ -430,14 +458,15 @@ async function applyStackMain(input = {}) {
430
458
  const confirmed = await renderDryRunPreview(detectedConfig, false);
431
459
  if (!confirmed) {
432
460
  cancel('Apply aborted.');
433
- process.exit(0);
461
+ exitZeroForCli();
462
+ return { ok: false, reason: 'cancelled' };
434
463
  }
435
464
  }
436
465
 
437
466
  const s = spinner();
438
467
  const runTerraform = options.runTerraformImpl || runTerraformCommand;
439
468
  const runSync = options.spawnSyncImpl || spawnSync;
440
- const lifecycleOpts = { markerDir: targetDir, timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS };
469
+ const lifecycleOpts = { markerDir: targetDir, timeoutMs: DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS, ...(progressMode ? { progress: progressMode } : {}) };
441
470
  const diskTarget = readTerraformComputeTarget(targetDir);
442
471
 
443
472
  try {
@@ -550,7 +579,8 @@ async function applyStackMain(input = {}) {
550
579
  ...costProps
551
580
  });
552
581
 
553
- process.exit(0);
582
+ exitZeroForCli();
583
+ return { ok: true, projectName: actualProjectName, target: diskTarget };
554
584
 
555
585
  } catch (error) {
556
586
  s.stop(color.red('❌ Terraform apply failed.'));
@@ -667,6 +697,7 @@ async function applyStackMain(input = {}) {
667
697
  });
668
698
  }
669
699
 
700
+ let adoptUpsertError = null;
670
701
  if (code === 'OIDC_PROVIDER_CONFLICT' && options._oidcAdopted !== true) {
671
702
  // Adopt the shared provider instead of hand-editing: the
672
703
  // GitHub provider URL is account-singleton, so the existing
@@ -688,12 +719,21 @@ async function applyStackMain(input = {}) {
688
719
  adopt = !isCancel(confirmed) && confirmed === true;
689
720
  }
690
721
  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 });
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
+ }
695
735
  }
696
- // Declined: fall through to the manual guidance below.
736
+ // Declined (or unwritable): fall through to the manual guidance below.
697
737
  }
698
738
 
699
739
  if (code === 'OIDC_PROVIDER_CONFLICT') {
@@ -703,8 +743,11 @@ async function applyStackMain(input = {}) {
703
743
  log.message('AWS only allows one GitHub Actions provider per account, and you already have one configured.');
704
744
  log.message('');
705
745
  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`)}`);
746
+ log.message(`1. Adopt the shared provider (safe to re-run): ${color.cyan(OIDC_ADOPT_MANUAL_COMMAND)}`);
707
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
+ }
708
751
  } else if (code === 'BACKEND_RECONFIGURE_REQUIRED' || code === 'CLOUDFRONT_IN_PROGRESS' || code === 'DELETION_PROTECTION_ACTIVE') {
709
752
  // Named but flow-neutral: runbook guidance with a coded
710
753
  // failure. (RECREATE_COLLISION has its dedicated branch
@@ -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
 
@@ -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 {
@@ -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
  }
@@ -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.
@@ -154,7 +154,7 @@ 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
158
  let changed;
159
159
  if (pattern.test(content)) {
160
160
  const next = content.replace(pattern, line);
@@ -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,6 +54,12 @@ 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
 
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'];
62
+
56
63
  // Runs a terraform command while piping the latest stdout line into a
57
64
  // @clack spinner. Resolves on exit 0; rejects with a structured error
58
65
  // (`{ code, stderr, lockId? }` classified via terraform-errors.js)
@@ -68,15 +75,28 @@ const SUMMARY_LINE_RE = /^(Plan:|Apply complete!|Destroy complete!|No changes\.)
68
75
  // Progress display: a live terminal rewrites one spinner line, but the
69
76
  // spinner re-renders every ~80ms — wherever cursor movement isn't
70
77
  // honored (piped output, log viewers) each tick becomes a line and
71
- // quiet stretches repeat the same message dozens of times. Non-TTY
78
+ // quiet stretches repeat the same message dozens of times. Non-live
72
79
  // runs therefore get deduped plain lines instead, and the caller's
73
80
  // 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.
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.
76
88
  export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}) {
77
- const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY } = options || {};
89
+ const opts = options || {};
90
+ const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY, progress = null } = opts;
78
91
  const wantsProgress = spin && typeof spin.message === 'function';
79
- const live = isTTY === true && wantsProgress;
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;
80
100
  let lastEmitted;
81
101
  const emit = (text) => {
82
102
  if (lastEmitted === text) return;
@@ -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: |